@metamask/snaps-rpc-methods 13.5.0 → 13.5.2

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 (42) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/permitted/createInterface.cjs +2 -2
  3. package/dist/permitted/createInterface.cjs.map +1 -1
  4. package/dist/permitted/createInterface.d.cts +15 -3
  5. package/dist/permitted/createInterface.d.cts.map +1 -1
  6. package/dist/permitted/createInterface.d.mts +15 -3
  7. package/dist/permitted/createInterface.d.mts.map +1 -1
  8. package/dist/permitted/createInterface.mjs +2 -2
  9. package/dist/permitted/createInterface.mjs.map +1 -1
  10. package/dist/permitted/sendWebSocketMessage.cjs +2 -2
  11. package/dist/permitted/sendWebSocketMessage.cjs.map +1 -1
  12. package/dist/permitted/sendWebSocketMessage.d.cts +1 -1
  13. package/dist/permitted/sendWebSocketMessage.d.cts.map +1 -1
  14. package/dist/permitted/sendWebSocketMessage.d.mts +1 -1
  15. package/dist/permitted/sendWebSocketMessage.d.mts.map +1 -1
  16. package/dist/permitted/sendWebSocketMessage.mjs +2 -2
  17. package/dist/permitted/sendWebSocketMessage.mjs.map +1 -1
  18. package/dist/permitted/setState.cjs +13 -6
  19. package/dist/permitted/setState.cjs.map +1 -1
  20. package/dist/permitted/setState.d.cts +7 -1
  21. package/dist/permitted/setState.d.cts.map +1 -1
  22. package/dist/permitted/setState.d.mts +7 -1
  23. package/dist/permitted/setState.d.mts.map +1 -1
  24. package/dist/permitted/setState.mjs +14 -7
  25. package/dist/permitted/setState.mjs.map +1 -1
  26. package/dist/permitted/updateInterface.cjs +2 -2
  27. package/dist/permitted/updateInterface.cjs.map +1 -1
  28. package/dist/permitted/updateInterface.d.cts +1 -1
  29. package/dist/permitted/updateInterface.d.cts.map +1 -1
  30. package/dist/permitted/updateInterface.d.mts +1 -1
  31. package/dist/permitted/updateInterface.d.mts.map +1 -1
  32. package/dist/permitted/updateInterface.mjs +2 -2
  33. package/dist/permitted/updateInterface.mjs.map +1 -1
  34. package/dist/restricted/manageState.cjs +16 -14
  35. package/dist/restricted/manageState.cjs.map +1 -1
  36. package/dist/restricted/manageState.d.cts +10 -3
  37. package/dist/restricted/manageState.d.cts.map +1 -1
  38. package/dist/restricted/manageState.d.mts +10 -3
  39. package/dist/restricted/manageState.d.mts.map +1 -1
  40. package/dist/restricted/manageState.mjs +18 -16
  41. package/dist/restricted/manageState.mjs.map +1 -1
  42. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"setState.mjs","sourceRoot":"","sources":["../../src/permitted/setState.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,6BAA6B;AAIjE,OAAO,EACL,OAAO,EACP,MAAM,EACN,MAAM,IAAI,YAAY,EACtB,QAAQ,EACR,WAAW,EACZ,8BAA8B;AAM/B,OAAO,EACL,WAAW,EACX,WAAW,EACX,QAAQ,EACR,MAAM,EACN,UAAU,EACX,wBAAwB;AAEzB,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EACnB,sCAAkC;AAEnC,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,qBAAiB;AAE1D,MAAM,SAAS,GAAqC;IAClD,aAAa,EAAE,IAAI;IACnB,YAAY,EAAE,IAAI;IAClB,gBAAgB,EAAE,IAAI;IACtB,eAAe,EAAE,IAAI;CACtB,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAIxB;IACF,WAAW,EAAE,CAAC,eAAe,CAAC;IAC9B,cAAc,EAAE,sBAAsB;IACtC,SAAS;CACV,CAAC;AAsCF,MAAM,wBAAwB,GAAG,YAAY,CAAC;IAC5C,GAAG,EAAE,QAAQ,CAAC,cAAc,CAAC;IAC7B,KAAK,EAAE,UAAU;IACjB,SAAS,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;CAC/B,CAAC,CAAC;AAOH;;;;;;;;;;;;;;;GAeG;AACH,KAAK,UAAU,sBAAsB,CACn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AAC,UAAU,CAAC,EAAE,CAAC;YACxC,MAAM,SAAS,CAAC,aAAa,CAC3B,oDAAoD,CACrD,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC1B,aAAa,CAAC,UAAU,CAAC,GAAG,KAAK,CAAC;YAClC,OAAO,cAAc,CAAC;QACxB,CAAC;QAED,IACE,CAAC,WAAW,CAAC,aAAa,EAAE,UAAU,CAAC;YACvC,aAAa,CAAC,UAAU,CAAC,KAAK,IAAI,EAClC,CAAC;YACD,aAAa,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC;QACjC,CAAC;aAAM,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;YAChD,MAAM,SAAS,CAAC,aAAa,CAC3B,oDAAoD,CACrD,CAAC;QACJ,CAAC;QAED,aAAa,GAAG,aAAa,CAAC,UAAU,CAAyB,CAAC;IACpE,CAAC;IAED,gCAAgC;IAChC,0BAA0B;IAC1B,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { SetStateParams, SetStateResult } from '@metamask/snaps-sdk';\nimport type { JsonObject } from '@metamask/snaps-sdk/jsx';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport {\n boolean,\n create,\n object as objectStruct,\n optional,\n StructError,\n} from '@metamask/superstruct';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport {\n getJsonSize,\n hasProperty,\n isObject,\n assert,\n JsonStruct,\n} from '@metamask/utils';\n\nimport {\n manageStateBuilder,\n STORAGE_SIZE_LIMIT,\n} from '../restricted/manageState';\nimport type { MethodHooksObject } from '../utils';\nimport { FORBIDDEN_KEYS, StateKeyStruct } from '../utils';\n\nconst hookNames: MethodHooksObject<SetStateHooks> = {\n hasPermission: true,\n getSnapState: true,\n getUnlockPromise: true,\n updateSnapState: true,\n};\n\n/**\n * `snap_setState` sets the state of the Snap.\n */\nexport const setStateHandler: PermittedHandlerExport<\n SetStateHooks,\n SetStateParameters,\n SetStateResult\n> = {\n methodNames: ['snap_setState'],\n implementation: setStateImplementation,\n hookNames,\n};\n\nexport type SetStateHooks = {\n /**\n * Check if the requesting origin has a given permission.\n *\n * @param permissionName - The name of the permission to check.\n * @returns Whether the origin has the permission.\n */\n hasPermission: (permissionName: string) => boolean;\n\n /**\n * Get the state of the requesting Snap.\n *\n * @param encrypted - Whether the state is encrypted.\n * @returns The current state of the Snap.\n */\n getSnapState: (encrypted: boolean) => Promise<Record<string, Json>>;\n\n /**\n * Wait 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 * Update the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n * @param encrypted - Whether the state should be encrypted.\n */\n updateSnapState: (\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n};\n\nconst SetStateParametersStruct = objectStruct({\n key: optional(StateKeyStruct),\n value: JsonStruct,\n encrypted: optional(boolean()),\n});\n\nexport type SetStateParameters = InferMatching<\n typeof SetStateParametersStruct,\n SetStateParams\n>;\n\n/**\n * The `snap_setState` method implementation.\n *\n * @param request - The JSON-RPC request object.\n * @param response - 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.hasPermission - Check whether a given origin has a given\n * permission.\n * @param hooks.getSnapState - Get the state of the requesting Snap.\n * @param hooks.getUnlockPromise - Wait for the extension to be unlocked.\n * @param hooks.updateSnapState - Update the state of the requesting Snap.\n * @returns Nothing.\n */\nasync function setStateImplementation(\n request: JsonRpcRequest<SetStateParameters>,\n response: PendingJsonRpcResponse<SetStateResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n hasPermission,\n getSnapState,\n getUnlockPromise,\n updateSnapState,\n }: SetStateHooks,\n): Promise<void> {\n const { params } = request;\n\n if (!hasPermission(manageStateBuilder.targetName)) {\n return end(providerErrors.unauthorized());\n }\n\n try {\n const validatedParams = getValidatedParams(params);\n const { key, value, encrypted = true } = validatedParams;\n\n if (key === undefined && !isObject(value)) {\n return end(\n rpcErrors.invalidParams(\n 'Invalid params: Value must be an object if key is not provided.',\n ),\n );\n }\n\n if (encrypted) {\n await getUnlockPromise(true);\n }\n\n const newState = await getNewState(key, value, encrypted, getSnapState);\n\n const size = getJsonSize(newState);\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n\n await updateSnapState(newState, encrypted);\n response.result = null;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the parameters of the `snap_setState` method.\n *\n * @param params - The parameters to validate.\n * @returns The validated parameters.\n */\nfunction getValidatedParams(params?: unknown) {\n try {\n return create(params, SetStateParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n\n/**\n * Get the new state of the Snap.\n *\n * If the key is `undefined`, the value is expected to be an object. In this\n * case, the value is returned as the new state.\n *\n * If the key is not `undefined`, the value is set in the state at the key. If\n * the key does not exist, it is created (and any missing intermediate keys are\n * created as well).\n *\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @param encrypted - Whether the state is encrypted.\n * @param getSnapState - The `getSnapState` hook.\n * @returns The new state of the Snap.\n */\nasync function getNewState(\n key: string | undefined,\n value: Json,\n encrypted: boolean,\n getSnapState: SetStateHooks['getSnapState'],\n) {\n if (key === undefined) {\n assert(isObject(value));\n return value;\n }\n\n const state = await getSnapState(encrypted);\n return set(state, key, value);\n}\n\n/**\n * Set the value of a key in an object. The key may contain Lodash-style path\n * syntax, e.g., `a.b.c` (with the exception of array syntax). If the key does\n * not exist, it is created (and any missing intermediate keys are created as\n * well).\n *\n * This is a simplified version of Lodash's `set` function, but Lodash doesn't\n * seem to be maintained anymore, so we're using our own implementation.\n *\n * @param object - The object to get the key from.\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @returns The new object with the key set to the value.\n */\nexport function set(\n object: Record<string, Json> | null,\n key: string,\n value: Json,\n): JsonObject {\n const keys = key.split('.');\n const requiredObject = object ?? {};\n let currentObject: Record<string, Json> = requiredObject;\n\n for (let i = 0; i < keys.length; i++) {\n const currentKey = keys[i];\n if (FORBIDDEN_KEYS.includes(currentKey)) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Key contains forbidden characters.',\n );\n }\n\n if (i === keys.length - 1) {\n currentObject[currentKey] = value;\n return requiredObject;\n }\n\n if (\n !hasProperty(currentObject, currentKey) ||\n currentObject[currentKey] === null\n ) {\n currentObject[currentKey] = {};\n } else if (!isObject(currentObject[currentKey])) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Cannot overwrite non-object value.',\n );\n }\n\n currentObject = currentObject[currentKey] as Record<string, Json>;\n }\n\n // This should never be reached.\n /* istanbul ignore next */\n throw new Error('Unexpected error while setting the state.');\n}\n"]}
