@metamask/snaps-rpc-methods 4.1.0 → 6.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 +24 -2
- package/dist/cjs/endowments/caveats/generic.js +40 -0
- package/dist/cjs/endowments/caveats/generic.js.map +1 -0
- package/dist/cjs/endowments/caveats/index.js +21 -0
- package/dist/cjs/endowments/caveats/index.js.map +1 -0
- package/dist/cjs/endowments/caveats/requestTime.js +99 -0
- package/dist/cjs/endowments/caveats/requestTime.js.map +1 -0
- package/dist/cjs/endowments/cronjob.js +100 -0
- package/dist/cjs/endowments/cronjob.js.map +1 -0
- package/dist/cjs/endowments/enum.js +26 -0
- package/dist/cjs/endowments/enum.js.map +1 -0
- package/dist/cjs/endowments/ethereum-provider.js +43 -0
- package/dist/cjs/endowments/ethereum-provider.js.map +1 -0
- package/dist/cjs/endowments/home-page.js +37 -0
- package/dist/cjs/endowments/home-page.js.map +1 -0
- package/dist/cjs/endowments/index.js +121 -0
- package/dist/cjs/endowments/index.js.map +1 -0
- package/dist/cjs/endowments/keyring.js +104 -0
- package/dist/cjs/endowments/keyring.js.map +1 -0
- package/dist/cjs/endowments/lifecycle-hooks.js +37 -0
- package/dist/cjs/endowments/lifecycle-hooks.js.map +1 -0
- package/dist/cjs/endowments/name-lookup.js +148 -0
- package/dist/cjs/endowments/name-lookup.js.map +1 -0
- package/dist/cjs/endowments/network-access.js +44 -0
- package/dist/cjs/endowments/network-access.js.map +1 -0
- package/dist/cjs/endowments/rpc.js +103 -0
- package/dist/cjs/endowments/rpc.js.map +1 -0
- package/dist/cjs/endowments/signature-insight.js +110 -0
- package/dist/cjs/endowments/signature-insight.js.map +1 -0
- package/dist/cjs/endowments/transaction-insight.js +111 -0
- package/dist/cjs/endowments/transaction-insight.js.map +1 -0
- package/dist/cjs/endowments/web-assembly.js +42 -0
- package/dist/cjs/endowments/web-assembly.js.map +1 -0
- package/dist/cjs/index.js +3 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/permissions.js +62 -0
- package/dist/cjs/permissions.js.map +1 -0
- package/dist/cjs/permitted/createInterface.js +68 -0
- package/dist/cjs/permitted/createInterface.js.map +1 -0
- package/dist/cjs/permitted/getClientStatus.js +40 -0
- package/dist/cjs/permitted/getClientStatus.js.map +1 -0
- package/dist/cjs/permitted/getFile.js +1 -1
- package/dist/cjs/permitted/getFile.js.map +1 -1
- package/dist/cjs/permitted/getInterfaceState.js +67 -0
- package/dist/cjs/permitted/getInterfaceState.js.map +1 -0
- package/dist/cjs/permitted/handlers.js +9 -1
- package/dist/cjs/permitted/handlers.js.map +1 -1
- package/dist/cjs/permitted/index.js.map +1 -1
- package/dist/cjs/permitted/invokeKeyring.js +2 -3
- package/dist/cjs/permitted/invokeKeyring.js.map +1 -1
- package/dist/cjs/permitted/updateInterface.js +70 -0
- package/dist/cjs/permitted/updateInterface.js.map +1 -0
- package/dist/cjs/restricted/dialog.js +51 -24
- package/dist/cjs/restricted/dialog.js.map +1 -1
- package/dist/cjs/restricted/index.js +3 -0
- package/dist/cjs/restricted/index.js.map +1 -1
- package/dist/cjs/restricted/manageState.js +4 -13
- package/dist/cjs/restricted/manageState.js.map +1 -1
- package/dist/esm/endowments/caveats/generic.js +40 -0
- package/dist/esm/endowments/caveats/generic.js.map +1 -0
- package/dist/esm/endowments/caveats/index.js +4 -0
- package/dist/esm/endowments/caveats/index.js.map +1 -0
- package/dist/esm/endowments/caveats/requestTime.js +93 -0
- package/dist/esm/endowments/caveats/requestTime.js.map +1 -0
- package/dist/esm/endowments/cronjob.js +99 -0
- package/dist/esm/endowments/cronjob.js.map +1 -0
- package/dist/esm/endowments/enum.js +16 -0
- package/dist/esm/endowments/enum.js.map +1 -0
- package/dist/esm/endowments/ethereum-provider.js +33 -0
- package/dist/esm/endowments/ethereum-provider.js.map +1 -0
- package/dist/esm/endowments/home-page.js +27 -0
- package/dist/esm/endowments/home-page.js.map +1 -0
- package/dist/esm/endowments/index.js +68 -0
- package/dist/esm/endowments/index.js.map +1 -0
- package/dist/esm/endowments/keyring.js +95 -0
- package/dist/esm/endowments/keyring.js.map +1 -0
- package/dist/esm/endowments/lifecycle-hooks.js +27 -0
- package/dist/esm/endowments/lifecycle-hooks.js.map +1 -0
- package/dist/esm/endowments/name-lookup.js +146 -0
- package/dist/esm/endowments/name-lookup.js.map +1 -0
- package/dist/esm/endowments/network-access.js +34 -0
- package/dist/esm/endowments/network-access.js.map +1 -0
- package/dist/esm/endowments/rpc.js +92 -0
- package/dist/esm/endowments/rpc.js.map +1 -0
- package/dist/esm/endowments/signature-insight.js +103 -0
- package/dist/esm/endowments/signature-insight.js.map +1 -0
- package/dist/esm/endowments/transaction-insight.js +104 -0
- package/dist/esm/endowments/transaction-insight.js.map +1 -0
- package/dist/esm/endowments/web-assembly.js +32 -0
- package/dist/esm/endowments/web-assembly.js.map +1 -0
- package/dist/esm/index.js +3 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/permissions.js +51 -0
- package/dist/esm/permissions.js.map +1 -0
- package/dist/esm/permitted/createInterface.js +58 -0
- package/dist/esm/permitted/createInterface.js.map +1 -0
- package/dist/esm/permitted/getClientStatus.js +32 -0
- package/dist/esm/permitted/getClientStatus.js.map +1 -0
- package/dist/esm/permitted/getFile.js +1 -1
- package/dist/esm/permitted/getFile.js.map +1 -1
- package/dist/esm/permitted/getInterfaceState.js +57 -0
- package/dist/esm/permitted/getInterfaceState.js.map +1 -0
- package/dist/esm/permitted/handlers.js +9 -1
- package/dist/esm/permitted/handlers.js.map +1 -1
- package/dist/esm/permitted/index.js.map +1 -1
- package/dist/esm/permitted/invokeKeyring.js +2 -3
- package/dist/esm/permitted/invokeKeyring.js.map +1 -1
- package/dist/esm/permitted/updateInterface.js +60 -0
- package/dist/esm/permitted/updateInterface.js.map +1 -0
- package/dist/esm/restricted/dialog.js +55 -29
- package/dist/esm/restricted/dialog.js.map +1 -1
- package/dist/esm/restricted/index.js +1 -0
- package/dist/esm/restricted/index.js.map +1 -1
- package/dist/esm/restricted/manageState.js +1 -1
- package/dist/esm/restricted/manageState.js.map +1 -1
- package/dist/types/endowments/caveats/generic.d.ts +19 -0
- package/dist/types/endowments/caveats/index.d.ts +2 -0
- package/dist/types/endowments/caveats/requestTime.d.ts +29 -0
- package/dist/types/endowments/cronjob.d.ts +51 -0
- package/dist/types/endowments/enum.d.ts +13 -0
- package/dist/types/endowments/ethereum-provider.d.ts +14 -0
- package/dist/types/endowments/home-page.d.ts +15 -0
- package/dist/types/endowments/index.d.ts +131 -0
- package/dist/types/endowments/keyring.d.ts +39 -0
- package/dist/types/endowments/lifecycle-hooks.d.ts +15 -0
- package/dist/types/endowments/name-lookup.d.ts +49 -0
- package/dist/types/endowments/network-access.d.ts +14 -0
- package/dist/types/endowments/rpc.d.ts +38 -0
- package/dist/types/endowments/signature-insight.d.ts +39 -0
- package/dist/types/endowments/transaction-insight.d.ts +39 -0
- package/dist/types/endowments/web-assembly.d.ts +14 -0
- package/dist/types/index.d.ts +4 -2
- package/dist/types/permissions.d.ts +16 -0
- package/dist/types/permitted/createInterface.d.ts +150 -0
- package/dist/types/permitted/getClientStatus.d.ts +13 -0
- package/dist/types/permitted/getInterfaceState.d.ts +18 -0
- package/dist/types/permitted/handlers.d.ts +5 -1
- package/dist/types/permitted/index.d.ts +5 -1
- package/dist/types/permitted/invokeKeyring.d.ts +3 -3
- package/dist/types/permitted/updateInterface.d.ts +152 -0
- package/dist/types/restricted/dialog.d.ts +776 -14
- package/dist/types/restricted/index.d.ts +1 -0
- package/dist/types/restricted/manageState.d.ts +18 -0
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/permitted/getFile.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { GetFileParams, GetFileResult } from '@metamask/snaps-sdk';\nimport { AuxiliaryFileEncoding, enumValue } from '@metamask/snaps-sdk';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse, JsonRpcRequest } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport { object, optional, string, union } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nexport const GetFileArgsStruct = object({\n path: string(),\n encoding: optional(\n union([\n enumValue(AuxiliaryFileEncoding.Base64),\n enumValue(AuxiliaryFileEncoding.Hex),\n enumValue(AuxiliaryFileEncoding.Utf8),\n ]),\n ),\n});\n\nexport type InferredGetFileParams = InferMatching<\n typeof GetFileArgsStruct,\n GetFileParams\n>;\n\nconst hookNames: MethodHooksObject<GetFileHooks> = {\n getSnapFile: true,\n};\n\nexport const getFileHandler: PermittedHandlerExport<\n GetFileHooks,\n InferredGetFileParams,\n string\n> = {\n methodNames: ['snap_getFile'],\n implementation,\n hookNames,\n};\n\nexport type GetFileHooks = {\n getSnapFile: (\n path: InferredGetFileParams['path'],\n encoding: InferredGetFileParams['encoding'],\n ) => Promise<string>;\n};\n\n/**\n * The `snap_getFile` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnapFile - The
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/getFile.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { GetFileParams, GetFileResult } from '@metamask/snaps-sdk';\nimport { AuxiliaryFileEncoding, enumValue } from '@metamask/snaps-sdk';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse, JsonRpcRequest } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport { object, optional, string, union } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nexport const GetFileArgsStruct = object({\n path: string(),\n encoding: optional(\n union([\n enumValue(AuxiliaryFileEncoding.Base64),\n enumValue(AuxiliaryFileEncoding.Hex),\n enumValue(AuxiliaryFileEncoding.Utf8),\n ]),\n ),\n});\n\nexport type InferredGetFileParams = InferMatching<\n typeof GetFileArgsStruct,\n GetFileParams\n>;\n\nconst hookNames: MethodHooksObject<GetFileHooks> = {\n getSnapFile: true,\n};\n\nexport const getFileHandler: PermittedHandlerExport<\n GetFileHooks,\n InferredGetFileParams,\n string\n> = {\n methodNames: ['snap_getFile'],\n implementation,\n hookNames,\n};\n\nexport type GetFileHooks = {\n getSnapFile: (\n path: InferredGetFileParams['path'],\n encoding: InferredGetFileParams['encoding'],\n ) => Promise<string>;\n};\n\n/**\n * The `snap_getFile` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.getSnapFile - The function to load a static snap file.\n * @returns Nothing.\n */\nasync function implementation(\n req: JsonRpcRequest<InferredGetFileParams>,\n res: PendingJsonRpcResponse<GetFileResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { getSnapFile }: GetFileHooks,\n): Promise<void> {\n const { params } = req;\n\n assertStruct(\n params,\n GetFileArgsStruct,\n 'Invalid \"snap_getFile\" parameters',\n rpcErrors.invalidParams,\n );\n\n try {\n res.result = await getSnapFile(\n params.path,\n params.encoding ?? AuxiliaryFileEncoding.Base64,\n );\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"],"names":["rpcErrors","AuxiliaryFileEncoding","enumValue","assertStruct","object","optional","string","union","GetFileArgsStruct","path","encoding","Base64","Hex","Utf8","hookNames","getSnapFile","getFileHandler","methodNames","implementation","req","res","_next","end","params","invalidParams","result","error"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,qBAAqB,EAAEC,SAAS,QAAQ,sBAAsB;AAGvE,SAASC,YAAY,QAAQ,kBAAkB;AAC/C,SAASC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,QAAQ,cAAc;AAI9D,OAAO,MAAMC,oBAAoBJ,OAAO;IACtCK,MAAMH;IACNI,UAAUL,SACRE,MAAM;QACJL,UAAUD,sBAAsBU,MAAM;QACtCT,UAAUD,sBAAsBW,GAAG;QACnCV,UAAUD,sBAAsBY,IAAI;KACrC;AAEL,GAAG;AAOH,MAAMC,YAA6C;IACjDC,aAAa;AACf;AAEA,OAAO,MAAMC,iBAIT;IACFC,aAAa;QAAC;KAAe;IAC7BC;IACAJ;AACF,EAAE;AASF;;;;;;;;;;;CAWC,GACD,eAAeI,eACbC,GAA0C,EAC1CC,GAA0C,EAC1CC,KAAc,EACdC,GAA6B,EAC7B,EAAEP,WAAW,EAAgB;IAE7B,MAAM,EAAEQ,MAAM,EAAE,GAAGJ;IAEnBhB,aACEoB,QACAf,mBACA,qCACAR,UAAUwB,aAAa;IAGzB,IAAI;QACFJ,IAAIK,MAAM,GAAG,MAAMV,YACjBQ,OAAOd,IAAI,EACXc,OAAOb,QAAQ,IAAIT,sBAAsBU,MAAM;IAEnD,EAAE,OAAOe,OAAO;QACd,OAAOJ,IAAII;IACb;IAEA,OAAOJ;AACT"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { rpcErrors } from '@metamask/rpc-errors';
|
|
2
|
+
import { StructError, create, object, string } from 'superstruct';
|
|
3
|
+
const hookNames = {
|
|
4
|
+
getInterfaceState: true
|
|
5
|
+
};
|
|
6
|
+
export const getInterfaceStateHandler = {
|
|
7
|
+
methodNames: [
|
|
8
|
+
'snap_getInterfaceState'
|
|
9
|
+
],
|
|
10
|
+
implementation: getGetInterfaceStateImplementation,
|
|
11
|
+
hookNames
|
|
12
|
+
};
|
|
13
|
+
const GetInterfaceStateParametersStruct = object({
|
|
14
|
+
id: string()
|
|
15
|
+
});
|
|
16
|
+
/**
|
|
17
|
+
* The `snap_getInterfaceState` method implementation.
|
|
18
|
+
*
|
|
19
|
+
* @param req - The JSON-RPC request object.
|
|
20
|
+
* @param res - The JSON-RPC response object.
|
|
21
|
+
* @param _next - The `json-rpc-engine` "next" callback. Not used by this
|
|
22
|
+
* function.
|
|
23
|
+
* @param end - The `json-rpc-engine` "end" callback.
|
|
24
|
+
* @param hooks - The RPC method hooks.
|
|
25
|
+
* @param hooks.getInterfaceState - The function to get the interface state.
|
|
26
|
+
* @returns Noting.
|
|
27
|
+
*/ function getGetInterfaceStateImplementation(req, res, _next, end, { getInterfaceState }) {
|
|
28
|
+
const { params } = req;
|
|
29
|
+
try {
|
|
30
|
+
const validatedParams = getValidatedParams(params);
|
|
31
|
+
const { id } = validatedParams;
|
|
32
|
+
res.result = getInterfaceState(id);
|
|
33
|
+
} catch (error) {
|
|
34
|
+
return end(error);
|
|
35
|
+
}
|
|
36
|
+
return end();
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Validate the getInterfaceState method `params` and returns them cast to the correct
|
|
40
|
+
* type. Throws if validation fails.
|
|
41
|
+
*
|
|
42
|
+
* @param params - The unvalidated params object from the method request.
|
|
43
|
+
* @returns The validated getInterfaceState method parameter object.
|
|
44
|
+
*/ function getValidatedParams(params) {
|
|
45
|
+
try {
|
|
46
|
+
return create(params, GetInterfaceStateParametersStruct);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (error instanceof StructError) {
|
|
49
|
+
throw rpcErrors.invalidParams({
|
|
50
|
+
message: `Invalid params: ${error.message}.`
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/* istanbul ignore next */ throw rpcErrors.internal();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=getInterfaceState.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/getInterfaceState.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n GetInterfaceStateParams,\n GetInterfaceStateResult,\n InterfaceState,\n JsonRpcRequest,\n} from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\nimport { StructError, create, object, string } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<GetInterfaceStateMethodHooks> = {\n getInterfaceState: true,\n};\n\nexport type GetInterfaceStateMethodHooks = {\n /**\n * @param id - The interface ID.\n * @returns The interface state.\n */\n getInterfaceState: (id: string) => InterfaceState;\n};\n\nexport const getInterfaceStateHandler: PermittedHandlerExport<\n GetInterfaceStateMethodHooks,\n GetInterfaceStateParameters,\n GetInterfaceStateResult\n> = {\n methodNames: ['snap_getInterfaceState'],\n implementation: getGetInterfaceStateImplementation,\n hookNames,\n};\n\nconst GetInterfaceStateParametersStruct = object({\n id: string(),\n});\n\nexport type GetInterfaceStateParameters = InferMatching<\n typeof GetInterfaceStateParametersStruct,\n GetInterfaceStateParams\n>;\n\n/**\n * The `snap_getInterfaceState` 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.getInterfaceState - The function to get the interface state.\n * @returns Noting.\n */\nfunction getGetInterfaceStateImplementation(\n req: JsonRpcRequest<GetInterfaceStateParameters>,\n res: PendingJsonRpcResponse<GetInterfaceStateResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { getInterfaceState }: GetInterfaceStateMethodHooks,\n): void {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { id } = validatedParams;\n\n res.result = getInterfaceState(id);\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the getInterfaceState 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 getInterfaceState method parameter object.\n */\nfunction getValidatedParams(params: unknown): GetInterfaceStateParameters {\n try {\n return create(params, GetInterfaceStateParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"],"names":["rpcErrors","StructError","create","object","string","hookNames","getInterfaceState","getInterfaceStateHandler","methodNames","implementation","getGetInterfaceStateImplementation","GetInterfaceStateParametersStruct","id","req","res","_next","end","params","validatedParams","getValidatedParams","result","error","invalidParams","message","internal"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AASjD,SAASC,WAAW,EAAEC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,cAAc;AAIlE,MAAMC,YAA6D;IACjEC,mBAAmB;AACrB;AAUA,OAAO,MAAMC,2BAIT;IACFC,aAAa;QAAC;KAAyB;IACvCC,gBAAgBC;IAChBL;AACF,EAAE;AAEF,MAAMM,oCAAoCR,OAAO;IAC/CS,IAAIR;AACN;AAOA;;;;;;;;;;;CAWC,GACD,SAASM,mCACPG,GAAgD,EAChDC,GAAoD,EACpDC,KAAc,EACdC,GAA6B,EAC7B,EAAEV,iBAAiB,EAAgC;IAEnD,MAAM,EAAEW,MAAM,EAAE,GAAGJ;IAEnB,IAAI;QACF,MAAMK,kBAAkBC,mBAAmBF;QAE3C,MAAM,EAAEL,EAAE,EAAE,GAAGM;QAEfJ,IAAIM,MAAM,GAAGd,kBAAkBM;IACjC,EAAE,OAAOS,OAAO;QACd,OAAOL,IAAIK;IACb;IAEA,OAAOL;AACT;AAEA;;;;;;CAMC,GACD,SAASG,mBAAmBF,MAAe;IACzC,IAAI;QACF,OAAOf,OAAOe,QAAQN;IACxB,EAAE,OAAOU,OAAO;QACd,IAAIA,iBAAiBpB,aAAa;YAChC,MAAMD,UAAUsB,aAAa,CAAC;gBAC5BC,SAAS,CAAC,gBAAgB,EAAEF,MAAME,OAAO,CAAC,CAAC,CAAC;YAC9C;QACF;QACA,wBAAwB,GACxB,MAAMvB,UAAUwB,QAAQ;IAC1B;AACF"}
|
|
@@ -1,16 +1,24 @@
|
|
|
1
|
+
import { createInterfaceHandler } from './createInterface';
|
|
1
2
|
import { getAllSnapsHandler } from './getAllSnaps';
|
|
3
|
+
import { getClientStatusHandler } from './getClientStatus';
|
|
2
4
|
import { getFileHandler } from './getFile';
|
|
5
|
+
import { getInterfaceStateHandler } from './getInterfaceState';
|
|
3
6
|
import { getSnapsHandler } from './getSnaps';
|
|
4
7
|
import { invokeKeyringHandler } from './invokeKeyring';
|
|
5
8
|
import { invokeSnapSugarHandler } from './invokeSnapSugar';
|
|
6
9
|
import { requestSnapsHandler } from './requestSnaps';
|
|
10
|
+
import { updateInterfaceHandler } from './updateInterface';
|
|
7
11
|
/* eslint-disable @typescript-eslint/naming-convention */ export const methodHandlers = {
|
|
8
12
|
wallet_getAllSnaps: getAllSnapsHandler,
|
|
9
13
|
wallet_getSnaps: getSnapsHandler,
|
|
10
14
|
wallet_requestSnaps: requestSnapsHandler,
|
|
11
15
|
wallet_invokeSnap: invokeSnapSugarHandler,
|
|
12
16
|
wallet_invokeKeyring: invokeKeyringHandler,
|
|
13
|
-
|
|
17
|
+
snap_getClientStatus: getClientStatusHandler,
|
|
18
|
+
snap_getFile: getFileHandler,
|
|
19
|
+
snap_createInterface: createInterfaceHandler,
|
|
20
|
+
snap_updateInterface: updateInterfaceHandler,
|
|
21
|
+
snap_getInterfaceState: getInterfaceStateHandler
|
|
14
22
|
};
|
|
15
23
|
/* eslint-enable @typescript-eslint/naming-convention */ export const handlers = Object.values(methodHandlers);
|
|
16
24
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/permitted/handlers.ts"],"sourcesContent":["import { getAllSnapsHandler } from './getAllSnaps';\nimport { 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_getAllSnaps: getAllSnapsHandler,\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":["getAllSnapsHandler","getFileHandler","getSnapsHandler","invokeKeyringHandler","invokeSnapSugarHandler","requestSnapsHandler","methodHandlers","wallet_getAllSnaps","wallet_getSnaps","wallet_requestSnaps","wallet_invokeSnap","wallet_invokeKeyring","snap_getFile","handlers","Object","values"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,eAAe,QAAQ,aAAa;AAC7C,SAASC,oBAAoB,QAAQ,kBAAkB;AACvD,SAASC,sBAAsB,QAAQ,oBAAoB;AAC3D,SAASC,mBAAmB,QAAQ,iBAAiB;
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/handlers.ts"],"sourcesContent":["import { createInterfaceHandler } from './createInterface';\nimport { getAllSnapsHandler } from './getAllSnaps';\nimport { getClientStatusHandler } from './getClientStatus';\nimport { getFileHandler } from './getFile';\nimport { getInterfaceStateHandler } from './getInterfaceState';\nimport { getSnapsHandler } from './getSnaps';\nimport { invokeKeyringHandler } from './invokeKeyring';\nimport { invokeSnapSugarHandler } from './invokeSnapSugar';\nimport { requestSnapsHandler } from './requestSnaps';\nimport { updateInterfaceHandler } from './updateInterface';\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const methodHandlers = {\n wallet_getAllSnaps: getAllSnapsHandler,\n wallet_getSnaps: getSnapsHandler,\n wallet_requestSnaps: requestSnapsHandler,\n wallet_invokeSnap: invokeSnapSugarHandler,\n wallet_invokeKeyring: invokeKeyringHandler,\n snap_getClientStatus: getClientStatusHandler,\n snap_getFile: getFileHandler,\n snap_createInterface: createInterfaceHandler,\n snap_updateInterface: updateInterfaceHandler,\n snap_getInterfaceState: getInterfaceStateHandler,\n};\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport const handlers = Object.values(methodHandlers);\n"],"names":["createInterfaceHandler","getAllSnapsHandler","getClientStatusHandler","getFileHandler","getInterfaceStateHandler","getSnapsHandler","invokeKeyringHandler","invokeSnapSugarHandler","requestSnapsHandler","updateInterfaceHandler","methodHandlers","wallet_getAllSnaps","wallet_getSnaps","wallet_requestSnaps","wallet_invokeSnap","wallet_invokeKeyring","snap_getClientStatus","snap_getFile","snap_createInterface","snap_updateInterface","snap_getInterfaceState","handlers","Object","values"],"mappings":"AAAA,SAASA,sBAAsB,QAAQ,oBAAoB;AAC3D,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,sBAAsB,QAAQ,oBAAoB;AAC3D,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,wBAAwB,QAAQ,sBAAsB;AAC/D,SAASC,eAAe,QAAQ,aAAa;AAC7C,SAASC,oBAAoB,QAAQ,kBAAkB;AACvD,SAASC,sBAAsB,QAAQ,oBAAoB;AAC3D,SAASC,mBAAmB,QAAQ,iBAAiB;AACrD,SAASC,sBAAsB,QAAQ,oBAAoB;AAE3D,uDAAuD,GACvD,OAAO,MAAMC,iBAAiB;IAC5BC,oBAAoBV;IACpBW,iBAAiBP;IACjBQ,qBAAqBL;IACrBM,mBAAmBP;IACnBQ,sBAAsBT;IACtBU,sBAAsBd;IACtBe,cAAcd;IACde,sBAAsBlB;IACtBmB,sBAAsBV;IACtBW,wBAAwBhB;AAC1B,EAAE;AACF,sDAAsD,GAEtD,OAAO,MAAMiB,WAAWC,OAAOC,MAAM,CAACb,gBAAgB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/permitted/index.ts"],"sourcesContent":["import type { GetAllSnapsHooks } from './getAllSnaps';\nimport type { GetSnapsHooks } from './getSnaps';\nimport type { RequestSnapsHooks } from './requestSnaps';\n\nexport type PermittedRpcMethodHooks = GetAllSnapsHooks &\n GetSnapsHooks &\n RequestSnapsHooks;\n\nexport * from './handlers';\nexport * from './middleware';\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/index.ts"],"sourcesContent":["import type { CreateInterfaceMethodHooks } from './createInterface';\nimport type { GetAllSnapsHooks } from './getAllSnaps';\nimport type { GetClientStatusHooks } from './getClientStatus';\nimport type { GetInterfaceStateMethodHooks } from './getInterfaceState';\nimport type { GetSnapsHooks } from './getSnaps';\nimport type { RequestSnapsHooks } from './requestSnaps';\nimport type { UpdateInterfaceMethodHooks } from './updateInterface';\n\nexport type PermittedRpcMethodHooks = GetAllSnapsHooks &\n GetClientStatusHooks &\n GetSnapsHooks &\n RequestSnapsHooks &\n CreateInterfaceMethodHooks &\n UpdateInterfaceMethodHooks &\n GetInterfaceStateMethodHooks;\n\nexport * from './handlers';\nexport * from './middleware';\n"],"names":[],"mappings":"AAgBA,cAAc,aAAa;AAC3B,cAAc,eAAe"}
|
|
@@ -43,7 +43,7 @@ const hookNames = {
|
|
|
43
43
|
// We expect the MM middleware stack to always add the origin to requests
|
|
44
44
|
const { origin } = req;
|
|
45
45
|
const { snapId, request } = params;
|
|
46
|
-
if (!origin || !hasPermission(
|
|
46
|
+
if (!origin || !hasPermission(WALLET_SNAP_PERMISSION_KEY)) {
|
|
47
47
|
return end(rpcErrors.invalidRequest({
|
|
48
48
|
message: `The snap "${snapId}" is not connected to "${origin}". Please connect before invoking the snap.`
|
|
49
49
|
}));
|
|
@@ -58,7 +58,7 @@ const hookNames = {
|
|
|
58
58
|
message: 'The request must have a method.'
|
|
59
59
|
}));
|
|
60
60
|
}
|
|
61
|
-
const allowedMethods = getAllowedKeyringMethods(
|
|
61
|
+
const allowedMethods = getAllowedKeyringMethods();
|
|
62
62
|
if (!allowedMethods.includes(request.method)) {
|
|
63
63
|
return end(rpcErrors.invalidRequest({
|
|
64
64
|
message: `The origin "${origin}" is not allowed to invoke the method "${request.method}".`
|
|
@@ -67,7 +67,6 @@ const hookNames = {
|
|
|
67
67
|
try {
|
|
68
68
|
res.result = await handleSnapRpcRequest({
|
|
69
69
|
snapId,
|
|
70
|
-
origin,
|
|
71
70
|
request,
|
|
72
71
|
handler: HandlerType.OnKeyringRequest
|
|
73
72
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/permitted/invokeKeyring.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n InvokeKeyringParams,\n InvokeKeyringResult,\n InvokeSnapParams,\n} from '@metamask/snaps-sdk';\nimport type { Snap, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { HandlerType, WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse, JsonRpcRequest } from '@metamask/utils';\nimport { hasProperty, type Json } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getValidatedParams } from './invokeSnapSugar';\n\nconst hookNames: MethodHooksObject<InvokeKeyringHooks> = {\n hasPermission: true,\n handleSnapRpcRequest: true,\n getSnap: true,\n getAllowedKeyringMethods: true,\n};\n\n/**\n * `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.\n */\nexport const invokeKeyringHandler: PermittedHandlerExport<\n InvokeKeyringHooks,\n InvokeSnapParams,\n InvokeKeyringResult\n> = {\n methodNames: ['wallet_invokeKeyring'],\n implementation: invokeKeyringImplementation,\n hookNames,\n};\n\nexport type InvokeKeyringHooks = {\n hasPermission: (
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/invokeKeyring.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n InvokeKeyringParams,\n InvokeKeyringResult,\n InvokeSnapParams,\n} from '@metamask/snaps-sdk';\nimport type { Snap, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { HandlerType, WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse, JsonRpcRequest } from '@metamask/utils';\nimport { hasProperty, type Json } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getValidatedParams } from './invokeSnapSugar';\n\nconst hookNames: MethodHooksObject<InvokeKeyringHooks> = {\n hasPermission: true,\n handleSnapRpcRequest: true,\n getSnap: true,\n getAllowedKeyringMethods: true,\n};\n\n/**\n * `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.\n */\nexport const invokeKeyringHandler: PermittedHandlerExport<\n InvokeKeyringHooks,\n InvokeSnapParams,\n InvokeKeyringResult\n> = {\n methodNames: ['wallet_invokeKeyring'],\n implementation: invokeKeyringImplementation,\n hookNames,\n};\n\nexport type InvokeKeyringHooks = {\n hasPermission: (permissionName: string) => boolean;\n\n handleSnapRpcRequest: ({\n snapId,\n handler,\n request,\n }: Omit<SnapRpcHookArgs, 'origin'> & { snapId: string }) => Promise<unknown>;\n\n getSnap: (snapId: string) => Snap | undefined;\n\n getAllowedKeyringMethods: () => string[];\n};\n\n/**\n * The `wallet_invokeKeyring` method implementation.\n * Invokes onKeyringRequest if the snap requested is installed and connected to the dapp.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.handleSnapRpcRequest - Invokes a snap with a given RPC request.\n * @param hooks.hasPermission - Checks whether a given origin has a given permission.\n * @param hooks.getSnap - Gets information about a given snap.\n * @param hooks.getAllowedKeyringMethods - Get the list of allowed Keyring\n * methods for a given origin.\n * @returns Nothing.\n */\nasync function invokeKeyringImplementation(\n req: JsonRpcRequest<InvokeKeyringParams>,\n res: PendingJsonRpcResponse<InvokeKeyringResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n handleSnapRpcRequest,\n hasPermission,\n getSnap,\n getAllowedKeyringMethods,\n }: InvokeKeyringHooks,\n): Promise<void> {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n // We expect the MM middleware stack to always add the origin to requests\n const { origin } = req as JsonRpcRequest & { origin: string };\n const { snapId, request } = params;\n\n if (!origin || !hasPermission(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();\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 request,\n handler: HandlerType.OnKeyringRequest,\n })) as Json;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"],"names":["rpcErrors","HandlerType","WALLET_SNAP_PERMISSION_KEY","hasProperty","getValidatedParams","hookNames","hasPermission","handleSnapRpcRequest","getSnap","getAllowedKeyringMethods","invokeKeyringHandler","methodNames","implementation","invokeKeyringImplementation","req","res","_next","end","params","error","origin","snapId","request","invalidRequest","message","method","allowedMethods","includes","result","handler","OnKeyringRequest"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AAOjD,SAASC,WAAW,EAAEC,0BAA0B,QAAQ,wBAAwB;AAEhF,SAASC,WAAW,QAAmB,kBAAkB;AAGzD,SAASC,kBAAkB,QAAQ,oBAAoB;AAEvD,MAAMC,YAAmD;IACvDC,eAAe;IACfC,sBAAsB;IACtBC,SAAS;IACTC,0BAA0B;AAC5B;AAEA;;CAEC,GACD,OAAO,MAAMC,uBAIT;IACFC,aAAa;QAAC;KAAuB;IACrCC,gBAAgBC;IAChBR;AACF,EAAE;AAgBF;;;;;;;;;;;;;;;;CAgBC,GACD,eAAeQ,4BACbC,GAAwC,EACxCC,GAAgD,EAChDC,KAAc,EACdC,GAA6B,EAC7B,EACEV,oBAAoB,EACpBD,aAAa,EACbE,OAAO,EACPC,wBAAwB,EACL;IAErB,IAAIS;IACJ,IAAI;QACFA,SAASd,mBAAmBU,IAAII,MAAM;IACxC,EAAE,OAAOC,OAAO;QACd,OAAOF,IAAIE;IACb;IAEA,yEAAyE;IACzE,MAAM,EAAEC,MAAM,EAAE,GAAGN;IACnB,MAAM,EAAEO,MAAM,EAAEC,OAAO,EAAE,GAAGJ;IAE5B,IAAI,CAACE,UAAU,CAACd,cAAcJ,6BAA6B;QACzD,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;IACvB,IAAI,CAACiB,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;YACAC;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 { ComponentStruct } from '@metamask/snaps-sdk';
|
|
3
|
+
import { StructError, create, object, string } from 'superstruct';
|
|
4
|
+
const hookNames = {
|
|
5
|
+
updateInterface: true
|
|
6
|
+
};
|
|
7
|
+
export const updateInterfaceHandler = {
|
|
8
|
+
methodNames: [
|
|
9
|
+
'snap_updateInterface'
|
|
10
|
+
],
|
|
11
|
+
implementation: getUpdateInterfaceImplementation,
|
|
12
|
+
hookNames
|
|
13
|
+
};
|
|
14
|
+
const UpdateInterfaceParametersStruct = object({
|
|
15
|
+
id: string(),
|
|
16
|
+
ui: ComponentStruct
|
|
17
|
+
});
|
|
18
|
+
/**
|
|
19
|
+
* The `snap_updateInterface` method implementation.
|
|
20
|
+
*
|
|
21
|
+
* @param req - The JSON-RPC request object.
|
|
22
|
+
* @param res - The JSON-RPC response object.
|
|
23
|
+
* @param _next - The `json-rpc-engine` "next" callback. Not used by this
|
|
24
|
+
* function.
|
|
25
|
+
* @param end - The `json-rpc-engine` "end" callback.
|
|
26
|
+
* @param hooks - The RPC method hooks.
|
|
27
|
+
* @param hooks.updateInterface - The function to update the interface.
|
|
28
|
+
* @returns Nothing.
|
|
29
|
+
*/ async function getUpdateInterfaceImplementation(req, res, _next, end, { updateInterface }) {
|
|
30
|
+
const { params } = req;
|
|
31
|
+
try {
|
|
32
|
+
const validatedParams = getValidatedParams(params);
|
|
33
|
+
const { id, ui } = validatedParams;
|
|
34
|
+
await updateInterface(id, ui);
|
|
35
|
+
res.result = null;
|
|
36
|
+
} catch (error) {
|
|
37
|
+
return end(error);
|
|
38
|
+
}
|
|
39
|
+
return end();
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Validate the updateInterface method `params` and returns them cast to the correct
|
|
43
|
+
* type. Throws if validation fails.
|
|
44
|
+
*
|
|
45
|
+
* @param params - The unvalidated params object from the method request.
|
|
46
|
+
* @returns The validated updateInterface method parameter object.
|
|
47
|
+
*/ function getValidatedParams(params) {
|
|
48
|
+
try {
|
|
49
|
+
return create(params, UpdateInterfaceParametersStruct);
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (error instanceof StructError) {
|
|
52
|
+
throw rpcErrors.invalidParams({
|
|
53
|
+
message: `Invalid params: ${error.message}.`
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/* istanbul ignore next */ throw rpcErrors.internal();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=updateInterface.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/permitted/updateInterface.ts"],"sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n Component,\n UpdateInterfaceParams,\n UpdateInterfaceResult,\n JsonRpcRequest,\n} from '@metamask/snaps-sdk';\nimport { ComponentStruct } from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\nimport { StructError, create, object, string } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<UpdateInterfaceMethodHooks> = {\n updateInterface: true,\n};\n\nexport type UpdateInterfaceMethodHooks = {\n /**\n * @param id - The interface ID.\n * @param ui - The UI components.\n */\n updateInterface: (id: string, ui: Component) => Promise<void>;\n};\n\nexport const updateInterfaceHandler: PermittedHandlerExport<\n UpdateInterfaceMethodHooks,\n UpdateInterfaceParameters,\n UpdateInterfaceResult\n> = {\n methodNames: ['snap_updateInterface'],\n implementation: getUpdateInterfaceImplementation,\n hookNames,\n};\n\nconst UpdateInterfaceParametersStruct = object({\n id: string(),\n ui: ComponentStruct,\n});\n\nexport type UpdateInterfaceParameters = InferMatching<\n typeof UpdateInterfaceParametersStruct,\n UpdateInterfaceParams\n>;\n\n/**\n * The `snap_updateInterface` 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.updateInterface - The function to update the interface.\n * @returns Nothing.\n */\nasync function getUpdateInterfaceImplementation(\n req: JsonRpcRequest<UpdateInterfaceParameters>,\n res: PendingJsonRpcResponse<UpdateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { updateInterface }: UpdateInterfaceMethodHooks,\n): Promise<void> {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { id, ui } = validatedParams;\n\n await updateInterface(id, ui);\n res.result = null;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the updateInterface 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 updateInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): UpdateInterfaceParameters {\n try {\n return create(params, UpdateInterfaceParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"],"names":["rpcErrors","ComponentStruct","StructError","create","object","string","hookNames","updateInterface","updateInterfaceHandler","methodNames","implementation","getUpdateInterfaceImplementation","UpdateInterfaceParametersStruct","id","ui","req","res","_next","end","params","validatedParams","getValidatedParams","result","error","invalidParams","message","internal"],"mappings":"AAEA,SAASA,SAAS,QAAQ,uBAAuB;AAOjD,SAASC,eAAe,QAAQ,sBAAsB;AAGtD,SAASC,WAAW,EAAEC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,cAAc;AAIlE,MAAMC,YAA2D;IAC/DC,iBAAiB;AACnB;AAUA,OAAO,MAAMC,yBAIT;IACFC,aAAa;QAAC;KAAuB;IACrCC,gBAAgBC;IAChBL;AACF,EAAE;AAEF,MAAMM,kCAAkCR,OAAO;IAC7CS,IAAIR;IACJS,IAAIb;AACN;AAOA;;;;;;;;;;;CAWC,GACD,eAAeU,iCACbI,GAA8C,EAC9CC,GAAkD,EAClDC,KAAc,EACdC,GAA6B,EAC7B,EAAEX,eAAe,EAA8B;IAE/C,MAAM,EAAEY,MAAM,EAAE,GAAGJ;IAEnB,IAAI;QACF,MAAMK,kBAAkBC,mBAAmBF;QAE3C,MAAM,EAAEN,EAAE,EAAEC,EAAE,EAAE,GAAGM;QAEnB,MAAMb,gBAAgBM,IAAIC;QAC1BE,IAAIM,MAAM,GAAG;IACf,EAAE,OAAOC,OAAO;QACd,OAAOL,IAAIK;IACb;IAEA,OAAOL;AACT;AAEA;;;;;;CAMC,GACD,SAASG,mBAAmBF,MAAe;IACzC,IAAI;QACF,OAAOhB,OAAOgB,QAAQP;IACxB,EAAE,OAAOW,OAAO;QACd,IAAIA,iBAAiBrB,aAAa;YAChC,MAAMF,UAAUwB,aAAa,CAAC;gBAC5BC,SAAS,CAAC,gBAAgB,EAAEF,MAAME,OAAO,CAAC,CAAC,CAAC;YAC9C;QACF;QACA,wBAAwB,GACxB,MAAMzB,UAAU0B,QAAQ;IAC1B;AACF"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { PermissionType, SubjectType } from '@metamask/permission-controller';
|
|
2
2
|
import { rpcErrors } from '@metamask/rpc-errors';
|
|
3
|
-
import { DialogType, ComponentStruct, enumValue } from '@metamask/snaps-sdk';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { DialogType, ComponentStruct, enumValue, union } from '@metamask/snaps-sdk';
|
|
4
|
+
import { createUnion } from '@metamask/snaps-utils';
|
|
5
|
+
import { hasProperty } from '@metamask/utils';
|
|
6
|
+
import { create, enums, object, optional, size, string, type } from 'superstruct';
|
|
6
7
|
const methodName = 'snap_dialog';
|
|
7
8
|
const PlaceholderStruct = optional(size(string(), 1, 40));
|
|
8
9
|
/**
|
|
@@ -31,8 +32,8 @@ const PlaceholderStruct = optional(size(string(), 1, 40));
|
|
|
31
32
|
};
|
|
32
33
|
const methodHooks = {
|
|
33
34
|
showDialog: true,
|
|
34
|
-
|
|
35
|
-
|
|
35
|
+
createInterface: true,
|
|
36
|
+
getInterface: true
|
|
36
37
|
};
|
|
37
38
|
export const dialogBuilder = Object.freeze({
|
|
38
39
|
targetName: methodName,
|
|
@@ -48,19 +49,44 @@ const BaseParamsStruct = type({
|
|
|
48
49
|
DialogType.Prompt
|
|
49
50
|
])
|
|
50
51
|
});
|
|
51
|
-
const
|
|
52
|
+
const AlertParametersWithContentStruct = object({
|
|
52
53
|
type: enumValue(DialogType.Alert),
|
|
53
54
|
content: ComponentStruct
|
|
54
55
|
});
|
|
55
|
-
const
|
|
56
|
+
const AlertParametersWithIdStruct = object({
|
|
57
|
+
type: enumValue(DialogType.Alert),
|
|
58
|
+
id: string()
|
|
59
|
+
});
|
|
60
|
+
const AlertParametersStruct = union([
|
|
61
|
+
AlertParametersWithContentStruct,
|
|
62
|
+
AlertParametersWithIdStruct
|
|
63
|
+
]);
|
|
64
|
+
const ConfirmationParametersWithContentStruct = object({
|
|
56
65
|
type: enumValue(DialogType.Confirmation),
|
|
57
66
|
content: ComponentStruct
|
|
58
67
|
});
|
|
59
|
-
const
|
|
68
|
+
const ConfirmationParametersWithIdStruct = object({
|
|
69
|
+
type: enumValue(DialogType.Confirmation),
|
|
70
|
+
id: string()
|
|
71
|
+
});
|
|
72
|
+
const ConfirmationParametersStruct = union([
|
|
73
|
+
ConfirmationParametersWithContentStruct,
|
|
74
|
+
ConfirmationParametersWithIdStruct
|
|
75
|
+
]);
|
|
76
|
+
const PromptParametersWithContentStruct = object({
|
|
60
77
|
type: enumValue(DialogType.Prompt),
|
|
61
78
|
content: ComponentStruct,
|
|
62
79
|
placeholder: PlaceholderStruct
|
|
63
80
|
});
|
|
81
|
+
const PromptParametersWithIdStruct = object({
|
|
82
|
+
type: enumValue(DialogType.Prompt),
|
|
83
|
+
id: string(),
|
|
84
|
+
placeholder: PlaceholderStruct
|
|
85
|
+
});
|
|
86
|
+
const PromptParametersStruct = union([
|
|
87
|
+
PromptParametersWithContentStruct,
|
|
88
|
+
PromptParametersWithIdStruct
|
|
89
|
+
]);
|
|
64
90
|
const DialogParametersStruct = union([
|
|
65
91
|
AlertParametersStruct,
|
|
66
92
|
ConfirmationParametersStruct,
|
|
@@ -77,21 +103,30 @@ const structs = {
|
|
|
77
103
|
* @param hooks - The RPC method hooks.
|
|
78
104
|
* @param hooks.showDialog - A function that shows the specified dialog in the
|
|
79
105
|
* MetaMask UI and returns the appropriate value for the dialog type.
|
|
80
|
-
* @param hooks.
|
|
81
|
-
*
|
|
82
|
-
* @param hooks.maybeUpdatePhishingList - A function that updates the phishing list if needed.
|
|
106
|
+
* @param hooks.createInterface - A function that creates the interface in SnapInterfaceController.
|
|
107
|
+
* @param hooks.getInterface - A function that gets an interface from SnapInterfaceController.
|
|
83
108
|
* @returns The method implementation which return value depends on the dialog
|
|
84
109
|
* type, valid return types are: string, boolean, null.
|
|
85
|
-
*/ export function getDialogImplementation({ showDialog,
|
|
110
|
+
*/ export function getDialogImplementation({ showDialog, createInterface, getInterface }) {
|
|
86
111
|
return async function dialogImplementation(args) {
|
|
87
112
|
const { params, context: { origin } } = args;
|
|
88
113
|
const validatedType = getValidatedType(params);
|
|
89
114
|
const validatedParams = getValidatedParams(params, structs[validatedType]);
|
|
90
|
-
const { content } = validatedParams;
|
|
91
|
-
await maybeUpdatePhishingList();
|
|
92
|
-
validateComponentLinks(content, isOnPhishingList);
|
|
93
115
|
const placeholder = validatedParams.type === DialogType.Prompt ? validatedParams.placeholder : undefined;
|
|
94
|
-
|
|
116
|
+
if (hasProperty(validatedParams, 'content')) {
|
|
117
|
+
const id = await createInterface(origin, validatedParams.content);
|
|
118
|
+
return showDialog(origin, validatedType, id, placeholder);
|
|
119
|
+
}
|
|
120
|
+
// Verify that the passed interface ID is valid.
|
|
121
|
+
// This will throw if the interface ID is invalid (not created by the snap or doesn't exist)
|
|
122
|
+
try {
|
|
123
|
+
getInterface(origin, validatedParams.id);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
throw rpcErrors.invalidParams({
|
|
126
|
+
message: `Invalid params: ${error.message}`
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return showDialog(origin, validatedType, validatedParams.id, placeholder);
|
|
95
130
|
};
|
|
96
131
|
}
|
|
97
132
|
/**
|
|
@@ -118,20 +153,11 @@ const structs = {
|
|
|
118
153
|
* @returns The validated confirm method parameter object.
|
|
119
154
|
*/ function getValidatedParams(params, struct) {
|
|
120
155
|
try {
|
|
121
|
-
return
|
|
156
|
+
return createUnion(params, struct, 'type');
|
|
122
157
|
} catch (error) {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
throw rpcErrors.invalidParams({
|
|
127
|
-
message: 'Invalid params: Alerts or confirmations may not specify a "placeholder" field.'
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
throw rpcErrors.invalidParams({
|
|
131
|
-
message: `Invalid params: ${error.message}.`
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
/* istanbul ignore next */ throw rpcErrors.internal();
|
|
158
|
+
throw rpcErrors.invalidParams({
|
|
159
|
+
message: `Invalid params: ${error.message}`
|
|
160
|
+
});
|
|
135
161
|
}
|
|
136
162
|
}
|
|
137
163
|
|
|
@@ -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 { DialogType, ComponentStruct, enumValue } from '@metamask/snaps-sdk';\nimport type { DialogParams, EnumToUnion, Component } from '@metamask/snaps-sdk';\nimport { validateComponentLinks } 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","enumValue","validateComponentLinks","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,EAAEC,SAAS,QAAQ,sBAAsB;AAE7E,SAASC,sBAAsB,QAAQ,wBAAwB;AAI/D,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,EACrB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,OAAO,CAACM,cAAc;QAEzE,MAAM,EAAEX,OAAO,EAAE,GAAGa;QAEpB,MAAMtB;QAENxB,uBAAuBiC,SAASV;QAEhC,MAAMa,cACJU,gBAAgBtC,IAAI,KAAKX,WAAWkC,MAAM,GACtCe,gBAAgBV,WAAW,GAC3BY;QAEN,OAAO1B,WAAWqB,QAAQC,eAAeX,SAASG;IACpD;AACF;AAEA;;;;;;CAMC,GACD,SAASS,iBAAiBJ,MAAe;IACvC,IAAI;QACF,OAAOxC,OAAOwC,QAAQb,kBAAkBpB,IAAI;IAC9C,EAAE,OAAOyC,OAAO;QACd,MAAMrD,UAAUsD,aAAa,CAAC;YAC5BC,SAAS,CAAC,oCAAoC,EAAEzB,OAAO0B,MAAM,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
|
+
{"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 {\n DialogType,\n ComponentStruct,\n enumValue,\n union,\n} from '@metamask/snaps-sdk';\nimport type {\n DialogParams,\n EnumToUnion,\n Component,\n InterfaceState,\n SnapId,\n} from '@metamask/snaps-sdk';\nimport { createUnion } from '@metamask/snaps-utils';\nimport type { InferMatching } from '@metamask/snaps-utils';\nimport { hasProperty, 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 type,\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 id: string,\n placeholder?: Placeholder,\n) => Promise<null | boolean | string>;\n\ntype CreateInterface = (snapId: string, content: Component) => Promise<string>;\ntype GetInterface = (\n snapId: string,\n id: string,\n) => { content: Component; snapId: SnapId; state: InterfaceState };\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 id - The interface ID.\n * @param placeholder - The placeholder for the Prompt dialog input.\n */\n showDialog: ShowDialog;\n\n /**\n * @param snapId - The Snap ID creating the interface.\n * @param content - The content of the interface.\n */\n createInterface: CreateInterface;\n /**\n * @param snapId - The SnapId requesting the interface.\n * @param id - The interface ID.\n */\n getInterface: GetInterface;\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 createInterface: true,\n getInterface: 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 AlertParametersWithContentStruct = object({\n type: enumValue(DialogType.Alert),\n content: ComponentStruct,\n});\nconst AlertParametersWithIdStruct = object({\n type: enumValue(DialogType.Alert),\n id: string(),\n});\n\nconst AlertParametersStruct = union([\n AlertParametersWithContentStruct,\n AlertParametersWithIdStruct,\n]);\n\nconst ConfirmationParametersWithContentStruct = object({\n type: enumValue(DialogType.Confirmation),\n content: ComponentStruct,\n});\n\nconst ConfirmationParametersWithIdStruct = object({\n type: enumValue(DialogType.Confirmation),\n id: string(),\n});\n\nconst ConfirmationParametersStruct = union([\n ConfirmationParametersWithContentStruct,\n ConfirmationParametersWithIdStruct,\n]);\n\nconst PromptParametersWithContentStruct = object({\n type: enumValue(DialogType.Prompt),\n content: ComponentStruct,\n placeholder: PlaceholderStruct,\n});\n\nconst PromptParametersWithIdStruct = object({\n type: enumValue(DialogType.Prompt),\n id: string(),\n placeholder: PlaceholderStruct,\n});\n\nconst PromptParametersStruct = union([\n PromptParametersWithContentStruct,\n PromptParametersWithIdStruct,\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.createInterface - A function that creates the interface in SnapInterfaceController.\n * @param hooks.getInterface - A function that gets an interface from SnapInterfaceController.\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 createInterface,\n getInterface,\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 placeholder =\n validatedParams.type === DialogType.Prompt\n ? validatedParams.placeholder\n : undefined;\n\n if (hasProperty(validatedParams, 'content')) {\n const id = await createInterface(\n origin,\n validatedParams.content as Component,\n );\n return showDialog(origin, validatedType, id, placeholder);\n }\n\n // Verify that the passed interface ID is valid.\n // This will throw if the interface ID is invalid (not created by the snap or doesn't exist)\n try {\n getInterface(origin, validatedParams.id);\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}`,\n });\n }\n\n return showDialog(origin, validatedType, validatedParams.id, 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, any>,\n): DialogParameters {\n try {\n return createUnion(params, struct, 'type');\n } catch (error) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}`,\n });\n }\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","DialogType","ComponentStruct","enumValue","union","createUnion","hasProperty","create","enums","object","optional","size","string","type","methodName","PlaceholderStruct","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getDialogImplementation","subjectTypes","Snap","showDialog","createInterface","getInterface","dialogBuilder","Object","freeze","BaseParamsStruct","Alert","Confirmation","Prompt","AlertParametersWithContentStruct","content","AlertParametersWithIdStruct","id","AlertParametersStruct","ConfirmationParametersWithContentStruct","ConfirmationParametersWithIdStruct","ConfirmationParametersStruct","PromptParametersWithContentStruct","placeholder","PromptParametersWithIdStruct","PromptParametersStruct","DialogParametersStruct","structs","dialogImplementation","args","params","context","origin","validatedType","getValidatedType","validatedParams","getValidatedParams","undefined","error","invalidParams","message","values","join","struct"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AACjD,SACEC,UAAU,EACVC,eAAe,EACfC,SAAS,EACTC,KAAK,QACA,sBAAsB;AAQ7B,SAASC,WAAW,QAAQ,wBAAwB;AAEpD,SAASC,WAAW,QAA4B,kBAAkB;AAElE,SACEC,MAAM,EACNC,KAAK,EACLC,MAAM,EACNC,QAAQ,EACRC,IAAI,EACJ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,kBAAkBnB,IAAI;IAC9C,EAAE,OAAO+C,OAAO;QACd,MAAM5D,UAAU6D,aAAa,CAAC;YAC5BC,SAAS,CAAC,oCAAoC,EAAEhC,OAAOiC,MAAM,CAC3D9D,YACA+D,IAAI,CAAC,MAAM,CAAC,CAAC;QACjB;IACF;AACF;AAEA;;;;;;;CAOC,GACD,SAASN,mBACPN,MAAe,EACfa,MAAwB;IAExB,IAAI;QACF,OAAO5D,YAAY+C,QAAQa,QAAQ;IACrC,EAAE,OAAOL,OAAO;QACd,MAAM5D,UAAU6D,aAAa,CAAC;YAC5BC,SAAS,CAAC,gBAAgB,EAAEF,MAAME,OAAO,CAAC,CAAC;QAC7C;IACF;AACF"}
|
|
@@ -9,6 +9,7 @@ import { manageAccountsBuilder } from './manageAccounts';
|
|
|
9
9
|
import { manageStateBuilder } from './manageState';
|
|
10
10
|
import { notifyBuilder } from './notify';
|
|
11
11
|
export { WALLET_SNAP_PERMISSION_KEY } from './invokeSnap';
|
|
12
|
+
export { getEncryptionKey } from './manageState';
|
|
12
13
|
export const restrictedMethodPermissionBuilders = {
|
|
13
14
|
[dialogBuilder.targetName]: dialogBuilder,
|
|
14
15
|
[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 { 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;
|
|
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';\nexport { getEncryptionKey } from './manageState';\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","getEncryptionKey","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;AAC1D,SAASC,gBAAgB,QAAQ,gBAAgB;AAajD,OAAO,MAAMC,qCAAqC;IAChD,CAACZ,cAAca,UAAU,CAAC,EAAEb;IAC5B,CAACC,uBAAuBY,UAAU,CAAC,EAAEZ;IACrC,CAACC,yBAAyBW,UAAU,CAAC,EAAEX;IACvC,CAACC,uBAAuBU,UAAU,CAAC,EAAEV;IACrC,CAACC,kBAAkBS,UAAU,CAAC,EAAET;IAChC,CAACE,kBAAkBO,UAAU,CAAC,EAAEP;IAChC,CAACE,mBAAmBK,UAAU,CAAC,EAAEL;IACjC,CAACC,cAAcI,UAAU,CAAC,EAAEJ;IAC5B,CAACF,sBAAsBM,UAAU,CAAC,EAAEN;IACpC,CAACF,iBAAiBQ,UAAU,CAAC,EAAER;AACjC,EAAW;AAEX,cAAc,YAAY"}
|
|
@@ -54,7 +54,7 @@ export const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
|
|
|
54
54
|
* @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key
|
|
55
55
|
* from.
|
|
56
56
|
* @returns The state encryption key.
|
|
57
|
-
*/ async function getEncryptionKey({ mnemonicPhrase, snapId }) {
|
|
57
|
+
*/ export async function getEncryptionKey({ mnemonicPhrase, snapId }) {
|
|
58
58
|
return await deriveEntropy({
|
|
59
59
|
mnemonicPhrase,
|
|
60
60
|
input: snapId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/restricted/manageState.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { ManageStateParams, ManageStateResult } from '@metamask/snaps-sdk';\nimport { ManageStateOperation } from '@metamask/snaps-sdk';\nimport { STATE_ENCRYPTION_MAGIC_VALUE, parseJson } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray, Hex } from '@metamask/utils';\nimport { isObject, getJsonSize, assert, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropy } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string, encrypted: boolean) => void;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (snapId: string, encrypted: boolean) => string;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (\n snapId: string,\n newState: string,\n encrypted: boolean,\n ) => void;\n\n /**\n * Encrypts data with a key. This is assumed to perform symmetric encryption.\n *\n * @param key - The key to use for encryption, in hexadecimal format.\n * @param data - The JSON data to encrypt.\n * @returns The ciphertext as a string. The format for this string is\n * dependent on the implementation, but MUST be a string.\n */\n encrypt: (key: string, data: Json) => Promise<string>;\n\n /**\n * Decrypts data with a key. This is assumed to perform symmetric decryption.\n *\n * @param key - The key to use for decryption, in hexadecimal format.\n * @param cipherText - The ciphertext to decrypt. The format for this string\n * is dependent on the implementation, but MUST be a string.\n * @returns The decrypted data as a JSON object.\n */\n decrypt: (key: Hex, cipherText: string) => Promise<unknown>;\n};\n\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n encrypt: true,\n decrypt: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n mnemonicPhrase: Uint8Array;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The state encryption key.\n */\nasync function getEncryptionKey({\n mnemonicPhrase,\n snapId,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropy({\n mnemonicPhrase,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n });\n}\n\ntype EncryptStateArgs = GetEncryptionKeyArgs & {\n state: Json;\n encryptFunction: ManageStateMethodHooks['encrypt'];\n};\n\n/**\n * Encrypt the state using a deterministic encryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to encrypt.\n * @param args.encryptFunction - The function to use for encrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function encryptState({\n state,\n encryptFunction,\n ...keyArgs\n}: EncryptStateArgs) {\n const encryptionKey = await getEncryptionKey(keyArgs);\n return await encryptFunction(encryptionKey, state);\n}\n\ntype DecryptStateArgs = GetEncryptionKeyArgs & {\n state: string;\n decryptFunction: ManageStateMethodHooks['decrypt'];\n};\n\n/**\n * Decrypt the state using a deterministic decryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to decrypt.\n * @param args.decryptFunction - The function to use for decrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function decryptState({\n state,\n decryptFunction,\n ...keyArgs\n}: DecryptStateArgs) {\n try {\n const encryptionKey = await getEncryptionKey(keyArgs);\n const decryptedState = await decryptFunction(encryptionKey, state);\n\n assert(isValidJson(decryptedState));\n\n return decryptedState as Record<string, Json>;\n } catch {\n throw rpcErrors.internal({\n message: 'Failed to decrypt snap state, the state must be corrupted.',\n });\n }\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase\n * of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @param hooks.encrypt - A function that encrypts the given state.\n * @param hooks.decrypt - A function that decrypts the given state.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getMnemonic,\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n encrypt,\n decrypt,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateParams>,\n ): Promise<ManageStateResult> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const validatedParams = getValidatedParams(params, method);\n\n // If the encrypted param is undefined or null we default to true.\n const shouldEncrypt = validatedParams.encrypted ?? true;\n\n // We only need to prompt the user when the mnemonic is needed\n // which it isn't for the clear operation or unencrypted storage.\n if (\n shouldEncrypt &&\n validatedParams.operation !== ManageStateOperation.ClearState\n ) {\n await getUnlockPromise(true);\n }\n\n switch (validatedParams.operation) {\n case ManageStateOperation.ClearState:\n clearSnapState(origin, shouldEncrypt);\n return null;\n\n case ManageStateOperation.GetState: {\n const state = getSnapState(origin, shouldEncrypt);\n if (state === null) {\n return state;\n }\n return shouldEncrypt\n ? await decryptState({\n state,\n decryptFunction: decrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : parseJson<Record<string, Json>>(state);\n }\n\n case ManageStateOperation.UpdateState: {\n const finalizedState = shouldEncrypt\n ? await encryptState({\n state: validatedParams.newState,\n encryptFunction: encrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : JSON.stringify(validatedParams.newState);\n\n updateSnapState(origin, finalizedState, shouldEncrypt);\n return null;\n }\n\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${\n validatedParams.operation as string\n }\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @param method - RPC method name used for debugging errors.\n * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n storageSizeLimit = STORAGE_SIZE_LIMIT,\n): ManageStateParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState, encrypted } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !Object.values(ManageStateOperation).includes(\n operation as ManageStateOperation,\n )\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (encrypted !== undefined && typeof encrypted !== 'boolean') {\n throw rpcErrors.invalidParams({\n message: '\"encrypted\" parameter must be a boolean if specified.',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be a plain object.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n let size;\n try {\n // `getJsonSize` will throw if the state is not JSON serializable.\n size = getJsonSize(newState);\n } catch {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be JSON serializable.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must not exceed ${storageSizeLimit} bytes in size.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","ManageStateOperation","STATE_ENCRYPTION_MAGIC_VALUE","parseJson","isObject","getJsonSize","assert","isValidJson","deriveEntropy","STATE_ENCRYPTION_SALT","methodName","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getManageStateImplementation","subjectTypes","Snap","getMnemonic","getUnlockPromise","clearSnapState","getSnapState","updateSnapState","encrypt","decrypt","manageStateBuilder","Object","freeze","STORAGE_SIZE_LIMIT","getEncryptionKey","mnemonicPhrase","snapId","input","salt","magic","encryptState","state","encryptFunction","keyArgs","encryptionKey","decryptState","decryptFunction","decryptedState","internal","message","manageState","options","params","method","context","origin","validatedParams","getValidatedParams","shouldEncrypt","encrypted","operation","ClearState","GetState","UpdateState","finalizedState","newState","JSON","stringify","invalidParams","storageSizeLimit","values","includes","undefined","data","receivedNewState","size"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAAuB;AAEjD,SAASC,oBAAoB,QAAQ,sBAAsB;AAC3D,SAASC,4BAA4B,EAAEC,SAAS,QAAQ,wBAAwB;AAEhF,SAASC,QAAQ,EAAEC,WAAW,EAAEC,MAAM,EAAEC,WAAW,QAAQ,kBAAkB;AAG7E,SAASC,aAAa,QAAQ,WAAW;AAEzC,oDAAoD;AACpD,OAAO,MAAMC,wBAAwB,8BAA8B;AAEnE,MAAMC,aAAa;AAuEnB;;;;;;;;;CASC,GACD,OAAO,MAAMC,uBAIT,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EAC4B;IACvC,OAAO;QACLC,gBAAgBhB,eAAeiB,gBAAgB;QAC/CC,YAAYN;QACZE;QACAK,sBAAsBC,6BAA6BL;QACnDM,cAAc;YAACpB,YAAYqB,IAAI;SAAC;IAClC;AACF,EAAE;AAEF,MAAMP,cAAyD;IAC7DQ,aAAa;IACbC,kBAAkB;IAClBC,gBAAgB;IAChBC,cAAc;IACdC,iBAAiB;IACjBC,SAAS;IACTC,SAAS;AACX;AAEA,OAAO,MAAMC,qBAAqBC,OAAOC,MAAM,CAAC;IAC9Cd,YAAYN;IACZC;IACAE;AACF,GAAY;AAEZ,OAAO,MAAMkB,qBAAqB,UAAU,CAAC,mBAAmB;AAOhE;;;;;;;;;;;;CAYC,GACD,eAAeC,iBAAiB,EAC9BC,cAAc,EACdC,MAAM,EACe;IACrB,OAAO,MAAM1B,cAAc;QACzByB;QACAE,OAAOD;QACPE,MAAM3B;QACN4B,OAAOnC;IACT;AACF;AAOA;;;;;;;;;;;CAWC,GACD,eAAeoC,aAAa,EAC1BC,KAAK,EACLC,eAAe,EACf,GAAGC,SACc;IACjB,MAAMC,gBAAgB,MAAMV,iB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YAAY0D;QACrB,EAAE,OAAM;YACN,MAAM/D,UAAUkE,aAAa,CAAC;gBAC5BnB,SAAS,CAAC,QAAQ,EAAEI,OAAO,kEAAkE,CAAC;gBAC9FoB,MAAM;oBACJC,kBACE,OAAOT,aAAa,cAAc,cAAcA;gBACpD;YACF;QACF;QAEA,IAAIU,OAAON,kBAAkB;YAC3B,MAAMnE,UAAUkE,aAAa,CAAC;gBAC5BnB,SAAS,CAAC,QAAQ,EAAEI,OAAO,wDAAwD,EAAEgB,iBAAiB,eAAe,CAAC;gBACtHI,MAAM;oBACJC,kBACE,OAAOT,aAAa,cAAc,cAAcA;gBACpD;YACF;QACF;IACF;IAEA,OAAOb;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../src/restricted/manageState.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { ManageStateParams, ManageStateResult } from '@metamask/snaps-sdk';\nimport { ManageStateOperation } from '@metamask/snaps-sdk';\nimport { STATE_ENCRYPTION_MAGIC_VALUE, parseJson } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray, Hex } from '@metamask/utils';\nimport { isObject, getJsonSize, assert, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropy } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string, encrypted: boolean) => void;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (snapId: string, encrypted: boolean) => string;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (\n snapId: string,\n newState: string,\n encrypted: boolean,\n ) => void;\n\n /**\n * Encrypts data with a key. This is assumed to perform symmetric encryption.\n *\n * @param key - The key to use for encryption, in hexadecimal format.\n * @param data - The JSON data to encrypt.\n * @returns The ciphertext as a string. The format for this string is\n * dependent on the implementation, but MUST be a string.\n */\n encrypt: (key: string, data: Json) => Promise<string>;\n\n /**\n * Decrypts data with a key. This is assumed to perform symmetric decryption.\n *\n * @param key - The key to use for decryption, in hexadecimal format.\n * @param cipherText - The ciphertext to decrypt. The format for this string\n * is dependent on the implementation, but MUST be a string.\n * @returns The decrypted data as a JSON object.\n */\n decrypt: (key: Hex, cipherText: string) => Promise<unknown>;\n};\n\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n encrypt: true,\n decrypt: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n mnemonicPhrase: Uint8Array;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The state encryption key.\n */\nexport async function getEncryptionKey({\n mnemonicPhrase,\n snapId,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropy({\n mnemonicPhrase,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n });\n}\n\ntype EncryptStateArgs = GetEncryptionKeyArgs & {\n state: Json;\n encryptFunction: ManageStateMethodHooks['encrypt'];\n};\n\n/**\n * Encrypt the state using a deterministic encryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to encrypt.\n * @param args.encryptFunction - The function to use for encrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function encryptState({\n state,\n encryptFunction,\n ...keyArgs\n}: EncryptStateArgs) {\n const encryptionKey = await getEncryptionKey(keyArgs);\n return await encryptFunction(encryptionKey, state);\n}\n\ntype DecryptStateArgs = GetEncryptionKeyArgs & {\n state: string;\n decryptFunction: ManageStateMethodHooks['decrypt'];\n};\n\n/**\n * Decrypt the state using a deterministic decryption algorithm, based on the\n * snap ID and mnemonic phrase.\n *\n * @param args - The encryption args.\n * @param args.state - The state to decrypt.\n * @param args.decryptFunction - The function to use for decrypting the state.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key\n * from.\n * @returns The encrypted state.\n */\nasync function decryptState({\n state,\n decryptFunction,\n ...keyArgs\n}: DecryptStateArgs) {\n try {\n const encryptionKey = await getEncryptionKey(keyArgs);\n const decryptedState = await decryptFunction(encryptionKey, state);\n\n assert(isValidJson(decryptedState));\n\n return decryptedState as Record<string, Json>;\n } catch {\n throw rpcErrors.internal({\n message: 'Failed to decrypt snap state, the state must be corrupted.',\n });\n }\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase\n * of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @param hooks.encrypt - A function that encrypts the given state.\n * @param hooks.decrypt - A function that decrypts the given state.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getMnemonic,\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n encrypt,\n decrypt,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateParams>,\n ): Promise<ManageStateResult> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const validatedParams = getValidatedParams(params, method);\n\n // If the encrypted param is undefined or null we default to true.\n const shouldEncrypt = validatedParams.encrypted ?? true;\n\n // We only need to prompt the user when the mnemonic is needed\n // which it isn't for the clear operation or unencrypted storage.\n if (\n shouldEncrypt &&\n validatedParams.operation !== ManageStateOperation.ClearState\n ) {\n await getUnlockPromise(true);\n }\n\n switch (validatedParams.operation) {\n case ManageStateOperation.ClearState:\n clearSnapState(origin, shouldEncrypt);\n return null;\n\n case ManageStateOperation.GetState: {\n const state = getSnapState(origin, shouldEncrypt);\n if (state === null) {\n return state;\n }\n return shouldEncrypt\n ? await decryptState({\n state,\n decryptFunction: decrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : parseJson<Record<string, Json>>(state);\n }\n\n case ManageStateOperation.UpdateState: {\n const finalizedState = shouldEncrypt\n ? await encryptState({\n state: validatedParams.newState,\n encryptFunction: encrypt,\n mnemonicPhrase: await getMnemonic(),\n snapId: origin,\n })\n : JSON.stringify(validatedParams.newState);\n\n updateSnapState(origin, finalizedState, shouldEncrypt);\n return null;\n }\n\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${\n validatedParams.operation as string\n }\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @param method - RPC method name used for debugging errors.\n * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n storageSizeLimit = STORAGE_SIZE_LIMIT,\n): ManageStateParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState, encrypted } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !Object.values(ManageStateOperation).includes(\n operation as ManageStateOperation,\n )\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (encrypted !== undefined && typeof encrypted !== 'boolean') {\n throw rpcErrors.invalidParams({\n message: '\"encrypted\" parameter must be a boolean if specified.',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be a plain object.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n let size;\n try {\n // `getJsonSize` will throw if the state is not JSON serializable.\n size = getJsonSize(newState);\n } catch {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must be JSON serializable.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"updateState\" parameter: The new state must not exceed ${storageSizeLimit} bytes in size.`,\n data: {\n receivedNewState:\n typeof newState === 'undefined' ? 'undefined' : newState,\n },\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"],"names":["PermissionType","SubjectType","rpcErrors","ManageStateOperation","STATE_ENCRYPTION_MAGIC_VALUE","parseJson","isObject","getJsonSize","assert","isValidJson","deriveEntropy","STATE_ENCRYPTION_SALT","methodName","specificationBuilder","allowedCaveats","methodHooks","permissionType","RestrictedMethod","targetName","methodImplementation","getManageStateImplementation","subjectTypes","Snap","getMnemonic","getUnlockPromise","clearSnapState","getSnapState","updateSnapState","encrypt","decrypt","manageStateBuilder","Object","freeze","STORAGE_SIZE_LIMIT","getEncryptionKey","mnemonicPhrase","snapId","input","salt","magic","encryptState","state","encryptFunction","keyArgs","encryptionKey","decryptState","decryptFunction","decryptedState","internal","message","manageState","options","params","method","context","origin","validatedParams","getValidatedParams","shouldEncrypt","encrypted","operation","ClearState","GetState","UpdateState","finalizedState","newState","JSON","stringify","invalidParams","storageSizeLimit","values","includes","undefined","data","receivedNewState","size"],"mappings":"AAKA,SAASA,cAAc,EAAEC,WAAW,QAAQ,kCAAkC;AAC9E,SAASC,SAAS,QAAQ,uBAA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