@metamask/snaps-rpc-methods 7.0.2 → 8.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.
Files changed (31) hide show
  1. package/CHANGELOG.md +7 -1
  2. package/dist/{chunk-AKRFLGOS.mjs → chunk-AMBEX4N4.mjs} +2 -2
  3. package/dist/{chunk-FBOZCV3C.js → chunk-EGKFC56F.js} +3 -3
  4. package/dist/{chunk-7NBRKDKJ.mjs → chunk-NESDQ4PF.mjs} +9 -54
  5. package/dist/chunk-NESDQ4PF.mjs.map +1 -0
  6. package/dist/{chunk-KO4MKRYZ.js → chunk-R2M4YLJ7.js} +7 -52
  7. package/dist/chunk-R2M4YLJ7.js.map +1 -0
  8. package/dist/{chunk-LVTN25J2.js → chunk-RZXF4KSR.js} +3 -3
  9. package/dist/{chunk-LVTN25J2.js.map → chunk-RZXF4KSR.js.map} +1 -1
  10. package/dist/{chunk-3S7DJI4I.mjs → chunk-SU6KOIVB.mjs} +2 -2
  11. package/dist/chunk-SU6KOIVB.mjs.map +1 -0
  12. package/dist/index.js +4 -4
  13. package/dist/index.mjs +5 -5
  14. package/dist/permissions.js +4 -4
  15. package/dist/permissions.mjs +3 -3
  16. package/dist/restricted/index.js +3 -3
  17. package/dist/restricted/index.mjs +4 -4
  18. package/dist/restricted/manageState.js +2 -2
  19. package/dist/restricted/manageState.mjs +3 -3
  20. package/dist/tsconfig.build.tsbuildinfo +1 -1
  21. package/dist/types/permitted/createInterface.d.ts +38 -38
  22. package/dist/types/permitted/updateInterface.d.ts +39 -39
  23. package/dist/types/restricted/dialog.d.ts +144 -144
  24. package/dist/types/restricted/index.d.ts +1 -1
  25. package/dist/types/restricted/manageState.d.ts +5 -31
  26. package/package.json +3 -4
  27. package/dist/chunk-3S7DJI4I.mjs.map +0 -1
  28. package/dist/chunk-7NBRKDKJ.mjs.map +0 -1
  29. package/dist/chunk-KO4MKRYZ.js.map +0 -1
  30. /package/dist/{chunk-AKRFLGOS.mjs.map → chunk-AMBEX4N4.mjs.map} +0 -0
  31. /package/dist/{chunk-FBOZCV3C.js.map → chunk-EGKFC56F.js.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, Hex } from '@metamask/utils';
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 getEncryptionKey({ mnemonicPhrase, snapId, }: GetEncryptionKeyArgs): Promise<`0x${string}`>;
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({ getMnemonic, getUnlockPromise, clearSnapState, getSnapState, updateSnapState, encrypt, decrypt, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
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": "7.0.2",
3
+ "version": "8.0.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": "^3.2.0",
46
- "@metamask/snaps-utils": "^7.0.4",
45
+ "@metamask/snaps-sdk": "^4.0.0",
46
+ "@metamask/snaps-utils": "^7.1.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/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/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;AAiFZ,IAAM,uBAIT,CAAC;AAAA,EACH,iBAAiB;AAAA,EACjB,aAAAA;AACF,MAA8C;AAC5C,SAAO;AAAA,IACL,gBAAgB,eAAe;AAAA,IAC/B,YAAY;AAAA,IACZ;AAAA,IACA,sBAAsB,6BAA6BA,YAAW;AAAA,IAC9D,cAAc,CAAC,YAAY,IAAI;AAAA,EACjC;AACF;AAEA,IAAM,cAAyD;AAAA,EAC7D,aAAa;AAAA,EACb,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,SAAS;AAAA,EACT,SAAS;AACX;AAEO,IAAM,qBAAqB,OAAO,OAAO;AAAA,EAC9C,YAAY;AAAA,EACZ;AAAA,EACA;AACF,CAAU;AAEH,IAAM,qBAAqB;AAoBlC,eAAsB,iBAAiB;AAAA,EACrC;AAAA,EACA;AACF,GAAyB;AACvB,SAAO,MAAM,cAAc;AAAA,IACzB;AAAA,IACA,OAAO;AAAA,IACP,MAAM;AAAA,IACN,OAAO;AAAA,EACT,CAAC;AACH;AAmBA,eAAe,aAAa;AAAA,EAC1B;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAqB;AACnB,QAAM,g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ACH;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;","names":["methodHooks"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/restricted/manageState.ts"],"names":["methodHooks"],"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;AAiFZ,IAAM,uBAIT,CAAC;AAAA,EACH,iBAAiB;AAAA,EACjB,aAAAA;AACF,MAA8C;AAC5C,SAAO;AAAA,IACL,gBAAgB,eAAe;AAAA,IAC/B,YAAY;AAAA,IACZ;AAAA,IACA,sBAAsB,6BAA6BA,YAAW;AAAA,IAC9D,cAAc,CAAC,YAAY,IAAI;AAAA,EACjC;AACF;AAEA,IAAM,cAAyD;AAAA,EAC7D,aAAa;AAAA,EACb,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,SAAS;AAAA,EACT,SAAS;AACX;AAEO,IAAM,qBAAqB,OAAO,OAAO;AAAA,EAC9C,YAAY;AAAA,EACZ;AAAA,EACA;AACF,CAAU;AAEH,IAAM,qBAAqB;AAoBlC,eAAsB,iBAAiB;AAAA,EACrC;AAAA,EACA;AACF,GAAyB;AACvB,SAAO,MAAM,cAAc;AAAA,IACzB;AAAA,IACA,OAAO;AAAA,IACP,MAAM;AAAA,IACN,OAAO;AAAA,EACT,CAAC;AACH;AAmBA,eAAe,aAAa;AAAA,EAC1B;AAAA,EACA;AAAA,EACA,GAAG;AAC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AAA,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"]}