1
+ {"version":3,"file":"setState.mjs","sourceRoot":"","sources":["../../src/permitted/setState.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,6BAA6B;AAGjE,OAAO,EACL,iBAAiB,EAGlB,8BAA8B;AAC/B,OAAO,EACL,OAAO,EACP,MAAM,EACN,MAAM,IAAI,YAAY,EACtB,QAAQ,EACR,WAAW,EACZ,8BAA8B;AAM/B,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,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EAAE,CAAC;QACjC,CAAC;aAAM,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;YAChD,MAAM,SAAS,CAAC,aAAa,CAC3B,oDAAoD,CACrD,CAAC;QACJ,CAAC;QAED,aAAa,GAAG,aAAa,CAAC,UAAU,CAAyB,CAAC;IACpE,CAAC;IAED,gCAAgC;IAChC,0BAA0B;IAC1B,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { SetStateParams, SetStateResult } from '@metamask/snaps-sdk';\nimport type { JsonObject } from '@metamask/snaps-sdk/jsx';\nimport {\n getJsonSizeUnsafe,\n type InferMatching,\n type Snap,\n} from '@metamask/snaps-utils';\nimport {\n boolean,\n create,\n object as objectStruct,\n optional,\n StructError,\n} from '@metamask/superstruct';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport { hasProperty, isObject, assert, JsonStruct } from '@metamask/utils';\n\nimport {\n manageStateBuilder,\n STORAGE_SIZE_LIMIT,\n} from '../restricted/manageState';\nimport type { MethodHooksObject } from '../utils';\nimport { FORBIDDEN_KEYS, StateKeyStruct } from '../utils';\n\nconst hookNames: MethodHooksObject<SetStateHooks> = {\n hasPermission: true,\n getSnapState: true,\n getUnlockPromise: true,\n updateSnapState: true,\n getSnap: true,\n};\n\n/**\n * `snap_setState` sets the state of the Snap.\n */\nexport const setStateHandler: PermittedHandlerExport<\n SetStateHooks,\n SetStateParameters,\n SetStateResult\n> = {\n methodNames: ['snap_setState'],\n implementation: setStateImplementation,\n hookNames,\n};\n\nexport type SetStateHooks = {\n /**\n * Check if the requesting origin has a given permission.\n *\n * @param permissionName - The name of the permission to check.\n * @returns Whether the origin has the permission.\n */\n hasPermission: (permissionName: string) => boolean;\n\n /**\n * Get the state of the requesting Snap.\n *\n * @param encrypted - Whether the state is encrypted.\n * @returns The current state of the Snap.\n */\n getSnapState: (encrypted: boolean) => Promise<Record<string, Json>>;\n\n /**\n * Wait 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 * Update the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n * @param encrypted - Whether the state should be encrypted.\n */\n updateSnapState: (\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n\n /**\n * Get Snap metadata.\n *\n * @param snapId - The ID of a Snap.\n */\n getSnap: (snapId: string) => Snap | undefined;\n};\n\nconst SetStateParametersStruct = objectStruct({\n key: optional(StateKeyStruct),\n value: JsonStruct,\n encrypted: optional(boolean()),\n});\n\nexport type SetStateParameters = InferMatching<\n typeof SetStateParametersStruct,\n SetStateParams\n>;\n\n/**\n * The `snap_setState` method implementation.\n *\n * @param request - The JSON-RPC request object.\n * @param response - 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.hasPermission - Check whether a given origin has a given\n * permission.\n * @param hooks.getSnapState - Get the state of the requesting Snap.\n * @param hooks.getUnlockPromise - Wait for the extension to be unlocked.\n * @param hooks.updateSnapState - Update the state of the requesting Snap.\n * @param hooks.getSnap - The hook function to get Snap metadata.\n * @returns Nothing.\n */\nasync function setStateImplementation(\n request: JsonRpcRequest<SetStateParameters>,\n response: PendingJsonRpcResponse<SetStateResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n hasPermission,\n getSnapState,\n getUnlockPromise,\n updateSnapState,\n getSnap,\n }: SetStateHooks,\n): Promise<void> {\n const { params } = request;\n\n if (!hasPermission(manageStateBuilder.targetName)) {\n return end(providerErrors.unauthorized());\n }\n\n try {\n const validatedParams = getValidatedParams(params);\n const { key, value, encrypted = true } = validatedParams;\n\n if (key === undefined && !isObject(value)) {\n return end(\n rpcErrors.invalidParams(\n 'Invalid params: Value must be an object if key is not provided.',\n ),\n );\n }\n\n if (encrypted) {\n await getUnlockPromise(true);\n }\n\n const newState = await getNewState(key, value, encrypted, getSnapState);\n\n const snap = getSnap(\n (request as JsonRpcRequest<SetStateParams> & { origin: string }).origin,\n );\n\n if (!snap?.preinstalled) {\n // We know that the state is valid JSON as per previous validation.\n const size = getJsonSizeUnsafe(newState, true);\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n }\n\n await updateSnapState(newState, encrypted);\n response.result = null;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the parameters of the `snap_setState` method.\n *\n * @param params - The parameters to validate.\n * @returns The validated parameters.\n */\nfunction getValidatedParams(params?: unknown) {\n try {\n return create(params, SetStateParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n\n/**\n * Get the new state of the Snap.\n *\n * If the key is `undefined`, the value is expected to be an object. In this\n * case, the value is returned as the new state.\n *\n * If the key is not `undefined`, the value is set in the state at the key. If\n * the key does not exist, it is created (and any missing intermediate keys are\n * created as well).\n *\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @param encrypted - Whether the state is encrypted.\n * @param getSnapState - The `getSnapState` hook.\n * @returns The new state of the Snap.\n */\nasync function getNewState(\n key: string | undefined,\n value: Json,\n encrypted: boolean,\n getSnapState: SetStateHooks['getSnapState'],\n) {\n if (key === undefined) {\n assert(isObject(value));\n return value;\n }\n\n const state = await getSnapState(encrypted);\n return set(state, key, value);\n}\n\n/**\n * Set the value of a key in an object. The key may contain Lodash-style path\n * syntax, e.g., `a.b.c` (with the exception of array syntax). If the key does\n * not exist, it is created (and any missing intermediate keys are created as\n * well).\n *\n * This is a simplified version of Lodash's `set` function, but Lodash doesn't\n * seem to be maintained anymore, so we're using our own implementation.\n *\n * @param object - The object to get the key from.\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @returns The new object with the key set to the value.\n */\nexport function set(\n object: Record<string, Json> | null,\n key: string,\n value: Json,\n): JsonObject {\n const keys = key.split('.');\n const requiredObject = object ?? {};\n let currentObject: Record<string, Json> = requiredObject;\n\n for (let i = 0; i < keys.length; i++) {\n const currentKey = keys[i];\n if (FORBIDDEN_KEYS.includes(currentKey)) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Key contains forbidden characters.',\n );\n }\n\n if (i === keys.length - 1) {\n currentObject[currentKey] = value;\n return requiredObject;\n }\n\n if (\n !hasProperty(currentObject, currentKey) ||\n currentObject[currentKey] === null\n ) {\n currentObject[currentKey] = {};\n } else if (!isObject(currentObject[currentKey])) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Cannot overwrite non-object value.',\n );\n }\n\n currentObject = currentObject[currentKey] as Record<string, Json>;\n }\n\n // This should never be reached.\n /* istanbul ignore next */\n throw new Error('Unexpected error while setting the state.');\n}\n"]}
@@ -29,12 +29,12 @@ const UpdateInterfaceParametersStruct = (0, superstruct_1.object)({
29
29
  * @param hooks.updateInterface - The function to update the interface.
30
30
  * @returns Nothing.
31
31
  */
32
- async function getUpdateInterfaceImplementation(req, res, _next, end, { updateInterface }) {
32
+ function getUpdateInterfaceImplementation(req, res, _next, end, { updateInterface }) {
33
33
  const { params } = req;
34
34
  try {
35
35
  const validatedParams = getValidatedParams(params);
36
36
  const { id, ui, context } = validatedParams;
37
- await updateInterface(id, ui, context);
37
+ updateInterface(id, ui, context);
38
38
  res.result = null;
39
39
  }
40
40
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"updateInterface.cjs","sourceRoot":"","sources":["../../src/permitted/updateIn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S,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,mBAAmB,KAAK,CAAC,OAAO,GAAG;aAC7C,CAAC,CAAC;QACL,CAAC;QACD,0BAA0B;QAC1B,MAAM,sBAAS,CAAC,QAAQ,EAAE,CAAC;IAC7B,CAAC;AACH,CAAC","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 UpdateInterfaceParams,\n UpdateInterfaceResult,\n JsonRpcRequest,\n ComponentOrElement,\n InterfaceContext,\n} from '@metamask/snaps-sdk';\nimport {\n ComponentOrElementStruct,\n InterfaceContextStruct,\n} from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport {\n StructError,\n create,\n object,\n optional,\n string,\n} from '@metamask/superstruct';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\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 * @param context - The optional interface context object.\n */\n updateInterface: (\n id: string,\n ui: ComponentOrElement,\n context?: InterfaceContext,\n ) => 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: ComponentOrElementStruct,\n context: optional(InterfaceContextStruct),\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, context } = validatedParams;\n\n await updateInterface(id, ui, context);\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
+ {"version":3,"file":"updateInterface.cjs","sourceRoot":"","sources":["../../src/permitted/updateInterface.ts"],"names":[],"mappings":";;;AAEA,qDAAiD;AAQjD,mDAG6B;AAE7B,uDAM+B;AAK/B,MAAM,SAAS,GAAkD;IAC/D,eAAe,EAAE,IAAI;CACtB,CAAC;AAeW,QAAA,sBAAsB,GAI/B;IACF,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,cAAc,EAAE,gCAAgC;IAChD,SAAS;CACV,CAAC;AAEF,MAAM,+BAA+B,GAAG,IAAA,oBAAM,EAAC;IAC7C,EAAE,EAAE,IAAA,oBAAM,GAAE;IACZ,EAAE,EAAE,oCAAwB;IAC5B,OAAO,EAAE,IAAA,sBAAQ,EAAC,kCAAsB,CAAC;CAC1C,CAAC,CAAC;AAOH;;;;;;;;;;;GAWG;AACH,SAAS,gCAAgC,CACvC,GAA8C,EAC9C,GAAkD,EAClD,KAAc,EACd,GAA6B,EAC7B,EAAE,eAAe,EAA8B;IAE/C,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,IAAI,CAAC;QACH,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;QAEnD,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC;QAE5C,eAAe,CAAC,EAAE,EAAE,EAAE,EAAE,OAAO,CAAC,CAAC;QACjC,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC;IACpB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,OAAO,GAAG,EAAE,CAAC;AACf,CAAC;AAED;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,MAAe;IACzC,IAAI,CAAC;QACH,OAAO,IAAA,oBAAM,EAAC,MAAM,EAAE,+BAA+B,CAAC,CAAC;IACzD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,yBAAW,EAAE,CAAC;YACjC,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,mBAAmB,KAAK,CAAC,OAAO,GAAG;aAC7C,CAAC,CAAC;QACL,CAAC;QACD,0BAA0B;QAC1B,MAAM,sBAAS,CAAC,QAAQ,EAAE,CAAC;IAC7B,CAAC;AACH,CAAC","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 UpdateInterfaceParams,\n UpdateInterfaceResult,\n JsonRpcRequest,\n ComponentOrElement,\n InterfaceContext,\n} from '@metamask/snaps-sdk';\nimport {\n ComponentOrElementStruct,\n InterfaceContextStruct,\n} from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport {\n StructError,\n create,\n object,\n optional,\n string,\n} from '@metamask/superstruct';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\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 * @param context - The optional interface context object.\n */\n updateInterface: (\n id: string,\n ui: ComponentOrElement,\n context?: InterfaceContext,\n ) => 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: ComponentOrElementStruct,\n context: optional(InterfaceContextStruct),\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 */\nfunction getUpdateInterfaceImplementation(\n req: JsonRpcRequest<UpdateInterfaceParameters>,\n res: PendingJsonRpcResponse<UpdateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { updateInterface }: UpdateInterfaceMethodHooks,\n): void {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { id, ui, context } = validatedParams;\n\n updateInterface(id, ui, context);\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"]}
@@ -7,7 +7,7 @@ export type UpdateInterfaceMethodHooks = {
7
7
  * @param ui - The UI components.
8
8
  * @param context - The optional interface context object.
9
9
  */
10
- updateInterface: (id: string, ui: ComponentOrElement, context?: InterfaceContext) => Promise<void>;
10
+ updateInterface: (id: string, ui: ComponentOrElement, context?: InterfaceContext) => void;
11
11
  };
12
12
  export declare const updateInterfaceHandler: PermittedHandlerExport<UpdateInterfaceMethodHooks, UpdateInterfaceParameters, UpdateInterfaceResult>;
13
13
  declare const UpdateInterfaceParametersStruct: import("@metamask/superstruct").Struct<{
@@ -1 +1 @@
1
- {"version":3,"file":"updateInterface.d.cts","sourceRoot":"","sources":["../../src/permitted/updateInterface.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAwC;AAE9E,OAAO,KAAK,EACV,qBAAqB,EACrB,qBAAqB,EAErB,kBAAkB,EAClB,gBAAgB,EACjB,4BAA4B;AAK7B,OAAO,EAAE,KAAK,aAAa,EAAE,8BAA8B;AAgB3D,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,eAAe,EAAE,CACf,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,kBAAkB,EACtB,OAAO,CAAC,EAAE,gBAAgB,KACvB,OAAO,CAAC,IAAI,CAAC,CAAC;CACpB,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,sBAAsB,CACzD,0BAA0B,EAC1B,yBAAyB,EACzB,qBAAqB,CAKtB,CAAC;AAEF,QAAA,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAInC,CAAC;AAEH,MAAM,MAAM,yBAAyB,GAAG,aAAa,CACnD,OAAO,+BAA+B,EACtC,qBAAqB,CACtB,CAAC"}
1
+ {"version":3,"file":"updateInterface.d.cts","sourceRoot":"","sources":["../../src/permitted/updateInterface.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAwC;AAE9E,OAAO,KAAK,EACV,qBAAqB,EACrB,qBAAqB,EAErB,kBAAkB,EAClB,gBAAgB,EACjB,4BAA4B;AAK7B,OAAO,EAAE,KAAK,aAAa,EAAE,8BAA8B;AAgB3D,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,eAAe,EAAE,CACf,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,kBAAkB,EACtB,OAAO,CAAC,EAAE,gBAAgB,KACvB,IAAI,CAAC;CACX,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,sBAAsB,CACzD,0BAA0B,EAC1B,yBAAyB,EACzB,qBAAqB,CAKtB,CAAC;AAEF,QAAA,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAInC,CAAC;AAEH,MAAM,MAAM,yBAAyB,GAAG,aAAa,CACnD,OAAO,+BAA+B,EACtC,qBAAqB,CACtB,CAAC"}
@@ -7,7 +7,7 @@ export type UpdateInterfaceMethodHooks = {
7
7
  * @param ui - The UI components.
8
8
  * @param context - The optional interface context object.
9
9
  */
10
- updateInterface: (id: string, ui: ComponentOrElement, context?: InterfaceContext) => Promise<void>;
10
+ updateInterface: (id: string, ui: ComponentOrElement, context?: InterfaceContext) => void;
11
11
  };
12
12
  export declare const updateInterfaceHandler: PermittedHandlerExport<UpdateInterfaceMethodHooks, UpdateInterfaceParameters, UpdateInterfaceResult>;
13
13
  declare const UpdateInterfaceParametersStruct: import("@metamask/superstruct").Struct<{
@@ -1 +1 @@
1
- {"version":3,"file":"updateInterface.d.mts","sourceRoot":"","sources":["../../src/permitted/updateInterface.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAwC;AAE9E,OAAO,KAAK,EACV,qBAAqB,EACrB,qBAAqB,EAErB,kBAAkB,EAClB,gBAAgB,EACjB,4BAA4B;AAK7B,OAAO,EAAE,KAAK,aAAa,EAAE,8BAA8B;AAgB3D,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,eAAe,EAAE,CACf,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,kBAAkB,EACtB,OAAO,CAAC,EAAE,gBAAgB,KACvB,OAAO,CAAC,IAAI,CAAC,CAAC;CACpB,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,sBAAsB,CACzD,0BAA0B,EAC1B,yBAAyB,EACzB,qBAAqB,CAKtB,CAAC;AAEF,QAAA,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAInC,CAAC;AAEH,MAAM,MAAM,yBAAyB,GAAG,aAAa,CACnD,OAAO,+BAA+B,EACtC,qBAAqB,CACtB,CAAC"}
1
+ {"version":3,"file":"updateInterface.d.mts","sourceRoot":"","sources":["../../src/permitted/updateInterface.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAwC;AAE9E,OAAO,KAAK,EACV,qBAAqB,EACrB,qBAAqB,EAErB,kBAAkB,EAClB,gBAAgB,EACjB,4BAA4B;AAK7B,OAAO,EAAE,KAAK,aAAa,EAAE,8BAA8B;AAgB3D,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,eAAe,EAAE,CACf,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,kBAAkB,EACtB,OAAO,CAAC,EAAE,gBAAgB,KACvB,IAAI,CAAC;CACX,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,sBAAsB,CACzD,0BAA0B,EAC1B,yBAAyB,EACzB,qBAAqB,CAKtB,CAAC;AAEF,QAAA,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAInC,CAAC;AAEH,MAAM,MAAM,yBAAyB,GAAG,aAAa,CACnD,OAAO,+BAA+B,EACtC,qBAAqB,CACtB,CAAC"}
@@ -26,12 +26,12 @@ const UpdateInterfaceParametersStruct = object({
26
26
  * @param hooks.updateInterface - The function to update the interface.
27
27
  * @returns Nothing.
28
28
  */
29
- async function getUpdateInterfaceImplementation(req, res, _next, end, { updateInterface }) {
29
+ function getUpdateInterfaceImplementation(req, res, _next, end, { updateInterface }) {
30
30
  const { params } = req;
31
31
  try {
32
32
  const validatedParams = getValidatedParams(params);
33
33
  const { id, ui, context } = validatedParams;
34
- await updateInterface(id, ui, context);
34
+ updateInterface(id, ui, context);
35
35
  res.result = null;
36
36
  }
37
37
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"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ACH,OAAO,MAAM,CAAC,MAAM,EAAE,+BAA+B,CAAC,CAAC;IACzD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,WAAW,EAAE,CAAC;YACjC,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,mBAAmB,KAAK,CAAC,OAAO,GAAG;aAC7C,CAAC,CAAC;QACL,CAAC;QACD,0BAA0B;QAC1B,MAAM,SAAS,CAAC,QAAQ,EAAE,CAAC;IAC7B,CAAC;AACH,CAAC","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 UpdateInterfaceParams,\n UpdateInterfaceResult,\n JsonRpcRequest,\n ComponentOrElement,\n InterfaceContext,\n} from '@metamask/snaps-sdk';\nimport {\n ComponentOrElementStruct,\n InterfaceContextStruct,\n} from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport {\n StructError,\n create,\n object,\n optional,\n string,\n} from '@metamask/superstruct';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\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 * @param context - The optional interface context object.\n */\n updateInterface: (\n id: string,\n ui: ComponentOrElement,\n context?: InterfaceContext,\n ) => 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: ComponentOrElementStruct,\n context: optional(InterfaceContextStruct),\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, context } = validatedParams;\n\n await updateInterface(id, ui, context);\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
+ {"version":3,"file":"updateInterface.mjs","sourceRoot":"","sources":["../../src/permitted/updateInterface.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAQjD,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACvB,4BAA4B;AAE7B,OAAO,EACL,WAAW,EACX,MAAM,EACN,MAAM,EACN,QAAQ,EACR,MAAM,EACP,8BAA8B;AAK/B,MAAM,SAAS,GAAkD;IAC/D,eAAe,EAAE,IAAI;CACtB,CAAC;AAeF,MAAM,CAAC,M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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 UpdateInterfaceParams,\n UpdateInterfaceResult,\n JsonRpcRequest,\n ComponentOrElement,\n InterfaceContext,\n} from '@metamask/snaps-sdk';\nimport {\n ComponentOrElementStruct,\n InterfaceContextStruct,\n} from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport {\n StructError,\n create,\n object,\n optional,\n string,\n} from '@metamask/superstruct';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\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 * @param context - The optional interface context object.\n */\n updateInterface: (\n id: string,\n ui: ComponentOrElement,\n context?: InterfaceContext,\n ) => 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: ComponentOrElementStruct,\n context: optional(InterfaceContextStruct),\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 */\nfunction getUpdateInterfaceImplementation(\n req: JsonRpcRequest<UpdateInterfaceParameters>,\n res: PendingJsonRpcResponse<UpdateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { updateInterface }: UpdateInterfaceMethodHooks,\n): void {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { id, ui, context } = validatedParams;\n\n updateInterface(id, ui, context);\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"]}
@@ -35,6 +35,7 @@ const methodHooks = {
35
35
  clearSnapState: true,
36
36
  getSnapState: true,
37
37
  updateSnapState: true,
38
+ getSnap: true,
38
39
  };
39
40
  exports.manageStateBuilder = Object.freeze({
40
41
  targetName: methodName,
@@ -80,14 +81,25 @@ exports.getEncryptionEntropy = getEncryptionEntropy;
80
81
  * @param hooks.getUnlockPromise - A function that resolves once the MetaMask
81
82
  * extension is unlocked and prompts the user to unlock their MetaMask if it is
82
83
  * locked.
84
+ * @param hooks.getSnap - The hook function to get Snap metadata.
83
85
  * @returns The method implementation which either returns `null` for a
84
86
  * successful state update/deletion or returns the decrypted state.
85
87
  * @throws If the params are invalid.
86
88
  */
87
- function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, }) {
89
+ function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, getSnap, }) {
88
90
  return async function manageState(options) {
89
91
  const { params = {}, method, context: { origin }, } = options;
90
92
  const validatedParams = getValidatedParams(params, method);
93
+ const snap = getSnap(origin);
94
+ if (!snap?.preinstalled &&
95
+ validatedParams.operation === snaps_sdk_1.ManageStateOperation.UpdateState) {
96
+ const size = (0, snaps_utils_1.getJsonSizeUnsafe)(validatedParams.newState, true);
97
+ if (size > exports.STORAGE_SIZE_LIMIT) {
98
+ throw rpc_errors_1.rpcErrors.invalidParams({
99
+ message: `Invalid ${method} "newState" parameter: The new state must not exceed ${exports.STORAGE_SIZE_LIMIT / 1000000} MB in size.`,
100
+ });
101
+ }
102
+ }
91
103
  // If the encrypted param is undefined or null we default to true.
92
104
  const shouldEncrypt = validatedParams.encrypted ?? true;
93
105
  // We only need to prompt the user when the mnemonic is needed
@@ -107,6 +119,7 @@ function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSna
107
119
  await updateSnapState(origin, validatedParams.newState, shouldEncrypt);
108
120
  return null;
109
121
  }
122
+ /* istanbul ignore next */
110
123
  default:
111
124
  throw rpc_errors_1.rpcErrors.invalidParams(`Invalid ${method} operation: "${validatedParams.operation}"`);
112
125
  }
@@ -119,10 +132,9 @@ exports.getManageStateImplementation = getManageStateImplementation;
119
132
  *
120
133
  * @param params - The unvalidated params object from the method request.
121
134
  * @param method - RPC method name used for debugging errors.
122
- * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.
123
135
  * @returns The validated method parameter object.
124
136
  */
125
- function getValidatedParams(params, method, storageSizeLimit = exports.STORAGE_SIZE_LIMIT) {
137
+ function getValidatedParams(params, method) {
126
138
  if (!(0, utils_1.isObject)(params)) {
127
139
  throw rpc_errors_1.rpcErrors.invalidParams({
128
140
  message: 'Expected params to be a single object.',
@@ -147,21 +159,11 @@ function getValidatedParams(params, method, storageSizeLimit = exports.STORAGE_S
147
159
  message: `Invalid ${method} "newState" parameter: The new state must be a plain object.`,
148
160
  });
149
161
  }
150
- let size;
151
- try {
152
- // `getJsonSize` will throw if the state is not JSON serializable.
153
- size = (0, utils_1.getJsonSize)(newState);
154
- }
155
- catch {
162
+ if (!(0, utils_1.isValidJson)(newState)) {
156
163
  throw rpc_errors_1.rpcErrors.invalidParams({
157
164
  message: `Invalid ${method} "newState" parameter: The new state must be JSON serializable.`,
158
165
  });
159
166
  }
160
- if (size > storageSizeLimit) {
161
- throw rpc_errors_1.rpcErrors.invalidParams({
162
- message: `Invalid ${method} "newState" parameter: The new state must not exceed ${storageSizeLimit / 1000000} MB in size.`,
163
- });
164
- }
165
167
  }
166
168
  return params;
167
169
  }
@@ -1 +1 @@
1
- {"version":3,"file":"manageState.cjs","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":";;;AAMA,2EAA8E;AAC9E,qDAAiD;AAEjD,mDAA2D;AAC3D,uDAAqE;AAErE,2CAAwD;AAGxD,wCAAiD;AAEjD,oDAAoD;AACvC,QAAA,qBAAqB,GAAG,6BAA6B,CAAC;AAEnE,MAAM,UAAU,GAAG,kBAAkB,CAAC;AAiDtC;;;;;;;;;GASG;AACI,MAAM,oBAAoB,GAI7B,CAAC,EACH,cAAc,GAAG,IAAI,EACrB,WAAW,GAC4B,EAAE,EAAE;IAC3C,OAAO;QACL,cAAc,EAAE,sCAAc,CAAC,gBAAgB;QAC/C,UAAU,EAAE,UAAU;QACtB,cAAc;QACd,oBAAoB,EAAE,4BAA4B,CAAC,WAAW,CAAC;QAC/D,YAAY,EAAE,CAAC,mCAAW,CAAC,IAAI,CAAC;KACjC,CAAC;AACJ,CAAC,CAAC;AAfW,QAAA,oBAAoB,wBAe/B;AAEF,MAAM,WAAW,GAA8C;IAC7D,gBAAgB,EAAE,IAAI;IACtB,cAAc,EAAE,IAAI;IACpB,YAAY,EAAE,IAAI;IAClB,eAAe,EAAE,IAAI;CACtB,CAAC;AAEW,QAAA,kBAAkB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC9C,UAAU,EAAE,UAAU;IACtB,oBAAoB,EAApB,4BAAoB;IACpB,WAAW;CACH,CAAC,CAAC;AAEC,QAAA,kBAAkB,GAAG,QAAU,CAAC,CAAC,mBAAmB;AAQjE;;;;;;;;;;;;;;GAcG;AACI,KAAK,UAAU,oBAAoB,CAAC,EACz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AC;QAAC,MAAM,CAAC;YACP,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,iEAAiE;aAC5F,CAAC,CAAC;QACL,CAAC;QAED,IAAI,IAAI,GAAG,gBAAgB,EAAE,CAAC;YAC5B,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,wDACxB,gBAAgB,GAAG,OACrB,cAAc;aACf,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAA2B,CAAC;AACrC,CAAC;AA1DD,gDA0DC","sourcesContent":["import type { CryptographicFunctions } from '@metamask/key-tree';\nimport 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 } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { isObject, getJsonSize } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropyFromSeed } 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 * 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: (\n snapId: string,\n encrypted: boolean,\n ) => Promise<Record<string, Json>>;\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: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\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 getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 64_000_000; // In bytes (64 MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n seed: Uint8Array;\n cryptographicFunctions?: CryptographicFunctions | undefined;\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.seed - The mnemonic seed to derive the encryption key\n * from.\n * @param args.cryptographicFunctions - The cryptographic functions to use for\n * the client.\n * @returns The state encryption key.\n */\nexport async function getEncryptionEntropy({\n seed,\n snapId,\n cryptographicFunctions,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropyFromSeed({\n seed,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n cryptographicFunctions,\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.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 * @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 getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\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 return await getSnapState(origin, shouldEncrypt);\n }\n\n case ManageStateOperation.UpdateState: {\n await updateSnapState(origin, validatedParams.newState, 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} \"newState\" parameter: The new state must be a plain object.`,\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} \"newState\" parameter: The new state must be JSON serializable.`,\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must not exceed ${\n storageSizeLimit / 1_000_000\n } MB in size.`,\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"]}
1
+ {"version":3,"file":"manageState.cjs","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":";;;AAMA,2EAA8E;AAC9E,qDAAiD;AAEjD,mDAA2D;AAE3D,uDAG+B;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AC,QAAQ,CAAC,EAAE,CAAC;YAC3B,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,iEAAiE;aAC5F,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAA2B,CAAC;AACrC,CAAC;AA7CD,gDA6CC","sourcesContent":["import type { CryptographicFunctions } from '@metamask/key-tree';\nimport 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 type { Snap } from '@metamask/snaps-utils';\nimport {\n getJsonSizeUnsafe,\n STATE_ENCRYPTION_MAGIC_VALUE,\n} from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { isObject, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropyFromSeed } 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 * 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: (\n snapId: string,\n encrypted: boolean,\n ) => Promise<Record<string, Json>>;\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: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n\n /**\n * Get Snap metadata.\n *\n * @param snapId - The ID of a Snap.\n */\n getSnap: (snapId: string) => Snap | undefined;\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 getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n getSnap: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 64_000_000; // In bytes (64 MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n seed: Uint8Array;\n cryptographicFunctions?: CryptographicFunctions | undefined;\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.seed - The mnemonic seed to derive the encryption key\n * from.\n * @param args.cryptographicFunctions - The cryptographic functions to use for\n * the client.\n * @returns The state encryption key.\n */\nexport async function getEncryptionEntropy({\n seed,\n snapId,\n cryptographicFunctions,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropyFromSeed({\n seed,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n cryptographicFunctions,\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.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.getSnap - The hook function to get Snap metadata.\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 getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n getSnap,\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 const snap = getSnap(origin);\n\n if (\n !snap?.preinstalled &&\n validatedParams.operation === ManageStateOperation.UpdateState\n ) {\n const size = getJsonSizeUnsafe(validatedParams.newState, true);\n\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n }\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 return await getSnapState(origin, shouldEncrypt);\n }\n\n case ManageStateOperation.UpdateState: {\n await updateSnapState(origin, validatedParams.newState, shouldEncrypt);\n return null;\n }\n\n /* istanbul ignore next */\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 * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\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} \"newState\" parameter: The new state must be a plain object.`,\n });\n }\n\n if (!isValidJson(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be JSON serializable.`,\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"]}
@@ -2,6 +2,7 @@ import type { CryptographicFunctions } from "@metamask/key-tree";
2
2
  import type { PermissionSpecificationBuilder, RestrictedMethodOptions, ValidPermissionSpecification } from "@metamask/permission-controller";
3
3
  import { PermissionType } from "@metamask/permission-controller";
4
4
  import type { ManageStateParams, ManageStateResult } from "@metamask/snaps-sdk";
5
+ import type { Snap } from "@metamask/snaps-utils";
5
6
  import type { Json, NonEmptyArray } from "@metamask/utils";
6
7
  import type { MethodHooksObject } from "../utils.cjs";
7
8
  export declare const STATE_ENCRYPTION_SALT = "snap_manageState encryption";
@@ -29,6 +30,12 @@ export type ManageStateMethodHooks = {
29
30
  * @param newState - The new state of the Snap.
30
31
  */
31
32
  updateSnapState: (snapId: string, newState: Record<string, Json>, encrypted: boolean) => Promise<void>;
33
+ /**
34
+ * Get Snap metadata.
35
+ *
36
+ * @param snapId - The ID of a Snap.
37
+ */
38
+ getSnap: (snapId: string) => Snap | undefined;
32
39
  };
33
40
  type ManageStateSpecificationBuilderOptions = {
34
41
  allowedCaveats?: Readonly<NonEmptyArray<string>> | null;
@@ -96,20 +103,20 @@ export declare function getEncryptionEntropy({ seed, snapId, cryptographicFuncti
96
103
  * @param hooks.getUnlockPromise - A function that resolves once the MetaMask
97
104
  * extension is unlocked and prompts the user to unlock their MetaMask if it is
98
105
  * locked.
106
+ * @param hooks.getSnap - The hook function to get Snap metadata.
99
107
  * @returns The method implementation which either returns `null` for a
100
108
  * successful state update/deletion or returns the decrypted state.
101
109
  * @throws If the params are invalid.
102
110
  */
103
- export declare function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
111
+ export declare function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, getSnap, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
104
112
  /**
105
113
  * Validates the manageState method `params` and returns them cast to the correct
106
114
  * type. Throws if validation fails.
107
115
  *
108
116
  * @param params - The unvalidated params object from the method request.
109
117
  * @param method - RPC method name used for debugging errors.
110
- * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.
111
118
  * @returns The validated method parameter object.
112
119
  */
113
- export declare function getValidatedParams(params: unknown, method: string, storageSizeLimit?: number): ManageStateParams;
120
+ export declare function getValidatedParams(params: unknown, method: string): ManageStateParams;
114
121
  export {};
115
122
  //# sourceMappingURL=manageState.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"manageState.d.cts","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,2BAA2B;AACjE,OAAO,KAAK,EACV,8BAA8B,EAC9B,uBAAuB,EACvB,4BAA4B,EAC7B,wCAAwC;AACzC,OAAO,EAAE,cAAc,EAAe,wCAAwC;AAE9E,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,4BAA4B;AAGhF,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAG3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,qBAAiB;AAIlD,eAAO,MAAM,qBAAqB,gCAAgC,CAAC;AAEnE,QAAA,MAAM,UAAU,qBAAqB,CAAC;AAEtC,MAAM,MAAM,sBAAsB,GAAG;IACnC;;;;OAIG;IACH,gBAAgB,EAAE,CAAC,uBAAuB,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtE;;OAEG;IACH,cAAc,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,KAAK,IAAI,CAAC;IAE7D;;;;OAIG;IACH,YAAY,EAAE,CACZ,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,OAAO,KACf,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;IAEnC;;;;OAIG;IACH,eAAe,EAAE,CACf,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,EAC9B,SAAS,EAAE,OAAO,KACf,OAAO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3C,gBAAgB,EAChB,cAAc,EACd,YAAY,EACZ,eAAe,EACf,OAAO,GACR,EAAE,sBAAsB,aAEZ,wBAAwB,iBAAiB,CAAC,KAClD,QAAQ,iBAAiB,CAAC,CA4D9B;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,OAAO,EACf,MAAM,EAAE,MAAM,GACb,iBAAiB,CA0CnB"}
@@ -2,6 +2,7 @@ import type { CryptographicFunctions } from "@metamask/key-tree";
2
2
  import type { PermissionSpecificationBuilder, RestrictedMethodOptions, ValidPermissionSpecification } from "@metamask/permission-controller";
3
3
  import { PermissionType } from "@metamask/permission-controller";
4
4
  import type { ManageStateParams, ManageStateResult } from "@metamask/snaps-sdk";
5
+ import type { Snap } from "@metamask/snaps-utils";
5
6
  import type { Json, NonEmptyArray } from "@metamask/utils";
6
7
  import type { MethodHooksObject } from "../utils.mjs";
7
8
  export declare const STATE_ENCRYPTION_SALT = "snap_manageState encryption";
@@ -29,6 +30,12 @@ export type ManageStateMethodHooks = {
29
30
  * @param newState - The new state of the Snap.
30
31
  */
31
32
  updateSnapState: (snapId: string, newState: Record<string, Json>, encrypted: boolean) => Promise<void>;
33
+ /**
34
+ * Get Snap metadata.
35
+ *
36
+ * @param snapId - The ID of a Snap.
37
+ */
38
+ getSnap: (snapId: string) => Snap | undefined;
32
39
  };
33
40
  type ManageStateSpecificationBuilderOptions = {
34
41
  allowedCaveats?: Readonly<NonEmptyArray<string>> | null;
@@ -96,20 +103,20 @@ export declare function getEncryptionEntropy({ seed, snapId, cryptographicFuncti
96
103
  * @param hooks.getUnlockPromise - A function that resolves once the MetaMask
97
104
  * extension is unlocked and prompts the user to unlock their MetaMask if it is
98
105
  * locked.
106
+ * @param hooks.getSnap - The hook function to get Snap metadata.
99
107
  * @returns The method implementation which either returns `null` for a
100
108
  * successful state update/deletion or returns the decrypted state.
101
109
  * @throws If the params are invalid.
102
110
  */
103
- export declare function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
111
+ export declare function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, getSnap, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
104
112
  /**
105
113
  * Validates the manageState method `params` and returns them cast to the correct
106
114
  * type. Throws if validation fails.
107
115
  *
108
116
  * @param params - The unvalidated params object from the method request.
109
117
  * @param method - RPC method name used for debugging errors.
110
- * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.
111
118
  * @returns The validated method parameter object.
112
119
  */
113
- export declare function getValidatedParams(params: unknown, method: string, storageSizeLimit?: number): ManageStateParams;
120
+ export declare function getValidatedParams(params: unknown, method: string): ManageStateParams;
114
121
  export {};
115
122
  //# sourceMappingURL=manageState.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"manageState.d.mts","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,2BAA2B;AACjE,OAAO,KAAK,EACV,8BAA8B,EAC9B,uBAAuB,EACvB,4BAA4B,EAC7B,wCAAwC;AACzC,OAAO,EAAE,cAAc,EAAe,wCAAwC;AAE9E,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,4BAA4B;AAGhF,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAG3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,qBAAiB;AAIlD,eAAO,MAAM,qBAAqB,gCAAgC,CAAC;AAEnE,QAAA,MAAM,UAAU,qBAAqB,CAAC;AAEtC,MAAM,MAAM,sBAAsB,GAAG;IACnC;;;;OAIG;IACH,gBAAgB,EAAE,CAAC,uBAAuB,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtE;;OAEG;IACH,cAAc,EAAE,CAAC,MAAM,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,CAAC;AAE7C,KAAK,oBAAoB,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,UAAU,CAAC;IACjB,sBAAsB,CAAC,EAAE,sBAAsB,GAAG,SAAS,CAAC;CAC7D,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,oBAAoB,CAAC,EACzC,IAAI,EACJ,MAAM,EACN,sBAAsB,GACvB,EAAE,oBAAoB,0BAQtB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,4BAA4B,CAAC,EAC3C,gBAAgB,EAChB,cAAc,EACd,YAAY,EACZ,eAAe,EACf,OAAO,GACR,EAAE,sBAAsB,aAEZ,wBAAwB,iBAAiB,CAAC,KAClD,QAAQ,iBAAiB,CAAC,CA4D9B;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,OAAO,EACf,MAAM,EAAE,MAAM,GACb,iBAAiB,CA0CnB"}
@@ -1,8 +1,8 @@
1
1
  import { PermissionType, SubjectType } from "@metamask/permission-controller";
2
2
  import { rpcErrors } from "@metamask/rpc-errors";
3
3
  import { ManageStateOperation } from "@metamask/snaps-sdk";
4
- import { STATE_ENCRYPTION_MAGIC_VALUE } from "@metamask/snaps-utils";
5
- import { isObject, getJsonSize } from "@metamask/utils";
4
+ import { getJsonSizeUnsafe, STATE_ENCRYPTION_MAGIC_VALUE } from "@metamask/snaps-utils";
5
+ import { isObject, isValidJson } from "@metamask/utils";
6
6
  import { deriveEntropyFromSeed } from "../utils.mjs";
7
7
  // The salt used for SIP-6-based entropy derivation.
8
8
  export const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';
@@ -31,6 +31,7 @@ const methodHooks = {
31
31
  clearSnapState: true,
32
32
  getSnapState: true,
33
33
  updateSnapState: true,
34
+ getSnap: true,
34
35
  };
35
36
  export const manageStateBuilder = Object.freeze({
36
37
  targetName: methodName,
@@ -75,14 +76,25 @@ export async function getEncryptionEntropy({ seed, snapId, cryptographicFunction
75
76
  * @param hooks.getUnlockPromise - A function that resolves once the MetaMask
76
77
  * extension is unlocked and prompts the user to unlock their MetaMask if it is
77
78
  * locked.
79
+ * @param hooks.getSnap - The hook function to get Snap metadata.
78
80
  * @returns The method implementation which either returns `null` for a
79
81
  * successful state update/deletion or returns the decrypted state.
80
82
  * @throws If the params are invalid.
81
83
  */
82
- export function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, }) {
84
+ export function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, getSnap, }) {
83
85
  return async function manageState(options) {
84
86
  const { params = {}, method, context: { origin }, } = options;
85
87
  const validatedParams = getValidatedParams(params, method);
88
+ const snap = getSnap(origin);
89
+ if (!snap?.preinstalled &&
90
+ validatedParams.operation === ManageStateOperation.UpdateState) {
91
+ const size = getJsonSizeUnsafe(validatedParams.newState, true);
92
+ if (size > STORAGE_SIZE_LIMIT) {
93
+ throw rpcErrors.invalidParams({
94
+ message: `Invalid ${method} "newState" parameter: The new state must not exceed ${STORAGE_SIZE_LIMIT / 1000000} MB in size.`,
95
+ });
96
+ }
97
+ }
86
98
  // If the encrypted param is undefined or null we default to true.
87
99
  const shouldEncrypt = validatedParams.encrypted ?? true;
88
100
  // We only need to prompt the user when the mnemonic is needed
@@ -102,6 +114,7 @@ export function getManageStateImplementation({ getUnlockPromise, clearSnapState,
102
114
  await updateSnapState(origin, validatedParams.newState, shouldEncrypt);
103
115
  return null;
104
116
  }
117
+ /* istanbul ignore next */
105
118
  default:
106
119
  throw rpcErrors.invalidParams(`Invalid ${method} operation: "${validatedParams.operation}"`);
107
120
  }
@@ -113,10 +126,9 @@ export function getManageStateImplementation({ getUnlockPromise, clearSnapState,
113
126
  *
114
127
  * @param params - The unvalidated params object from the method request.
115
128
  * @param method - RPC method name used for debugging errors.
116
- * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.
117
129
  * @returns The validated method parameter object.
118
130
  */
119
- export function getValidatedParams(params, method, storageSizeLimit = STORAGE_SIZE_LIMIT) {
131
+ export function getValidatedParams(params, method) {
120
132
  if (!isObject(params)) {
121
133
  throw rpcErrors.invalidParams({
122
134
  message: 'Expected params to be a single object.',
@@ -141,21 +153,11 @@ export function getValidatedParams(params, method, storageSizeLimit = STORAGE_SI
141
153
  message: `Invalid ${method} "newState" parameter: The new state must be a plain object.`,
142
154
  });
143
155
  }
144
- let size;
145
- try {
146
- // `getJsonSize` will throw if the state is not JSON serializable.
147
- size = getJsonSize(newState);
148
- }
149
- catch {
156
+ if (!isValidJson(newState)) {
150
157
  throw rpcErrors.invalidParams({
151
158
  message: `Invalid ${method} "newState" parameter: The new state must be JSON serializable.`,
152
159
  });
153
160
  }
154
- if (size > storageSizeLimit) {
155
- throw rpcErrors.invalidParams({
156
- message: `Invalid ${method} "newState" parameter: The new state must not exceed ${storageSizeLimit / 1000000} MB in size.`,
157
- });
158
- }
159
161
  }
160
162
  return params;
161
163
  }
@@ -1 +1 @@
1
- {"version":3,"file":"manageState.mjs","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,wCAAwC;AAC9E,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,oBAAoB,EAAE,4BAA4B;AAC3D,OAAO,EAAE,4BAA4B,EAAE,8BAA8B;AAErE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,wBAAwB;AAGxD,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AAEjD,oDAAoD;AACpD,MAAM,CAAC,MAAM,qBAAqB,GAAG,6BAA6B,CAAC;AAEnE,MAAM,UAAU,GAAG,kBAAkB,CAAC;AAiDtC;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAI7B,CAAC,EACH,cAAc,GAAG,IAAI,EACrB,WAAW,GAC4B,EAAE,EAAE;IAC3C,OAAO;QACL,cAAc,EAAE,cAAc,CAAC,gBAAgB;QAC/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AC,CAAC;IACL,CAAC;IAED,IAAI,SAAS,KAAK,SAAS,IAAI,OAAO,SAAS,KAAK,SAAS,EAAE,CAAC;QAC9D,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,uDAAuD;SACjE,CAAC,CAAC;IACL,CAAC;IAED,IAAI,SAAS,KAAK,oBAAoB,CAAC,WAAW,EAAE,CAAC;QACnD,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;YACxB,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,8DAA8D;aACzF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,IAAI,CAAC;QACT,IAAI,CAAC;YACH,kEAAkE;YAClE,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,iEAAiE;aAC5F,CAAC,CAAC;QACL,CAAC;QAED,IAAI,IAAI,GAAG,gBAAgB,EAAE,CAAC;YAC5B,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,wDACxB,gBAAgB,GAAG,OACrB,cAAc;aACf,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAA2B,CAAC;AACrC,CAAC","sourcesContent":["import type { CryptographicFunctions } from '@metamask/key-tree';\nimport 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 } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { isObject, getJsonSize } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropyFromSeed } 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 * 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: (\n snapId: string,\n encrypted: boolean,\n ) => Promise<Record<string, Json>>;\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: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\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 getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 64_000_000; // In bytes (64 MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n seed: Uint8Array;\n cryptographicFunctions?: CryptographicFunctions | undefined;\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.seed - The mnemonic seed to derive the encryption key\n * from.\n * @param args.cryptographicFunctions - The cryptographic functions to use for\n * the client.\n * @returns The state encryption key.\n */\nexport async function getEncryptionEntropy({\n seed,\n snapId,\n cryptographicFunctions,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropyFromSeed({\n seed,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n cryptographicFunctions,\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.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 * @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 getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\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 return await getSnapState(origin, shouldEncrypt);\n }\n\n case ManageStateOperation.UpdateState: {\n await updateSnapState(origin, validatedParams.newState, 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} \"newState\" parameter: The new state must be a plain object.`,\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} \"newState\" parameter: The new state must be JSON serializable.`,\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must not exceed ${\n storageSizeLimit / 1_000_000\n } MB in size.`,\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"]}
1
+ {"version":3,"file":"manageState.mjs","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,wCAAwC;AAC9E,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,oBAAoB,EAAE,4BAA4B;AAE3D,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC7B,8BAA8B;AAE/B,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,wBAAwB;AAGxD,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AAEjD,oDAAoD;AACpD,MAAM,CAAC,MAAM,qBAAqB,GAAG,6BAA6B,CAAC;AAEnE,MAAM,UAAU,GAAG,kBAAkB,CAAC;AAwDtC;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAI7B,CAAC,EACH,cAAc,GAAG,IAAI,EACrB,WAAW,GAC4B,EAAE,EAAE;IAC3C,OAAO;QACL,cAAc,EAAE,cAAc,CAAC,gBAAgB;QAC/C,UAAU,EAAE,UAAU;QACtB,cAAc;QACd,oBAAoB,EAAE,4BAA4B,CAAC,WAAW,CAAC;QAC/D,YAAY,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC;KACjC,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,WAAW,GAA8C;IAC7D,gBAAgB,EAAE,IAAI;IACtB,cAAc,EAAE,I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IACE,CAAC,SAAS;QACV,OAAO,SAAS,KAAK,QAAQ;QAC7B,CAAC,MAAM,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC,QAAQ,CAC3C,SAAiC,CAClC,EACD,CAAC;QACD,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,gDAAgD;SAC1D,CAAC,CAAC;IACL,CAAC;IAED,IAAI,SAAS,KAAK,SAAS,IAAI,OAAO,SAAS,KAAK,SAAS,EAAE,CAAC;QAC9D,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,uDAAuD;SACjE,CAAC,CAAC;IACL,CAAC;IAED,IAAI,SAAS,KAAK,oBAAoB,CAAC,WAAW,EAAE,CAAC;QACnD,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;YACxB,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,8DAA8D;aACzF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC3B,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,iEAAiE;aAC5F,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAA2B,CAAC;AACrC,CAAC","sourcesContent":["import type { CryptographicFunctions } from '@metamask/key-tree';\nimport 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 type { Snap } from '@metamask/snaps-utils';\nimport {\n getJsonSizeUnsafe,\n STATE_ENCRYPTION_MAGIC_VALUE,\n} from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { isObject, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropyFromSeed } 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 * 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: (\n snapId: string,\n encrypted: boolean,\n ) => Promise<Record<string, Json>>;\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: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n\n /**\n * Get Snap metadata.\n *\n * @param snapId - The ID of a Snap.\n */\n getSnap: (snapId: string) => Snap | undefined;\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 getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n getSnap: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 64_000_000; // In bytes (64 MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n seed: Uint8Array;\n cryptographicFunctions?: CryptographicFunctions | undefined;\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.seed - The mnemonic seed to derive the encryption key\n * from.\n * @param args.cryptographicFunctions - The cryptographic functions to use for\n * the client.\n * @returns The state encryption key.\n */\nexport async function getEncryptionEntropy({\n seed,\n snapId,\n cryptographicFunctions,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropyFromSeed({\n seed,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n cryptographicFunctions,\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.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.getSnap - The hook function to get Snap metadata.\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 getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n getSnap,\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 const snap = getSnap(origin);\n\n if (\n !snap?.preinstalled &&\n validatedParams.operation === ManageStateOperation.UpdateState\n ) {\n const size = getJsonSizeUnsafe(validatedParams.newState, true);\n\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n }\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 return await getSnapState(origin, shouldEncrypt);\n }\n\n case ManageStateOperation.UpdateState: {\n await updateSnapState(origin, validatedParams.newState, shouldEncrypt);\n return null;\n }\n\n /* istanbul ignore next */\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 * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\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} \"newState\" parameter: The new state must be a plain object.`,\n });\n }\n\n if (!isValidJson(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be JSON serializable.`,\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"]}