@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
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "updateInterfaceHandler", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return updateInterfaceHandler;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
const _rpcerrors = require("@metamask/rpc-errors");
|
|
12
|
+
const _snapssdk = require("@metamask/snaps-sdk");
|
|
13
|
+
const _superstruct = require("superstruct");
|
|
14
|
+
const hookNames = {
|
|
15
|
+
updateInterface: true
|
|
16
|
+
};
|
|
17
|
+
const updateInterfaceHandler = {
|
|
18
|
+
methodNames: [
|
|
19
|
+
'snap_updateInterface'
|
|
20
|
+
],
|
|
21
|
+
implementation: getUpdateInterfaceImplementation,
|
|
22
|
+
hookNames
|
|
23
|
+
};
|
|
24
|
+
const UpdateInterfaceParametersStruct = (0, _superstruct.object)({
|
|
25
|
+
id: (0, _superstruct.string)(),
|
|
26
|
+
ui: _snapssdk.ComponentStruct
|
|
27
|
+
});
|
|
28
|
+
/**
|
|
29
|
+
* The `snap_updateInterface` method implementation.
|
|
30
|
+
*
|
|
31
|
+
* @param req - The JSON-RPC request object.
|
|
32
|
+
* @param res - The JSON-RPC response object.
|
|
33
|
+
* @param _next - The `json-rpc-engine` "next" callback. Not used by this
|
|
34
|
+
* function.
|
|
35
|
+
* @param end - The `json-rpc-engine` "end" callback.
|
|
36
|
+
* @param hooks - The RPC method hooks.
|
|
37
|
+
* @param hooks.updateInterface - The function to update the interface.
|
|
38
|
+
* @returns Nothing.
|
|
39
|
+
*/ async function getUpdateInterfaceImplementation(req, res, _next, end, { updateInterface }) {
|
|
40
|
+
const { params } = req;
|
|
41
|
+
try {
|
|
42
|
+
const validatedParams = getValidatedParams(params);
|
|
43
|
+
const { id, ui } = validatedParams;
|
|
44
|
+
await updateInterface(id, ui);
|
|
45
|
+
res.result = null;
|
|
46
|
+
} catch (error) {
|
|
47
|
+
return end(error);
|
|
48
|
+
}
|
|
49
|
+
return end();
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Validate the updateInterface method `params` and returns them cast to the correct
|
|
53
|
+
* type. Throws if validation fails.
|
|
54
|
+
*
|
|
55
|
+
* @param params - The unvalidated params object from the method request.
|
|
56
|
+
* @returns The validated updateInterface method parameter object.
|
|
57
|
+
*/ function getValidatedParams(params) {
|
|
58
|
+
try {
|
|
59
|
+
return (0, _superstruct.create)(params, UpdateInterfaceParametersStruct);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (error instanceof _superstruct.StructError) {
|
|
62
|
+
throw _rpcerrors.rpcErrors.invalidParams({
|
|
63
|
+
message: `Invalid params: ${error.message}.`
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/* istanbul ignore next */ throw _rpcerrors.rpcErrors.internal();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
//# 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":["updateInterfaceHandler","hookNames","updateInterface","methodNames","implementation","getUpdateInterfaceImplementation","UpdateInterfaceParametersStruct","object","id","string","ui","ComponentStruct","req","res","_next","end","params","validatedParams","getValidatedParams","result","error","create","StructError","rpcErrors","invalidParams","message","internal"],"mappings":";;;;+BA4BaA;;;eAAAA;;;2BA1Ba;0BAOM;6BAGoB;AAIpD,MAAMC,YAA2D;IAC/DC,iBAAiB;AACnB;AAUO,MAAMF,yBAIT;IACFG,aAAa;QAAC;KAAuB;IACrCC,gBAAgBC;IAChBJ;AACF;AAEA,MAAMK,kCAAkCC,IAAAA,mBAAM,EAAC;IAC7CC,IAAIC,IAAAA,mBAAM;IACVC,IAAIC,yBAAe;AACrB;AAOA;;;;;;;;;;;CAWC,GACD,eAAeN,iCACbO,GAA8C,EAC9CC,GAAkD,EAClDC,KAAc,EACdC,GAA6B,EAC7B,EAAEb,eAAe,EAA8B;IAE/C,MAAM,EAAEc,MAAM,EAAE,GAAGJ;IAEnB,IAAI;QACF,MAAMK,kBAAkBC,mBAAmBF;QAE3C,MAAM,EAAER,EAAE,EAAEE,EAAE,EAAE,GAAGO;QAEnB,MAAMf,gBAAgBM,IAAIE;QAC1BG,IAAIM,MAAM,GAAG;IACf,EAAE,OAAOC,OAAO;QACd,OAAOL,IAAIK;IACb;IAEA,OAAOL;AACT;AAEA;;;;;;CAMC,GACD,SAASG,mBAAmBF,MAAe;IACzC,IAAI;QACF,OAAOK,IAAAA,mBAAM,EAACL,QAAQV;IACxB,EAAE,OAAOc,OAAO;QACd,IAAIA,iBAAiBE,wBAAW,EAAE;YAChC,MAAMC,oBAAS,CAACC,aAAa,CAAC;gBAC5BC,SAAS,CAAC,gBAAgB,EAAEL,MAAMK,OAAO,CAAC,CAAC,CAAC;YAC9C;QACF;QACA,wBAAwB,GACxB,MAAMF,oBAAS,CAACG,QAAQ;IAC1B;AACF"}
|
|
@@ -20,6 +20,7 @@ const _permissioncontroller = require("@metamask/permission-controller");
|
|
|
20
20
|
const _rpcerrors = require("@metamask/rpc-errors");
|
|
21
21
|
const _snapssdk = require("@metamask/snaps-sdk");
|
|
22
22
|
const _snapsutils = require("@metamask/snaps-utils");
|
|
23
|
+
const _utils = require("@metamask/utils");
|
|
23
24
|
const _superstruct = require("superstruct");
|
|
24
25
|
const methodName = 'snap_dialog';
|
|
25
26
|
const PlaceholderStruct = (0, _superstruct.optional)((0, _superstruct.size)((0, _superstruct.string)(), 1, 40));
|
|
@@ -49,8 +50,8 @@ const PlaceholderStruct = (0, _superstruct.optional)((0, _superstruct.size)((0,
|
|
|
49
50
|
};
|
|
50
51
|
const methodHooks = {
|
|
51
52
|
showDialog: true,
|
|
52
|
-
|
|
53
|
-
|
|
53
|
+
createInterface: true,
|
|
54
|
+
getInterface: true
|
|
54
55
|
};
|
|
55
56
|
const dialogBuilder = Object.freeze({
|
|
56
57
|
targetName: methodName,
|
|
@@ -66,20 +67,45 @@ const BaseParamsStruct = (0, _superstruct.type)({
|
|
|
66
67
|
_snapssdk.DialogType.Prompt
|
|
67
68
|
])
|
|
68
69
|
});
|
|
69
|
-
const
|
|
70
|
+
const AlertParametersWithContentStruct = (0, _superstruct.object)({
|
|
70
71
|
type: (0, _snapssdk.enumValue)(_snapssdk.DialogType.Alert),
|
|
71
72
|
content: _snapssdk.ComponentStruct
|
|
72
73
|
});
|
|
73
|
-
const
|
|
74
|
+
const AlertParametersWithIdStruct = (0, _superstruct.object)({
|
|
75
|
+
type: (0, _snapssdk.enumValue)(_snapssdk.DialogType.Alert),
|
|
76
|
+
id: (0, _superstruct.string)()
|
|
77
|
+
});
|
|
78
|
+
const AlertParametersStruct = (0, _snapssdk.union)([
|
|
79
|
+
AlertParametersWithContentStruct,
|
|
80
|
+
AlertParametersWithIdStruct
|
|
81
|
+
]);
|
|
82
|
+
const ConfirmationParametersWithContentStruct = (0, _superstruct.object)({
|
|
74
83
|
type: (0, _snapssdk.enumValue)(_snapssdk.DialogType.Confirmation),
|
|
75
84
|
content: _snapssdk.ComponentStruct
|
|
76
85
|
});
|
|
77
|
-
const
|
|
86
|
+
const ConfirmationParametersWithIdStruct = (0, _superstruct.object)({
|
|
87
|
+
type: (0, _snapssdk.enumValue)(_snapssdk.DialogType.Confirmation),
|
|
88
|
+
id: (0, _superstruct.string)()
|
|
89
|
+
});
|
|
90
|
+
const ConfirmationParametersStruct = (0, _snapssdk.union)([
|
|
91
|
+
ConfirmationParametersWithContentStruct,
|
|
92
|
+
ConfirmationParametersWithIdStruct
|
|
93
|
+
]);
|
|
94
|
+
const PromptParametersWithContentStruct = (0, _superstruct.object)({
|
|
78
95
|
type: (0, _snapssdk.enumValue)(_snapssdk.DialogType.Prompt),
|
|
79
96
|
content: _snapssdk.ComponentStruct,
|
|
80
97
|
placeholder: PlaceholderStruct
|
|
81
98
|
});
|
|
82
|
-
const
|
|
99
|
+
const PromptParametersWithIdStruct = (0, _superstruct.object)({
|
|
100
|
+
type: (0, _snapssdk.enumValue)(_snapssdk.DialogType.Prompt),
|
|
101
|
+
id: (0, _superstruct.string)(),
|
|
102
|
+
placeholder: PlaceholderStruct
|
|
103
|
+
});
|
|
104
|
+
const PromptParametersStruct = (0, _snapssdk.union)([
|
|
105
|
+
PromptParametersWithContentStruct,
|
|
106
|
+
PromptParametersWithIdStruct
|
|
107
|
+
]);
|
|
108
|
+
const DialogParametersStruct = (0, _snapssdk.union)([
|
|
83
109
|
AlertParametersStruct,
|
|
84
110
|
ConfirmationParametersStruct,
|
|
85
111
|
PromptParametersStruct
|
|
@@ -89,16 +115,26 @@ const structs = {
|
|
|
89
115
|
[_snapssdk.DialogType.Confirmation]: ConfirmationParametersStruct,
|
|
90
116
|
[_snapssdk.DialogType.Prompt]: PromptParametersStruct
|
|
91
117
|
};
|
|
92
|
-
function getDialogImplementation({ showDialog,
|
|
118
|
+
function getDialogImplementation({ showDialog, createInterface, getInterface }) {
|
|
93
119
|
return async function dialogImplementation(args) {
|
|
94
120
|
const { params, context: { origin } } = args;
|
|
95
121
|
const validatedType = getValidatedType(params);
|
|
96
122
|
const validatedParams = getValidatedParams(params, structs[validatedType]);
|
|
97
|
-
const { content } = validatedParams;
|
|
98
|
-
await maybeUpdatePhishingList();
|
|
99
|
-
(0, _snapsutils.validateComponentLinks)(content, isOnPhishingList);
|
|
100
123
|
const placeholder = validatedParams.type === _snapssdk.DialogType.Prompt ? validatedParams.placeholder : undefined;
|
|
101
|
-
|
|
124
|
+
if ((0, _utils.hasProperty)(validatedParams, 'content')) {
|
|
125
|
+
const id = await createInterface(origin, validatedParams.content);
|
|
126
|
+
return showDialog(origin, validatedType, id, placeholder);
|
|
127
|
+
}
|
|
128
|
+
// Verify that the passed interface ID is valid.
|
|
129
|
+
// This will throw if the interface ID is invalid (not created by the snap or doesn't exist)
|
|
130
|
+
try {
|
|
131
|
+
getInterface(origin, validatedParams.id);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
throw _rpcerrors.rpcErrors.invalidParams({
|
|
134
|
+
message: `Invalid params: ${error.message}`
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
return showDialog(origin, validatedType, validatedParams.id, placeholder);
|
|
102
138
|
};
|
|
103
139
|
}
|
|
104
140
|
/**
|
|
@@ -125,20 +161,11 @@ function getDialogImplementation({ showDialog, isOnPhishingList, maybeUpdatePhis
|
|
|
125
161
|
* @returns The validated confirm method parameter object.
|
|
126
162
|
*/ function getValidatedParams(params, struct) {
|
|
127
163
|
try {
|
|
128
|
-
return (0,
|
|
164
|
+
return (0, _snapsutils.createUnion)(params, struct, 'type');
|
|
129
165
|
} catch (error) {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
throw _rpcerrors.rpcErrors.invalidParams({
|
|
134
|
-
message: 'Invalid params: Alerts or confirmations may not specify a "placeholder" field.'
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
throw _rpcerrors.rpcErrors.invalidParams({
|
|
138
|
-
message: `Invalid params: ${error.message}.`
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
/* istanbul ignore next */ throw _rpcerrors.rpcErrors.internal();
|
|
166
|
+
throw _rpcerrors.rpcErrors.invalidParams({
|
|
167
|
+
message: `Invalid params: ${error.message}`
|
|
168
|
+
});
|
|
142
169
|
}
|
|
143
170
|
}
|
|
144
171
|
|
|
@@ -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":["dialogBuilder","getDialogImplementation","methodName","PlaceholderStruct","optional","size","string","specificationBuilder","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","showDialog","isOnPhishingList","maybeUpdatePhishingList","Object","freeze","BaseParamsStruct","type","enums","DialogType","Alert","Confirmation","Prompt","AlertParametersStruct","object","enumValue","content","ComponentStruct","ConfirmationParametersStruct","PromptParametersStruct","placeholder","DialogParametersStruct","union","structs","dialogImplementation","args","params","context","origin","validatedType","getValidatedType","validatedParams","getValidatedParams","validateComponentLinks","undefined","create","error","rpcErrors","invalidParams","message","values","join","struct","StructError","key","errorType","internal"],"mappings":";;;;;;;;;;;IA6GaA,aAAa;eAAbA;;IAyDGC,uBAAuB;eAAvBA;;;sCAjK4B;2BAClB;0BAC6B;4BAEhB;6BAchC;AAIP,MAAMC,aAAa;AAEnB,MAAMC,oBAAoBC,IAAAA,qBAAQ,EAACC,IAAAA,iBAAI,EAACC,IAAAA,mBAAM,KAAI,GAAG;AA2CrD;;;;;;;;;;;;;CAaC,GACD,MAAMC,uBAIF,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EACuB;IAClC,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,gBAAgB;QAC/CC,YAAYX;QACZM;QACAM,sBAAsBb,wBAAwBQ;QAC9CM,cAAc;YAACC,iCAAW,CAACC,IAAI;SAAC;IAClC;AACF;AAEA,MAAMR,cAAoD;IACxDS,YAAY;IACZC,kBAAkB;IAClBC,yBAAyB;AAC3B;AAEO,MAAMpB,gBAAgBqB,OAAOC,MAAM,CAAC;IACzCT,YAAYX;IACZK;IACAE;AACF;AAEA,gFAAgF;AAChF,iDAAiD;AACjD,MAAMc,mBAAmBC,IAAAA,iBAAI,EAAC;IAC5BA,MAAMC,IAAAA,kBAAK,EAAC;QAACC,oBAAU,CAACC,KAAK;QAAED,oBAAU,CAACE,YAAY;QAAEF,oBAAU,CAACG,MAAM;KAAC;AAC5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QpB,kBAAkBC,IAAI;IAC9C,EAAE,OAAO6B,OAAO;QACd,MAAMC,oBAAS,CAACC,aAAa,CAAC;YAC5BC,SAAS,CAAC,oCAAoC,EAAEnC,OAAOoC,MAAM,CAC3D/B,oBAAU,EACVgC,IAAI,CAAC,MAAM,CAAC,CAAC;QACjB;IACF;AACF;AAEA;;;;;;;CAOC,GACD,SAAST,mBACPN,MAAe,EACfgB,MAAmB;IAEnB,IAAI;QACF,OAAOP,IAAAA,mBAAM,EAACT,QAAQgB;IACxB,EAAE,OAAON,OAAO;QACd,IAAIA,iBAAiBO,wBAAW,EAAE;YAChC,MAAM,EAAEC,GAAG,EAAErC,MAAMsC,SAAS,EAAE,GAAGT;YAEjC,IAAIQ,QAAQ,iBAAiBC,cAAc,SAAS;gBAClD,MAAMR,oBAAS,CAACC,aAAa,CAAC;oBAC5BC,SACE;gBACJ;YACF;YAEA,MAAMF,oBAAS,CAACC,aAAa,CAAC;gBAC5BC,SAAS,CAAC,gBAAgB,EAAEH,MAAMG,OAAO,CAAC,CAAC,CAAC;YAC9C;QACF;QAEA,wBAAwB,GACxB,MAAMF,oBAAS,CAACS,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":["dialogBuilder","getDialogImplementation","methodName","PlaceholderStruct","optional","size","string","specificationBuilder","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","showDialog","createInterface","getInterface","Object","freeze","BaseParamsStruct","type","enums","DialogType","Alert","Confirmation","Prompt","AlertParametersWithContentStruct","object","enumValue","content","ComponentStruct","AlertParametersWithIdStruct","id","AlertParametersStruct","union","ConfirmationParametersWithContentStruct","ConfirmationParametersWithIdStruct","ConfirmationParametersStruct","PromptParametersWithContentStruct","placeholder","PromptParametersWithIdStruct","PromptParametersStruct","DialogParametersStruct","structs","dialogImplementation","args","params","context","origin","validatedType","getValidatedType","validatedParams","getValidatedParams","undefined","hasProperty","error","rpcErrors","invalidParams","message","create","values","join","struct","createUnion"],"mappings":";;;;;;;;;;;IA6HaA,aAAa;eAAbA;;IAsFGC,uBAAuB;eAAvBA;;;sCA9M4B;2BAClB;0BAMnB;4BAQqB;uBAEoB;6BAUzC;AAIP,MAAMC,aAAa;AAEnB,MAAMC,oBAAoBC,IAAAA,qBAAQ,EAACC,IAAAA,iBAAI,EAACC,IAAAA,mBAAM,KAAI,GAAG;AAkDrD;;;;;;;;;;;;;CAaC,GACD,MAAMC,uBAIF,CAAC,EACHC,iBAAiB,IAAI,EACrBC,WAAW,EACuB;IAClC,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,gBAAgB;QAC/CC,YAAYX;QACZM;QACAM,sBAAsBb,wBAAwBQ;QAC9CM,cAAc;YAACC,iCAAW,CAACC,IAAI;SAAC;IAClC;AACF;AAEA,MAAMR,cAAoD;IACxDS,YAAY;IACZC,iBAAiB;IACjBC,cAAc;AAChB;AAEO,MAAMpB,gBAAgBqB,OAAOC,MAAM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,SAAS,CAAC,oCAAoC,EAAEzC,OAAO2C,MAAM,CAC3DtC,oBAAU,EACVuC,IAAI,CAAC,MAAM,CAAC,CAAC;QACjB;IACF;AACF;AAEA;;;;;;;CAOC,GACD,SAAST,mBACPN,MAAe,EACfgB,MAAwB;IAExB,IAAI;QACF,OAAOC,IAAAA,uBAAW,EAACjB,QAAQgB,QAAQ;IACrC,EAAE,OAAOP,OAAO;QACd,MAAMC,oBAAS,CAACC,aAAa,CAAC;YAC5BC,SAAS,CAAC,gBAAgB,EAAEH,MAAMG,OAAO,CAAC,CAAC;QAC7C;IACF;AACF"}
|
|
@@ -12,6 +12,9 @@ _export(exports, {
|
|
|
12
12
|
WALLET_SNAP_PERMISSION_KEY: function() {
|
|
13
13
|
return _invokeSnap.WALLET_SNAP_PERMISSION_KEY;
|
|
14
14
|
},
|
|
15
|
+
getEncryptionKey: function() {
|
|
16
|
+
return _manageState.getEncryptionKey;
|
|
17
|
+
},
|
|
15
18
|
restrictedMethodPermissionBuilders: function() {
|
|
16
19
|
return restrictedMethodPermissionBuilders;
|
|
17
20
|
}
|
|
@@ -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":["WALLET_SNAP_PERMISSION_KEY","restrictedMethodPermissionBuilders","dialogBuilder","targetName","getBip32EntropyBuilder","getBip32PublicKeyBuilder","getBip44EntropyBuilder","getEntropyBuilder","invokeSnapBuilder","manageStateBuilder","notifyBuilder","manageAccountsBuilder","getLocaleBuilder"],"mappings":";;;;;;;;;;;IAqBSA,0BAA0B;eAA1BA,sCAA0B;;
|
|
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":["WALLET_SNAP_PERMISSION_KEY","getEncryptionKey","restrictedMethodPermissionBuilders","dialogBuilder","targetName","getBip32EntropyBuilder","getBip32PublicKeyBuilder","getBip44EntropyBuilder","getEntropyBuilder","invokeSnapBuilder","manageStateBuilder","notifyBuilder","manageAccountsBuilder","getLocaleBuilder"],"mappings":";;;;;;;;;;;IAqBSA,0BAA0B;eAA1BA,sCAA0B;;IAC1BC,gBAAgB;eAAhBA,6BAAgB;;IAaZC,kCAAkC;eAAlCA;;;wBAlCiB;iCAES;mCAEE;iCAEF;4BAEL;2BAED;4BAEC;gCAEI;6BAEH;wBAEL;qBA6BhB;;;;;;;;;;;;;;AAbP,MAAMA,qCAAqC;IAChD,CAACC,qBAAa,CAACC,UAAU,CAAC,EAAED,qBAAa;IACzC,CAACE,uCAAsB,CAACD,UAAU,CAAC,EAAEC,uCAAsB;IAC3D,CAACC,2CAAwB,CAACF,UAAU,CAAC,EAAEE,2CAAwB;IAC/D,CAACC,uCAAsB,CAACH,UAAU,CAAC,EAAEG,uCAAsB;IAC3D,CAACC,6BAAiB,CAACJ,UAAU,CAAC,EAAEI,6BAAiB;IACjD,CAACC,6BAAiB,CAACL,UAAU,CAAC,EAAEK,6BAAiB;IACjD,CAACC,+BAAkB,CAACN,UAAU,CAAC,EAAEM,+BAAkB;IACnD,CAACC,qBAAa,CAACP,UAAU,CAAC,EAAEO,qBAAa;IACzC,CAACC,qCAAqB,CAACR,UAAU,CAAC,EAAEQ,qCAAqB;IACzD,CAACC,2BAAgB,CAACT,UAAU,CAAC,EAAES,2BAAgB;AACjD"}
|
|
@@ -21,6 +21,9 @@ _export(exports, {
|
|
|
21
21
|
STORAGE_SIZE_LIMIT: function() {
|
|
22
22
|
return STORAGE_SIZE_LIMIT;
|
|
23
23
|
},
|
|
24
|
+
getEncryptionKey: function() {
|
|
25
|
+
return getEncryptionKey;
|
|
26
|
+
},
|
|
24
27
|
getManageStateImplementation: function() {
|
|
25
28
|
return getManageStateImplementation;
|
|
26
29
|
},
|
|
@@ -62,19 +65,7 @@ const manageStateBuilder = Object.freeze({
|
|
|
62
65
|
methodHooks
|
|
63
66
|
});
|
|
64
67
|
const STORAGE_SIZE_LIMIT = 104857600; // In bytes (100MB)
|
|
65
|
-
|
|
66
|
-
* Get a deterministic encryption key to use for encrypting and decrypting the
|
|
67
|
-
* state.
|
|
68
|
-
*
|
|
69
|
-
* This key should only be used for state encryption using `snap_manageState`.
|
|
70
|
-
* To get other encryption keys, a different salt can be used.
|
|
71
|
-
*
|
|
72
|
-
* @param args - The encryption key args.
|
|
73
|
-
* @param args.snapId - The ID of the snap to get the encryption key for.
|
|
74
|
-
* @param args.mnemonicPhrase - The mnemonic phrase to derive the encryption key
|
|
75
|
-
* from.
|
|
76
|
-
* @returns The state encryption key.
|
|
77
|
-
*/ async function getEncryptionKey({ mnemonicPhrase, snapId }) {
|
|
68
|
+
async function getEncryptionKey({ mnemonicPhrase, snapId }) {
|
|
78
69
|
return await (0, _utils1.deriveEntropy)({
|
|
79
70
|
mnemonicPhrase,
|
|
80
71
|
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":["STATE_ENCRYPTION_SALT","specificationBuilder","manageStateBuilder","STORAGE_SIZE_LIMIT","getManageStateImplementation","getValidatedParams","methodName","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","getMnemonic","getUnlockPromise","clearSnapState","getSnapState","updateSnapState","encrypt","decrypt","Object","freeze","getEncryptionKey","mnemonicPhrase","snapId","deriveEntropy","input","salt","magic","STATE_ENCRYPTION_MAGIC_VALUE","encryptState","state","encryptFunction","keyArgs","encryptionKey","decryptState","decryptFunction","decryptedState","assert","isValidJson","rpcErrors","internal","message","manageState","options","params","method","context","origin","validatedParams","shouldEncrypt","encrypted","operation","ManageStateOperation","ClearState","GetState","parseJson","UpdateState","finalizedState","newState","JSON","stringify","invalidParams","storageSizeLimit","isObject","values","includes","undefined","data","receivedNewState","size","getJsonSize"],"mappings":";;;;;;;;;;;IAiBaA,qBAAqB;eAArBA;;IAmFAC,oBAAoB;eAApBA;;IA2BAC,kBAAkB;eAAlBA;;IAMAC,kBAAkB;eAAlBA;;IAmHGC,4BAA4B;eAA5BA;;IAoFAC,kBAAkB;eAAlBA;;;sCAvU4B;2BAClB;0BAEW;4BACmB;uBAEG;wBAG7B;AAGvB,MAAML,wBAAwB;AAErC,MAAMM,aAAa;AAiFZ,MAAML,uBAIT,CAAC,EACHM,iBAAiB,IAAI,EACrBC,WAAW,EAC4B;IACvC,OAAO;QACLC,gBAAgBC,oCAAc,CAACC,gBAAgB;QAC/CC,YAAYN;QACZC;QACAM,sBAAsBT,6BAA6BI;QACnDM,cAAc;YAACC,iCAAW,CAACC,IAAI;SAAC;IAClC;AACF;AAEA,MAAMR,cAAyD;IAC7DS,aAAa;IACbC,kBAAkB;IAClBC,gBAAgB;IAChBC,cAAc;IACdC,iBAAiB;IACjBC,SAAS;IACTC,SAAS;AACX;AAEO,MAAMrB,qBAAqBsB,OAAOC,MAAM,CAAC;IAC9Cb,YAAYN;IACZL;IACAO;AACF;AAEO,MAAML,qBAAqB,WAAW,mBAAmB;AAOhE;;;;;;;;;;;;CAYC,GACD,eAAeuB,iBAAiB,EAC9BC,cAAc,EACdC,MAAM,EACe;IACrB,OAAO,MAAMC,IAAAA,qBAAa,EAAC;QACzBF;QACAG,OAAOF;QACPG,MAAM/B;QACNgC,OAAOC,wCAA4B;IACrC;AACF;AAOA;;;;;;;;;;;CAWC,GACD,eAAeC,aAAa,EAC1BC,KAAK,EACLC,eAAe,EACf,GAAGC,SACc;IACjB,MAAMC,gBAAgB,MAAMZ,iBAAiBW;IAC7C,OAAO,MAAMD,gBAAgBE,eAAeH;AAC9C;AAOA;;;;;;;;;;;CAWC,GACD,eAAeI,aAAa,EA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MnB,oBAAS,CAACsB,aAAa,CAAC;gBAC5BpB,SAAS,CAAC,QAAQ,EAAEI,OAAO,kEAAkE,CAAC;gBAC9FsB,MAAM;oBACJC,kBACE,OAAOV,aAAa,cAAc,cAAcA;gBACpD;YACF;QACF;QAEA,IAAIW,OAAOP,kBAAkB;YAC3B,MAAMvB,oBAAS,CAACsB,aAAa,CAAC;gBAC5BpB,SAAS,CAAC,QAAQ,EAAEI,OAAO,wDAAwD,EAAEiB,iBAAiB,eAAe,CAAC;gBACtHK,MAAM;oBACJC,kBACE,OAAOV,aAAa,cAAc,cAAcA;gBACpD;YACF;QACF;IACF;IAEA,OAAOd;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":["STATE_ENCRYPTION_SALT","specificationBuilder","manageStateBuilder","STORAGE_SIZE_LIMIT","getEncryptionKey","getManageStateImplementation","getValidatedParams","methodName","allowedCaveats","methodHooks","permissionType","PermissionType","RestrictedMethod","targetName","methodImplementation","subjectTypes","SubjectType","Snap","getMnemonic","getUnlockPromise","clearSnapState","getSnapState","updateSnapState","encrypt","decrypt","Object","freeze","mnemonicPhrase","snapId","deriveEntropy","input","salt","magic","STATE_ENCRYPTION_MAGIC_VALUE","encryptState","state","encryptFunction","keyArgs","encryptionKey","decryptState","decryptFunction","decryptedState","assert","isValidJson","rpcErrors","internal","message","manageState","options","params","method","context","origin","validatedParams","shouldEncrypt","encrypted","operation","ManageStateOperation","ClearState","GetState","parseJson","UpdateState","finalizedState","newState","JSON","stringify","invalidParams","storageSizeLimit","isObject","values","includes","undefined","data","receivedNewState","size","getJsonSize"],"mappings":";;;;;;;;;;;IAiBaA,qBAAqB;eAArBA;;IAmFAC,oBAAoB;eAApBA;;IA2BAC,kBAAkB;eAAlBA;;IAMAC,kBA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oBAAS,CAACsB,aAAa,CAAC;gBAC5BpB,SAAS,CAAC,QAAQ,EAAEI,OAAO,wDAAwD,EAAEiB,iBAAiB,eAAe,CAAC;gBACtHK,MAAM;oBACJC,kBACE,OAAOV,aAAa,cAAc,cAAcA;gBACpD;YACF;QACF;IACF;IAEA,OAAOd;AACT"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { rpcErrors } from '@metamask/rpc-errors';
|
|
2
|
+
/**
|
|
3
|
+
* Create a generic permission validator that validates the presence of certain caveats.
|
|
4
|
+
*
|
|
5
|
+
* This validator only validates the types of the caveats, not the values.
|
|
6
|
+
*
|
|
7
|
+
* @param caveatsToValidate - A list of objects that represent caveats.
|
|
8
|
+
* @param caveatsToValidate.type - The string defining the caveat type.
|
|
9
|
+
* @param caveatsToValidate.optional - An optional boolean flag that defines
|
|
10
|
+
* whether the caveat is optional or not.
|
|
11
|
+
* @returns A function that validates a permission.
|
|
12
|
+
*/ export function createGenericPermissionValidator(caveatsToValidate) {
|
|
13
|
+
const validCaveatTypes = new Set(caveatsToValidate.map((caveat)=>caveat.type));
|
|
14
|
+
const requiredCaveats = caveatsToValidate.filter((caveat)=>!caveat.optional);
|
|
15
|
+
return function({ caveats }) {
|
|
16
|
+
const actualCaveats = caveats ?? [];
|
|
17
|
+
const passedCaveatTypes = actualCaveats.map((caveat)=>caveat.type);
|
|
18
|
+
const passedCaveatsSet = new Set(passedCaveatTypes);
|
|
19
|
+
// Disallow duplicates
|
|
20
|
+
if (passedCaveatsSet.size !== passedCaveatTypes.length) {
|
|
21
|
+
throw rpcErrors.invalidParams({
|
|
22
|
+
message: 'Duplicate caveats are not allowed.'
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
// Disallow caveats that don't match expected types
|
|
26
|
+
if (!actualCaveats.every((caveat)=>validCaveatTypes.has(caveat.type))) {
|
|
27
|
+
throw rpcErrors.invalidParams({
|
|
28
|
+
message: `Expected the following caveats: ${caveatsToValidate.map((caveat)=>`"${caveat.type}"`).join(', ')}, received ${actualCaveats.map((caveat)=>`"${caveat.type}"`).join(', ')}.`
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
// Fail if not all required caveats are specified
|
|
32
|
+
if (!requiredCaveats.every((caveat)=>passedCaveatsSet.has(caveat.type))) {
|
|
33
|
+
throw rpcErrors.invalidParams({
|
|
34
|
+
message: `Expected the following caveats: ${requiredCaveats.map((caveat)=>`"${caveat.type}"`).join(', ')}.`
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=generic.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/endowments/caveats/generic.ts"],"sourcesContent":["import type {\n PermissionConstraint,\n PermissionValidatorConstraint,\n} from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Json } from '@metamask/utils';\n\nexport type CaveatMapperReturnValue = Pick<PermissionConstraint, 'caveats'>;\n\nexport type CaveatMapperFunction = (value: Json) => CaveatMapperReturnValue;\n\n/**\n * Create a generic permission validator that validates the presence of certain caveats.\n *\n * This validator only validates the types of the caveats, not the values.\n *\n * @param caveatsToValidate - A list of objects that represent caveats.\n * @param caveatsToValidate.type - The string defining the caveat type.\n * @param caveatsToValidate.optional - An optional boolean flag that defines\n * whether the caveat is optional or not.\n * @returns A function that validates a permission.\n */\nexport function createGenericPermissionValidator(\n caveatsToValidate: {\n type: string;\n optional?: boolean;\n }[],\n): PermissionValidatorConstraint {\n const validCaveatTypes = new Set(\n caveatsToValidate.map((caveat) => caveat.type),\n );\n const requiredCaveats = caveatsToValidate.filter(\n (caveat) => !caveat.optional,\n );\n\n return function ({ caveats }) {\n const actualCaveats = caveats ?? [];\n const passedCaveatTypes = actualCaveats.map((caveat) => caveat.type);\n const passedCaveatsSet = new Set(passedCaveatTypes);\n\n // Disallow duplicates\n if (passedCaveatsSet.size !== passedCaveatTypes.length) {\n throw rpcErrors.invalidParams({\n message: 'Duplicate caveats are not allowed.',\n });\n }\n\n // Disallow caveats that don't match expected types\n if (!actualCaveats.every((caveat) => validCaveatTypes.has(caveat.type))) {\n throw rpcErrors.invalidParams({\n message: `Expected the following caveats: ${caveatsToValidate\n .map((caveat) => `\"${caveat.type}\"`)\n .join(', ')}, received ${actualCaveats\n .map((caveat) => `\"${caveat.type}\"`)\n .join(', ')}.`,\n });\n }\n\n // Fail if not all required caveats are specified\n if (!requiredCaveats.every((caveat) => passedCaveatsSet.has(caveat.type))) {\n throw rpcErrors.invalidParams({\n message: `Expected the following caveats: ${requiredCaveats\n .map((caveat) => `\"${caveat.type}\"`)\n .join(', ')}.`,\n });\n }\n };\n}\n"],"names":["rpcErrors","createGenericPermissionValidator","caveatsToValidate","validCaveatTypes","Set","map","caveat","type","requiredCaveats","filter","optional","caveats","actualCaveats","passedCaveatTypes","passedCaveatsSet","size","length","invalidParams","message","every","has","join"],"mappings":"AAIA,SAASA,SAAS,QAAQ,uBAAuB;AAOjD;;;;;;;;;;CAUC,GACD,OAAO,SAASC,iCACdC,iBAGG;IAEH,MAAMC,mBAAmB,IAAIC,IAC3BF,kBAAkBG,GAAG,CAAC,CAACC,SAAWA,OAAOC,IAAI;IAE/C,MAAMC,kBAAkBN,kBAAkBO,MAAM,CAC9C,CAACH,SAAW,CAACA,OAAOI,QAAQ;IAG9B,OAAO,SAAU,EAAEC,OAAO,EAAE;QAC1B,MAAMC,gBAAgBD,WAAW,EAAE;QACnC,MAAME,oBAAoBD,cAAcP,GAAG,CAAC,CAACC,SAAWA,OAAOC,IAAI;QACnE,MAAMO,mBAAmB,IAAIV,IAAIS;QAEjC,sBAAsB;QACtB,IAAIC,iBAAiBC,IAAI,KAAKF,kBAAkBG,MAAM,EAAE;YACtD,MAAMhB,UAAUiB,aAAa,CAAC;gBAC5BC,SAAS;YACX;QACF;QAEA,mDAAmD;QACnD,IAAI,CAACN,cAAcO,KAAK,CAAC,CAACb,SAAWH,iBAAiBiB,GAAG,CAACd,OAAOC,IAAI,IAAI;YACvE,MAAMP,UAAUiB,aAAa,CAAC;gBAC5BC,SAAS,CAAC,gCAAgC,EAAEhB,kBACzCG,GAAG,CAAC,CAACC,SAAW,CAAC,CAAC,EAAEA,OAAOC,IAAI,CAAC,CAAC,CAAC,EAClCc,IAAI,CAAC,MAAM,WAAW,EAAET,cACxBP,GAAG,CAAC,CAACC,SAAW,CAAC,CAAC,EAAEA,OAAOC,IAAI,CAAC,CAAC,CAAC,EAClCc,IAAI,CAAC,MAAM,CAAC,CAAC;YAClB;QACF;QAEA,iDAAiD;QACjD,IAAI,CAACb,gBAAgBW,KAAK,CAAC,CAACb,SAAWQ,iBAAiBM,GAAG,CAACd,OAAOC,IAAI,IAAI;YACzE,MAAMP,UAAUiB,aAAa,CAAC;gBAC5BC,SAAS,CAAC,gCAAgC,EAAEV,gBACzCH,GAAG,CAAC,CAACC,SAAW,CAAC,CAAC,EAAEA,OAAOC,IAAI,CAAC,CAAC,CAAC,EAClCc,IAAI,CAAC,MAAM,CAAC,CAAC;YAClB;QACF;IACF;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/endowments/caveats/index.ts"],"sourcesContent":["export * from './generic';\nexport * from './requestTime';\n"],"names":[],"mappings":"AAAA,cAAc,YAAY;AAC1B,cAAc,gBAAgB"}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { rpcErrors } from '@metamask/rpc-errors';
|
|
2
|
+
import { MaxRequestTimeStruct, SnapCaveatType } from '@metamask/snaps-utils';
|
|
3
|
+
import { assertStruct, hasProperty, isObject } from '@metamask/utils';
|
|
4
|
+
/**
|
|
5
|
+
* Asserts that the given value is a valid `maxRequestTime` value.
|
|
6
|
+
*
|
|
7
|
+
* @param value - The value to assert.
|
|
8
|
+
* @param ErrorWrapper - An optional error wrapper to use. Defaults to
|
|
9
|
+
* {@link AssertionError}.
|
|
10
|
+
* @throws If the value is not a valid `maxRequestTime` value.
|
|
11
|
+
*/ function assertIsMaxRequestTime(value, ErrorWrapper) {
|
|
12
|
+
assertStruct(value, MaxRequestTimeStruct, 'Invalid maxRequestTime', ErrorWrapper);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Validate the value of a caveat. This does not validate the type of the
|
|
16
|
+
* caveat itself, only the value of the caveat.
|
|
17
|
+
*
|
|
18
|
+
* @param caveat - The caveat to validate.
|
|
19
|
+
* @throws If the caveat value is invalid.
|
|
20
|
+
*/ function validateMaxRequestTimeCaveat(caveat) {
|
|
21
|
+
if (!hasProperty(caveat, 'value')) {
|
|
22
|
+
throw rpcErrors.invalidParams({
|
|
23
|
+
message: 'Invalid maxRequestTime caveat.'
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
const { value } = caveat;
|
|
27
|
+
assertIsMaxRequestTime(value, rpcErrors.invalidParams);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Map a raw value from the `initialPermissions` to a caveat specification.
|
|
31
|
+
* Note that this function does not do any validation, that's handled by the
|
|
32
|
+
* PermissionsController when the permission is requested.
|
|
33
|
+
*
|
|
34
|
+
* @param value - The raw value from the `initialPermissions`.
|
|
35
|
+
* @returns The caveat specification.
|
|
36
|
+
*/ export function getMaxRequestTimeCaveatMapper(value) {
|
|
37
|
+
if (!value || !isObject(value) || isObject(value) && !hasProperty(value, 'maxRequestTime')) {
|
|
38
|
+
return {
|
|
39
|
+
caveats: null
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
caveats: [
|
|
44
|
+
{
|
|
45
|
+
type: SnapCaveatType.MaxRequestTime,
|
|
46
|
+
value: value.maxRequestTime
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Creates a wrapping caveat mapper that creates the `maxRequestTime` caveat
|
|
53
|
+
* and merges it with any other caveats created by the mapper function.
|
|
54
|
+
*
|
|
55
|
+
* @param mapper - Another caveat mapper function.
|
|
56
|
+
* @returns The caveat specification.
|
|
57
|
+
*/ export function createMaxRequestTimeMapper(mapper) {
|
|
58
|
+
return function(value) {
|
|
59
|
+
// We assume this to be used only with caveats of this type
|
|
60
|
+
const { maxRequestTime, ...rest } = value;
|
|
61
|
+
const mapperResult = mapper(rest);
|
|
62
|
+
if (!maxRequestTime) {
|
|
63
|
+
return mapperResult;
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
...mapperResult,
|
|
67
|
+
caveats: [
|
|
68
|
+
...mapperResult.caveats ?? [],
|
|
69
|
+
{
|
|
70
|
+
type: SnapCaveatType.MaxRequestTime,
|
|
71
|
+
value: maxRequestTime
|
|
72
|
+
}
|
|
73
|
+
]
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Getter function to get the {@link MaxRequestTime} caveat value from a permission if specified.
|
|
79
|
+
*
|
|
80
|
+
* @param permission - The permission to get the caveat value from.
|
|
81
|
+
* @returns The caveat value if present, otherwise null.
|
|
82
|
+
*/ export function getMaxRequestTimeCaveat(permission) {
|
|
83
|
+
const foundCaveat = permission?.caveats?.find((caveat)=>caveat.type === SnapCaveatType.MaxRequestTime);
|
|
84
|
+
return (foundCaveat?.value) ?? null;
|
|
85
|
+
}
|
|
86
|
+
export const maxRequestTimeCaveatSpecifications = {
|
|
87
|
+
[SnapCaveatType.MaxRequestTime]: Object.freeze({
|
|
88
|
+
type: SnapCaveatType.MaxRequestTime,
|
|
89
|
+
validator: (caveat)=>validateMaxRequestTimeCaveat(caveat)
|
|
90
|
+
})
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=requestTime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/endowments/caveats/requestTime.ts"],"sourcesContent":["import type {\n Caveat,\n CaveatSpecificationConstraint,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { MaxRequestTimeStruct, SnapCaveatType } from '@metamask/snaps-utils';\nimport type { AssertionErrorConstructor, Json } from '@metamask/utils';\nimport { assertStruct, hasProperty, isObject } from '@metamask/utils';\n\nimport type { CaveatMapperFunction, CaveatMapperReturnValue } from './generic';\n\n/**\n * Asserts that the given value is a valid `maxRequestTime` value.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid `maxRequestTime` value.\n */\nfunction assertIsMaxRequestTime(\n value: unknown, // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is number {\n assertStruct(\n value,\n MaxRequestTimeStruct,\n 'Invalid maxRequestTime',\n ErrorWrapper,\n );\n}\n\n/**\n * Validate the value of a caveat. This does not validate the type of the\n * caveat itself, only the value of the caveat.\n *\n * @param caveat - The caveat to validate.\n * @throws If the caveat value is invalid.\n */\nfunction validateMaxRequestTimeCaveat(caveat: Caveat<string, any>) {\n if (!hasProperty(caveat, 'value')) {\n throw rpcErrors.invalidParams({\n message: 'Invalid maxRequestTime caveat.',\n });\n }\n\n const { value } = caveat;\n assertIsMaxRequestTime(value, rpcErrors.invalidParams);\n}\n\n/**\n * Map a raw value from the `initialPermissions` to a caveat specification.\n * Note that this function does not do any validation, that's handled by the\n * PermissionsController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function getMaxRequestTimeCaveatMapper(\n value: Json,\n): CaveatMapperReturnValue {\n if (\n !value ||\n !isObject(value) ||\n (isObject(value) && !hasProperty(value, 'maxRequestTime'))\n ) {\n return { caveats: null };\n }\n return {\n caveats: [\n {\n type: SnapCaveatType.MaxRequestTime,\n value: value.maxRequestTime,\n },\n ],\n };\n}\n\n/**\n * Creates a wrapping caveat mapper that creates the `maxRequestTime` caveat\n * and merges it with any other caveats created by the mapper function.\n *\n * @param mapper - Another caveat mapper function.\n * @returns The caveat specification.\n */\nexport function createMaxRequestTimeMapper(\n mapper: CaveatMapperFunction,\n): CaveatMapperFunction {\n return function (value: Json) {\n // We assume this to be used only with caveats of this type\n const { maxRequestTime, ...rest } = value as Record<string, Json>;\n\n const mapperResult = mapper(rest);\n\n if (!maxRequestTime) {\n return mapperResult;\n }\n\n return {\n ...mapperResult,\n caveats: [\n ...(mapperResult.caveats ?? []),\n {\n type: SnapCaveatType.MaxRequestTime,\n value: maxRequestTime,\n },\n ],\n };\n };\n}\n\n/**\n * Getter function to get the {@link MaxRequestTime} caveat value from a permission if specified.\n *\n * @param permission - The permission to get the caveat value from.\n * @returns The caveat value if present, otherwise null.\n */\nexport function getMaxRequestTimeCaveat(\n permission?: PermissionConstraint,\n): number | null {\n const foundCaveat = permission?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.MaxRequestTime,\n );\n return (foundCaveat?.value as number) ?? null;\n}\n\nexport const maxRequestTimeCaveatSpecifications: Record<\n SnapCaveatType.MaxRequestTime,\n CaveatSpecificationConstraint\n> = {\n [SnapCaveatType.MaxRequestTime]: Object.freeze({\n type: SnapCaveatType.MaxRequestTime,\n validator: (caveat: Caveat<string, any>) =>\n validateMaxRequestTimeCaveat(caveat),\n }),\n};\n"],"names":["rpcErrors","MaxRequestTimeStruct","SnapCaveatType","assertStruct","hasProperty","isObject","assertIsMaxRequestTime","value","ErrorWrapper","validateMaxRequestTimeCaveat","caveat","invalidParams","message","getMaxRequestTimeCaveatMapper","caveats","type","MaxRequestTime","maxRequestTime","createMaxRequestTimeMapper","mapper","rest","mapperResult","getMaxRequestTimeCaveat","permission","foundCaveat","find","maxRequestTimeCaveatSpecifications","Object","freeze","validator"],"mappings":"AAKA,SAASA,SAAS,QAAQ,uBAAuB;AACjD,SAASC,oBAAoB,EAAEC,cAAc,QAAQ,wBAAwB;AAE7E,SAASC,YAAY,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,kBAAkB;AAItE;;;;;;;CAOC,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