# Profiles

## Список профилей

`GET /profiles`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Список профилей",
  "description": "Возвращает постоянные профили (временные скрыты), от новых к старым,\nзакреплённые; вверху. Каждая запись дополнена актуальным состоянием запуска.\n",
  "responses": {
    "200": {
      "description": "Список профилей.",
      "content": {
        "application/json": {
          "schema": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProfileListItem"
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    }
  }
}
```

## Создать профиль

`POST /profiles`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Создать профиль",
  "description": "Сохраняет профиль из переданного клиентом объекта `fingerprint` **ровно\nкак есть** (повторная рандомизация не выполняется; уникализация уже\nпрошла в `/fingerprint/new`). Используйте `folder`, чтобы разместить\nпрофиль в папке; привяжите прокси по `proxy_id` из хранилища или\nинлайн через `proxy` (строка, **не** сохраняется в хранилище прокси).\n",
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "$ref": "#/components/schemas/CreateProfileRequest"
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "Метаданные созданного профиля.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/ProfileMeta"
          }
        }
      }
    },
    "400": {
      "description": "Отсутствует или не является объектом `fingerprint`, либо неразбираемая строка прокси.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    }
  }
}
```

## Создать временный профиль

`POST /profiles/temporary`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Создать временный профиль",
  "description": "Создаёт профиль из случайного (или указанного) отпечатка библиотеки,\nуникализированного как в `/fingerprint/new` и сохранённого дословно,\nс флагом `temporary`: скрыт из списков и **автоматически удаляется\nпосле закрытия браузера** (или при следующем запуске после краша).\nИспользуйте вместе с `POST /profiles/{id}/start`.\n",
  "requestBody": {
    "required": false,
    "content": {
      "application/json": {
        "schema": {
          "$ref": "#/components/schemas/TempProfileRequest"
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "Созданный временный профиль.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "fingerprint_id": {
                "type": "string",
                "description": "Запись библиотеки, на основе которой сгенерирован профиль."
              },
              "temporary": {
                "type": "boolean",
                "example": true
              },
              "proxy_inline": {
                "type": "boolean",
                "description": "Был ли прикреплён инлайн-прокси."
              }
            }
          }
        }
      }
    },
    "400": {
      "description": "Неразбираемая прокси-строка или неизвестный вектор шума.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Подходящий отпечаток не найден / пустая библиотека.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Получить профиль

`GET /profiles/{id}`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Получить профиль",
  "description": "Возвращает полный сохранённый профиль: оболочку `_meta` плюс\nразвёрнутый FingerprintConfig. Если профиль запущен; добавляются\n`running` и `cdp`.\n",
  "parameters": [
    {
      "$ref": "#/components/parameters/ProfileId"
    }
  ],
  "responses": {
    "200": {
      "description": "Сохранённый профиль.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/StoredProfile"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Профиль не найден.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Удалить профиль

`DELETE /profiles/{id}`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Удалить профиль",
  "description": "Перемещает профиль в корзину. Его можно восстановить за 7 дней. Архив включает файлы cookie, логины, веб-данные, настройки, локальное хранилище и IndexedDB. Данные кэша исключены. Исходная конфигурация и каталог пользовательских данных удаляются после создания архива.\n\nВременные профили удаляются автоматически при закрытии браузера и не перемещаются в корзину.",
  "parameters": [
    {
      "$ref": "#/components/parameters/ProfileId"
    }
  ],
  "responses": {
    "200": {
      "description": "Профиль перемещен в корзину.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "deleted": {
                "type": "boolean",
                "example": true
              },
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "trashed": {
                "type": "boolean",
                "example": true,
                "description": "Можно восстановить из корзины в течение 7 дней."
              }
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "500": {
      "description": "Ошибка при удалении.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Редактировать профиль

`PATCH /profiles/{id}`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Редактировать профиль",
  "description": "Обновляет только переданные поля. Если передан `fingerprint`; он\nЗАМЕНЯЕТ сохранённый дословно (без перерандомизации).\n`folder: \"\"` убирает профиль из папки; `proxy_id: \"\"` отвязывает прокси;\nстрока `proxy` сохраняется (дедупликация) + проходит полный тест,\nзатем привязывается. Возвращает обновлённый профиль.\n",
  "parameters": [
    {
      "$ref": "#/components/parameters/ProfileId"
    }
  ],
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "$ref": "#/components/schemas/EditProfileRequest"
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "Обновлённый сохранённый профиль.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/StoredProfile"
          }
        }
      }
    },
    "400": {
      "description": "Неверный fingerprint (не объект) или неразбираемый прокси.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Профиль не найден.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Запустить профиль (с CDP)

`POST /profiles/{id}/start`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Запустить профиль (с CDP)",
  "description": "Запускает ShardX-браузер для профиля с включённым remote-debugging,\nподставляет часовой пояс/локаль/гео из `auto`-полей через привязанный\nпрокси и возвращает CDP-эндпоинт после того, как Chrome записал\nDevToolsActivePort. CDP включается **только** при запуске через API\n(запуски из UI не открывают отладочный порт; анти-детект не страдает).\n`cdp` равен `null`, если эндпоинт не удалось прочитать в течение\nтаймаута. Работает для обычных и временных профилей.\n",
  "parameters": [
    {
      "$ref": "#/components/parameters/ProfileId"
    }
  ],
  "requestBody": {
    "required": false,
    "description": "Необязательно. Пустое тело запускает в графическом режиме.",
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "properties": {
            "headless": {
              "type": "boolean",
              "default": false,
              "description": "Запустить в headless-режиме (--headless=new)."
            }
          }
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "Запущен.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "profile_id": {
                "type": "string"
              },
              "pid": {
                "type": "integer",
                "format": "int64",
                "description": "PID процесса ОС."
              },
              "headless": {
                "type": "boolean"
              },
              "cdp": {
                "nullable": true,
                "allOf": [
                  {
                    "$ref": "#/components/schemas/CdpInfo"
                  }
                ]
              },
              "cdp_error": {
                "type": "string",
                "nullable": true,
                "description": "Почему `cdp` имеет значение null. Если значение не равно null, это поле отсутствует."
              }
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "500": {
      "description": "Бинарный файл не настроен / не удалось запустить процесс.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Остановить профиль

`POST /profiles/{id}/stop`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Остановить профиль",
  "description": "Отправляет браузеру сигнал graceful shutdown (SIGTERM на Unix; 5 секунд\nожидания, затем SIGKILL). Временные профили удаляются в процессе закрытия.\n`stopped` равен `false`, если профиль не был запущен.\n",
  "parameters": [
    {
      "$ref": "#/components/parameters/ProfileId"
    }
  ],
  "responses": {
    "200": {
      "description": "Команда остановки отправлена.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "profile_id": {
                "type": "string"
              },
              "stopped": {
                "type": "boolean"
              }
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    }
  }
}
```

## Экспортировать cookies

`GET /profiles/{id}/cookies`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Экспортировать cookies",
  "description": "Читает хранилище cookies Chromium профиля и возвращает все cookies\n**в расшифрованном виде**. Работает как для запущенного, так и для\nостановленного профиля. Пустой массив, если профиль ни разу не запускался.\n",
  "parameters": [
    {
      "$ref": "#/components/parameters/ProfileId"
    }
  ],
  "responses": {
    "200": {
      "description": "Печенье.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "cookies": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/Cookie"
                }
              }
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "500": {
      "description": "Ошибка чтения или расшифровки БД cookies.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Импортировать cookies

`POST /profiles/{id}/cookies`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Импортировать cookies",
  "description": "Записывает cookies в хранилище профиля (повторно шифруя по схеме\nChromium v10). Профиль **должен быть остановлен**; запущенный браузер\nперезапишет хранилище при выходе и затрёт импорт.\n",
  "parameters": [
    {
      "$ref": "#/components/parameters/ProfileId"
    }
  ],
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "required": [
            "cookies"
          ],
          "properties": {
            "cookies": {
              "type": "array",
              "items": {
                "$ref": "#/components/schemas/Cookie"
              }
            }
          }
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "Импортировано.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "imported": {
                "type": "integer",
                "description": "Количество записанных cookies."
              }
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "409": {
      "description": "Профиль запущен; сначала остановите его.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "500": {
      "description": "Ошибка записи БД cookies.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Список запущенных профилей

`GET /running`

```json
{
  "tags": [
    "Profiles"
  ],
  "summary": "Список запущенных профилей",
  "description": "Профили с живым процессом браузера, включая CDP-эндпоинт при запуске через API.",
  "responses": {
    "200": {
      "description": "Запущенные профили.",
      "content": {
        "application/json": {
          "schema": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/RunningProfile"
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    }
  }
}
```
