@metamask/snaps-rpc-methods 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/LICENSE +18 -0
- package/README.md +3 -0
- package/dist/cjs/index.js +43 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/permitted/common/snapInstallation.js +33 -0
- package/dist/cjs/permitted/common/snapInstallation.js.map +1 -0
- package/dist/cjs/permitted/getFile.js +63 -0
- package/dist/cjs/permitted/getFile.js.map +1 -0
- package/dist/cjs/permitted/getSnaps.js +39 -0
- package/dist/cjs/permitted/getSnaps.js.map +1 -0
- package/dist/cjs/permitted/handlers.js +33 -0
- package/dist/cjs/permitted/handlers.js.map +1 -0
- package/dist/cjs/permitted/index.js +21 -0
- package/dist/cjs/permitted/index.js.map +1 -0
- package/dist/cjs/permitted/invokeKeyring.js +88 -0
- package/dist/cjs/permitted/invokeKeyring.js.map +1 -0
- package/dist/cjs/permitted/invokeSnapSugar.js +62 -0
- package/dist/cjs/permitted/invokeSnapSugar.js.map +1 -0
- package/dist/cjs/permitted/middleware.js +38 -0
- package/dist/cjs/permitted/middleware.js.map +1 -0
- package/dist/cjs/permitted/requestSnaps.js +122 -0
- package/dist/cjs/permitted/requestSnaps.js.map +1 -0
- package/dist/cjs/request.js +6 -0
- package/dist/cjs/request.js.map +1 -0
- package/dist/cjs/restricted/caveats/index.js +38 -0
- package/dist/cjs/restricted/caveats/index.js.map +1 -0
- package/dist/cjs/restricted/caveats/permittedCoinTypes.js +83 -0
- package/dist/cjs/restricted/caveats/permittedCoinTypes.js.map +1 -0
- package/dist/cjs/restricted/caveats/permittedDerivationPaths.js +67 -0
- package/dist/cjs/restricted/caveats/permittedDerivationPaths.js.map +1 -0
- package/dist/cjs/restricted/caveats/snapIds.js +59 -0
- package/dist/cjs/restricted/caveats/snapIds.js.map +1 -0
- package/dist/cjs/restricted/dialog.js +150 -0
- package/dist/cjs/restricted/dialog.js.map +1 -0
- package/dist/cjs/restricted/getBip32Entropy.js +76 -0
- package/dist/cjs/restricted/getBip32Entropy.js.map +1 -0
- package/dist/cjs/restricted/getBip32PublicKey.js +91 -0
- package/dist/cjs/restricted/getBip32PublicKey.js.map +1 -0
- package/dist/cjs/restricted/getBip44Entropy.js +77 -0
- package/dist/cjs/restricted/getBip44Entropy.js.map +1 -0
- package/dist/cjs/restricted/getEntropy.js +76 -0
- package/dist/cjs/restricted/getEntropy.js.map +1 -0
- package/dist/cjs/restricted/getLocale.js +49 -0
- package/dist/cjs/restricted/getLocale.js.map +1 -0
- package/dist/cjs/restricted/index.js +65 -0
- package/dist/cjs/restricted/index.js.map +1 -0
- package/dist/cjs/restricted/invokeSnap.js +99 -0
- package/dist/cjs/restricted/invokeSnap.js.map +1 -0
- package/dist/cjs/restricted/manageAccounts.js +68 -0
- package/dist/cjs/restricted/manageAccounts.js.map +1 -0
- package/dist/cjs/restricted/manageState.js +216 -0
- package/dist/cjs/restricted/manageState.js.map +1 -0
- package/dist/cjs/restricted/notify.js +94 -0
- package/dist/cjs/restricted/notify.js.map +1 -0
- package/dist/cjs/utils.js +98 -0
- package/dist/cjs/utils.js.map +1 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/permitted/common/snapInstallation.js +33 -0
- package/dist/esm/permitted/common/snapInstallation.js.map +1 -0
- package/dist/esm/permitted/getFile.js +45 -0
- package/dist/esm/permitted/getFile.js.map +1 -0
- package/dist/esm/permitted/getSnaps.js +31 -0
- package/dist/esm/permitted/getSnaps.js.map +1 -0
- package/dist/esm/permitted/handlers.js +15 -0
- package/dist/esm/permitted/handlers.js.map +1 -0
- package/dist/esm/permitted/index.js +4 -0
- package/dist/esm/permitted/index.js.map +1 -0
- package/dist/esm/permitted/invokeKeyring.js +80 -0
- package/dist/esm/permitted/invokeKeyring.js.map +1 -0
- package/dist/esm/permitted/invokeSnapSugar.js +60 -0
- package/dist/esm/permitted/invokeSnapSugar.js.map +1 -0
- package/dist/esm/permitted/middleware.js +34 -0
- package/dist/esm/permitted/middleware.js.map +1 -0
- package/dist/esm/permitted/requestSnaps.js +117 -0
- package/dist/esm/permitted/requestSnaps.js.map +1 -0
- package/dist/esm/request.js +3 -0
- package/dist/esm/request.js.map +1 -0
- package/dist/esm/restricted/caveats/index.js +20 -0
- package/dist/esm/restricted/caveats/index.js.map +1 -0
- package/dist/esm/restricted/caveats/permittedCoinTypes.js +77 -0
- package/dist/esm/restricted/caveats/permittedCoinTypes.js.map +1 -0
- package/dist/esm/restricted/caveats/permittedDerivationPaths.js +64 -0
- package/dist/esm/restricted/caveats/permittedDerivationPaths.js.map +1 -0
- package/dist/esm/restricted/caveats/snapIds.js +50 -0
- package/dist/esm/restricted/caveats/snapIds.js.map +1 -0
- package/dist/esm/restricted/dialog.js +137 -0
- package/dist/esm/restricted/dialog.js.map +1 -0
- package/dist/esm/restricted/getBip32Entropy.js +67 -0
- package/dist/esm/restricted/getBip32Entropy.js.map +1 -0
- package/dist/esm/restricted/getBip32PublicKey.js +79 -0
- package/dist/esm/restricted/getBip32PublicKey.js.map +1 -0
- package/dist/esm/restricted/getBip44Entropy.js +70 -0
- package/dist/esm/restricted/getBip44Entropy.js.map +1 -0
- package/dist/esm/restricted/getEntropy.js +58 -0
- package/dist/esm/restricted/getEntropy.js.map +1 -0
- package/dist/esm/restricted/getLocale.js +42 -0
- package/dist/esm/restricted/getLocale.js.map +1 -0
- package/dist/esm/restricted/index.js +29 -0
- package/dist/esm/restricted/index.js.map +1 -0
- package/dist/esm/restricted/invokeSnap.js +89 -0
- package/dist/esm/restricted/invokeSnap.js.map +1 -0
- package/dist/esm/restricted/manageAccounts.js +60 -0
- package/dist/esm/restricted/manageAccounts.js.map +1 -0
- package/dist/esm/restricted/manageState.js +221 -0
- package/dist/esm/restricted/manageState.js.map +1 -0
- package/dist/esm/restricted/notify.js +89 -0
- package/dist/esm/restricted/notify.js.map +1 -0
- package/dist/esm/utils.js +124 -0
- package/dist/esm/utils.js.map +1 -0
- package/dist/types/__fixtures__/entropy.d.ts +14 -0
- package/dist/types/__fixtures__/index.d.ts +1 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/permitted/common/snapInstallation.d.ts +16 -0
- package/dist/types/permitted/getFile.d.ts +14 -0
- package/dist/types/permitted/getSnaps.d.ts +13 -0
- package/dist/types/permitted/handlers.d.ts +14 -0
- package/dist/types/permitted/index.d.ts +5 -0
- package/dist/types/permitted/invokeKeyring.d.ts +17 -0
- package/dist/types/permitted/invokeSnapSugar.d.ts +32 -0
- package/dist/types/permitted/middleware.d.ts +10 -0
- package/dist/types/permitted/requestSnaps.d.ts +50 -0
- package/dist/types/request.d.ts +99 -0
- package/dist/types/restricted/caveats/index.d.ts +8 -0
- package/dist/types/restricted/caveats/permittedCoinTypes.d.ts +29 -0
- package/dist/types/restricted/caveats/permittedDerivationPaths.d.ts +32 -0
- package/dist/types/restricted/caveats/snapIds.d.ts +21 -0
- package/dist/types/restricted/dialog.d.ts +113 -0
- package/dist/types/restricted/getBip32Entropy.d.ts +45 -0
- package/dist/types/restricted/getBip32PublicKey.d.ts +60 -0
- package/dist/types/restricted/getBip44Entropy.d.ts +49 -0
- package/dist/types/restricted/getEntropy.d.ts +60 -0
- package/dist/types/restricted/getLocale.d.ts +47 -0
- package/dist/types/restricted/index.d.ts +232 -0
- package/dist/types/restricted/invokeSnap.d.ts +62 -0
- package/dist/types/restricted/manageAccounts.d.ts +63 -0
- package/dist/types/restricted/manageState.d.ts +127 -0
- package/dist/types/restricted/notify.d.ts +81 -0
- package/dist/types/utils.d.ts +94 -0
- package/package.json +88 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { rpcErrors } from '@metamask/rpc-errors';
|
|
2
|
+
import { enumValue, AuxiliaryFileEncoding } from '@metamask/snaps-utils';
|
|
3
|
+
import { assertStruct } from '@metamask/utils';
|
|
4
|
+
import { object, optional, string, union } from 'superstruct';
|
|
5
|
+
export const GetFileArgsStruct = object({
|
|
6
|
+
path: string(),
|
|
7
|
+
encoding: optional(union([
|
|
8
|
+
enumValue(AuxiliaryFileEncoding.Base64),
|
|
9
|
+
enumValue(AuxiliaryFileEncoding.Hex),
|
|
10
|
+
enumValue(AuxiliaryFileEncoding.Utf8)
|
|
11
|
+
]))
|
|
12
|
+
});
|
|
13
|
+
const hookNames = {
|
|
14
|
+
getSnapFile: true
|
|
15
|
+
};
|
|
16
|
+
export const getFileHandler = {
|
|
17
|
+
methodNames: [
|
|
18
|
+
'snap_getFile'
|
|
19
|
+
],
|
|
20
|
+
implementation,
|
|
21
|
+
hookNames
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* The `snap_getFile` method implementation.
|
|
25
|
+
*
|
|
26
|
+
* @param req - The JSON-RPC request object.
|
|
27
|
+
* @param res - The JSON-RPC response object.
|
|
28
|
+
* @param _next - The `json-rpc-engine` "next" callback. Not used by this
|
|
29
|
+
* function.
|
|
30
|
+
* @param end - The `json-rpc-engine` "end" callback.
|
|
31
|
+
* @param hooks - The RPC method hooks.
|
|
32
|
+
* @param hooks.getSnapFile - The funnction to load a static snap file.
|
|
33
|
+
* @returns Nothing.
|
|
34
|
+
*/ async function implementation(req, res, _next, end, { getSnapFile }) {
|
|
35
|
+
const { params } = req;
|
|
36
|
+
assertStruct(params, GetFileArgsStruct, 'Invalid "snap_getFile" parameters', rpcErrors.invalidParams);
|
|
37
|
+
try {
|
|
38
|
+
res.result = await getSnapFile(params.path, params.encoding ?? AuxiliaryFileEncoding.Base64);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
return end(error);
|
|
41
|
+
}
|
|
42
|
+
return end();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=getFile.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/getFile.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { enumValue, AuxiliaryFileEncoding } from '@metamask/snaps-utils';\nimport type {\n PendingJsonRpcResponse,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { object, optional, string, union } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nexport const GetFileArgsStruct = object({\n path: string(),\n encoding: optional(\n union([\n enumValue(AuxiliaryFileEncoding.Base64),\n enumValue(AuxiliaryFileEncoding.Hex),\n enumValue(AuxiliaryFileEncoding.Utf8),\n ]),\n ),\n});\n\nexport type GetFileArgs = Infer<typeof GetFileArgsStruct>;\n\nconst hookNames: MethodHooksObject<GetFileHooks> = {\n getSnapFile: true,\n};\n\nexport const getFileHandler: PermittedHandlerExport<\n GetFileHooks,\n GetFileArgs,\n string\n> = {\n methodNames: ['snap_getFile'],\n implementation,\n hookNames,\n};\n\nexport type GetFileHooks = {\n getSnapFile: (\n path: GetFileArgs['path'],\n encoding: GetFileArgs['encoding'],\n ) => Promise<string>;\n};\n\n/**\n * The `snap_getFile` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnapFile - The funnction to load a static snap file.\n * @returns Nothing.\n */\nasync function implementation(\n req: JsonRpcRequest<GetFileArgs>,\n res: PendingJsonRpcResponse<Json>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { getSnapFile }: GetFileHooks,\n): Promise<void> {\n const { params } = req;\n\n assertStruct(\n params,\n GetFileArgsStruct,\n 'Invalid \"snap_getFile\" parameters',\n rpcErrors.invalidParams,\n );\n\n try {\n res.result = await getSnapFile(\n params.path,\n params.encoding ?? AuxiliaryFileEncoding.Base64,\n );\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"],"names":["rpcErrors","enumValue","AuxiliaryFileEncoding","assertStruct","object","optional","string","union","GetFileArgsStruct","path","encoding","Base64","Hex","Utf8","hookNames","getSnapFile","getFileHandler","methodNames","implementation","req","res","_next","end","params","invalidParams","result","error"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AACjD,SAASC,SAAS,EAAEC,qBAAqB,QAAQ,wBAAwB;AAMzE,SAASC,YAAY,QAAQ,kBAAkB;AAE/C,SAASC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,QAAQ,cAAc;AAI9D,OAAO,MAAMC,oBAAoBJ,OAAO;IACtCK,MAAMH;IACNI,UAAUL,SACRE,MAAM;QACJN,UAAUC,sBAAsBS,MAAM;QACtCV,UAAUC,sBAAsBU,GAAG;QACnCX,UAAUC,sBAAsBW,IAAI;KACrC;AAEL,GAAG;AAIH,MAAMC,YAA6C;IACjDC,aAAa;AACf;AAEA,OAAO,MAAMC,iBAIT;IACFC,aAAa;QAAC;KAAe;IAC7BC;IACAJ;AACF,EAAE;AASF;;;;;;;;;;;CAWC,GACD,eAAeI,eACbC,GAAgC,EAChCC,GAAiC,EACjCC,KAAc,EACdC,GAA6B,EAC7B,EAAEP,WAAW,EAAgB;IAE7B,MAAM,EAAEQ,MAAM,EAAE,GAAGJ;IAEnBhB,aACEoB,QACAf,mBACA,qCACAR,UAAUwB,aAAa;IAGzB,IAAI;QACFJ,IAAIK,MAAM,GAAG,MAAMV,YACjBQ,OAAOd,IAAI,EACXc,OAAOb,QAAQ,IAAIR,sBAAsBS,MAAM;IAEnD,EAAE,OAAOe,OAAO;QACd,OAAOJ,IAAII;IACb;IAEA,OAAOJ;AACT"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const hookNames = {
|
|
2
|
+
getSnaps: true
|
|
3
|
+
};
|
|
4
|
+
/**
|
|
5
|
+
* `wallet_getSnaps` gets the requester's permitted and installed Snaps.
|
|
6
|
+
*/ export const getSnapsHandler = {
|
|
7
|
+
methodNames: [
|
|
8
|
+
'wallet_getSnaps'
|
|
9
|
+
],
|
|
10
|
+
implementation: getSnapsImplementation,
|
|
11
|
+
hookNames
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The `wallet_getSnaps` method implementation.
|
|
15
|
+
* Fetches available snaps for the requesting origin and adds them to the JSON-RPC response.
|
|
16
|
+
*
|
|
17
|
+
* @param _req - The JSON-RPC request object. Not used by this function.
|
|
18
|
+
* @param res - The JSON-RPC response object.
|
|
19
|
+
* @param _next - The `json-rpc-engine` "next" callback. Not used by this
|
|
20
|
+
* function.
|
|
21
|
+
* @param end - The `json-rpc-engine` "end" callback.
|
|
22
|
+
* @param hooks - The RPC method hooks.
|
|
23
|
+
* @param hooks.getSnaps - A function that returns the snaps available for the requesting origin.
|
|
24
|
+
* @returns Nothing.
|
|
25
|
+
*/ async function getSnapsImplementation(_req, res, _next, end, { getSnaps }) {
|
|
26
|
+
// getSnaps is already bound to the origin
|
|
27
|
+
res.result = await getSnaps();
|
|
28
|
+
return end();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=getSnaps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/getSnaps.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport type { InstallSnapsResult } from '@metamask/snaps-utils';\nimport type { JsonRpcParams, PendingJsonRpcResponse } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<GetSnapsHooks> = {\n getSnaps: true,\n};\n\n/**\n * `wallet_getSnaps` gets the requester's permitted and installed Snaps.\n */\nexport const getSnapsHandler: PermittedHandlerExport<\n GetSnapsHooks,\n JsonRpcParams,\n InstallSnapsResult\n> = {\n methodNames: ['wallet_getSnaps'],\n implementation: getSnapsImplementation,\n hookNames,\n};\n\nexport type GetSnapsHooks = {\n /**\n * @returns The permitted and installed snaps for the requesting origin.\n */\n getSnaps: () => Promise<InstallSnapsResult>;\n};\n\n/**\n * The `wallet_getSnaps` method implementation.\n * Fetches available snaps for the requesting origin and adds them to the JSON-RPC response.\n *\n * @param _req - The JSON-RPC request object. Not used by this function.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnaps - A function that returns the snaps available for the requesting origin.\n * @returns Nothing.\n */\nasync function getSnapsImplementation(\n _req: unknown,\n res: PendingJsonRpcResponse<InstallSnapsResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { getSnaps }: GetSnapsHooks,\n): Promise<void> {\n // getSnaps is already bound to the origin\n res.result = await getSnaps();\n return end();\n}\n"],"names":["hookNames","getSnaps","getSnapsHandler","methodNames","implementation","getSnapsImplementation","_req","res","_next","end","result"],"mappings":"AAOA,MAAMA,YAA8C;IAClDC,UAAU;AACZ;AAEA;;CAEC,GACD,OAAO,MAAMC,kBAIT;IACFC,aAAa;QAAC;KAAkB;IAChCC,gBAAgBC;IAChBL;AACF,EAAE;AASF;;;;;;;;;;;;CAYC,GACD,eAAeK,uBACbC,IAAa,EACbC,GAA+C,EAC/CC,KAAc,EACdC,GAA6B,EAC7B,EAAER,QAAQ,EAAiB;IAE3B,0CAA0C;IAC1CM,IAAIG,MAAM,GAAG,MAAMT;IACnB,OAAOQ;AACT"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { getFileHandler } from './getFile';
|
|
2
|
+
import { getSnapsHandler } from './getSnaps';
|
|
3
|
+
import { invokeKeyringHandler } from './invokeKeyring';
|
|
4
|
+
import { invokeSnapSugarHandler } from './invokeSnapSugar';
|
|
5
|
+
import { requestSnapsHandler } from './requestSnaps';
|
|
6
|
+
/* eslint-disable @typescript-eslint/naming-convention */ export const methodHandlers = {
|
|
7
|
+
wallet_getSnaps: getSnapsHandler,
|
|
8
|
+
wallet_requestSnaps: requestSnapsHandler,
|
|
9
|
+
wallet_invokeSnap: invokeSnapSugarHandler,
|
|
10
|
+
wallet_invokeKeyring: invokeKeyringHandler,
|
|
11
|
+
snap_getFile: getFileHandler
|
|
12
|
+
};
|
|
13
|
+
/* eslint-enable @typescript-eslint/naming-convention */ export const handlers = Object.values(methodHandlers);
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=handlers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/handlers.ts"],"sourcesContent":["import { getFileHandler } from './getFile';\nimport { getSnapsHandler } from './getSnaps';\nimport { invokeKeyringHandler } from './invokeKeyring';\nimport { invokeSnapSugarHandler } from './invokeSnapSugar';\nimport { requestSnapsHandler } from './requestSnaps';\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const methodHandlers = {\n wallet_getSnaps: getSnapsHandler,\n wallet_requestSnaps: requestSnapsHandler,\n wallet_invokeSnap: invokeSnapSugarHandler,\n wallet_invokeKeyring: invokeKeyringHandler,\n snap_getFile: getFileHandler,\n};\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport const handlers = Object.values(methodHandlers);\n"],"names":["getFileHandler","getSnapsHandler","invokeKeyringHandler","invokeSnapSugarHandler","requestSnapsHandler","methodHandlers","wallet_getSnaps","wallet_requestSnaps","wallet_invokeSnap","wallet_invokeKeyring","snap_getFile","handlers","Object","values"],"mappings":"AAAA,SAASA,cAAc,QAAQ,YAAY;AAC3C,SAASC,eAAe,QAAQ,aAAa;AAC7C,SAASC,oBAAoB,QAAQ,kBAAkB;AACvD,SAASC,sBAAsB,QAAQ,oBAAoB;AAC3D,SAASC,mBAAmB,QAAQ,iBAAiB;AAErD,uDAAuD,GACvD,OAAO,MAAMC,iBAAiB;IAC5BC,iBAAiBL;IACjBM,qBAAqBH;IACrBI,mBAAmBL;IACnBM,sBAAsBP;IACtBQ,cAAcV;AAChB,EAAE;AACF,sDAAsD,GAEtD,OAAO,MAAMW,WAAWC,OAAOC,MAAM,CAACR,gBAAgB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/index.ts"],"sourcesContent":["import type { GetSnapsHooks } from './getSnaps';\nimport type { RequestSnapsHooks } from './requestSnaps';\n\nexport type PermittedRpcMethodHooks = GetSnapsHooks & RequestSnapsHooks;\n\nexport * from './handlers';\nexport * from './middleware';\n"],"names":[],"mappings":"AAKA,cAAc,aAAa;AAC3B,cAAc,eAAe"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { rpcErrors } from '@metamask/rpc-errors';
|
|
2
|
+
import { HandlerType, WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-utils';
|
|
3
|
+
import { hasProperty } from '@metamask/utils';
|
|
4
|
+
import { getValidatedParams } from './invokeSnapSugar';
|
|
5
|
+
const hookNames = {
|
|
6
|
+
hasPermission: true,
|
|
7
|
+
handleSnapRpcRequest: true,
|
|
8
|
+
getSnap: true,
|
|
9
|
+
getAllowedKeyringMethods: true
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.
|
|
13
|
+
*/ export const invokeKeyringHandler = {
|
|
14
|
+
methodNames: [
|
|
15
|
+
'wallet_invokeKeyring'
|
|
16
|
+
],
|
|
17
|
+
implementation: invokeKeyringImplementation,
|
|
18
|
+
hookNames
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The `wallet_invokeKeyring` method implementation.
|
|
22
|
+
* Invokes onKeyringRequest if the snap requested is installed and connected to the dapp.
|
|
23
|
+
*
|
|
24
|
+
* @param req - The JSON-RPC request object.
|
|
25
|
+
* @param res - The JSON-RPC response object.
|
|
26
|
+
* @param _next - The `json-rpc-engine` "next" callback. Not used by this
|
|
27
|
+
* function.
|
|
28
|
+
* @param end - The `json-rpc-engine` "end" callback.
|
|
29
|
+
* @param hooks - The RPC method hooks.
|
|
30
|
+
* @param hooks.handleSnapRpcRequest - Invokes a snap with a given RPC request.
|
|
31
|
+
* @param hooks.hasPermission - Checks whether a given origin has a given permission.
|
|
32
|
+
* @param hooks.getSnap - Gets information about a given snap.
|
|
33
|
+
* @param hooks.getAllowedKeyringMethods - Get the list of allowed Keyring
|
|
34
|
+
* methods for a given origin.
|
|
35
|
+
* @returns Nothing.
|
|
36
|
+
*/ async function invokeKeyringImplementation(req, res, _next, end, { handleSnapRpcRequest, hasPermission, getSnap, getAllowedKeyringMethods }) {
|
|
37
|
+
let params;
|
|
38
|
+
try {
|
|
39
|
+
params = getValidatedParams(req.params);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
return end(error);
|
|
42
|
+
}
|
|
43
|
+
// We expect the MM middleware stack to always add the origin to requests
|
|
44
|
+
const { origin } = req;
|
|
45
|
+
const { snapId, request } = params;
|
|
46
|
+
if (!origin || !hasPermission(origin, WALLET_SNAP_PERMISSION_KEY)) {
|
|
47
|
+
return end(rpcErrors.invalidRequest({
|
|
48
|
+
message: `The snap "${snapId}" is not connected to "${origin}". Please connect before invoking the snap.`
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
if (!getSnap(snapId)) {
|
|
52
|
+
return end(rpcErrors.invalidRequest({
|
|
53
|
+
message: `The snap "${snapId}" is not installed. Please install it first, before invoking the snap.`
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
56
|
+
if (!hasProperty(request, 'method') || typeof request.method !== 'string') {
|
|
57
|
+
return end(rpcErrors.invalidRequest({
|
|
58
|
+
message: 'The request must have a method.'
|
|
59
|
+
}));
|
|
60
|
+
}
|
|
61
|
+
const allowedMethods = getAllowedKeyringMethods(origin);
|
|
62
|
+
if (!allowedMethods.includes(request.method)) {
|
|
63
|
+
return end(rpcErrors.invalidRequest({
|
|
64
|
+
message: `The origin "${origin}" is not allowed to invoke the method "${request.method}".`
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
res.result = await handleSnapRpcRequest({
|
|
69
|
+
snapId,
|
|
70
|
+
origin,
|
|
71
|
+
request,
|
|
72
|
+
handler: HandlerType.OnKeyringRequest
|
|
73
|
+
});
|
|
74
|
+
} catch (error) {
|
|
75
|
+
return end(error);
|
|
76
|
+
}
|
|
77
|
+
return end();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
//# sourceMappingURL=invokeKeyring.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/invokeKeyring.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Snap } from '@metamask/snaps-utils';\nimport {\n HandlerType,\n WALLET_SNAP_PERMISSION_KEY,\n type SnapId,\n type SnapRpcHookArgs,\n} from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse, JsonRpcRequest } from '@metamask/utils';\nimport { hasProperty, type Json } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport type { InvokeSnapSugarArgs } from './invokeSnapSugar';\nimport { getValidatedParams } from './invokeSnapSugar';\n\nconst hookNames: MethodHooksObject<InvokeKeyringHooks> = {\n hasPermission: true,\n handleSnapRpcRequest: true,\n getSnap: true,\n getAllowedKeyringMethods: true,\n};\n\n/**\n * `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.\n */\nexport const invokeKeyringHandler: PermittedHandlerExport<\n InvokeKeyringHooks,\n JsonRpcRequest,\n Json\n> = {\n methodNames: ['wallet_invokeKeyring'],\n implementation: invokeKeyringImplementation,\n hookNames,\n};\n\nexport type InvokeKeyringHooks = {\n hasPermission: (origin: string, permissionName: string) => boolean;\n\n handleSnapRpcRequest: ({\n snapId,\n origin,\n handler,\n request,\n }: SnapRpcHookArgs & { snapId: SnapId }) => Promise<unknown>;\n\n getSnap: (snapId: SnapId) => Snap | undefined;\n\n getAllowedKeyringMethods: (origin: string) => string[];\n};\n\n/**\n * The `wallet_invokeKeyring` method implementation.\n * Invokes onKeyringRequest if the snap requested is installed and connected to the dapp.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.handleSnapRpcRequest - Invokes a snap with a given RPC request.\n * @param hooks.hasPermission - Checks whether a given origin has a given permission.\n * @param hooks.getSnap - Gets information about a given snap.\n * @param hooks.getAllowedKeyringMethods - Get the list of allowed Keyring\n * methods for a given origin.\n * @returns Nothing.\n */\nasync function invokeKeyringImplementation(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse<Json>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n handleSnapRpcRequest,\n hasPermission,\n getSnap,\n getAllowedKeyringMethods,\n }: InvokeKeyringHooks,\n): Promise<void> {\n let params: InvokeSnapSugarArgs;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n // We expect the MM middleware stack to always add the origin to requests\n const { origin } = req as JsonRpcRequest & { origin: string };\n const { snapId, request } = params;\n\n if (!origin || !hasPermission(origin, WALLET_SNAP_PERMISSION_KEY)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not connected to \"${origin}\". Please connect before invoking the snap.`,\n }),\n );\n }\n\n if (!getSnap(snapId)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not installed. Please install it first, before invoking the snap.`,\n }),\n );\n }\n\n if (!hasProperty(request, 'method') || typeof request.method !== 'string') {\n return end(\n rpcErrors.invalidRequest({\n message: 'The request must have a method.',\n }),\n );\n }\n\n const allowedMethods = getAllowedKeyringMethods(origin);\n if (!allowedMethods.includes(request.method)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The origin \"${origin}\" is not allowed to invoke the method \"${request.method}\".`,\n }),\n );\n }\n\n try {\n res.result = (await handleSnapRpcRequest({\n snapId,\n origin,\n request,\n handler: HandlerType.OnKeyringRequest,\n })) as Json;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"],"names":["rpcErrors","HandlerType","WALLET_SNAP_PERMISSION_KEY","hasProperty","getValidatedParams","hookNames","hasPermission","handleSnapRpcRequest","getSnap","getAllowedKeyringMethods","invokeKeyringHandler","methodNames","implementation","invokeKeyringImplementation","req","res","_next","end","params","error","origin","snapId","request","invalidRequest","message","method","allowedMethods","includes","result","handler","OnKeyringRequest"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SACEC,WAAW,EACXC,0BAA0B,QAGrB,wBAAwB;AAE/B,SAASC,WAAW,QAAmB,kBAAkB;AAIzD,SAASC,kBAAkB,QAAQ,oBAAoB;AAEvD,MAAMC,YAAmD;IACvDC,eAAe;IACfC,sBAAsB;IACtBC,SAAS;IACTC,0BAA0B;AAC5B;AAEA;;CAEC,GACD,OAAO,MAAMC,uBAIT;IACFC,aAAa;QAAC;KAAuB;IACrCC,gBAAgBC;IAChBR;AACF,EAAE;AAiBF;;;;;;;;;;;;;;;;CAgBC,GACD,eAAeQ,4BACbC,GAAmB,EACnBC,GAAiC,EACjCC,KAAc,EACdC,GAA6B,EAC7B,EACEV,oBAAoB,EACpBD,aAAa,EACbE,OAAO,EACPC,wBAAwB,EACL;IAErB,IAAIS;IACJ,IAAI;QACFA,SAASd,mBAAmBU,IAAII,MAAM;IACxC,EAAE,OAAOC,OAAO;QACd,OAAOF,IAAIE;IACb;IAEA,yEAAyE;IACzE,MAAM,EAAEC,MAAM,EAAE,GAAGN;IACnB,MAAM,EAAEO,MAAM,EAAEC,OAAO,EAAE,GAAGJ;IAE5B,IAAI,CAACE,UAAU,CAACd,cAAcc,QAAQlB,6BAA6B;QACjE,OAAOe,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS,CAAC,UAAU,EAAEH,OAAO,uBAAuB,EAAED,OAAO,2CAA2C,CAAC;QAC3G;IAEJ;IAEA,IAAI,CAACZ,QAAQa,SAAS;QACpB,OAAOJ,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS,CAAC,UAAU,EAAEH,OAAO,sEAAsE,CAAC;QACtG;IAEJ;IAEA,IAAI,CAAClB,YAAYmB,SAAS,aAAa,OAAOA,QAAQG,MAAM,KAAK,UAAU;QACzE,OAAOR,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS;QACX;IAEJ;IAEA,MAAME,iBAAiBjB,yBAAyBW;IAChD,IAAI,CAACM,eAAeC,QAAQ,CAACL,QAAQG,MAAM,GAAG;QAC5C,OAAOR,IACLjB,UAAUuB,cAAc,CAAC;YACvBC,SAAS,CAAC,YAAY,EAAEJ,OAAO,uCAAuC,EAAEE,QAAQG,MAAM,CAAC,EAAE,CAAC;QAC5F;IAEJ;IAEA,IAAI;QACFV,IAAIa,MAAM,GAAI,MAAMrB,qBAAqB;YACvCc;YACAD;YACAE;YACAO,SAAS5B,YAAY6B,gBAAgB;QACvC;IACF,EAAE,OAAOX,OAAO;QACd,OAAOF,IAAIE;IACb;IAEA,OAAOF;AACT"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { rpcErrors } from '@metamask/rpc-errors';
|
|
2
|
+
import { isObject } from '@metamask/utils';
|
|
3
|
+
/**
|
|
4
|
+
* `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.
|
|
5
|
+
*/ export const invokeSnapSugarHandler = {
|
|
6
|
+
methodNames: [
|
|
7
|
+
'wallet_invokeSnap'
|
|
8
|
+
],
|
|
9
|
+
implementation: invokeSnapSugar,
|
|
10
|
+
hookNames: undefined
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* The `wallet_invokeSnap` method implementation.
|
|
14
|
+
* Reroutes incoming JSON-RPC requests that are targeting snaps, by modifying the method and params.
|
|
15
|
+
*
|
|
16
|
+
* @param req - The JSON-RPC request object.
|
|
17
|
+
* @param _res - The JSON-RPC response object. Not used by this
|
|
18
|
+
* function.
|
|
19
|
+
* @param next - The `json-rpc-engine` "next" callback.
|
|
20
|
+
* @param end - The `json-rpc-engine` "end" callback.
|
|
21
|
+
* @returns Nothing.
|
|
22
|
+
* @throws If the params are invalid.
|
|
23
|
+
*/ export function invokeSnapSugar(req, _res, next, end) {
|
|
24
|
+
let params;
|
|
25
|
+
try {
|
|
26
|
+
params = getValidatedParams(req.params);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
return end(error);
|
|
29
|
+
}
|
|
30
|
+
req.method = 'wallet_snap';
|
|
31
|
+
req.params = params;
|
|
32
|
+
return next();
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Validates the wallet_invokeSnap method `params` and returns them cast to the correct
|
|
36
|
+
* type. Throws if validation fails.
|
|
37
|
+
*
|
|
38
|
+
* @param params - The unvalidated params object from the method request.
|
|
39
|
+
* @returns The validated method parameter object.
|
|
40
|
+
*/ export function getValidatedParams(params) {
|
|
41
|
+
if (!isObject(params)) {
|
|
42
|
+
throw rpcErrors.invalidParams({
|
|
43
|
+
message: 'Expected params to be a single object.'
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
const { snapId, request } = params;
|
|
47
|
+
if (!snapId || typeof snapId !== 'string' || snapId === '') {
|
|
48
|
+
throw rpcErrors.invalidParams({
|
|
49
|
+
message: 'Must specify a valid snap ID.'
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
if (!isObject(request)) {
|
|
53
|
+
throw rpcErrors.invalidParams({
|
|
54
|
+
message: 'Expected request to be a single object.'
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
return params;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=invokeSnapSugar.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/invokeSnapSugar.ts"],"sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport { isObject } from '@metamask/utils';\n\nexport type InvokeSnapSugarArgs = {\n snapId: string;\n request: Record<string, Json>;\n};\n\n/**\n * `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.\n */\nexport const invokeSnapSugarHandler: PermittedHandlerExport<\n void,\n InvokeSnapSugarArgs,\n Json\n> = {\n methodNames: ['wallet_invokeSnap'],\n implementation: invokeSnapSugar,\n hookNames: undefined,\n};\n\n/**\n * The `wallet_invokeSnap` method implementation.\n * Reroutes incoming JSON-RPC requests that are targeting snaps, by modifying the method and params.\n *\n * @param req - The JSON-RPC request object.\n * @param _res - The JSON-RPC response object. Not used by this\n * function.\n * @param next - The `json-rpc-engine` \"next\" callback.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @returns Nothing.\n * @throws If the params are invalid.\n */\nexport function invokeSnapSugar(\n req: JsonRpcRequest<InvokeSnapSugarArgs>,\n _res: unknown,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n): void {\n let params: InvokeSnapSugarArgs;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n req.method = 'wallet_snap';\n req.params = params;\n return next();\n}\n\n/**\n * Validates the wallet_invokeSnap method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(params: unknown): InvokeSnapSugarArgs {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { snapId, request } = params;\n\n if (!snapId || typeof snapId !== 'string' || snapId === '') {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid snap ID.',\n });\n }\n\n if (!isObject(request)) {\n throw rpcErrors.invalidParams({\n message: 'Expected request to be a single object.',\n });\n }\n\n return params as InvokeSnapSugarArgs;\n}\n"],"names":["rpcErrors","isObject","invokeSnapSugarHandler","methodNames","implementation","invokeSnapSugar","hookNames","undefined","req","_res","next","end","params","getValidatedParams","error","method","invalidParams","message","snapId","request"],"mappings":"AAKA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,QAAQ,QAAQ,kBAAkB;AAO3C;;CAEC,GACD,OAAO,MAAMC,yBAIT;IACFC,aAAa;QAAC;KAAoB;IAClCC,gBAAgBC;IAChBC,WAAWC;AACb,EAAE;AAEF;;;;;;;;;;;CAWC,GACD,OAAO,SAASF,gBACdG,GAAwC,EACxCC,IAAa,EACbC,IAA+B,EAC/BC,GAA6B;IAE7B,IAAIC;IACJ,IAAI;QACFA,SAASC,mBAAmBL,IAAII,MAAM;IACxC,EAAE,OAAOE,OAAO;QACd,OAAOH,IAAIG;IACb;IAEAN,IAAIO,MAAM,GAAG;IACbP,IAAII,MAAM,GAAGA;IACb,OAAOF;AACT;AAEA;;;;;;CAMC,GACD,OAAO,SAASG,mBAAmBD,MAAe;IAChD,IAAI,CAACX,SAASW,SAAS;QACrB,MAAMZ,UAAUgB,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAE,GAAGP;IAE5B,IAAI,CAACM,UAAU,OAAOA,WAAW,YAAYA,WAAW,IAAI;QAC1D,MAAMlB,UAAUgB,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,IAAI,CAAChB,SAASkB,UAAU;QACtB,MAAMnB,UAAUgB,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,OAAOL;AACT"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { rpcErrors } from '@metamask/rpc-errors';
|
|
2
|
+
import { logError } from '@metamask/snaps-utils';
|
|
3
|
+
import { selectHooks } from '../utils';
|
|
4
|
+
import { methodHandlers } from './handlers';
|
|
5
|
+
/**
|
|
6
|
+
* Creates a middleware that handles permitted snap RPC methods.
|
|
7
|
+
*
|
|
8
|
+
* @param isSnap - A flag that should indicate whether the requesting origin is a snap or not.
|
|
9
|
+
* @param hooks - An object containing the hooks made available to the permitted RPC methods.
|
|
10
|
+
* @returns The middleware.
|
|
11
|
+
*/ export function createSnapsMethodMiddleware(isSnap, hooks) {
|
|
12
|
+
// This is not actually a misused promise, the type is just wrong
|
|
13
|
+
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
14
|
+
return async function methodMiddleware(request, response, next, end) {
|
|
15
|
+
const handler = methodHandlers[request.method];
|
|
16
|
+
if (handler) {
|
|
17
|
+
if (request.method.startsWith('snap_') && !isSnap) {
|
|
18
|
+
return end(rpcErrors.methodNotFound());
|
|
19
|
+
}
|
|
20
|
+
// TODO: Once json-rpc-engine types are up to date, we should type this correctly
|
|
21
|
+
const { implementation, hookNames } = handler;
|
|
22
|
+
try {
|
|
23
|
+
// Implementations may or may not be async, so we must await them.
|
|
24
|
+
return await implementation(request, response, next, end, selectHooks(hooks, hookNames));
|
|
25
|
+
} catch (error) {
|
|
26
|
+
logError(error);
|
|
27
|
+
return end(error);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return next();
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=middleware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/middleware.ts"],"sourcesContent":["import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { logError } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport { selectHooks } from '../utils';\nimport { methodHandlers } from './handlers';\n\n/**\n * Creates a middleware that handles permitted snap RPC methods.\n *\n * @param isSnap - A flag that should indicate whether the requesting origin is a snap or not.\n * @param hooks - An object containing the hooks made available to the permitted RPC methods.\n * @returns The middleware.\n */\nexport function createSnapsMethodMiddleware(\n isSnap: boolean,\n hooks: Record<string, unknown>,\n): JsonRpcMiddleware<JsonRpcParams, Json> {\n // This is not actually a misused promise, the type is just wrong\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n return async function methodMiddleware(request, response, next, end) {\n const handler =\n methodHandlers[request.method as keyof typeof methodHandlers];\n if (handler) {\n if (request.method.startsWith('snap_') && !isSnap) {\n return end(rpcErrors.methodNotFound());\n }\n\n // TODO: Once json-rpc-engine types are up to date, we should type this correctly\n const { implementation, hookNames } = handler as any;\n try {\n // Implementations may or may not be async, so we must await them.\n return await implementation(\n request,\n response,\n next,\n end,\n selectHooks(hooks, hookNames),\n );\n } catch (error) {\n logError(error);\n return end(error);\n }\n }\n\n return next();\n };\n}\n"],"names":["rpcErrors","logError","selectHooks","methodHandlers","createSnapsMethodMiddleware","isSnap","hooks","methodMiddleware","request","response","next","end","handler","method","startsWith","methodNotFound","implementation","hookNames","error"],"mappings":"AACA,SAASA,SAAS,QAAQ,uBAAuB;AACjD,SAASC,QAAQ,QAAQ,wBAAwB;AAGjD,SAASC,WAAW,QAAQ,WAAW;AACvC,SAASC,cAAc,QAAQ,aAAa;AAE5C;;;;;;CAMC,GACD,OAAO,SAASC,4BACdC,MAAe,EACfC,KAA8B;IAE9B,iEAAiE;IACjE,kEAAkE;IAClE,OAAO,eAAeC,iBAAiBC,OAAO,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,GAAG;QACjE,MAAMC,UACJT,cAAc,CAACK,QAAQK,MAAM,CAAgC;QAC/D,IAAID,SAAS;YACX,IAAIJ,QAAQK,MAAM,CAACC,UAAU,CAAC,YAAY,CAACT,QAAQ;gBACjD,OAAOM,IAAIX,UAAUe,cAAc;YACrC;YAEA,iFAAiF;YACjF,MAAM,EAAEC,cAAc,EAAEC,SAAS,EAAE,GAAGL;YACtC,IAAI;gBACF,kEAAkE;gBAClE,OAAO,MAAMI,eACXR,SACAC,UACAC,MACAC,KACAT,YAAYI,OAAOW;YAEvB,EAAE,OAAOC,OAAO;gBACdjB,SAASiB;gBACT,OAAOP,IAAIO;YACb;QACF;QAEA,OAAOR;IACT;AACF"}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { rpcErrors } from '@metamask/rpc-errors';
|
|
2
|
+
import { SnapCaveatType, verifyRequestedSnapPermissions } from '@metamask/snaps-utils';
|
|
3
|
+
import { hasProperty, isObject } from '@metamask/utils';
|
|
4
|
+
import { WALLET_SNAP_PERMISSION_KEY } from '../restricted/invokeSnap';
|
|
5
|
+
import { handleInstallSnaps } from './common/snapInstallation';
|
|
6
|
+
const hookNames = {
|
|
7
|
+
installSnaps: true,
|
|
8
|
+
requestPermissions: true,
|
|
9
|
+
getPermissions: true
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* `wallet_requestSnaps` installs the requested Snaps and requests permission to use them if necessary.
|
|
13
|
+
*/ export const requestSnapsHandler = {
|
|
14
|
+
methodNames: [
|
|
15
|
+
'wallet_requestSnaps'
|
|
16
|
+
],
|
|
17
|
+
implementation: requestSnapsImplementation,
|
|
18
|
+
hookNames
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Checks whether an origin has existing `wallet_snap` permission and
|
|
22
|
+
* whether or not it has the requested snapIds caveat.
|
|
23
|
+
*
|
|
24
|
+
* @param existingPermissions - The existing permissions for the origin.
|
|
25
|
+
* @param requestedSnaps - The requested snaps.
|
|
26
|
+
* @returns True if the existing permissions satisfy the requested snaps, otherwise false.
|
|
27
|
+
*/ export function hasRequestedSnaps(existingPermissions, requestedSnaps) {
|
|
28
|
+
const snapIdCaveat = existingPermissions[WALLET_SNAP_PERMISSION_KEY]?.caveats?.find((caveat)=>caveat.type === SnapCaveatType.SnapIds);
|
|
29
|
+
const permittedSnaps = snapIdCaveat?.value;
|
|
30
|
+
if (isObject(permittedSnaps)) {
|
|
31
|
+
return Object.keys(requestedSnaps).every((requestedSnap)=>hasProperty(permittedSnaps, requestedSnap));
|
|
32
|
+
}
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Constructs a valid permission request with merged caveats based on existing permissions
|
|
37
|
+
* and the requested snaps.
|
|
38
|
+
*
|
|
39
|
+
* @param existingPermissions - The existing permissions for the origin.
|
|
40
|
+
* @param requestedPermissions - The permission request passed into `requestPermissions`.
|
|
41
|
+
* @returns `requestedPermissions`.
|
|
42
|
+
*/ export function getSnapPermissionsRequest(existingPermissions, requestedPermissions) {
|
|
43
|
+
verifyRequestedSnapPermissions(requestedPermissions);
|
|
44
|
+
if (!existingPermissions[WALLET_SNAP_PERMISSION_KEY]) {
|
|
45
|
+
return requestedPermissions;
|
|
46
|
+
}
|
|
47
|
+
const snapIdCaveat = existingPermissions[WALLET_SNAP_PERMISSION_KEY].caveats?.find((caveat)=>caveat.type === SnapCaveatType.SnapIds);
|
|
48
|
+
const permittedSnaps = (snapIdCaveat?.value) ?? {};
|
|
49
|
+
const requestedSnaps = requestedPermissions[WALLET_SNAP_PERMISSION_KEY].caveats[0].value;
|
|
50
|
+
const snapIdSet = new Set([
|
|
51
|
+
...Object.keys(permittedSnaps),
|
|
52
|
+
...Object.keys(requestedSnaps)
|
|
53
|
+
]);
|
|
54
|
+
const mergedCaveatValue = [
|
|
55
|
+
...snapIdSet
|
|
56
|
+
].reduce((request, snapId)=>{
|
|
57
|
+
request[snapId] = requestedSnaps[snapId] ?? permittedSnaps[snapId];
|
|
58
|
+
return request;
|
|
59
|
+
}, {});
|
|
60
|
+
requestedPermissions[WALLET_SNAP_PERMISSION_KEY].caveats[0].value = mergedCaveatValue;
|
|
61
|
+
return requestedPermissions;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The `wallet_requestSnaps` method implementation.
|
|
65
|
+
* Tries to install the requested snaps and adds them to the JSON-RPC response.
|
|
66
|
+
*
|
|
67
|
+
* @param req - The JSON-RPC request object.
|
|
68
|
+
* @param res - The JSON-RPC response object.
|
|
69
|
+
* @param _next - The `json-rpc-engine` "next" callback. Not used by this
|
|
70
|
+
* function.
|
|
71
|
+
* @param end - The `json-rpc-engine` "end" callback.
|
|
72
|
+
* @param hooks - The RPC method hooks.
|
|
73
|
+
* @param hooks.installSnaps - A function that tries to install a given snap, prompting the user if necessary.
|
|
74
|
+
* @param hooks.requestPermissions - A function that requests permissions on
|
|
75
|
+
* behalf of a subject.
|
|
76
|
+
* @param hooks.getPermissions - A function that gets the current permissions.
|
|
77
|
+
* @returns A promise that resolves once the JSON-RPC response has been modified.
|
|
78
|
+
* @throws If the params are invalid.
|
|
79
|
+
*/ async function requestSnapsImplementation(req, res, _next, end, { installSnaps, requestPermissions, getPermissions }) {
|
|
80
|
+
const requestedSnaps = req.params;
|
|
81
|
+
if (!isObject(requestedSnaps)) {
|
|
82
|
+
return end(rpcErrors.invalidParams({
|
|
83
|
+
message: '"params" must be an object.'
|
|
84
|
+
}));
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
if (!Object.keys(requestedSnaps).length) {
|
|
88
|
+
throw new Error('Request must have at least one requested snap.');
|
|
89
|
+
}
|
|
90
|
+
const requestedPermissions = {
|
|
91
|
+
[WALLET_SNAP_PERMISSION_KEY]: {
|
|
92
|
+
caveats: [
|
|
93
|
+
{
|
|
94
|
+
type: SnapCaveatType.SnapIds,
|
|
95
|
+
value: requestedSnaps
|
|
96
|
+
}
|
|
97
|
+
]
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
const existingPermissions = await getPermissions();
|
|
101
|
+
if (!existingPermissions) {
|
|
102
|
+
const [, metadata] = await requestPermissions(requestedPermissions);
|
|
103
|
+
res.result = metadata.data[WALLET_SNAP_PERMISSION_KEY];
|
|
104
|
+
} else if (hasRequestedSnaps(existingPermissions, requestedSnaps)) {
|
|
105
|
+
res.result = await handleInstallSnaps(requestedSnaps, installSnaps);
|
|
106
|
+
} else {
|
|
107
|
+
const mergedPermissionsRequest = getSnapPermissionsRequest(existingPermissions, requestedPermissions);
|
|
108
|
+
const [, metadata] = await requestPermissions(mergedPermissionsRequest);
|
|
109
|
+
res.result = metadata.data[WALLET_SNAP_PERMISSION_KEY];
|
|
110
|
+
}
|
|
111
|
+
} catch (error) {
|
|
112
|
+
res.error = error;
|
|
113
|
+
}
|
|
114
|
+
return end();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
//# sourceMappingURL=requestSnaps.js.map
|
|
@@ -0,0 +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,CAACV,gBAAgBW,KAAK,CAAC,CAACC,gBACxC1B,YAAYqB,gBAAgBK;IAEhC;IACA,OAAO;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,0BACdd,mBAAyD,EACzDe,oBAA6B;IAE7B7B,+BAA+B6B;IAE/B,IAAI,CAACf,mBAAmB,CAACX,2BAA2B,EAAE;QACpD,OAAO0B;IACT;IAEA,MAAMb,eAAeF,mBAAmB,CACtCX,2BACD,CAACc,OAAO,EAAEC,KACT,CAACC,SAAiCA,OAAOC,IAAI,KAAKrB,eAAesB,OAAO;IAG1E,MAAMC,iBAAiB,CAACN,cAAcO,KAA6B,KAAK,CAAC;IAEzE,MAAMR,iBACJc,oBAAoB,CAAC1B,2BAA2B,CAACc,OAAO,CAAC,EAAE,CAACM,KAAK;IAEnE,MAAMO,YAAY,IAAIC,IAAI;WACrBP,OAAOC,IAAI,CAACH;WACZE,OAAOC,IAAI,CAACV;KAChB;IAED,MAAMiB,oBAAoB;WAAIF;KAAU,CAACG,MAAM,CAC7C,CAACC,SAASC;QACRD,OAAO,CAACC,OAAO,GAAGpB,cAAc,CAACoB,OAAO,IAAIb,cAAc,CAACa,OAAO;QAClE,OAAOD;IACT,GACA,CAAC;IAGHL,oBAAoB,CAAC1B,2BAA2B,CAACc,OAAO,CAAC,EAAE,CAACM,KAAK,GAC/DS;IAEF,OAAOH;AACT;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,eAAejB,2BACbwB,GAAyC,EACzCC,GAA+C,EAC/CC,KAAc,EACdC,GAA6B,EAC7B,EAAEjC,YAAY,EAAEC,kBAAkB,EAAEC,cAAc,EAAqB;IAEvE,MAAMO,iBAAiBqB,IAAII,MAAM;IACjC,IAAI,CAACtC,SAASa,iBAAiB;QAC7B,OAAOwB,IACLzC,UAAU2C,aAAa,CAAC;YACtBC,SAAS;QACX;IAEJ;IAEA,IAAI;QACF,IAAI,CAAClB,OAAOC,IAAI,CAACV,gBAAgB4B,MAAM,EAAE;YACvC,MAAM,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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/request.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n PermissionType,\n RestrictedMethodOptions,\n PermittedHandlerExport,\n} from '@metamask/permission-controller';\nimport type { JsonRpcParams } from '@metamask/utils';\n\nimport type { methodHandlers } from './permitted';\nimport type { restrictedMethodPermissionBuilders } from './restricted';\n\n/**\n * Get the method implementation from a {@link PermittedHandlerExport}.\n *\n * @template Handler - A permitted handler export.\n */\ntype PermittedMethodImplementation<Handler> =\n Handler extends PermittedHandlerExport<any, infer Args, infer Result>\n ? (args: Args) => Promise<Result>\n : never;\n\n/**\n * Get a JSON-RPC method type from a {@link PermittedHandlerExport} and a method\n * name.\n *\n * @template MethodName - The name of the method.\n * @template Handler - A permitted handler export.\n */\ntype PermittedMethod<\n MethodName extends string,\n Handler,\n> = PermittedMethodImplementation<Handler> extends (\n args: infer Args,\n) => infer Return\n ? (args: { method: MethodName; params?: Args }) => Return\n : never;\n\n/**\n * Get a restricted method implementation from a\n * {@link PermissionSpecificationBuilder}.\n *\n * @template Builder - A permission specification builder.\n */\ntype RestrictedMethodImplementation<Builder> = Builder extends {\n specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n any,\n infer Specification\n >;\n}\n ? Specification['methodImplementation']\n : never;\n\n/**\n * Get a JSON-RPC method type from a {@link PermissionSpecificationBuilder}.\n *\n * @template Builder - A permission specification builder.\n */\ntype RestrictedMethod<Builder extends { targetName: string }> =\n RestrictedMethodImplementation<Builder> extends (\n args: infer Args,\n ) => infer Return\n ? Args extends RestrictedMethodOptions<infer Params>\n ? (args: { method: Builder['targetName']; params?: Params }) => Return\n : never\n : never;\n\n/**\n * A type containing all permitted JSON-RPC methods as functions.\n */\ntype PermittedMethodFunction = {\n [MethodName in keyof typeof methodHandlers]: PermittedMethod<\n MethodName,\n (typeof methodHandlers)[MethodName]\n >;\n};\n\n/**\n * A type containing all restricted JSON-RPC methods as functions.\n */\ntype RestrictedMethodFunction = {\n [Builder in keyof typeof restrictedMethodPermissionBuilders]: RestrictedMethod<\n (typeof restrictedMethodPermissionBuilders)[Builder]\n >;\n};\n\n/**\n * A type containing all supported JSON-RPC methods as functions.\n */\ntype MethodFunction = RestrictedMethodFunction & PermittedMethodFunction;\n\n/**\n * Fallback method name. `wallet_*` is supported by Snaps, but these functions\n * are not implemented in `@metamask/snaps-rpc-methods`, so we don't have a type for\n * them.\n */\ntype WalletMethodName = `wallet_${string}`;\n\n/**\n * Get a typed function if the method is defined in {@link MethodFunction}, or\n * a generic function if the method name extends {@link WalletMethodName}.\n * Otherwise, this returns `never`.\n */\ntype MethodFunctionFallback<MethodName> =\n MethodName extends keyof MethodFunction\n ? MethodFunction[MethodName]\n : MethodName extends WalletMethodName\n ? (args: { method: MethodName; params?: JsonRpcParams }) => Promise<unknown>\n : never;\n\n/**\n * Get the JSON-RPC object from a method name.\n *\n * @template MethodName - The name of the method. In most cases this is inferred\n * from the args.\n */\nexport type ObjectFromMethodName<\n MethodName extends keyof MethodFunction | WalletMethodName,\n> = {\n method: MethodName;\n params?: Parameters<MethodFunctionFallback<MethodName>>[0] extends {\n params?: infer Params;\n }\n ? Params\n : never;\n};\n\nexport type MethodReturnType<\n MethodName extends keyof MethodFunction | WalletMethodName,\n> = ReturnType<MethodFunctionFallback<MethodName>>;\n\n/**\n * A function that takes a JSON-RPC request and returns a JSON-RPC response.\n *\n * @template MethodName - The name of the method. In most cases this is inferred\n * from the args.\n */\nexport type RequestFunction = <\n MethodName extends keyof MethodFunction | WalletMethodName,\n>(\n args: ObjectFromMethodName<MethodName>,\n) => MethodReturnType<MethodName>;\n\n/**\n * The global `snap` object. This is injected into the global scope of a snap.\n */\nexport type SnapsGlobalObject = {\n request: RequestFunction;\n};\n"],"names":[],"mappings":"AAAA,WAoJE"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { getBip32EntropyBuilder } from '../getBip32Entropy';
|
|
2
|
+
import { getBip32PublicKeyBuilder } from '../getBip32PublicKey';
|
|
3
|
+
import { getBip44EntropyBuilder } from '../getBip44Entropy';
|
|
4
|
+
import { invokeSnapBuilder } from '../invokeSnap';
|
|
5
|
+
import { permittedCoinTypesCaveatMapper, PermittedCoinTypesCaveatSpecification } from './permittedCoinTypes';
|
|
6
|
+
import { permittedDerivationPathsCaveatMapper, PermittedDerivationPathsCaveatSpecification } from './permittedDerivationPaths';
|
|
7
|
+
import { snapIdsCaveatMapper, SnapIdsCaveatSpecification } from './snapIds';
|
|
8
|
+
export const caveatSpecifications = {
|
|
9
|
+
...PermittedDerivationPathsCaveatSpecification,
|
|
10
|
+
...PermittedCoinTypesCaveatSpecification,
|
|
11
|
+
...SnapIdsCaveatSpecification
|
|
12
|
+
};
|
|
13
|
+
export const caveatMappers = {
|
|
14
|
+
[getBip32EntropyBuilder.targetName]: permittedDerivationPathsCaveatMapper,
|
|
15
|
+
[getBip32PublicKeyBuilder.targetName]: permittedDerivationPathsCaveatMapper,
|
|
16
|
+
[getBip44EntropyBuilder.targetName]: permittedCoinTypesCaveatMapper,
|
|
17
|
+
[invokeSnapBuilder.targetName]: snapIdsCaveatMapper
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/restricted/caveats/index.ts"],"sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { Json } from '@metamask/utils';\n\nimport { getBip32EntropyBuilder } from '../getBip32Entropy';\nimport { getBip32PublicKeyBuilder } from '../getBip32PublicKey';\nimport { getBip44EntropyBuilder } from '../getBip44Entropy';\nimport { invokeSnapBuilder } from '../invokeSnap';\nimport {\n permittedCoinTypesCaveatMapper,\n PermittedCoinTypesCaveatSpecification,\n} from './permittedCoinTypes';\nimport {\n permittedDerivationPathsCaveatMapper,\n PermittedDerivationPathsCaveatSpecification,\n} from './permittedDerivationPaths';\nimport { snapIdsCaveatMapper, SnapIdsCaveatSpecification } from './snapIds';\n\nexport const caveatSpecifications = {\n ...PermittedDerivationPathsCaveatSpecification,\n ...PermittedCoinTypesCaveatSpecification,\n ...SnapIdsCaveatSpecification,\n} as const;\n\nexport const caveatMappers: Record<\n string,\n (value: Json) => Pick<PermissionConstraint, 'caveats'>\n> = {\n [getBip32EntropyBuilder.targetName]: permittedDerivationPathsCaveatMapper,\n [getBip32PublicKeyBuilder.targetName]: permittedDerivationPathsCaveatMapper,\n [getBip44EntropyBuilder.targetName]: permittedCoinTypesCaveatMapper,\n [invokeSnapBuilder.targetName]: snapIdsCaveatMapper,\n};\n"],"names":["getBip32EntropyBuilder","getBip32PublicKeyBuilder","getBip44EntropyBuilder","invokeSnapBuilder","permittedCoinTypesCaveatMapper","PermittedCoinTypesCaveatSpecification","permittedDerivationPathsCaveatMapper","PermittedDerivationPathsCaveatSpecification","snapIdsCaveatMapper","SnapIdsCaveatSpecification","caveatSpecifications","caveatMappers","targetName"],"mappings":"AAGA,SAASA,sBAAsB,QAAQ,qBAAqB;AAC5D,SAASC,wBAAwB,QAAQ,uBAAuB;AAChE,SAASC,sBAAsB,QAAQ,qBAAqB;AAC5D,SAASC,iBAAiB,QAAQ,gBAAgB;AAClD,SACEC,8BAA8B,EAC9BC,qCAAqC,QAChC,uBAAuB;AAC9B,SACEC,oCAAoC,EACpCC,2CAA2C,QACtC,6BAA6B;AACpC,SAASC,mBAAmB,EAAEC,0BAA0B,QAAQ,YAAY;AAE5E,OAAO,MAAMC,uBAAuB;IAClC,GAAGH,2CAA2C;IAC9C,GAAGF,qCAAqC;IACxC,GAAGI,0BAA0B;AAC/B,EAAW;AAEX,OAAO,MAAME,gBAGT;IACF,CAACX,uBAAuBY,UAAU,CAAC,EAAEN;IACrC,CAACL,yBAAyBW,UAAU,CAAC,EAAEN;IACvC,CAACJ,uBAAuBU,UAAU,CAAC,EAAER;IACrC,CAACD,kBAAkBS,UAAU,CAAC,EAAEJ;AAClC,EAAE"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { providerErrors, rpcErrors } from '@metamask/rpc-errors';
|
|
2
|
+
import { FORBIDDEN_COIN_TYPES, SnapCaveatType } from '@metamask/snaps-utils';
|
|
3
|
+
import { hasProperty, isPlainObject } from '@metamask/utils';
|
|
4
|
+
/**
|
|
5
|
+
* Map a raw value from the `initialPermissions` to a caveat specification.
|
|
6
|
+
* Note that this function does not do any validation, that's handled by the
|
|
7
|
+
* PermissionsController when the permission is requested.
|
|
8
|
+
*
|
|
9
|
+
* @param value - The raw value from the `initialPermissions`.
|
|
10
|
+
* @returns The caveat specification.
|
|
11
|
+
*/ export function permittedCoinTypesCaveatMapper(value) {
|
|
12
|
+
return {
|
|
13
|
+
caveats: [
|
|
14
|
+
{
|
|
15
|
+
type: SnapCaveatType.PermittedCoinTypes,
|
|
16
|
+
value
|
|
17
|
+
}
|
|
18
|
+
]
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Validate the params for `snap_getBip44Entropy`.
|
|
23
|
+
*
|
|
24
|
+
* @param value - The params to validate.
|
|
25
|
+
* @throws If the params are invalid.
|
|
26
|
+
*/ export function validateBIP44Params(value) {
|
|
27
|
+
if (!isPlainObject(value) || !hasProperty(value, 'coinType')) {
|
|
28
|
+
throw rpcErrors.invalidParams({
|
|
29
|
+
message: 'Expected a plain object containing a coin type.'
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
if (typeof value.coinType !== 'number' || !Number.isInteger(value.coinType) || value.coinType < 0 || value.coinType > 0x7fffffff) {
|
|
33
|
+
throw rpcErrors.invalidParams({
|
|
34
|
+
message: 'Invalid "coinType" parameter. Coin type must be a non-negative integer.'
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
if (FORBIDDEN_COIN_TYPES.includes(value.coinType)) {
|
|
38
|
+
throw rpcErrors.invalidParams({
|
|
39
|
+
message: `Coin type ${value.coinType} is forbidden.`
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Validate the coin types values associated with a caveat. This checks if the
|
|
45
|
+
* values are non-negative integers (>= 0).
|
|
46
|
+
*
|
|
47
|
+
* @param caveat - The caveat to validate.
|
|
48
|
+
* @throws If the caveat is invalid.
|
|
49
|
+
*/ export function validateBIP44Caveat(caveat) {
|
|
50
|
+
if (!hasProperty(caveat, 'value') || !Array.isArray(caveat.value) || caveat.value.length === 0) {
|
|
51
|
+
throw rpcErrors.invalidParams({
|
|
52
|
+
message: 'Expected non-empty array of coin types.'
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
caveat.value.forEach(validateBIP44Params);
|
|
56
|
+
}
|
|
57
|
+
export const PermittedCoinTypesCaveatSpecification = {
|
|
58
|
+
[SnapCaveatType.PermittedCoinTypes]: Object.freeze({
|
|
59
|
+
type: SnapCaveatType.PermittedCoinTypes,
|
|
60
|
+
decorator: (method, caveat)=>{
|
|
61
|
+
return async (args)=>{
|
|
62
|
+
const { params } = args;
|
|
63
|
+
validateBIP44Params(params);
|
|
64
|
+
const coinType = caveat.value.find((caveatValue)=>caveatValue.coinType === params.coinType);
|
|
65
|
+
if (!coinType) {
|
|
66
|
+
throw providerErrors.unauthorized({
|
|
67
|
+
message: 'The requested coin type is not permitted. Allowed coin types must be specified in the snap manifest.'
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return await method(args);
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
validator: (caveat)=>validateBIP44Caveat(caveat)
|
|
74
|
+
})
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
//# sourceMappingURL=permittedCoinTypes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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 { FORBIDDEN_COIN_TYPES, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport { hasProperty, isPlainObject } from '@metamask/utils';\n\nimport type { GetBip44EntropyParams } from '../getBip44Entropy';\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;AACjE,SAASC,oBAAoB,EAAEC,cAAc,QAAQ,wBAAwB;AAE7E,SAASC,WAAW,EAAEC,aAAa,QAAQ,kBAAkB;AAI7D;;;;;;;CAOC,GACD,OAAO,SAASC,+BACdC,KAAW;IAEX,OAAO;QACLC,SAAS;YACP;gBACEC,MAAMN,eAAeO,kBAAkB;gBACvCH;YACF;SACD;IACH;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASI,oBACdJ,KAAc;IAEd,IAAI,CAACF,cAAcE,UAAU,CAACH,YAAYG,OAAO,aAAa;QAC5D,MAAMN,UAAUW,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEA,IACE,OAAON,MAAMO,QAAQ,KAAK,YAC1B,CAACC,OAAOC,SAAS,CAACT,MAAMO,QAAQ,KAChCP,MAAMO,QAAQ,GAAG,KACjBP,MAAMO,QAAQ,GAAG,YACjB;QACA,MAAMb,UAAUW,aAAa,CAAC;YAC5BC,SACE;QACJ;IACF;IAEA,IAAIX,qBAAqBe,QAAQ,CAACV,MAAMO,QAAQ,GAAG;QACjD,MAAMb,UAAUW,aAAa,CAAC;YAC5BC,SAAS,CAAC,UAAU,EAAEN,MAAMO,QAAQ,CAAC,cAAc,CAAC;QACtD;IACF;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASI,oBAAoBC,MAA2B;IAC7D,IACE,CAACf,YAAYe,QAAQ,YACrB,CAACC,MAAMC,OAAO,CAACF,OAAOZ,KAAK,KAC3BY,OAAOZ,KAAK,CAACe,MAAM,KAAK,GACxB;QACA,MAAMrB,UAAUW,aAAa,CAAC;YAC5BC,SAAS;QACX;IACF;IAEAM,OAAOZ,KAAK,CAACgB,OAAO,CAACZ;AACvB;AAEA,OAAO,MAAMa,wCAGT;IACF,CAACrB,eAAeO,kBAAkB,CAAC,EAAEe,OAAOC,MAAM,CAAC;QACjDjB,MAAMN,eAAeO,kBAAkB;QACvCiB,WAAW,CACTC,QACAT;YAKA,OAAO,OAAOU;gBACZ,MAAM,EAAEC,MAAM,EAAE,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"}
|