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;IAChC,0BAA0B;IAC1B,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type {\n  JsonRpcEngineEndCallback,\n  MethodHandler,\n} from '@metamask/json-rpc-engine';\nimport type { Messenger } from '@metamask/messenger';\nimport type { PermissionControllerHasPermissionAction } from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type {\n  SetStateParams,\n  SetStateResult,\n  SnapId,\n} from '@metamask/snaps-sdk';\nimport type { JsonObject } from '@metamask/snaps-sdk/jsx';\nimport { getJsonSizeUnsafe, 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 { PendingJsonRpcResponse, Json } from '@metamask/utils';\nimport { hasProperty, isObject, assert, JsonStruct } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport {\n  manageStateBuilder,\n  STORAGE_SIZE_LIMIT,\n} from '../restricted/manageState';\nimport type {\n  JsonRpcRequestWithOrigin,\n  SnapControllerGetSnapAction,\n  SnapControllerGetSnapStateAction,\n  SnapControllerUpdateSnapStateAction,\n} from '../types';\nimport type { MethodHooksObject } from '../utils';\nimport { FORBIDDEN_KEYS, StateKeyStruct } from '../utils';\n\nconst hookNames: MethodHooksObject<SetStateMethodHooks> = {\n  getUnlockPromise: true,\n};\n\nexport type SetStateMethodHooks = {\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\nexport type SetStateMethodActions =\n  | PermissionControllerHasPermissionAction\n  | SnapControllerGetSnapStateAction\n  | SnapControllerUpdateSnapStateAction\n  | SnapControllerGetSnapAction;\n\n/**\n * Allow the Snap to persist up to 64 MB of data to disk and retrieve it at\n * will. By default, the data is automatically encrypted using a Snap-specific\n * key and automatically decrypted when retrieved. You can set `encrypted` to\n * `false` to use unencrypted storage (available when the client is locked).\n *\n * If the key is `undefined`, the value is expected to be an object. In this\n * case, the value is set as the new root 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 * @example\n * ```json name=\"Manifest\"\n * {\n *   \"initialPermissions\": {\n *     \"snap_manageState\": {}\n *   }\n * }\n * ```\n * ```ts name=\"Usage\"\n * // Set the entire state:\n * await snap.request({\n *   method: 'snap_setState',\n *   params: {\n *     value: {\n *       some: {\n *         nested: {\n *           value: 'Hello, world!',\n *         },\n *       },\n *     },\n *     encrypted: true, // Optional, defaults to `true`\n *   },\n * });\n *\n * // Set a specific value within the state:\n * await snap.request({\n *   method: 'snap_setState',\n *   params: {\n *     key: 'some.nested.value',\n *     value: 'Hello, world!',\n *     encrypted: true, // Optional, defaults to `true`\n *   },\n * });\n * ```\n */\nexport const setStateHandler = {\n  implementation: setStateImplementation,\n  hookNames,\n  actionNames: [\n    'PermissionController:hasPermission',\n    'SnapController:getSnapState',\n    'SnapController:updateSnapState',\n    'SnapController:getSnap',\n  ],\n} satisfies MethodHandler<\n  SetStateMethodHooks,\n  SetStateMethodActions,\n  SetStateParameters,\n  SetStateResult,\n  { origin: SnapId }\n>;\n\nconst mutexes = new Map();\n\n/**\n * Get the corresponding state modification mutex for a given Snap ID.\n *\n * @param snapId - The Snap ID.\n * @returns A mutex for that specific Snap.\n */\nfunction getMutex(snapId: SnapId) {\n  if (!mutexes.has(snapId)) {\n    mutexes.set(snapId, new Mutex());\n  }\n  return mutexes.get(snapId);\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.getUnlockPromise - Wait for the extension to be unlocked.\n * @param messenger - The messenger used to call controller actions.\n * @returns Nothing.\n */\nasync function setStateImplementation(\n  request: JsonRpcRequestWithOrigin<SetStateParameters>,\n  response: PendingJsonRpcResponse<SetStateResult>,\n  _next: unknown,\n  end: JsonRpcEngineEndCallback,\n  { getUnlockPromise }: SetStateMethodHooks,\n  messenger: Messenger<string, SetStateMethodActions>,\n): Promise<void> {\n  const { params, origin } = request;\n\n  if (\n    !messenger.call(\n      'PermissionController:hasPermission',\n      origin,\n      manageStateBuilder.targetName,\n    )\n  ) {\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 snapId = origin as SnapId;\n\n    const mutex = getMutex(snapId);\n\n    // The expectation when using `snap_setState` is for the operation to safe\n    // to do in parallel. The mutex ensures that and prevents a bug that was\n    // mostly prevalent on mobile and caused data loss.\n    await mutex.runExclusive(async () => {\n      const newState = await getNewState(\n        snapId,\n        key,\n        value,\n        encrypted,\n        messenger,\n      );\n\n      const snap = messenger.call('SnapController:getSnap', origin);\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 messenger.call(\n        'SnapController:updateSnapState',\n        origin,\n        newState,\n        encrypted,\n      );\n      response.result = null;\n    });\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 snapId - The Snap ID.\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 messenger - The messenger used to call controller actions.\n * @returns The new state of the Snap.\n */\nasync function getNewState(\n  snapId: SnapId,\n  key: string | undefined,\n  value: Json,\n  encrypted: boolean,\n  messenger: Messenger<string, SetStateMethodActions>,\n): Promise<Record<string, Json>> {\n  if (key === undefined) {\n    assert(isObject(value));\n    return value;\n  }\n\n  const state = await messenger.call(\n    'SnapController:getSnapState',\n    snapId,\n    encrypted,\n  );\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"]}