@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.
- package/CHANGELOG.md +18 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/permitted/common/snapInstallation.js.map +1 -1
- package/dist/cjs/permitted/getFile.js +5 -4
- package/dist/cjs/permitted/getFile.js.map +1 -1
- package/dist/cjs/permitted/getSnaps.js.map +1 -1
- package/dist/cjs/permitted/invokeKeyring.js.map +1 -1
- package/dist/cjs/permitted/invokeSnapSugar.js.map +1 -1
- package/dist/cjs/permitted/requestSnaps.js.map +1 -1
- package/dist/cjs/restricted/caveats/permittedCoinTypes.js.map +1 -1
- package/dist/cjs/restricted/dialog.js +16 -25
- package/dist/cjs/restricted/dialog.js.map +1 -1
- package/dist/cjs/restricted/getBip32Entropy.js.map +1 -1
- package/dist/cjs/restricted/getBip32PublicKey.js.map +1 -1
- package/dist/cjs/restricted/getBip44Entropy.js +0 -1
- package/dist/cjs/restricted/getBip44Entropy.js.map +1 -1
- package/dist/cjs/restricted/getEntropy.js.map +1 -1
- package/dist/cjs/restricted/getLocale.js.map +1 -1
- package/dist/cjs/restricted/index.js +0 -9
- package/dist/cjs/restricted/index.js.map +1 -1
- package/dist/cjs/restricted/invokeSnap.js.map +1 -1
- package/dist/cjs/restricted/manageAccounts.js.map +1 -1
- package/dist/cjs/restricted/manageState.js +32 -31
- package/dist/cjs/restricted/manageState.js.map +1 -1
- package/dist/cjs/restricted/notify.js +6 -13
- package/dist/cjs/restricted/notify.js.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/permitted/common/snapInstallation.js.map +1 -1
- package/dist/esm/permitted/getFile.js +2 -1
- package/dist/esm/permitted/getFile.js.map +1 -1
- package/dist/esm/permitted/getSnaps.js.map +1 -1
- package/dist/esm/permitted/invokeKeyring.js.map +1 -1
- package/dist/esm/permitted/invokeSnapSugar.js.map +1 -1
- package/dist/esm/permitted/requestSnaps.js.map +1 -1
- package/dist/esm/restricted/caveats/permittedCoinTypes.js.map +1 -1
- package/dist/esm/restricted/dialog.js +3 -9
- package/dist/esm/restricted/dialog.js.map +1 -1
- package/dist/esm/restricted/getBip32Entropy.js.map +1 -1
- package/dist/esm/restricted/getBip32PublicKey.js.map +1 -1
- package/dist/esm/restricted/getBip44Entropy.js +0 -1
- package/dist/esm/restricted/getBip44Entropy.js.map +1 -1
- package/dist/esm/restricted/getEntropy.js.map +1 -1
- package/dist/esm/restricted/getLocale.js.map +1 -1
- package/dist/esm/restricted/index.js +0 -3
- package/dist/esm/restricted/index.js.map +1 -1
- package/dist/esm/restricted/invokeSnap.js.map +1 -1
- package/dist/esm/restricted/manageAccounts.js.map +1 -1
- package/dist/esm/restricted/manageState.js +28 -24
- package/dist/esm/restricted/manageState.js.map +1 -1
- package/dist/esm/restricted/notify.js +3 -7
- package/dist/esm/restricted/notify.js.map +1 -1
- package/dist/types/index.d.ts +0 -1
- package/dist/types/permitted/common/snapInstallation.d.ts +3 -5
- package/dist/types/permitted/getFile.d.ts +5 -4
- package/dist/types/permitted/getSnaps.d.ts +3 -3
- package/dist/types/permitted/handlers.d.ts +6 -12
- package/dist/types/permitted/invokeKeyring.d.ts +5 -7
- package/dist/types/permitted/invokeSnapSugar.d.ts +5 -8
- package/dist/types/permitted/requestSnaps.d.ts +3 -2
- package/dist/types/restricted/caveats/permittedCoinTypes.d.ts +1 -1
- package/dist/types/restricted/dialog.d.ts +34 -35
- package/dist/types/restricted/getBip32Entropy.d.ts +2 -3
- package/dist/types/restricted/getBip32PublicKey.d.ts +2 -6
- package/dist/types/restricted/getBip44Entropy.d.ts +2 -5
- package/dist/types/restricted/getEntropy.d.ts +3 -2
- package/dist/types/restricted/getLocale.d.ts +2 -1
- package/dist/types/restricted/index.d.ts +9 -90
- package/dist/types/restricted/invokeSnap.d.ts +8 -7
- package/dist/types/restricted/manageAccounts.d.ts +4 -3
- package/dist/types/restricted/manageState.d.ts +6 -15
- package/dist/types/restricted/notify.d.ts +4 -7
- package/package.json +4 -5
- package/dist/cjs/request.js +0 -6
- package/dist/cjs/request.js.map +0 -1
- package/dist/esm/request.js +0 -3
- package/dist/esm/request.js.map +0 -1
- package/dist/types/request.d.ts +0 -99
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/permitted/requestSnaps.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type {\n PermissionConstraint,\n RequestedPermissions,\n Caveat,\n PermittedHandlerExport,\n} from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsPermissionRequest } from '@metamask/snaps-utils';\nimport {\n SnapCaveatType,\n verifyRequestedSnapPermissions,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcRequest,\n PendingJsonRpcResponse,\n Json,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport { WALLET_SNAP_PERMISSION_KEY } from '../restricted/invokeSnap';\nimport type { MethodHooksObject } from '../utils';\nimport type {\n InstallSnapsHook,\n InstallSnapsResult,\n} from './common/snapInstallation';\nimport { handleInstallSnaps } from './common/snapInstallation';\n\nconst hookNames: MethodHooksObject<RequestSnapsHooks> = {\n installSnaps: true,\n requestPermissions: true,\n getPermissions: true,\n};\n\n/**\n * `wallet_requestSnaps` installs the requested Snaps and requests permission to use them if necessary.\n */\nexport const requestSnapsHandler: PermittedHandlerExport<\n RequestSnapsHooks,\n RequestedPermissions,\n InstallSnapsResult\n> = {\n methodNames: ['wallet_requestSnaps'],\n implementation: requestSnapsImplementation,\n hookNames,\n};\n\nexport type RequestSnapsHooks = {\n /**\n * Installs the requested snaps if they are permitted.\n */\n installSnaps: InstallSnapsHook;\n\n /**\n * Initiates a permission request for the requesting origin.\n *\n * @returns The result of the permissions request.\n */\n requestPermissions: (\n permissions: RequestedPermissions,\n ) => Promise<\n [\n Record<string, PermissionConstraint>,\n { data: Record<string, unknown>; id: string; origin: string },\n ]\n >;\n\n /**\n * Gets the current permissions for the requesting origin.\n *\n * @returns The current permissions of the requesting origin.\n */\n getPermissions: () => Promise<\n Record<string, PermissionConstraint> | undefined\n >;\n};\n\n/**\n * Checks whether an origin has existing `wallet_snap` permission and\n * whether or not it has the requested snapIds caveat.\n *\n * @param existingPermissions - The existing permissions for the origin.\n * @param requestedSnaps - The requested snaps.\n * @returns True if the existing permissions satisfy the requested snaps, otherwise false.\n */\nexport function hasRequestedSnaps(\n existingPermissions: Record<string, PermissionConstraint>,\n requestedSnaps: Record<string, unknown>,\n): boolean {\n const snapIdCaveat = existingPermissions[\n WALLET_SNAP_PERMISSION_KEY\n ]?.caveats?.find(\n (caveat: Caveat<string, Json>) => caveat.type === SnapCaveatType.SnapIds,\n );\n\n const permittedSnaps = snapIdCaveat?.value;\n if (isObject(permittedSnaps)) {\n return Object.keys(requestedSnaps).every((requestedSnap) =>\n hasProperty(permittedSnaps, requestedSnap),\n );\n }\n return false;\n}\n\n/**\n * Constructs a valid permission request with merged caveats based on existing permissions\n * and the requested snaps.\n *\n * @param existingPermissions - The existing permissions for the origin.\n * @param requestedPermissions - The permission request passed into `requestPermissions`.\n * @returns `requestedPermissions`.\n */\nexport function getSnapPermissionsRequest(\n existingPermissions: Record<string, PermissionConstraint>,\n requestedPermissions: unknown,\n): SnapsPermissionRequest {\n verifyRequestedSnapPermissions(requestedPermissions);\n\n if (!existingPermissions[WALLET_SNAP_PERMISSION_KEY]) {\n return requestedPermissions;\n }\n\n const snapIdCaveat = existingPermissions[\n WALLET_SNAP_PERMISSION_KEY\n ].caveats?.find(\n (caveat: Caveat<string, Json>) => caveat.type === SnapCaveatType.SnapIds,\n );\n\n const permittedSnaps = (snapIdCaveat?.value as Record<string, Json>) ?? {};\n\n const requestedSnaps =\n requestedPermissions[WALLET_SNAP_PERMISSION_KEY].caveats[0].value;\n\n const snapIdSet = new Set([\n ...Object.keys(permittedSnaps),\n ...Object.keys(requestedSnaps),\n ]);\n\n const mergedCaveatValue = [...snapIdSet].reduce<Record<string, Json>>(\n (request, snapId) => {\n request[snapId] = requestedSnaps[snapId] ?? permittedSnaps[snapId];\n return request;\n },\n {},\n );\n\n requestedPermissions[WALLET_SNAP_PERMISSION_KEY].caveats[0].value =\n mergedCaveatValue;\n\n return requestedPermissions;\n}\n\n/**\n * The `wallet_requestSnaps` method implementation.\n * Tries to install the requested snaps and adds them to the JSON-RPC response.\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.installSnaps - A function that tries to install a given snap, prompting the user if necessary.\n * @param hooks.requestPermissions - A function that requests permissions on\n * behalf of a subject.\n * @param hooks.getPermissions - A function that gets the current permissions.\n * @returns A promise that resolves once the JSON-RPC response has been modified.\n * @throws If the params are invalid.\n */\nasync function requestSnapsImplementation(\n req: JsonRpcRequest<RequestedPermissions>,\n res: PendingJsonRpcResponse<InstallSnapsResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { installSnaps, requestPermissions, getPermissions }: RequestSnapsHooks,\n): Promise<void> {\n const requestedSnaps = req.params;\n if (!isObject(requestedSnaps)) {\n return end(\n rpcErrors.invalidParams({\n message: '\"params\" must be an object.',\n }),\n );\n }\n\n try {\n if (!Object.keys(requestedSnaps).length) {\n throw new Error('Request must have at least one requested snap.');\n }\n\n const requestedPermissions = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [{ type: SnapCaveatType.SnapIds, value: requestedSnaps }],\n },\n } as RequestedPermissions;\n const existingPermissions = await getPermissions();\n\n if (!existingPermissions) {\n const [, metadata] = await requestPermissions(requestedPermissions);\n res.result = metadata.data[\n WALLET_SNAP_PERMISSION_KEY\n ] as InstallSnapsResult;\n } else if (hasRequestedSnaps(existingPermissions, requestedSnaps)) {\n res.result = await handleInstallSnaps(requestedSnaps, installSnaps);\n } else {\n const mergedPermissionsRequest = getSnapPermissionsRequest(\n existingPermissions,\n requestedPermissions,\n );\n\n const [, metadata] = await requestPermissions(mergedPermissionsRequest);\n res.result = metadata.data[\n WALLET_SNAP_PERMISSION_KEY\n ] as InstallSnapsResult;\n }\n } catch (error) {\n res.error = error;\n }\n\n return end();\n}\n"],"names":["rpcErrors","SnapCaveatType","verifyRequestedSnapPermissions","hasProperty","isObject","WALLET_SNAP_PERMISSION_KEY","handleInstallSnaps","hookNames","installSnaps","requestPermissions","getPermissions","requestSnapsHandler","methodNames","implementation","requestSnapsImplementation","hasRequestedSnaps","existingPermissions","requestedSnaps","snapIdCaveat","caveats","find","caveat","type","SnapIds","permittedSnaps","value","Object","keys","every","requestedSnap","getSnapPermissionsRequest","requestedPermissions","snapIdSet","Set","mergedCaveatValue","reduce","request","snapId","req","res","_next","end","params","invalidParams","message","length","Error","metadata","result","data","mergedPermissionsRequest","error"],"mappings":"AAOA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SACEC,cAAc,EACdC,8BAA8B,QACzB,wBAAwB;AAM/B,SAASC,WAAW,EAAEC,QAAQ,QAAQ,kBAAkB;AAExD,SAASC,0BAA0B,QAAQ,2BAA2B;AAMtE,SAASC,kBAAkB,QAAQ,4BAA4B;AAE/D,MAAMC,YAAkD;IACtDC,cAAc;IACdC,oBAAoB;IACpBC,gBAAgB;AAClB;AAEA;;CAEC,GACD,OAAO,MAAMC,sBAIT;IACFC,aAAa;QAAC;KAAsB;IACpCC,gBAAgBC;IAChBP;AACF,EAAE;AAgCF;;;;;;;CAOC,GACD,OAAO,SAASQ,kBACdC,mBAAyD,EACzDC,cAAuC;IAEvC,MAAMC,eAAeF,mBAAmB,CACtCX,2BACD,EAAEc,SAASC,KACV,CAACC,SAAiCA,OAAOC,IAAI,KAAKrB,eAAesB,OAAO;IAG1E,MAAMC,iBAAiBN,cAAcO;IACrC,IAAIrB,SAASoB,iBAAiB;QAC5B,OAAOE,OAAOC,IAAI,CA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IAAIC,MAAM;QAClB;QAEA,MAAMf,uBAAuB;YAC3B,CAAC1B,2BAA2B,EAAE;gBAC5Bc,SAAS;oBAAC;wBAAEG,MAAMrB,eAAesB,OAAO;wBAAEE,OAAOR;oBAAe;iBAAE;YACpE;QACF;QACA,MAAMD,sBAAsB,MAAMN;QAElC,IAAI,CAACM,qBAAqB;YACxB,MAAM,GAAG+B,SAAS,GAAG,MAAMtC,mBAAmBsB;YAC9CQ,IAAIS,MAAM,GAAGD,SAASE,IAAI,CACxB5C,2BACD;QACH,OAAO,IAAIU,kBAAkBC,qBAAqBC,iBAAiB;YACjEsB,IAAIS,MAAM,GAAG,MAAM1C,mBAAmBW,gBAAgBT;QACxD,OAAO;YACL,MAAM0C,2BAA2BpB,0BAC/Bd,qBACAe;YAGF,MAAM,GAAGgB,SAAS,GAAG,MAAMtC,mBAAmByC;YAC9CX,IAAIS,MAAM,GAAGD,SAASE,IAAI,CACxB5C,2BACD;QACH;IACF,EAAE,OAAO8C,OAAO;QACdZ,IAAIY,KAAK,GAAGA;IACd;IAEA,OAAOV;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/requestSnaps.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type {\n PermissionConstraint,\n RequestedPermissions,\n Caveat,\n PermittedHandlerExport,\n} from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n RequestSnapsParams,\n RequestSnapsResult,\n} from '@metamask/snaps-sdk';\nimport type { SnapsPermissionRequest } from '@metamask/snaps-utils';\nimport {\n SnapCaveatType,\n verifyRequestedSnapPermissions,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcRequest,\n PendingJsonRpcResponse,\n Json,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport { WALLET_SNAP_PERMISSION_KEY } from '../restricted/invokeSnap';\nimport type { MethodHooksObject } from '../utils';\nimport type { InstallSnapsHook } from './common/snapInstallation';\nimport { handleInstallSnaps } from './common/snapInstallation';\n\nconst hookNames: MethodHooksObject<RequestSnapsHooks> = {\n installSnaps: true,\n requestPermissions: true,\n getPermissions: true,\n};\n\n/**\n * `wallet_requestSnaps` installs the requested Snaps and requests permission to use them if necessary.\n */\nexport const requestSnapsHandler: PermittedHandlerExport<\n RequestSnapsHooks,\n RequestSnapsParams,\n RequestSnapsResult\n> = {\n methodNames: ['wallet_requestSnaps'],\n implementation: requestSnapsImplementation,\n hookNames,\n};\n\nexport type RequestSnapsHooks = {\n /**\n * Installs the requested snaps if they are permitted.\n */\n installSnaps: InstallSnapsHook;\n\n /**\n * Initiates a permission request for the requesting origin.\n *\n * @returns The result of the permissions request.\n */\n requestPermissions: (\n permissions: RequestedPermissions,\n ) => Promise<\n [\n Record<string, PermissionConstraint>,\n { data: Record<string, unknown>; id: string; origin: string },\n ]\n >;\n\n /**\n * Gets the current permissions for the requesting origin.\n *\n * @returns The current permissions of the requesting origin.\n */\n getPermissions: () => Promise<\n Record<string, PermissionConstraint> | undefined\n >;\n};\n\n/**\n * Checks whether an origin has existing `wallet_snap` permission and\n * whether or not it has the requested snapIds caveat.\n *\n * @param existingPermissions - The existing permissions for the origin.\n * @param requestedSnaps - The requested snaps.\n * @returns True if the existing permissions satisfy the requested snaps, otherwise false.\n */\nexport function hasRequestedSnaps(\n existingPermissions: Record<string, PermissionConstraint>,\n requestedSnaps: Record<string, unknown>,\n): boolean {\n const snapIdCaveat = existingPermissions[\n WALLET_SNAP_PERMISSION_KEY\n ]?.caveats?.find(\n (caveat: Caveat<string, Json>) => caveat.type === SnapCaveatType.SnapIds,\n );\n\n const permittedSnaps = snapIdCaveat?.value;\n if (isObject(permittedSnaps)) {\n return Object.keys(requestedSnaps).every((requestedSnap) =>\n hasProperty(permittedSnaps, requestedSnap),\n );\n }\n return false;\n}\n\n/**\n * Constructs a valid permission request with merged caveats based on existing permissions\n * and the requested snaps.\n *\n * @param existingPermissions - The existing permissions for the origin.\n * @param requestedPermissions - The permission request passed into `requestPermissions`.\n * @returns `requestedPermissions`.\n */\nexport function getSnapPermissionsRequest(\n existingPermissions: Record<string, PermissionConstraint>,\n requestedPermissions: unknown,\n): SnapsPermissionRequest {\n verifyRequestedSnapPermissions(requestedPermissions);\n\n if (!existingPermissions[WALLET_SNAP_PERMISSION_KEY]) {\n return requestedPermissions;\n }\n\n const snapIdCaveat = existingPermissions[\n WALLET_SNAP_PERMISSION_KEY\n ].caveats?.find(\n (caveat: Caveat<string, Json>) => caveat.type === SnapCaveatType.SnapIds,\n );\n\n const permittedSnaps = (snapIdCaveat?.value as Record<string, Json>) ?? {};\n\n const requestedSnaps =\n requestedPermissions[WALLET_SNAP_PERMISSION_KEY].caveats[0].value;\n\n const snapIdSet = new Set([\n ...Object.keys(permittedSnaps),\n ...Object.keys(requestedSnaps),\n ]);\n\n const mergedCaveatValue = [...snapIdSet].reduce<Record<string, Json>>(\n (request, snapId) => {\n request[snapId] = requestedSnaps[snapId] ?? permittedSnaps[snapId];\n return request;\n },\n {},\n );\n\n requestedPermissions[WALLET_SNAP_PERMISSION_KEY].caveats[0].value =\n mergedCaveatValue;\n\n return requestedPermissions;\n}\n\n/**\n * The `wallet_requestSnaps` method implementation.\n * Tries to install the requested snaps and adds them to the JSON-RPC response.\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.installSnaps - A function that tries to install a given snap, prompting the user if necessary.\n * @param hooks.requestPermissions - A function that requests permissions on\n * behalf of a subject.\n * @param hooks.getPermissions - A function that gets the current permissions.\n * @returns A promise that resolves once the JSON-RPC response has been modified.\n * @throws If the params are invalid.\n */\nasync function requestSnapsImplementation(\n req: JsonRpcRequest<RequestSnapsParams>,\n res: PendingJsonRpcResponse<RequestSnapsResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { installSnaps, requestPermissions, getPermissions }: RequestSnapsHooks,\n): Promise<void> {\n const requestedSnaps = req.params;\n if (!isObject(requestedSnaps)) {\n return end(\n rpcErrors.invalidParams({\n message: '\"params\" must be an object.',\n }),\n );\n }\n\n try {\n if (!Object.keys(requestedSnaps).length) {\n throw new Error('Request must have at least one requested snap.');\n }\n\n const requestedPermissions = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [{ type: SnapCaveatType.SnapIds, value: requestedSnaps }],\n },\n } as RequestedPermissions;\n const existingPermissions = await getPermissions();\n\n if (!existingPermissions) {\n const [, metadata] = await requestPermissions(requestedPermissions);\n res.result = metadata.data[\n WALLET_SNAP_PERMISSION_KEY\n ] as RequestSnapsResult;\n } else if (hasRequestedSnaps(existingPermissions, requestedSnaps)) {\n res.result = await handleInstallSnaps(requestedSnaps, installSnaps);\n } else {\n const mergedPermissionsRequest = getSnapPermissionsRequest(\n existingPermissions,\n requestedPermissions,\n );\n\n const [, metadata] = await requestPermissions(mergedPermissionsRequest);\n res.result = metadata.data[\n WALLET_SNAP_PERMISSION_KEY\n ] as RequestSnapsResult;\n }\n } catch (error) {\n res.error = error;\n }\n\n return end();\n}\n"],"names":["rpcErrors","SnapCaveatType","verifyRequestedSnapPermissions","hasProperty","isObject","WALLET_SNAP_PERMISSION_KEY","handleInstallSnaps","hookNames","installSnaps","requestPermissions","getPermissions","requestSnapsHandler","methodNames","implementation","requestSnapsImplementation","hasRequestedSnaps","existingPermissions","requestedSnaps","snapIdCaveat","caveats","find","caveat","type","SnapIds","permittedSnaps","value","Object","keys","every","requestedSnap","getSnapPermissionsRequest","requestedPermissions","snapIdSet","Set","mergedCaveatValue","reduce","request","snapId","req","res","_next","end","params","invalidParams","message","length","Error","metadata","result","data","mergedPermissionsRequest","error"],"mappings":"AAOA,SAASA,SAAS,QAAQ,uBAAuB;AAMjD,SACEC,cAAc,EACdC,8BAA8B,QACzB,wBAAwB;AAM/B,SAASC,WAAW,EAAEC,QAAQ,QAAQ,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":3,"sources":["../../../../src/restricted/caveats/permittedCoinTypes.ts"],"sourcesContent":["import type {\n PermissionConstraint,\n RestrictedMethodCaveatSpecificationConstraint,\n Caveat,\n} from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport { FORBIDDEN_COIN_TYPES, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isPlainObject } from '@metamask/utils';\n\
|
|
1
|
+
{"version":3,"sources":["../../../../src/restricted/caveats/permittedCoinTypes.ts"],"sourcesContent":["import type {\n PermissionConstraint,\n RestrictedMethodCaveatSpecificationConstraint,\n Caveat,\n} from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { GetBip44EntropyParams } from '@metamask/snaps-sdk';\nimport { FORBIDDEN_COIN_TYPES, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isPlainObject } from '@metamask/utils';\n\n/**\n * Map a raw value from the `initialPermissions` to a caveat specification.\n * Note that this function does not do any validation, that's handled by the\n * PermissionsController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function permittedCoinTypesCaveatMapper(\n value: Json,\n): Pick<PermissionConstraint, 'caveats'> {\n return {\n caveats: [\n {\n type: SnapCaveatType.PermittedCoinTypes,\n value,\n },\n ],\n };\n}\n\n/**\n * Validate the params for `snap_getBip44Entropy`.\n *\n * @param value - The params to validate.\n * @throws If the params are invalid.\n */\nexport function validateBIP44Params(\n value: unknown,\n): asserts value is GetBip44EntropyParams {\n if (!isPlainObject(value) || !hasProperty(value, 'coinType')) {\n throw rpcErrors.invalidParams({\n message: 'Expected a plain object containing a coin type.',\n });\n }\n\n if (\n typeof value.coinType !== 'number' ||\n !Number.isInteger(value.coinType) ||\n value.coinType < 0 ||\n value.coinType > 0x7fffffff\n ) {\n throw rpcErrors.invalidParams({\n message:\n 'Invalid \"coinType\" parameter. Coin type must be a non-negative integer.',\n });\n }\n\n if (FORBIDDEN_COIN_TYPES.includes(value.coinType)) {\n throw rpcErrors.invalidParams({\n message: `Coin type ${value.coinType} is forbidden.`,\n });\n }\n}\n\n/**\n * Validate the coin types values associated with a caveat. This checks if the\n * values are non-negative integers (>= 0).\n *\n * @param caveat - The caveat to validate.\n * @throws If the caveat is invalid.\n */\nexport function validateBIP44Caveat(caveat: Caveat<string, any>) {\n if (\n !hasProperty(caveat, 'value') ||\n !Array.isArray(caveat.value) ||\n caveat.value.length === 0\n ) {\n throw rpcErrors.invalidParams({\n message: 'Expected non-empty array of coin types.',\n });\n }\n\n caveat.value.forEach(validateBIP44Params);\n}\n\nexport const PermittedCoinTypesCaveatSpecification: Record<\n SnapCaveatType.PermittedCoinTypes,\n RestrictedMethodCaveatSpecificationConstraint\n> = {\n [SnapCaveatType.PermittedCoinTypes]: Object.freeze({\n type: SnapCaveatType.PermittedCoinTypes,\n decorator: (\n method,\n caveat: Caveat<\n SnapCaveatType.PermittedCoinTypes,\n GetBip44EntropyParams[]\n >,\n ) => {\n return async (args) => {\n const { params } = args;\n validateBIP44Params(params);\n\n const coinType = caveat.value.find(\n (caveatValue) => caveatValue.coinType === params.coinType,\n );\n\n if (!coinType) {\n throw providerErrors.unauthorized({\n message:\n 'The requested coin type is not permitted. Allowed coin types must be specified in the snap manifest.',\n });\n }\n\n return await method(args);\n };\n },\n validator: (caveat) => validateBIP44Caveat(caveat),\n }),\n};\n"],"names":["providerErrors","rpcErrors","FORBIDDEN_COIN_TYPES","SnapCaveatType","hasProperty","isPlainObject","permittedCoinTypesCaveatMapper","value","caveats","type","PermittedCoinTypes","validateBIP44Params","invalidParams","message","coinType","Number","isInteger","includes","validateBIP44Caveat","caveat","Array","isArray","length","forEach","PermittedCoinTypesCaveatSpecification","Object","freeze","decorator","method","args","params","find","caveatValue","unauthorized","validator"],"mappings":"AAKA,SAASA,cAAc,EAAEC,SAAS,QAAQ,uBAAuB;AAEjE,SAAS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AAE,GAAGD;gBACnBlB,oBAAoBmB;gBAEpB,MAAMhB,WAAWK,OAAOZ,KAAK,CAACwB,IAAI,CAChC,CAACC,cAAgBA,YAAYlB,QAAQ,KAAKgB,OAAOhB,QAAQ;gBAG3D,IAAI,CAACA,UAAU;oBACb,MAAMd,eAAeiC,YAAY,CAAC;wBAChCpB,SACE;oBACJ;gBACF;gBAEA,OAAO,MAAMe,OAAOC;YACtB;QACF;QACAK,WAAW,CAACf,SAAWD,oBAAoBC;IAC7C;AACF,EAAE"}
|
|
@@ -1,15 +1,9 @@
|
|
|
1
1
|
import { PermissionType, SubjectType } from '@metamask/permission-controller';
|
|
2
2
|
import { rpcErrors } from '@metamask/rpc-errors';
|
|
3
|
-
import {
|
|
4
|
-
import { enumValue } from '@metamask/snaps-utils';
|
|
3
|
+
import { DialogType, ComponentStruct } from '@metamask/snaps-sdk';
|
|
4
|
+
import { validateComponentLinks, enumValue } from '@metamask/snaps-utils';
|
|
5
5
|
import { create, enums, object, optional, size, string, StructError, type, union } from 'superstruct';
|
|
6
6
|
const methodName = 'snap_dialog';
|
|
7
|
-
export var DialogType;
|
|
8
|
-
(function(DialogType) {
|
|
9
|
-
DialogType["Alert"] = 'alert';
|
|
10
|
-
DialogType["Confirmation"] = 'confirmation';
|
|
11
|
-
DialogType["Prompt"] = 'prompt';
|
|
12
|
-
})(DialogType || (DialogType = {}));
|
|
13
7
|
const PlaceholderStruct = optional(size(string(), 1, 40));
|
|
14
8
|
/**
|
|
15
9
|
* The specification builder for the `snap_dialog` permission. `snap_dialog`
|
|
@@ -95,7 +89,7 @@ const structs = {
|
|
|
95
89
|
const validatedParams = getValidatedParams(params, structs[validatedType]);
|
|
96
90
|
const { content } = validatedParams;
|
|
97
91
|
await maybeUpdatePhishingList();
|
|
98
|
-
|
|
92
|
+
validateComponentLinks(content, isOnPhishingList);
|
|
99
93
|
const placeholder = validatedParams.type === DialogType.Prompt ? validatedParams.placeholder : undefined;
|
|
100
94
|
return showDialog(origin, validatedType, content, placeholder);
|
|
101
95
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/dialog.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 { Component } from '@metamask/snaps-ui';\nimport { ComponentStruct, assertUILinksAreSafe } from '@metamask/snaps-ui';\nimport type { EnumToUnion } from '@metamask/snaps-utils';\nimport { enumValue } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n create,\n enums,\n object,\n optional,\n size,\n string,\n StructError,\n type,\n union,\n} from 'superstruct';\n\nimport { type MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_dialog';\n\nexport enum DialogType {\n Alert = 'alert',\n Confirmation = 'confirmation',\n Prompt = 'prompt',\n}\n\nconst PlaceholderStruct = optional(size(string(), 1, 40));\n\nexport type Placeholder = Infer<typeof PlaceholderStruct>;\n\ntype ShowDialog = (\n snapId: string,\n type: EnumToUnion<DialogType>,\n content: Component,\n placeholder?: Placeholder,\n) => Promise<null | boolean | string>;\n\ntype MaybeUpdatePhisingList = () => Promise<void>;\ntype IsOnPhishingList = (url: string) => boolean;\n\nexport type DialogMethodHooks = {\n /**\n * @param snapId - The ID of the Snap that created the alert.\n * @param type - The dialog type.\n * @param content - The dialog custom UI.\n * @param placeholder - The placeholder for the Prompt dialog input.\n */\n showDialog: ShowDialog;\n\n maybeUpdatePhishingList: MaybeUpdatePhisingList;\n\n /**\n * @param url - The URL to check against the phishing list.\n */\n isOnPhishingList: IsOnPhishingList;\n};\n\ntype DialogSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: DialogMethodHooks;\n};\n\ntype DialogSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getDialogImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_dialog` permission. `snap_dialog`\n * lets the Snap display one of the following dialogs to the user:\n * - An alert, for displaying information.\n * - A confirmation, for accepting or rejecting some action.\n * - A prompt, for inputting some information.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the\n * permission.\n * @param options.methodHooks - The RPC method hooks needed by the method\n * implementation.\n * @returns The specification for the `snap_dialog` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n DialogSpecificationBuilderOptions,\n DialogSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: DialogSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getDialogImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<DialogMethodHooks> = {\n showDialog: true,\n isOnPhishingList: true,\n maybeUpdatePhishingList: true,\n};\n\nexport const dialogBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n// Note: We use `type` here instead of `object` because `type` does not validate\n// the keys of the object, which is what we want.\nconst BaseParamsStruct = type({\n type: enums([DialogType.Alert, DialogType.Confirmation, DialogType.Prompt]),\n});\n\nconst AlertParametersStruct = object({\n type: enumValue(DialogType.Alert),\n content: ComponentStruct,\n});\n\nconst ConfirmationParametersStruct = object({\n type: enumValue(DialogType.Confirmation),\n content: ComponentStruct,\n});\n\nconst PromptParametersStruct = object({\n type: enumValue(DialogType.Prompt),\n content: ComponentStruct,\n placeholder: PlaceholderStruct,\n});\n\nconst DialogParametersStruct = union([\n AlertParametersStruct,\n ConfirmationParametersStruct,\n PromptParametersStruct,\n]);\n\nexport type DialogParameters = Infer<typeof DialogParametersStruct>;\n\nconst structs = {\n [DialogType.Alert]: AlertParametersStruct,\n [DialogType.Confirmation]: ConfirmationParametersStruct,\n [DialogType.Prompt]: PromptParametersStruct,\n};\n\n/**\n * Builds the method implementation for `snap_dialog`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.showDialog - A function that shows the specified dialog in the\n * MetaMask UI and returns the appropriate value for the dialog type.\n * @param hooks.isOnPhishingList - A function that checks a link against the\n * phishing list and return true if it's in, otherwise false.\n * @param hooks.maybeUpdatePhishingList - A function that updates the phishing list if needed.\n * @returns The method implementation which return value depends on the dialog\n * type, valid return types are: string, boolean, null.\n */\nexport function getDialogImplementation({\n showDialog,\n isOnPhishingList,\n maybeUpdatePhishingList,\n}: DialogMethodHooks) {\n return async function dialogImplementation(\n args: RestrictedMethodOptions<DialogParameters>,\n ): Promise<boolean | null | string> {\n const {\n params,\n context: { origin },\n } = args;\n\n const validatedType = getValidatedType(params);\n const validatedParams = getValidatedParams(params, structs[validatedType]);\n\n const { content } = validatedParams;\n\n await maybeUpdatePhishingList();\n\n assertUILinksAreSafe(content, isOnPhishingList);\n\n const placeholder =\n validatedParams.type === DialogType.Prompt\n ? validatedParams.placeholder\n : undefined;\n\n return showDialog(origin, validatedType, content, placeholder);\n };\n}\n\n/**\n * Get the validated type of the dialog parameters. Throws an error if the type\n * is invalid.\n *\n * @param params - The parameters to validate.\n * @returns The validated type of the dialog parameters.\n */\nfunction getValidatedType(params: unknown): DialogType {\n try {\n return create(params, BaseParamsStruct).type;\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `The \"type\" property must be one of: ${Object.values(\n DialogType,\n ).join(', ')}.`,\n });\n }\n}\n\n/**\n * Validates the confirm 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 struct - The struct to validate the params against.\n * @returns The validated confirm method parameter object.\n */\nfunction getValidatedParams(\n params: unknown,\n struct: Struct<any>,\n): DialogParameters {\n try {\n return create(params, struct);\n } catch (error) {\n if (error instanceof StructError) {\n const { key, type: errorType } = error;\n\n if (key === 'placeholder' && errorType === 'never') {\n throw rpcErrors.invalidParams({\n message:\n 'Invalid params: Alerts or confirmations may not specify a \"placeholder\" field.',\n });\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","ComponentStruct","assertUILinksAreSafe","enumValue","create","enums","object","optional","size","string","StructError","type","union","methodName","DialogType","Alert","Confirmation","Prompt","PlaceholderStruct","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getDialogImplementation","subjectTypes","Snap","showDialog","isOnPhishingList","maybeUpdatePhishingList","dialogBuilder","Object","freeze","BaseParamsStruct","AlertParametersStruct","content","ConfirmationParametersStruct","PromptParametersStruct","placeholder","DialogParametersStruct","structs","dialogImplementation","args","params","context","origin","validatedType","getValidatedType","validatedParams","getValidatedParams","undefined","error","invalidParams","message","values","join","struct","key","errorType","internal"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,eAAe,EAAEC,oBAAoB,QAAQ,qBAAqB;AAE3E,SAASC,SAAS,QAAQ,wBAAwB;AAGlD,SACEC,MAAM,EACNC,KAAK,EACLC,MAAM,EACNC,QAAQ,EACRC,IAAI,EACJC,MAAM,EACNC,WAAW,EACXC,IAAI,EACJC,KAAK,QACA,cAAc;AAIrB,MAAMC,aAAa;WAEZ;UAAKC,UAAU;IAAVA,WACVC,WAAQ;IADED,WAEVE,kBAAe;IAFLF,WAGVG,YAAS;GAHCH,eAAAA;AAMZ,MAAMI,oBAAoBX,SAASC,KAAKC,UAAU,GAAG;AA2CrD;;;;;;;;;;;;;CAaC,GACD,MAAMU,uBAIF,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EACuB;IAClC,OAAO;QACLC,gB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,OAAO,EAAE,GAAGa;QAEpB,MAAMnB;QAEN7B,qBAAqBmC,SAASP;QAE9B,MAAMU,cACJU,gBAAgBvC,IAAI,KAAKG,WAAWG,MAAM,GACtCiC,gBAAgBV,WAAW,GAC3BY;QAEN,OAAOvB,WAAWkB,QAAQC,eAAeX,SAASG;IACpD;AACF;AAEA;;;;;;CAMC,GACD,SAASS,iBAAiBJ,MAAe;IACvC,IAAI;QACF,OAAOzC,OAAOyC,QAAQV,kBAAkBxB,IAAI;IAC9C,EAAE,OAAO0C,OAAO;QACd,MAAMrD,UAAUsD,aAAa,CAAC;YAC5BC,SAAS,CAAC,oCAAoC,EAAEtB,OAAOuB,MAAM,CAC3D1C,YACA2C,IAAI,CAAC,MAAM,CAAC,CAAC;QACjB;IACF;AACF;AAEA;;;;;;;CAOC,GACD,SAASN,mBACPN,MAAe,EACfa,MAAmB;IAEnB,IAAI;QACF,OAAOtD,OAAOyC,QAAQa;IACxB,EAAE,OAAOL,OAAO;QACd,IAAIA,iBAAiB3C,aAAa;YAChC,MAAM,EAAEiD,GAAG,EAAEhD,MAAMiD,SAAS,EAAE,GAAGP;YAEjC,IAAIM,QAAQ,iBAAiBC,cAAc,SAAS;gBAClD,MAAM5D,UAAUsD,aAAa,CAAC;oBAC5BC,SACE;gBACJ;YACF;YAEA,MAAMvD,UAAUsD,aAAa,CAAC;gBAC5BC,SAAS,CAAC,gBAAgB,EAAEF,MAAME,OAAO,CAAC,CAAC,CAAC;YAC9C;QACF;QAEA,wBAAwB,GACxB,MAAMvD,UAAU6D,QAAQ;IAC1B;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/dialog.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 { DialogType, ComponentStruct } from '@metamask/snaps-sdk';\nimport type { DialogParams, EnumToUnion, Component } from '@metamask/snaps-sdk';\nimport { validateComponentLinks, enumValue } from '@metamask/snaps-utils';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n create,\n enums,\n object,\n optional,\n size,\n string,\n StructError,\n type,\n union,\n} from 'superstruct';\n\nimport { type MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_dialog';\n\nconst PlaceholderStruct = optional(size(string(), 1, 40));\n\nexport type Placeholder = Infer<typeof PlaceholderStruct>;\n\ntype ShowDialog = (\n snapId: string,\n type: EnumToUnion<DialogType>,\n content: Component,\n placeholder?: Placeholder,\n) => Promise<null | boolean | string>;\n\ntype MaybeUpdatePhisingList = () => Promise<void>;\ntype IsOnPhishingList = (url: string) => boolean;\n\nexport type DialogMethodHooks = {\n /**\n * @param snapId - The ID of the Snap that created the alert.\n * @param type - The dialog type.\n * @param content - The dialog custom UI.\n * @param placeholder - The placeholder for the Prompt dialog input.\n */\n showDialog: ShowDialog;\n\n maybeUpdatePhishingList: MaybeUpdatePhisingList;\n\n /**\n * @param url - The URL to check against the phishing list.\n */\n isOnPhishingList: IsOnPhishingList;\n};\n\ntype DialogSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: DialogMethodHooks;\n};\n\ntype DialogSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getDialogImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_dialog` permission. `snap_dialog`\n * lets the Snap display one of the following dialogs to the user:\n * - An alert, for displaying information.\n * - A confirmation, for accepting or rejecting some action.\n * - A prompt, for inputting some information.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the\n * permission.\n * @param options.methodHooks - The RPC method hooks needed by the method\n * implementation.\n * @returns The specification for the `snap_dialog` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n DialogSpecificationBuilderOptions,\n DialogSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: DialogSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getDialogImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<DialogMethodHooks> = {\n showDialog: true,\n isOnPhishingList: true,\n maybeUpdatePhishingList: true,\n};\n\nexport const dialogBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n// Note: We use `type` here instead of `object` because `type` does not validate\n// the keys of the object, which is what we want.\nconst BaseParamsStruct = type({\n type: enums([DialogType.Alert, DialogType.Confirmation, DialogType.Prompt]),\n});\n\nconst AlertParametersStruct = object({\n type: enumValue(DialogType.Alert),\n content: ComponentStruct,\n});\n\nconst ConfirmationParametersStruct = object({\n type: enumValue(DialogType.Confirmation),\n content: ComponentStruct,\n});\n\nconst PromptParametersStruct = object({\n type: enumValue(DialogType.Prompt),\n content: ComponentStruct,\n placeholder: PlaceholderStruct,\n});\n\nconst DialogParametersStruct = union([\n AlertParametersStruct,\n ConfirmationParametersStruct,\n PromptParametersStruct,\n]);\n\nexport type DialogParameters = InferMatching<\n typeof DialogParametersStruct,\n DialogParams\n>;\n\nconst structs = {\n [DialogType.Alert]: AlertParametersStruct,\n [DialogType.Confirmation]: ConfirmationParametersStruct,\n [DialogType.Prompt]: PromptParametersStruct,\n};\n\n/**\n * Builds the method implementation for `snap_dialog`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.showDialog - A function that shows the specified dialog in the\n * MetaMask UI and returns the appropriate value for the dialog type.\n * @param hooks.isOnPhishingList - A function that checks a link against the\n * phishing list and return true if it's in, otherwise false.\n * @param hooks.maybeUpdatePhishingList - A function that updates the phishing list if needed.\n * @returns The method implementation which return value depends on the dialog\n * type, valid return types are: string, boolean, null.\n */\nexport function getDialogImplementation({\n showDialog,\n isOnPhishingList,\n maybeUpdatePhishingList,\n}: DialogMethodHooks) {\n return async function dialogImplementation(\n args: RestrictedMethodOptions<DialogParameters>,\n ): Promise<boolean | null | string> {\n const {\n params,\n context: { origin },\n } = args;\n\n const validatedType = getValidatedType(params);\n const validatedParams = getValidatedParams(params, structs[validatedType]);\n\n const { content } = validatedParams;\n\n await maybeUpdatePhishingList();\n\n validateComponentLinks(content, isOnPhishingList);\n\n const placeholder =\n validatedParams.type === DialogType.Prompt\n ? validatedParams.placeholder\n : undefined;\n\n return showDialog(origin, validatedType, content, placeholder);\n };\n}\n\n/**\n * Get the validated type of the dialog parameters. Throws an error if the type\n * is invalid.\n *\n * @param params - The parameters to validate.\n * @returns The validated type of the dialog parameters.\n */\nfunction getValidatedType(params: unknown): DialogType {\n try {\n return create(params, BaseParamsStruct).type;\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `The \"type\" property must be one of: ${Object.values(\n DialogType,\n ).join(', ')}.`,\n });\n }\n}\n\n/**\n * Validates the confirm 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 struct - The struct to validate the params against.\n * @returns The validated confirm method parameter object.\n */\nfunction getValidatedParams(\n params: unknown,\n struct: Struct<any>,\n): DialogParameters {\n try {\n return create(params, struct);\n } catch (error) {\n if (error instanceof StructError) {\n const { key, type: errorType } = error;\n\n if (key === 'placeholder' && errorType === 'never') {\n throw rpcErrors.invalidParams({\n message:\n 'Invalid params: Alerts or confirmations may not specify a \"placeholder\" field.',\n });\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","DialogType","ComponentStruct","validateComponentLinks","enumValue","create","enums","object","optional","size","string","StructError","type","union","methodName","PlaceholderStruct","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getDialogImplementation","subjectTypes","Snap","showDialog","isOnPhishingList","maybeUpdatePhishingList","dialogBuilder","Object","freeze","BaseParamsStruct","Alert","Confirmation","Prompt","AlertParametersStruct","content","ConfirmationParametersStruct","PromptParametersStruct","placeholder","DialogParametersStruct","structs","dialogImplementation","args","params","context","origin","validatedType","getValidatedType","validatedParams","getValidatedParams","undefined","error","invalidParams","message","values","join","struct","key","errorType","internal"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AACjD,SAASC,UAAU,EAAEC,eAAe,QAAQ,sBAAsB;AAElE,SAASC,sBAAsB,EAAEC,SAAS,QAAQ,wBAAwB;AAI1E,SACEC,MAAM,EACNC,KAAK,EACLC,MAAM,EACNC,QAAQ,EACRC,IAAI,EACJC,MAAM,EACNC,WAAW,EACXC,IAAI,EACJC,KAAK,QACA,cAAc;AAIrB,MAAMC,aAAa;AAEnB,MAAMC,oBAAoBP,SAASC,KAAKC,UAAU,GAAG;AA2CrD;;;;;;;;;;;;;CAaC,GACD,MAAMM,uBAIF,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EACuB;IAClC,OAAO;QACLC,gBAAgBrB,eAAesB,gBAAgB;QAC/CC,YAAYP;QACZG;QACAK,sBAAsBC,wBAAwBL;QAC9CM,cAAc;YAACzB,YAAY0B,IAAI;SAAC;IAClC;AACF;AAEA,MAAMP,cAAoD;IACxDQ,YAAY;IACZC,kBAAkB;IAClBC,yBAAyB;AAC3B;AAEA,OAAO,MAAMC,gBAAgBC,OAAOC,MAAM,CAAC;IACzCV,YAAYP;IACZE;IACAE;AACF,GAAY;AAEZ,gFAAgF;AAChF,iDAAiD;AACjD,MAAMc,mBAAmBpB,KAAK;IAC5BA,MAAMN,MAAM;QAACL,WAAWgC,KAAK;QAAEhC,WAAWiC,YAAY;QAAEjC,WAAWkC,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,CAC3DvD,YACAwD,IAAI,CAAC,MAAM,CAAC,CAAC;QACjB;IACF;AACF;AAEA;;;;;;;CAOC,GACD,SAASN,mBACPN,MAAe,EACfa,MAAmB;IAEnB,IAAI;QACF,OAAOrD,OAAOwC,QAAQa;IACxB,EAAE,OAAOL,OAAO;QACd,IAAIA,iBAAiB1C,aAAa;YAChC,MAAM,EAAEgD,GAAG,EAAE/C,MAAMgD,SAAS,EAAE,GAAGP;YAEjC,IAAIM,QAAQ,iBAAiBC,cAAc,SAAS;gBAClD,MAAM5D,UAAUsD,aAAa,CAAC;oBAC5BC,SACE;gBACJ;YACF;YAEA,MAAMvD,UAAUsD,aAAa,CAAC;gBAC5BC,SAAS,CAAC,gBAAgB,EAAEF,MAAME,OAAO,CAAC,CAAC,CAAC;YAC9C;QACF;QAEA,wBAAwB,GACxB,MAAMvD,UAAU6D,QAAQ;IAC1B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getBip32Entropy.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getBip32Entropy.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n GetBip32EntropyParams,\n GetBip32EntropyResult,\n} from '@metamask/snaps-sdk';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getNode } from '../utils';\n\nconst targetName = 'snap_getBip32Entropy';\n\nexport type GetBip32EntropyMethodHooks = {\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\ntype GetBip32EntropySpecificationBuilderOptions = {\n methodHooks: GetBip32EntropyMethodHooks;\n};\n\ntype GetBip32EntropySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip32EntropyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\n/**\n * The specification builder for the `snap_getBip32Entropy` permission.\n * `snap_getBip32Entropy` lets the Snap control private keys for a particular\n * BIP-32 node.\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 `snap_getBip32Entropy` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetBip32EntropySpecificationBuilderOptions,\n GetBip32EntropySpecification\n> = ({ methodHooks }: GetBip32EntropySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats: [SnapCaveatType.PermittedDerivationPaths],\n methodImplementation: getBip32EntropyImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (\n caveats?.length !== 1 ||\n caveats[0].type !== SnapCaveatType.PermittedDerivationPaths\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.PermittedDerivationPaths}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetBip32EntropyMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getBip32EntropyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getBip32Entropy`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask extension is unlocked\n * and prompts the user to unlock their MetaMask if it is locked.\n * @returns The method implementation which returns a `JsonSLIP10Node`.\n * @throws If the params are invalid.\n */\nexport function getBip32EntropyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetBip32EntropyMethodHooks) {\n return async function getBip32Entropy(\n args: RestrictedMethodOptions<GetBip32EntropyParams>,\n ): Promise<GetBip32EntropyResult> {\n await getUnlockPromise(true);\n\n const { params } = args;\n assert(params);\n\n const node = await getNode({\n curve: params.curve,\n path: params.path,\n secretRecoveryPhrase: await getMnemonic(),\n });\n\n return node.toJSON();\n };\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","SnapCaveatType","assert","getNode","targetName","specificationBuilder","methodHooks","permissionType","RestrictedMethod","allowedCaveats","PermittedDerivationPaths","methodImplementation","getBip32EntropyImplementation","validator","caveats","length","type","invalidParams","message","subjectTypes","Snap","getMnemonic","getUnlockPromise","getBip32EntropyBuilder","Object","freeze","getBip32Entropy","args","params","node","curve","path","secretRecoveryPhrase","toJSON"],"mappings":"AAMA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAKjD,SAASC,cAAc,QAAQ,wBAAwB;AAEvD,SAASC,MAAM,QAAQ,kBAAkB;AAGzC,SAASC,OAAO,QAAQ,WAAW;AAEnC,MAAMC,aAAa;AA4BnB;;;;;;;;CAQC,GACD,MAAMC,uBAIF,CAAC,EAAEC,WAAW,EAA8C;IAC9D,OAAO;QACLC,gBAAgBT,eAAeU,gBAAgB;QAC/CJ;QACAK,gBAAgB;YAACR,eAAeS,wBAAwB;SAAC;QACzDC,sBAAsBC,8BAA8BN;QACpDO,WAAW,CAAC,EAAEC,OAAO,EAAE;YACrB,IACEA,SAASC,WAAW,KACpBD,OAAO,CAAC,EAAE,CAACE,IAAI,KAAKf,eAAeS,wBAAwB,EAC3D;gBACA,MAAMV,UAAUiB,aAAa,CAAC;oBAC5BC,SAAS,CAAC,mBAAmB,EAAEjB,eAAeS,wBAAwB,CAAC,SAAS,CAAC;gBACnF;YACF;QACF;QACAS,cAAc;YAACpB,YAAYqB,IAAI;SAAC;IAClC;AACF;AAEA,MAAMd,cAA6D;IACjEe,aAAa;IACbC,kBAAkB;AACpB;AAEA,OAAO,MAAMC,yBAAyBC,OAAOC,MAAM,CAAC;IAClDrB;IACAC;IACAC;AACF,GAAY;AAEZ;;;;;;;;;CASC,GACD,OAAO,SAASM,8BAA8B,EAC5CS,WAAW,EACXC,gBAAgB,EACW;IAC3B,OAAO,eAAeI,gBACpBC,IAAoD;QAEpD,MAAML,iBAAiB;QAEvB,MAAM,EAAEM,MAAM,EAAE,GAAGD;QACnBzB,OAAO0B;QAEP,MAAMC,OAAO,MAAM1B,QAAQ;YACzB2B,OAAOF,OAAOE,KAAK;YACnBC,MAAMH,OAAOG,IAAI;YACjBC,sBAAsB,MAAMX;QAC9B;QAEA,OAAOQ,KAAKI,MAAM;IACpB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getBip32PublicKey.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport {\n bip32entropy,\n Bip32PathStruct,\n SnapCaveatType,\n} from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport { boolean, enums, object, optional } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getNode } from '../utils';\n\nconst targetName = 'snap_getBip32PublicKey';\n\nexport type GetBip32PublicKeyMethodHooks = {\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\ntype GetBip32PublicKeySpecificationBuilderOptions = {\n methodHooks: GetBip32PublicKeyMethodHooks;\n};\n\ntype GetBip32PublicKeySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip32PublicKeyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getBip32PublicKey.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n GetBip32PublicKeyParams,\n GetBip32PublicKeyResult,\n} from '@metamask/snaps-sdk';\nimport {\n bip32entropy,\n Bip32PathStruct,\n SnapCaveatType,\n} from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport { boolean, enums, object, optional } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getNode } from '../utils';\n\nconst targetName = 'snap_getBip32PublicKey';\n\nexport type GetBip32PublicKeyMethodHooks = {\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\ntype GetBip32PublicKeySpecificationBuilderOptions = {\n methodHooks: GetBip32PublicKeyMethodHooks;\n};\n\ntype GetBip32PublicKeySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip32PublicKeyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\nexport const Bip32PublicKeyArgsStruct = bip32entropy(\n object({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n compressed: optional(boolean()),\n }),\n);\n\n/**\n * The specification builder for the `snap_getBip32PublicKey` permission.\n * `snap_getBip32PublicKey` lets the Snap retrieve public keys for a particular\n * BIP-32 node.\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 `snap_getBip32PublicKey` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetBip32PublicKeySpecificationBuilderOptions,\n GetBip32PublicKeySpecification\n> = ({ methodHooks }: GetBip32PublicKeySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats: [SnapCaveatType.PermittedDerivationPaths],\n methodImplementation: getBip32PublicKeyImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (\n caveats?.length !== 1 ||\n caveats[0].type !== SnapCaveatType.PermittedDerivationPaths\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.PermittedDerivationPaths}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetBip32PublicKeyMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getBip32PublicKeyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getBip32PublicKey`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask extension is unlocked\n * and prompts the user to unlock their MetaMask if it is locked.\n * @returns The method implementation which returns a public key.\n * @throws If the params are invalid.\n */\nexport function getBip32PublicKeyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetBip32PublicKeyMethodHooks) {\n return async function getBip32PublicKey(\n args: RestrictedMethodOptions<GetBip32PublicKeyParams>,\n ): Promise<GetBip32PublicKeyResult> {\n await getUnlockPromise(true);\n\n assertStruct(\n args.params,\n Bip32PublicKeyArgsStruct,\n 'Invalid BIP-32 public key params',\n rpcErrors.invalidParams,\n );\n\n const { params } = args;\n const node = await getNode({\n curve: params.curve,\n path: params.path,\n secretRecoveryPhrase: await getMnemonic(),\n });\n\n if (params.compressed) {\n return node.compressedPublicKey;\n }\n\n return node.publicKey;\n };\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","bip32entropy","Bip32PathStruct","SnapCaveatType","assertStruct","boolean","enums","object","optional","getNode","targetName","Bip32PublicKeyArgsStruct","path","curve","compressed","specificationBuilder","methodHooks","permissionType","RestrictedMethod","allowedCaveats","PermittedDerivationPaths","methodImplementation","getBip32PublicKeyImplementation","validator","caveats","length","type","invalidParams","message","subjectTypes","Snap","getMnemonic","getUnlockPromise","getBip32PublicKeyBuilder","Object","freeze","getBip32PublicKey","args","params","node","secretRecoveryPhrase","compressedPublicKey","publicKey"],"mappings":"AAMA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAKjD,SACEC,YAAY,EACZC,eAAe,EACfC,cAAc,QACT,wBAAwB;AAE/B,SAASC,YAAY,QAAQ,kBAAkB;AAC/C,SAASC,OAAO,EAAEC,KAAK,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,cAAc;AAG/D,SAASC,OAAO,QAAQ,WAAW;AAEnC,MAAMC,aAAa;AA4BnB,OAAO,MAAMC,2BAA2BV,aACtCM,OAAO;IACLK,MAAMV;IACNW,OAAOP,MAAM;QAAC;QAAW;KAAY;IACrCQ,YAAYN,SAASH;AACvB,IACA;AAEF;;;;;;;;CAQC,GACD,MAAMU,uBAIF,CAAC,EAAEC,WAAW,EAAgD;IAChE,OAAO;QACLC,gBAAgBnB,eAAeoB,gBAAgB;QAC/CR;QACAS,gBAAgB;YAAChB,eAAeiB,wBAAwB;SAAC;QACzDC,sBAAsBC,gCAAgCN;QACtDO,WAAW,CAAC,EAAEC,OAAO,EAAE;YACrB,IACEA,SAASC,WAAW,KACpBD,OAAO,CAAC,EAAE,CAACE,IAAI,KAAKvB,eAAeiB,wBAAwB,EAC3D;gBACA,MAAMpB,UAAU2B,aAAa,CAAC;oBAC5BC,SAAS,CAAC,mBAAmB,EAAEzB,eAAeiB,wBAAwB,CAAC,SAAS,CAAC;gBACnF;YACF;QACF;QACAS,cAAc;YAAC9B,YAAY+B,IAAI;SAAC;IAClC;AACF;AAEA,MAAMd,cAA+D;IACnEe,aAAa;IACbC,kBAAkB;AACpB;AAEA,OAAO,MAAMC,2BAA2BC,OAAOC,MAAM,CAAC;IACpDzB;IACAK;IACAC;AACF,GAAY;AAEZ;;;;;;;;;CASC,GACD,OAAO,SAASM,gCAAgC,EAC9CS,WAAW,EACXC,gBAAgB,EACa;IAC7B,OAAO,eAAeI,kBACpBC,IAAsD;QAEtD,MAAML,iBAAiB;QAEvB5B,aACEiC,KAAKC,MAAM,EACX3B,0BACA,oCACAX,UAAU2B,aAAa;QAGzB,MAAM,EAAEW,MAAM,EAAE,GAAGD;QACnB,MAAME,OAAO,MAAM9B,QAAQ;YACzBI,OAAOyB,OAAOzB,KAAK;YACnBD,MAAM0B,OAAO1B,IAAI;YACjB4B,sBAAsB,MAAMT;QAC9B;QAEA,IAAIO,OAAOxB,UAAU,EAAE;YACrB,OAAOyB,KAAKE,mBAAmB;QACjC;QAEA,OAAOF,KAAKG,SAAS;IACvB;AACF"}
|
|
@@ -56,7 +56,6 @@ export const getBip44EntropyBuilder = Object.freeze({
|
|
|
56
56
|
return async function getBip44Entropy(args) {
|
|
57
57
|
await getUnlockPromise(true);
|
|
58
58
|
// `args.params` is validated by the decorator, so it's safe to assert here.
|
|
59
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
60
59
|
const params = args.params;
|
|
61
60
|
const node = await BIP44CoinTypeNode.fromDerivationPath([
|
|
62
61
|
await getMnemonic(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getBip44Entropy.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getBip44Entropy.ts"],"sourcesContent":["import { BIP44CoinTypeNode } from '@metamask/key-tree';\nimport type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n GetBip44EntropyParams,\n GetBip44EntropyResult,\n} from '@metamask/snaps-sdk';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst targetName = 'snap_getBip44Entropy';\n\nexport type GetBip44EntropyMethodHooks = {\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\ntype GetBip44EntropySpecificationBuilderOptions = {\n methodHooks: GetBip44EntropyMethodHooks;\n};\n\ntype GetBip44EntropySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip44EntropyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\n/**\n * The specification builder for the `snap_getBip44Entropy` permission.\n * `snap_getBip44Entropy_*` lets the Snap control private keys for a particular\n * BIP-32 coin type.\n *\n * @param options - The specification builder options.\n * @param options.methodHooks - The RPC method hooks needed by the method\n * implementation.\n * @returns The specification for the `snap_getBip44Entropy` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetBip44EntropySpecificationBuilderOptions,\n GetBip44EntropySpecification\n> = ({ methodHooks }: GetBip44EntropySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats: [SnapCaveatType.PermittedCoinTypes],\n methodImplementation: getBip44EntropyImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (\n caveats?.length !== 1 ||\n caveats[0].type !== SnapCaveatType.PermittedCoinTypes\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.PermittedCoinTypes}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetBip44EntropyMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getBip44EntropyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getBip44Entropy`.\n *\n * @param hooks - The RPC method hooks.\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 * @returns The method implementation which returns a `BIP44CoinTypeNode`.\n * @throws If the params are invalid.\n */\nexport function getBip44EntropyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetBip44EntropyMethodHooks) {\n return async function getBip44Entropy(\n args: RestrictedMethodOptions<GetBip44EntropyParams>,\n ): Promise<GetBip44EntropyResult> {\n await getUnlockPromise(true);\n\n // `args.params` is validated by the decorator, so it's safe to assert here.\n const params = args.params as GetBip44EntropyParams;\n\n const node = await BIP44CoinTypeNode.fromDerivationPath([\n await getMnemonic(),\n `bip32:44'`,\n `bip32:${params.coinType}'`,\n ]);\n\n return node.toJSON();\n };\n}\n"],"names":["BIP44CoinTypeNode","PermissionType","SubjectType","rpcErrors","SnapCaveatType","targetName","specificationBuilder","methodHooks","permissionType","RestrictedMethod","allowedCaveats","PermittedCoinTypes","methodImplementation","getBip44EntropyImplementation","validator","caveats","length","type","invalidParams","message","subjectTypes","Snap","getMnemonic","getUnlockPromise","getBip44EntropyBuilder","Object","freeze","getBip44Entropy","args","params","node","fromDerivationPath","coinType","toJSON"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,qBAAqB;AAOvD,SAASC,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAKjD,SAASC,cAAc,QAAQ,wBAAwB;AAKvD,MAAMC,aAAa;AA4BnB;;;;;;;;;CASC,GACD,MAAMC,uBAIF,CAAC,EAAEC,WAAW,EAA8C;IAC9D,OAAO;QACLC,gBAAgBP,eAAeQ,gBAAgB;QAC/CJ;QACAK,gBAAgB;YAACN,eAAeO,kBAAkB;SAAC;QACnDC,sBAAsBC,8BAA8BN;QACpDO,WAAW,CAAC,EAAEC,OAAO,EAAE;YACrB,IACEA,SAASC,WAAW,KACpBD,OAAO,CAAC,EAAE,CAACE,IAAI,KAAKb,eAAeO,kBAAkB,EACrD;gBACA,MAAMR,UAAUe,aAAa,CAAC;oBAC5BC,SAAS,CAAC,mBAAmB,EAAEf,eAAeO,kBAAkB,CAAC,SAAS,CAAC;gBAC7E;YACF;QACF;QACAS,cAAc;YAAClB,YAAYmB,IAAI;SAAC;IAClC;AACF;AAEA,MAAMd,cAA6D;IACjEe,aAAa;IACbC,kBAAkB;AACpB;AAEA,OAAO,MAAMC,yBAAyBC,OAAOC,MAAM,CAAC;IAClDrB;IACAC;IACAC;AACF,GAAY;AAEZ;;;;;;;;;;;CAWC,GACD,OAAO,SAASM,8BAA8B,EAC5CS,WAAW,EACXC,gBAAgB,EACW;IAC3B,OAAO,eAAeI,gBACpBC,IAAoD;QAEpD,MAAML,iBAAiB;QAEvB,4EAA4E;QAC5E,MAAMM,SAASD,KAAKC,MAAM;QAE1B,MAAMC,OAAO,MAAM9B,kBAAkB+B,kBAAkB,CAAC;YACtD,MAAMT;YACN,CAAC,SAAS,CAAC;YACX,CAAC,MAAM,EAAEO,OAAOG,QAAQ,CAAC,CAAC,CAAC;SAC5B;QAED,OAAOF,KAAKG,MAAM;IACpB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getEntropy.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 { SIP_6_MAGIC_VALUE } from '@metamask/snaps-utils';\nimport type {
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getEntropy.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 { GetEntropyParams, GetEntropyResult } from '@metamask/snaps-sdk';\nimport { SIP_6_MAGIC_VALUE } from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { literal, object, optional, string } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropy } from '../utils';\n\nconst targetName = 'snap_getEntropy';\n\ntype GetEntropySpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: GetEntropyHooks;\n};\n\ntype GetEntropySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getEntropyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\nexport const GetEntropyArgsStruct = object({\n version: literal(1),\n salt: optional(string()),\n});\n\n/**\n * @property version - The version of the `snap_getEntropy` method. This must be\n * the numeric literal `1`.\n * @property salt - A string to use as the salt when deriving the entropy. If\n * omitted, the salt will be an empty string.\n */\nexport type GetEntropyArgs = Infer<typeof GetEntropyArgsStruct>;\n\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetEntropySpecificationBuilderOptions,\n GetEntropySpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: GetEntropySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats,\n methodImplementation: getEntropyImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetEntropyHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getEntropyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport type GetEntropyHooks = {\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/**\n * Builds the method implementation for `snap_getEntropy`. The implementation\n * is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getMnemonic - The method to get the mnemonic of the user's\n * primary keyring.\n * @param hooks.getUnlockPromise - The method to get a promise that resolves\n * once the extension is unlocked.\n * @returns The method implementation.\n */\nfunction getEntropyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetEntropyHooks) {\n return async function getEntropy(\n options: RestrictedMethodOptions<GetEntropyParams>,\n ): Promise<GetEntropyResult> {\n const {\n params,\n context: { origin },\n } = options;\n\n assertStruct(\n params,\n GetEntropyArgsStruct,\n 'Invalid \"snap_getEntropy\" parameters',\n rpcErrors.invalidParams,\n );\n\n await getUnlockPromise(true);\n const mnemonicPhrase = await getMnemonic();\n\n return deriveEntropy({\n input: origin,\n salt: params.salt,\n mnemonicPhrase,\n magic: SIP_6_MAGIC_VALUE,\n });\n };\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","SIP_6_MAGIC_VALUE","assertStruct","literal","object","optional","string","deriveEntropy","targetName","GetEntropyArgsStruct","version","salt","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","methodImplementation","getEntropyImplementation","subjectTypes","Snap","getMnemonic","getUnlockPromise","getEntropyBuilder","Object","freeze","getEntropy","options","params","context","origin","invalidParams","mnemonicPhrase","input","magic"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,iBAAiB,QAAQ,wBAAwB;AAE1D,SAASC,YAAY,QAAQ,kBAAkB;AAE/C,SAASC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,QAAQ,cAAc;AAGhE,SAASC,aAAa,QAAQ,WAAW;AAEzC,MAAMC,aAAa;AAcnB,OAAO,MAAMC,uBAAuBL,OAAO;IACzCM,SAASP,QAAQ;IACjBQ,MAAMN,SAASC;AACjB,GAAG;AAUH,MAAMM,uBAIF,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EAC2B;IACtC,OAAO;QACLC,gBAAgBjB,eAAekB,gBAAgB;QAC/CR;QACAK;QACAI,sBAAsBC,yBAAyBJ;QAC/CK,cAAc;YAACpB,YAAYqB,IAAI;SAAC;IAClC;AACF;AAEA,MAAMN,cAAkD;IACtDO,aAAa;IACbC,kBAAkB;AACpB;AAEA,OAAO,MAAMC,oBAAoBC,OAAOC,MAAM,CAAC;IAC7CjB;IACAI;IACAE;AACF,GAAY;AAgBZ;;;;;;;;;;;CAWC,GACD,SAASI,yBAAyB,EAChCG,WAAW,EACXC,gBAAgB,EACA;IAChB,OAAO,eAAeI,WACpBC,OAAkD;QAElD,MAAM,EACJC,MAAM,EACNC,SAAS,EAAEC,MAAM,EAAE,EACpB,GAAGH;QAEJzB,aACE0B,QACAnB,sBACA,wCACAT,UAAU+B,aAAa;QAGzB,MAAMT,iBAAiB;QACvB,MAAMU,iBAAiB,MAAMX;QAE7B,OAAOd,cAAc;YACnB0B,OAAOH;YACPnB,MAAMiB,OAAOjB,IAAI;YACjBqB;YACAE,OAAOjC;QACT;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/getLocale.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n ValidPermissionSpecification,\n RestrictedMethodOptions,\n RestrictedMethodParameters,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport type { NonEmptyArray } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_getLocale';\n\nexport type GetLocaleMethodHooks = {\n getLocale: () => Promise<string>;\n};\n\ntype SpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: GetLocaleMethodHooks;\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_getLocale` permission.\n * `snap_getLocale` allows snaps to get the user selected locale.\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_getLocale` 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<GetLocaleMethodHooks> = {\n getLocale: true,\n};\n\nexport const getLocaleBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getLocale`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getLocale - A function that returns the user selected locale.\n * @returns The user selected locale.\n */\nexport function getImplementation({ getLocale }: GetLocaleMethodHooks) {\n return async function implementation(\n _args: RestrictedMethodOptions<RestrictedMethodParameters>,\n ): Promise<
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/getLocale.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n ValidPermissionSpecification,\n RestrictedMethodOptions,\n RestrictedMethodParameters,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport type { GetLocaleResult } from '@metamask/snaps-sdk';\nimport type { NonEmptyArray } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst methodName = 'snap_getLocale';\n\nexport type GetLocaleMethodHooks = {\n getLocale: () => Promise<string>;\n};\n\ntype SpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: GetLocaleMethodHooks;\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_getLocale` permission.\n * `snap_getLocale` allows snaps to get the user selected locale.\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_getLocale` 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<GetLocaleMethodHooks> = {\n getLocale: true,\n};\n\nexport const getLocaleBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getLocale`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getLocale - A function that returns the user selected locale.\n * @returns The user selected locale.\n */\nexport function getImplementation({ getLocale }: GetLocaleMethodHooks) {\n return async function implementation(\n _args: RestrictedMethodOptions<RestrictedMethodParameters>,\n ): Promise<GetLocaleResult> {\n return getLocale();\n };\n}\n"],"names":["PermissionType","SubjectType","methodName","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getImplementation","subjectTypes","Snap","getLocale","getLocaleBuilder","Object","freeze","implementation","_args"],"mappings":"AAMA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAM9E,MAAMC,aAAa;AAkBnB;;;;;;;;CAQC,GACD,OAAO,MAAMC,uBAIT,CAAC,EAAEC,iBAAiB,IAAI,EAAEC,WAAW,EAA+B;IACtE,OAAO;QACLC,gBAAgBN,eAAeO,gBAAgB;QAC/CC,YAAYN;QACZE;QACAK,sBAAsBC,kBAAkBL;QACxCM,cAAc;YAACV,YAAYW,IAAI;SAAC;IAClC;AACF,EAAE;AAEF,MAAMP,cAAuD;IAC3DQ,WAAW;AACb;AAEA,OAAO,MAAMC,mBAAmBC,OAAOC,MAAM,CAAC;IAC5CR,YAAYN;IACZC;IACAE;AACF,GAAY;AAEZ;;;;;;CAMC,GACD,OAAO,SAASK,kBAAkB,EAAEG,SAAS,EAAwB;IACnE,OAAO,eAAeI,eACpBC,KAA0D;QAE1D,OAAOL;IACT;AACF"}
|
|
@@ -8,10 +8,7 @@ import { invokeSnapBuilder } from './invokeSnap';
|
|
|
8
8
|
import { manageAccountsBuilder } from './manageAccounts';
|
|
9
9
|
import { manageStateBuilder } from './manageState';
|
|
10
10
|
import { notifyBuilder } from './notify';
|
|
11
|
-
export { DialogType } from './dialog';
|
|
12
|
-
export { ManageStateOperation } from './manageState';
|
|
13
11
|
export { WALLET_SNAP_PERMISSION_KEY } from './invokeSnap';
|
|
14
|
-
export { NotificationType } from './notify';
|
|
15
12
|
export const restrictedMethodPermissionBuilders = {
|
|
16
13
|
[dialogBuilder.targetName]: dialogBuilder,
|
|
17
14
|
[getBip32EntropyBuilder.targetName]: getBip32EntropyBuilder,
|
|
@@ -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
|
|
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":["dialogBuilder","getBip32EntropyBuilder","getBip32PublicKeyBuilder","getBip44EntropyBuilder","getEntropyBuilder","getLocaleBuilder","invokeSnapBuilder","manageAccountsBuilder","manageStateBuilder","notifyBuilder","WALLET_SNAP_PERMISSION_KEY","restrictedMethodPermissionBuilders","targetName"],"mappings":"AACA,SAASA,aAAa,QAAQ,WAAW;AAEzC,SAASC,sBAAsB,QAAQ,oBAAoB;AAE3D,SAASC,wBAAwB,QAAQ,sBAAsB;AAE/D,SAASC,sBAAsB,QAAQ,oBAAoB;AAE3D,SAASC,iBAAiB,QAAQ,eAAe;AAEjD,SAASC,gBAAgB,QAAQ,cAAc;AAE/C,SAASC,iBAAiB,QAAQ,eAAe;AAEjD,SAASC,qBAAqB,QAAQ,mBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,gBAAgB;AAEnD,SAASC,aAAa,QAAQ,WAAW;AAEzC,SAASC,0BAA0B,QAAQ,eAAe;AAa1D,OAAO,MAAMC,qCAAqC;IAChD,CAACX,cAAcY,UAAU,CAAC,EAAEZ;IAC5B,CAACC,uBAAuBW,UAAU,CAAC,EAAEX;IACrC,CAACC,yBAAyBU,UAAU,CAAC,EAAEV;IACvC,CAACC,uBAAuBS,UAAU,CAAC,EAAET;IACrC,CAACC,kBAAkBQ,UAAU,CAAC,EAAER;IAChC,CAACE,kBAAkBM,UAAU,CAAC,EAAEN;IAChC,CAACE,mBAAmBI,UAAU,CAAC,EAAEJ;IACjC,CAACC,cAAcG,UAAU,CAAC,EAAEH;IAC5B,CAACF,sBAAsBK,UAAU,CAAC,EAAEL;IACpC,CAACF,iBAAiBO,UAAU,CAAC,EAAEP;AACjC,EAAW;AAEX,cAAc,YAAY"}
|
|
@@ -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
|
|
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":["PermissionType","rpcErrors","HandlerType","SnapCaveatType","WALLET_SNAP_PERMISSION_KEY","handleSnapInstall","requestData","messagingSystem","snaps","permissions","caveats","value","permittedSnaps","call","metadata","origin","dedupedSnaps","Object","keys","reduce","filteredSnaps","snap","specificationBuilder","methodHooks","permissionType","RestrictedMethod","targetName","allowedCaveats","SnapIds","methodImplementation","getInvokeSnapImplementation","validator","length","type","invalidParams","message","sideEffect","onPermitted","getSnap","handleSnapRpcRequest","invokeSnapBuilder","freeze","invokeSnap","options","params","context","snapId","request","invalidRequest","handler","OnRpcRequest"],"m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F;AACF;AAEA,MAAMkB,cAAwD;IAC5De,SAAS;IACTC,sBAAsB;AACxB;AAEA,OAAO,MAAMC,oBAAoBvB,OAAOwB,MAAM,CAAC;IAC7Cf,YAAYtB;IACZkB;IACAC;AACF,GAAY;AAEZ;;;;;;;;CAQC,GACD,OAAO,SAASO,4BAA4B,EAC1CQ,OAAO,EACPC,oBAAoB,EACE;IACtB,OAAO,eAAeG,WACpBC,OAAkD;QAElD,MAAM,EAAEC,SAAS,CAAC,CAAC,EAAEC,OAAO,EAAE,GAAGF;QAEjC,MAAM,EAAEG,MAAM,EAAEC,OAAO,EAAE,GAAGH;QAE5B,IAAI,CAACN,QAAQQ,SAAS;YACpB,MAAM7C,UAAU+C,cAAc,CAAC;gBAC7Bb,SAAS,CAAC,UAAU,EAAEW,OAAO,sEAAsE,CAAC;YACtG;QACF;QAEA,MAAM,EAAE/B,MAAM,EAAE,GAAG8B;QAEnB,OAAQ,MAAMN,qBAAqB;YACjCO;YACA/B;YACAgC;YACAE,SAAS/C,YAAYgD,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 {
|
|
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":["SubjectType","PermissionType","JsonStruct","assert","string","object","union","array","record","SnapMessageStruct","method","params","methodName","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","manageAccountsImplementation","subjectTypes","Snap","getSnapKeyring","manageAccounts","options","context","origin","keyring","handleKeyringSnapMessage","manageAccountsBuilder","Object","freeze"],"mappings":"AAKA,SAASA,WAAW,EAAEC,cAAc,QAAQ,kCAAkC;AAO9E,SAASC,UAAU,QAAQ,kBAAkB;AAC7C,SAASC,MAAM,EAAEC,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAEC,KAAK,EAAEC,MAAM,QAAQ,cAAc;AAE3E,MAAMC,oBAAoBH,MAAM;IAC9BD,OAAO;QACLK,QAAQN;IACV;IACAC,OAAO;QACLK,QAAQN;QACRO,QAAQL,MAAM;YAACC,MAAML;YAAaM,OAAOJ,UAAUF;SAAY;IACjE;CACD;AAID,OAAO,MAAMU,aAAa,sBAAsB;AA0BhD;;;;;;;;CAQC,GACD,OAAO,MAAMC,uBAIT,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EAC+B;IAC1C,OAAO;QACLC,gBAAgBf,eAAegB,gBAAgB;QAC/CC,YAAYN;QACZE;QACAK,sBAAsBC,6BAA6BL;QACnDM,cAAc;YAACrB,YAAYsB,IAAI;SAAC;IAClC;AACF,EAAE;AAEF;;;;;;;;CAQC,GACD,OAAO,SAASF,6BAA6B,EAC3CG,cAAc,EACY;IAC1B,OAAO,eAAeC,eACpBC,OAAsD;QAEtD,MAAM,EACJC,SAAS,EAAEC,MAAM,EAAE,EACnBhB,MAAM,EACP,GAAGc;QAEJtB,OAAOQ,QAAQF;QACf,MAAMmB,UAAU,MAAML,eAAeI;QACrC,OAAO,MAAMC,QAAQC,wBAAwB,CAACF,QAAQhB;IACxD;AACF;AAEA,OAAO,MAAMmB,wBAAwBC,OAAOC,MAAM,CAAC;IACjDd,YAAYN;IACZC;IACAE,aAAa;QACXQ,gBAAgB;IAClB;AACF,GAAY"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { PermissionType, SubjectType } from '@metamask/permission-controller';
|
|
2
2
|
import { rpcErrors } from '@metamask/rpc-errors';
|
|
3
|
-
import {
|
|
3
|
+
import { ManageStateOperation } from '@metamask/snaps-sdk';
|
|
4
|
+
import { STATE_ENCRYPTION_MAGIC_VALUE, parseJson } from '@metamask/snaps-utils';
|
|
4
5
|
import { isObject, getJsonSize, assert, isValidJson } from '@metamask/utils';
|
|
5
6
|
import { deriveEntropy } from '../utils';
|
|
6
7
|
// The salt used for SIP-6-based entropy derivation.
|
|
@@ -40,12 +41,6 @@ export const manageStateBuilder = Object.freeze({
|
|
|
40
41
|
specificationBuilder,
|
|
41
42
|
methodHooks
|
|
42
43
|
});
|
|
43
|
-
export var ManageStateOperation;
|
|
44
|
-
(function(ManageStateOperation) {
|
|
45
|
-
ManageStateOperation["ClearState"] = 'clear';
|
|
46
|
-
ManageStateOperation["GetState"] = 'get';
|
|
47
|
-
ManageStateOperation["UpdateState"] = 'update';
|
|
48
|
-
})(ManageStateOperation || (ManageStateOperation = {}));
|
|
49
44
|
export const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
|
|
50
45
|
/**
|
|
51
46
|
* Get a deterministic encryption key to use for encrypting and decrypting the
|
|
@@ -128,40 +123,44 @@ export const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
|
|
|
128
123
|
*/ export function getManageStateImplementation({ getMnemonic, getUnlockPromise, clearSnapState, getSnapState, updateSnapState, encrypt, decrypt }) {
|
|
129
124
|
return async function manageState(options) {
|
|
130
125
|
const { params = {}, method, context: { origin } } = options;
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
|
|
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 !== ManageStateOperation.ClearState) {
|
|
132
|
+
await getUnlockPromise(true);
|
|
133
|
+
}
|
|
134
|
+
switch(validatedParams.operation){
|
|
135
135
|
case ManageStateOperation.ClearState:
|
|
136
|
-
|
|
136
|
+
clearSnapState(origin, shouldEncrypt);
|
|
137
137
|
return null;
|
|
138
138
|
case ManageStateOperation.GetState:
|
|
139
139
|
{
|
|
140
|
-
const state =
|
|
140
|
+
const state = getSnapState(origin, shouldEncrypt);
|
|
141
141
|
if (state === null) {
|
|
142
142
|
return state;
|
|
143
143
|
}
|
|
144
|
-
return await decryptState({
|
|
144
|
+
return shouldEncrypt ? await decryptState({
|
|
145
145
|
state,
|
|
146
146
|
decryptFunction: decrypt,
|
|
147
|
-
mnemonicPhrase,
|
|
147
|
+
mnemonicPhrase: await getMnemonic(),
|
|
148
148
|
snapId: origin
|
|
149
|
-
});
|
|
149
|
+
}) : parseJson(state);
|
|
150
150
|
}
|
|
151
151
|
case ManageStateOperation.UpdateState:
|
|
152
152
|
{
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
state: newState,
|
|
153
|
+
const finalizedState = shouldEncrypt ? await encryptState({
|
|
154
|
+
state: validatedParams.newState,
|
|
156
155
|
encryptFunction: encrypt,
|
|
157
|
-
mnemonicPhrase,
|
|
156
|
+
mnemonicPhrase: await getMnemonic(),
|
|
158
157
|
snapId: origin
|
|
159
|
-
});
|
|
160
|
-
|
|
158
|
+
}) : JSON.stringify(validatedParams.newState);
|
|
159
|
+
updateSnapState(origin, finalizedState, shouldEncrypt);
|
|
161
160
|
return null;
|
|
162
161
|
}
|
|
163
162
|
default:
|
|
164
|
-
throw rpcErrors.invalidParams(`Invalid ${method} operation: "${operation}"`);
|
|
163
|
+
throw rpcErrors.invalidParams(`Invalid ${method} operation: "${validatedParams.operation}"`);
|
|
165
164
|
}
|
|
166
165
|
};
|
|
167
166
|
}
|
|
@@ -179,12 +178,17 @@ export const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
|
|
|
179
178
|
message: 'Expected params to be a single object.'
|
|
180
179
|
});
|
|
181
180
|
}
|
|
182
|
-
const { operation, newState } = params;
|
|
181
|
+
const { operation, newState, encrypted } = params;
|
|
183
182
|
if (!operation || typeof operation !== 'string' || !Object.values(ManageStateOperation).includes(operation)) {
|
|
184
183
|
throw rpcErrors.invalidParams({
|
|
185
184
|
message: 'Must specify a valid manage state "operation".'
|
|
186
185
|
});
|
|
187
186
|
}
|
|
187
|
+
if (encrypted !== undefined && typeof encrypted !== 'boolean') {
|
|
188
|
+
throw rpcErrors.invalidParams({
|
|
189
|
+
message: '"encrypted" parameter must be a boolean if specified.'
|
|
190
|
+
});
|
|
191
|
+
}
|
|
188
192
|
if (operation === ManageStateOperation.UpdateState) {
|
|
189
193
|
if (!isObject(newState)) {
|
|
190
194
|
throw rpcErrors.invalidParams({
|