@metamask/snaps-rpc-methods 7.0.2 → 8.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -1
- package/dist/{chunk-JQ456NCC.mjs → chunk-3W4SMZFD.mjs} +3 -3
- package/dist/{chunk-WLDEPJGG.mjs → chunk-634BK2VP.mjs} +3 -3
- package/dist/chunk-634BK2VP.mjs.map +1 -0
- package/dist/{chunk-GP5KW5FU.js → chunk-D5WQBUZB.js} +2 -2
- package/dist/chunk-D5WQBUZB.js.map +1 -0
- package/dist/{chunk-6UY23OOZ.js → chunk-GP6TDVNT.js} +3 -3
- package/dist/{chunk-YS6TYXCP.mjs → chunk-GVJLWGSI.mjs} +3 -3
- package/dist/chunk-GVJLWGSI.mjs.map +1 -0
- package/dist/{chunk-GYZV5UBD.js → chunk-I7DR6BFO.js} +4 -4
- package/dist/chunk-I7DR6BFO.js.map +1 -0
- package/dist/{chunk-D6MUXDVI.js → chunk-INB4AX37.js} +5 -5
- package/dist/{chunk-AKRFLGOS.mjs → chunk-L675SYPP.mjs} +2 -2
- package/dist/{chunk-7NBRKDKJ.mjs → chunk-NESDQ4PF.mjs} +9 -54
- package/dist/chunk-NESDQ4PF.mjs.map +1 -0
- package/dist/{chunk-3S7DJI4I.mjs → chunk-PG32JMWC.mjs} +3 -3
- package/dist/chunk-PG32JMWC.mjs.map +1 -0
- package/dist/{chunk-KO4MKRYZ.js → chunk-R2M4YLJ7.js} +7 -52
- package/dist/chunk-R2M4YLJ7.js.map +1 -0
- package/dist/{chunk-LVTN25J2.js → chunk-RIALLTR7.js} +5 -5
- package/dist/{chunk-LVTN25J2.js.map → chunk-RIALLTR7.js.map} +1 -1
- package/dist/{chunk-FBOZCV3C.js → chunk-RX7WZZ32.js} +3 -3
- package/dist/{chunk-3LPBU737.js → chunk-UDB4MUXI.js} +2 -2
- package/dist/chunk-UDB4MUXI.js.map +1 -0
- package/dist/{chunk-7OMVZR5X.mjs → chunk-VNH2GKLV.mjs} +2 -2
- package/dist/{chunk-4SQWLI2S.mjs → chunk-X247BMMW.mjs} +6 -6
- package/dist/chunk-X247BMMW.mjs.map +1 -0
- package/dist/index.js +9 -9
- package/dist/index.mjs +10 -10
- package/dist/permissions.js +5 -5
- package/dist/permissions.mjs +4 -4
- package/dist/permitted/createInterface.js +2 -2
- package/dist/permitted/createInterface.mjs +1 -1
- package/dist/permitted/handlers.js +4 -4
- package/dist/permitted/handlers.mjs +3 -3
- package/dist/permitted/index.js +5 -5
- package/dist/permitted/index.mjs +4 -4
- package/dist/permitted/middleware.js +5 -5
- package/dist/permitted/middleware.mjs +4 -4
- package/dist/permitted/updateInterface.js +2 -2
- package/dist/permitted/updateInterface.mjs +1 -1
- package/dist/restricted/dialog.js +2 -2
- package/dist/restricted/dialog.mjs +1 -1
- package/dist/restricted/index.js +4 -4
- package/dist/restricted/index.mjs +5 -5
- package/dist/restricted/manageState.js +2 -2
- package/dist/restricted/manageState.mjs +3 -3
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/permitted/createInterface.d.ts +8 -8
- package/dist/types/permitted/updateInterface.d.ts +8 -8
- package/dist/types/restricted/dialog.d.ts +207 -39
- package/dist/types/restricted/index.d.ts +1 -1
- package/dist/types/restricted/manageAccounts.d.ts +1 -1
- package/dist/types/restricted/manageState.d.ts +5 -31
- package/package.json +3 -4
- package/dist/chunk-3LPBU737.js.map +0 -1
- package/dist/chunk-3S7DJI4I.mjs.map +0 -1
- package/dist/chunk-4SQWLI2S.mjs.map +0 -1
- package/dist/chunk-7NBRKDKJ.mjs.map +0 -1
- package/dist/chunk-GP5KW5FU.js.map +0 -1
- package/dist/chunk-GYZV5UBD.js.map +0 -1
- package/dist/chunk-KO4MKRYZ.js.map +0 -1
- package/dist/chunk-WLDEPJGG.mjs.map +0 -1
- package/dist/chunk-YS6TYXCP.mjs.map +0 -1
- /package/dist/{chunk-JQ456NCC.mjs.map → chunk-3W4SMZFD.mjs.map} +0 -0
- /package/dist/{chunk-6UY23OOZ.js.map → chunk-GP6TDVNT.js.map} +0 -0
- /package/dist/{chunk-D6MUXDVI.js.map → chunk-INB4AX37.js.map} +0 -0
- /package/dist/{chunk-AKRFLGOS.mjs.map → chunk-L675SYPP.mjs.map} +0 -0
- /package/dist/{chunk-FBOZCV3C.js.map → chunk-RX7WZZ32.js.map} +0 -0
- /package/dist/{chunk-7OMVZR5X.mjs.map → chunk-VNH2GKLV.mjs.map} +0 -0
|
@@ -1,15 +1,11 @@
|
|
|
1
1
|
import type { PermissionSpecificationBuilder, RestrictedMethodOptions, ValidPermissionSpecification } from '@metamask/permission-controller';
|
|
2
2
|
import { PermissionType } from '@metamask/permission-controller';
|
|
3
3
|
import type { ManageStateParams, ManageStateResult } from '@metamask/snaps-sdk';
|
|
4
|
-
import type { Json, NonEmptyArray
|
|
4
|
+
import type { Json, NonEmptyArray } from '@metamask/utils';
|
|
5
5
|
import type { MethodHooksObject } from '../utils';
|
|
6
6
|
export declare const STATE_ENCRYPTION_SALT = "snap_manageState encryption";
|
|
7
7
|
declare const methodName = "snap_manageState";
|
|
8
8
|
export declare type ManageStateMethodHooks = {
|
|
9
|
-
/**
|
|
10
|
-
* @returns The mnemonic of the user's primary keyring.
|
|
11
|
-
*/
|
|
12
|
-
getMnemonic: () => Promise<Uint8Array>;
|
|
13
9
|
/**
|
|
14
10
|
* Waits for the extension to be unlocked.
|
|
15
11
|
*
|
|
@@ -25,31 +21,13 @@ export declare type ManageStateMethodHooks = {
|
|
|
25
21
|
*
|
|
26
22
|
* @returns The current state of the Snap.
|
|
27
23
|
*/
|
|
28
|
-
getSnapState: (snapId: string, encrypted: boolean) => string
|
|
24
|
+
getSnapState: (snapId: string, encrypted: boolean) => Promise<Record<string, Json>>;
|
|
29
25
|
/**
|
|
30
26
|
* A function that updates the state of the requesting Snap.
|
|
31
27
|
*
|
|
32
28
|
* @param newState - The new state of the Snap.
|
|
33
29
|
*/
|
|
34
|
-
updateSnapState: (snapId: string, newState: string, encrypted: boolean) => void
|
|
35
|
-
/**
|
|
36
|
-
* Encrypts data with a key. This is assumed to perform symmetric encryption.
|
|
37
|
-
*
|
|
38
|
-
* @param key - The key to use for encryption, in hexadecimal format.
|
|
39
|
-
* @param data - The JSON data to encrypt.
|
|
40
|
-
* @returns The ciphertext as a string. The format for this string is
|
|
41
|
-
* dependent on the implementation, but MUST be a string.
|
|
42
|
-
*/
|
|
43
|
-
encrypt: (key: string, data: Json) => Promise<string>;
|
|
44
|
-
/**
|
|
45
|
-
* Decrypts data with a key. This is assumed to perform symmetric decryption.
|
|
46
|
-
*
|
|
47
|
-
* @param key - The key to use for decryption, in hexadecimal format.
|
|
48
|
-
* @param cipherText - The ciphertext to decrypt. The format for this string
|
|
49
|
-
* is dependent on the implementation, but MUST be a string.
|
|
50
|
-
* @returns The decrypted data as a JSON object.
|
|
51
|
-
*/
|
|
52
|
-
decrypt: (key: Hex, cipherText: string) => Promise<unknown>;
|
|
30
|
+
updateSnapState: (snapId: string, newState: Record<string, Json>, encrypted: boolean) => Promise<void>;
|
|
53
31
|
};
|
|
54
32
|
declare type ManageStateSpecificationBuilderOptions = {
|
|
55
33
|
allowedCaveats?: Readonly<NonEmptyArray<string>> | null;
|
|
@@ -100,7 +78,7 @@ declare type GetEncryptionKeyArgs = {
|
|
|
100
78
|
* from.
|
|
101
79
|
* @returns The state encryption key.
|
|
102
80
|
*/
|
|
103
|
-
export declare function
|
|
81
|
+
export declare function getEncryptionEntropy({ mnemonicPhrase, snapId, }: GetEncryptionKeyArgs): Promise<`0x${string}`>;
|
|
104
82
|
/**
|
|
105
83
|
* Builds the method implementation for `snap_manageState`.
|
|
106
84
|
*
|
|
@@ -111,18 +89,14 @@ export declare function getEncryptionKey({ mnemonicPhrase, snapId, }: GetEncrypt
|
|
|
111
89
|
* state for a snap.
|
|
112
90
|
* @param hooks.updateSnapState - A function that updates the state stored for a
|
|
113
91
|
* snap.
|
|
114
|
-
* @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase
|
|
115
|
-
* of the user.
|
|
116
92
|
* @param hooks.getUnlockPromise - A function that resolves once the MetaMask
|
|
117
93
|
* extension is unlocked and prompts the user to unlock their MetaMask if it is
|
|
118
94
|
* locked.
|
|
119
|
-
* @param hooks.encrypt - A function that encrypts the given state.
|
|
120
|
-
* @param hooks.decrypt - A function that decrypts the given state.
|
|
121
95
|
* @returns The method implementation which either returns `null` for a
|
|
122
96
|
* successful state update/deletion or returns the decrypted state.
|
|
123
97
|
* @throws If the params are invalid.
|
|
124
98
|
*/
|
|
125
|
-
export declare function getManageStateImplementation({
|
|
99
|
+
export declare function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
|
|
126
100
|
/**
|
|
127
101
|
* Validates the manageState method `params` and returns them cast to the correct
|
|
128
102
|
* type. Throws if validation fails.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-rpc-methods",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "8.1.0",
|
|
4
4
|
"description": "MetaMask Snaps JSON-RPC method implementations.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
"@metamask/key-tree": "^9.0.0",
|
|
43
43
|
"@metamask/permission-controller": "^9.0.2",
|
|
44
44
|
"@metamask/rpc-errors": "^6.2.1",
|
|
45
|
-
"@metamask/snaps-sdk": "^
|
|
46
|
-
"@metamask/snaps-utils": "^7.0
|
|
45
|
+
"@metamask/snaps-sdk": "^4.1.0",
|
|
46
|
+
"@metamask/snaps-utils": "^7.3.0",
|
|
47
47
|
"@metamask/utils": "^8.3.0",
|
|
48
48
|
"@noble/hashes": "^1.3.1",
|
|
49
49
|
"superstruct": "^1.0.3"
|
|
@@ -51,7 +51,6 @@
|
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@lavamoat/allow-scripts": "^3.0.3",
|
|
53
53
|
"@metamask/auto-changelog": "^3.4.4",
|
|
54
|
-
"@metamask/browser-passworder": "^4.3.0",
|
|
55
54
|
"@metamask/eslint-config": "^12.1.0",
|
|
56
55
|
"@metamask/eslint-config-jest": "^12.1.0",
|
|
57
56
|
"@metamask/eslint-config-nodejs": "^12.1.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/permitted/createInterface.ts"],"names":[],"mappings":";AAEA,SAAS,iBAAiB;AAO1B,SAAS,uBAAuB;AAGhC,SAAS,aAAa,QAAQ,cAAc;AAI5C,IAAM,YAA2D;AAAA,EAC/D,iBAAiB;AACnB;AAUO,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,sBAAsB;AAAA,EACpC,gBAAgB;AAAA,EAChB;AACF;AAEA,IAAM,kCAAkC,OAAO;AAAA,EAC7C,IAAI;AACN,CAAC;AAmBD,eAAe,iCACb,KACA,KACA,OACA,KACA,EAAE,gBAAgB,GACH;AACf,QAAM,EAAE,OAAO,IAAI;AAEnB,MAAI;AACF,UAAM,kBAAkB,mBAAmB,MAAM;AAEjD,UAAM,EAAE,GAAG,IAAI;AAEf,QAAI,SAAS,MAAM,gBAAgB,EAAE;AAAA,EACvC,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,SAAO,IAAI;AACb;AASA,SAAS,mBAAmB,QAA4C;AACtE,MAAI;AACF,WAAO,OAAO,QAAQ,+BAA+B;AAAA,EACvD,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,UAAM,UAAU,SAAS;AAAA,EAC3B;AACF","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 CreateInterfaceParams,\n CreateInterfaceResult,\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 } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<CreateInterfaceMethodHooks> = {\n createInterface: true,\n};\n\nexport type CreateInterfaceMethodHooks = {\n /**\n * @param ui - The UI components.\n * @returns The unique identifier of the interface.\n */\n createInterface: (ui: Component) => Promise<string>;\n};\n\nexport const createInterfaceHandler: PermittedHandlerExport<\n CreateInterfaceMethodHooks,\n CreateInterfaceParameters,\n CreateInterfaceResult\n> = {\n methodNames: ['snap_createInterface'],\n implementation: getCreateInterfaceImplementation,\n hookNames,\n};\n\nconst CreateInterfaceParametersStruct = object({\n ui: ComponentStruct,\n});\n\nexport type CreateInterfaceParameters = InferMatching<\n typeof CreateInterfaceParametersStruct,\n CreateInterfaceParams\n>;\n\n/**\n * The `snap_createInterface` 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.createInterface - The function to create the interface.\n * @returns Nothing.\n */\nasync function getCreateInterfaceImplementation(\n req: JsonRpcRequest<CreateInterfaceParameters>,\n res: PendingJsonRpcResponse<CreateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { createInterface }: CreateInterfaceMethodHooks,\n): Promise<void> {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { ui } = validatedParams;\n\n res.result = await createInterface(ui);\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the createInterface 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 createInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): CreateInterfaceParameters {\n try {\n return create(params, CreateInterfaceParametersStruct);\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"]}
|
|
@@ -1 +0,0 @@
|
|
|
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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCO,IAAM,qCAAqC;AAAA,EAChD,CAAC,cAAc,UAAU,GAAG;AAAA,EAC5B,CAAC,uBAAuB,UAAU,GAAG;AAAA,EACrC,CAAC,yBAAyB,UAAU,GAAG;AAAA,EACvC,CAAC,uBAAuB,UAAU,GAAG;AAAA,EACrC,CAAC,kBAAkB,UAAU,GAAG;AAAA,EAChC,CAAC,kBAAkB,UAAU,GAAG;AAAA,EAChC,CAAC,mBAAmB,UAAU,GAAG;AAAA,EACjC,CAAC,cAAc,UAAU,GAAG;AAAA,EAC5B,CAAC,sBAAsB,UAAU,GAAG;AAAA,EACpC,CAAC,iBAAiB,UAAU,GAAG;AACjC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
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"],"mappings":";AAKA,SAAS,gBAAgB,mBAAmB;AAC5C,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAQP,SAAS,mBAAmB;AAE5B,SAAS,mBAAuC;AAEhD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAIP,IAAM,aAAa;AAEnB,IAAM,oBAAoB,SAAS,KAAK,OAAO,GAAG,GAAG,EAAE,CAAC;AAgExD,IAAM,uBAIF,CAAC;AAAA,EACH,iBAAiB;AAAA,EACjB,aAAAA;AACF,MAAyC;AACvC,SAAO;AAAA,IACL,gBAAgB,eAAe;AAAA,IAC/B,YAAY;AAAA,IACZ;AAAA,IACA,sBAAsB,wBAAwBA,YAAW;AAAA,IACzD,cAAc,CAAC,YAAY,IAAI;AAAA,EACjC;AACF;AAEA,IAAM,cAAoD;AAAA,EACxD,YAAY;AAAA,EACZ,iBAAiB;AAAA,EACjB,cAAc;AAChB;AAEO,IAAM,gBAAgB,OAAO,OAAO;AAAA,EACzC,YAAY;AAAA,EACZ;AAAA,EACA;AACF,CAAU;AAIV,IAAM,mBAAmB,KAAK;AAAA,EAC5B,MAAM,MAAM,CAAC,WAAW,OAAO,WAAW,cAAc,WAAW,MAAM,CAAC;AAC5E,CAAC;AAED,IAAM,mCAAmC,OAAO;AAAA,EAC9C,MAAM,UAAU,WAAW,KAAK;AAAA,E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,QAAI,YAAY,iBAAiB,SAAS,GAAG;AAC3C,YAAM,KAAK,MAAM;AAAA,QACf;AAAA,QACA,gBAAgB;AAAA,MAClB;AACA,aAAO,WAAW,QAAQ,eAAe,IAAI,WAAW;AAAA,IAC1D;AAIA,QAAI;AACF,mBAAa,QAAQ,gBAAgB,EAAE;AAAA,IACzC,SAAS,OAAO;AACd,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,WAAO,WAAW,QAAQ,eAAe,gBAAgB,IAAI,WAAW;AAAA,EAC1E;AACF;AASA,SAAS,iBAAiB,QAA6B;AACrD,MAAI;AACF,WAAO,OAAO,QAAQ,gBAAgB,EAAE;AAAA,EAC1C,SAAS,OAAO;AACd,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS,uCAAuC,OAAO;AAAA,QACrD;AAAA,MACF,EAAE,KAAK,IAAI,CAAC;AAAA,IACd,CAAC;AAAA,EACH;AACF;AAUA,SAAS,mBACP,QACA,QACkB;AAClB,MAAI;AACF,WAAO,YAAY,QAAQ,QAAQ,MAAM;AAAA,EAC3C,SAAS,OAAO;AACd,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,IAC3C,CAAC;AAAA,EACH;AACF;","names":["methodHooks"]}
|
|
@@ -1 +0,0 @@
|
|
|
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"],"mappings":";;;;;AAKA,SAAS,gBAAgB,mBAAmB;AAC5C,SAAS,iBAAiB;AAE1B,SAAS,4BAA4B;AACrC,SAAS,8BAA8B,iBAAiB;AAExD,SAAS,UAAU,aAAa,QAAQ,mBAAmB;AAMpD,IAAM,wBAAwB;AAErC,IAAM,aAAa;AAi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EACF,aAAa,CAAC,sBAAsB;AAAA,EACpC,gBAAgB;AAAA,EAChB;AACF;AAEA,IAAM,kCAAkC,OAAO;AAAA,EAC7C,IAAI,OAAO;AAAA,EACX,IAAI;AACN,CAAC;AAmBD,eAAe,iCACb,KACA,KACA,OACA,KACA,EAAE,gBAAgB,GACH;AACf,QAAM,EAAE,OAAO,IAAI;AAEnB,MAAI;AACF,UAAM,kBAAkB,mBAAmB,MAAM;AAEjD,UAAM,EAAE,IAAI,GAAG,IAAI;AAEnB,UAAM,gBAAgB,IAAI,EAAE;AAC5B,QAAI,SAAS;AAAA,EACf,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,SAAO,IAAI;AACb;AASA,SAAS,mBAAmB,QAA4C;AACtE,MAAI;AACF,WAAO,OAAO,QAAQ,+BAA+B;AAAA,EACvD,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,UAAM,UAAU,SAAS;AAAA,EAC3B;AACF","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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/restricted/dialog.ts"],"names":["methodHooks"],"mappings":";AAKA,SAAS,gBAAgB,mBAAmB;AAC5C,S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,IAAI,WAAW;AAAA,EAC1E;AACF;AASA,SAAS,iBAAiB,QAA6B;AACrD,MAAI;AACF,WAAO,OAAO,QAAQ,gBAAgB,EAAE;AAAA,EAC1C,SAAS,OAAO;AACd,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS,uCAAuC,OAAO;AAAA,QACrD;AAAA,MACF,EAAE,KAAK,IAAI,CAAC;AAAA,IACd,CAAC;AAAA,EACH;AACF;AAUA,SAAS,mBACP,QACA,QACkB;AAClB,MAAI;AACF,WAAO,YAAY,QAAQ,QAAQ,MAAM;AAAA,EAC3C,SAAS,OAAO;AACd,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,IAC3C,CAAC;AAAA,EACH;AACF","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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/restricted/manageState.ts"],"names":["methodHooks"],"mappings":";;;;;AAKA,SAAS,gBAAgB,mBAAmB;AAC5C,SAAS,iBAAiB;AAE1B,SAAS,4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C,SAAS,MAAM,GAAG;AACrB,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,QAAM,EAAE,WAAW,UAAU,UAAU,IAAI;AAE3C,MACE,CAAC,aACD,OAAO,cAAc,YACrB,CAAC,OAAO,OAAO,oBAAoB,EAAE;AAAA,IACnC;AAAA,EACF,GACA;AACA,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,MAAI,cAAc,UAAa,OAAO,cAAc,WAAW;AAC7D,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,MAAI,cAAc,qBAAqB,aAAa;AAClD,QAAI,CAAC,SAAS,QAAQ,GAAG;AACvB,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,WAAW,MAAM;AAAA,QAC1B,MAAM;AAAA,UACJ,kBACE,OAAO,aAAa,cAAc,cAAc;AAAA,QACpD;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI;AACJ,QAAI;AAEF,aAAO,YAAY,QAAQ;AAAA,IAC7B,QAAQ;AACN,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,WAAW,MAAM;AAAA,QAC1B,MAAM;AAAA,UACJ,kBACE,OAAO,aAAa,cAAc,cAAc;AAAA,QACpD;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,OAAO,kBAAkB;AAC3B,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,WAAW,MAAM,2DAA2D,gBAAgB;AAAA,QACrG,MAAM;AAAA,UACJ,kBACE,OAAO,aAAa,cAAc,cAAc;AAAA,QACpD;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT","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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/permitted/createInterface.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 CreateInterfaceParams,\n CreateInterfaceResult,\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 } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<CreateInterfaceMethodHooks> = {\n createInterface: true,\n};\n\nexport type CreateInterfaceMethodHooks = {\n /**\n * @param ui - The UI components.\n * @returns The unique identifier of the interface.\n */\n createInterface: (ui: Component) => Promise<string>;\n};\n\nexport const createInterfaceHandler: PermittedHandlerExport<\n CreateInterfaceMethodHooks,\n CreateInterfaceParameters,\n CreateInterfaceResult\n> = {\n methodNames: ['snap_createInterface'],\n implementation: getCreateInterfaceImplementation,\n hookNames,\n};\n\nconst CreateInterfaceParametersStruct = object({\n ui: ComponentStruct,\n});\n\nexport type CreateInterfaceParameters = InferMatching<\n typeof CreateInterfaceParametersStruct,\n CreateInterfaceParams\n>;\n\n/**\n * The `snap_createInterface` 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.createInterface - The function to create the interface.\n * @returns Nothing.\n */\nasync function getCreateInterfaceImplementation(\n req: JsonRpcRequest<CreateInterfaceParameters>,\n res: PendingJsonRpcResponse<CreateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { createInterface }: CreateInterfaceMethodHooks,\n): Promise<void> {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { ui } = validatedParams;\n\n res.result = await createInterface(ui);\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the createInterface 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 createInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): CreateInterfaceParameters {\n try {\n return create(params, CreateInterfaceParametersStruct);\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"],"mappings":";AAEA,SAAS,iBAAiB;AAO1B,SAAS,uBAAuB;AAGhC,SAAS,aAAa,QAAQ,cAAc;AAI5C,IAAM,YAA2D;AAAA,EAC/D,iBAAiB;AACnB;AAUO,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,sBAAsB;AAAA,EACpC,gBAAgB;AAAA,EAChB;AACF;AAEA,IAAM,kCAAkC,OAAO;AAAA,EAC7C,IAAI;AACN,CAAC;AAmBD,eAAe,iCACb,KACA,KACA,OACA,KACA,EAAE,gBAAgB,GACH;AACf,QAAM,EAAE,OAAO,IAAI;AAEnB,MAAI;AACF,UAAM,kBAAkB,mBAAmB,MAAM;AAEjD,UAAM,EAAE,GAAG,IAAI;AAEf,QAAI,SAAS,MAAM,gBAAgB,EAAE;AAAA,EACvC,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,SAAO,IAAI;AACb;AASA,SAAS,mBAAmB,QAA4C;AACtE,MAAI;AACF,WAAO,OAAO,QAAQ,+BAA+B;AAAA,EACvD,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,UAAM,UAAU,SAAS;AAAA,EAC3B;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
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"],"mappings":";AAEA,SAAS,iBAAiB;AAO1B,SAAS,uBAAuB;AAGhC,SAAS,aAAa,QAAQ,QAAQ,cAAc;AAIpD,IAAM,YAA2D;AAAA,EAC/D,iBAAiB;AACnB;AAUO,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,sBAAsB;AAAA,EACpC,gBAAgB;AAAA,EAChB;AACF;AAEA,IAAM,kCAAkC,OAAO;AAAA,EAC7C,IAAI,OAAO;AAAA,EACX,IAAI;AACN,CAAC;AAmBD,eAAe,iCACb,KACA,KACA,OACA,KACA,EAAE,gBAAgB,GACH;AACf,QAAM,EAAE,OAAO,IAAI;AAEnB,MAAI;AACF,UAAM,kBAAkB,mBAAmB,MAAM;AAEjD,UAAM,EAAE,IAAI,GAAG,IAAI;AAEnB,UAAM,gBAAgB,IAAI,EAAE;AAC5B,QAAI,SAAS;AAAA,EACf,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,SAAO,IAAI;AACb;AASA,SAAS,mBAAmB,QAA4C;AACtE,MAAI;AACF,WAAO,OAAO,QAAQ,+BAA+B;AAAA,EACvD,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa;AAChC,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS,mBAAmB,MAAM,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,UAAM,UAAU,SAAS;AAAA,EAC3B;AACF;","names":[]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|