GITBOOK-14: Govor.API: документация по текущему коду и диагностика 03.10.2026

This commit is contained in:
stalcke2288969
2026-10-03 06:20:45 +00:00
committed by gitbook-bot
parent 4603be9f71
commit 6c8abb23e3
27 changed files with 827 additions and 1901 deletions
+25 -30
View File
@@ -3,46 +3,41 @@ icon: face-confounded
coverY: 0
---
# The invitation code RU
# Govor.API — обзор
### Что это такое
Govor — мессенджер на ASP.NET Core и .NET MAUI. Эта документация описывает сервер Govor.API и его контракт с клиентом. Стек сервера: .NET 10, EF Core, PostgreSQL, JWT, SignalR, Firebase и локальное хранилище файлов.
**Код приглашения** — это временный механизм доступа, действующий на этапах **альфа-** и **бета-тестирования** мессенджера **Говор**.\
Он используется для **ограничения количества аккаунтов** и **контроля числа пользователей**, получающих ранний доступ к продукту.
## Что реализовано
Пока Говор находится в стадии активной разработки и внутреннего тестирования, регистрация новых пользователей возможна **только при наличии действующего кода приглашения**.
| Область | Состояние по коду |
| -------------------- | ------------------------------------------------------------------------------ |
| Регистрация и вход | Регистрация по приглашению, BCrypt, открытие сессии и пара токенов |
| Сессии | Список, отзыв одной или всех сессий, обновление токенов |
| Друзья | Поиск, списки, отправка/принятие/отклонение заявок через SignalR |
| Личные чаты | Создание между друзьями, история, отправка и редактирование |
| Прочтение и удаление | Методы есть; проверки доступа и семантика требуют исправления |
| Профиль | Описание, аватар, загрузка профиля и события изменений |
| Присутствие | События подключения/отключения; HTTP status сломан |
| Медиа и push | Загрузка/скачивание файлов, регистрация FCM-токена |
| Группы | Модели и часть сервисов сообщений; полноценный сценарий управления не завершён |
| Шифрование | Есть хранение публичных ключей, но готового E2EE нет |
### Как получить код приглашения
## Как читать
Коды приглашения **создаются администрацией проекта** и **выдаются вручную** по мере готовности новых тестовых слотов.
Начните с «Запуск и конфигурация» и «Аутентификация». Для чатов используйте HTTP для истории и SignalR для команд и событий. Раздел «Диагностика» описывает ограничения, которые нельзя считать рабочими гарантиями API.
Чтобы запросить код приглашения:
Имена `userId`, `friendId`, `chatId` обозначают разные сущности. В сообщениях личного чата `recipientId` — ID записи PrivateChat, а не ID собеседника.
1. Свяжитесь с командой разработчиков.
2. Кратко опишите, зачем вы хотите протестировать Говор.
3. Дождитесь ответа с вашим уникальным кодом.
## Границы готовности
📩 **Контакт для запроса:**\
`BurntRoostersOfficial@protonmail.com`
Текущая версия не готова к открытому развёртыванию: обнаружены критичные ошибки авторизации и доступа к личным чатам. Контракты ниже полезны для разработки, но не являются подтверждением безопасности.
### Как выглядит код
Эффект стекла относится к MAUI-интерфейсу. API передаёт данные и события; производительность размытия, контрастность и анимации нужно проверять отдельно на устройствах.
Код приглашения представляет собой **уникальный случайно сгенерированный идентификатор** (объект `Guid`).\
Пример:
Регистрация сейчас требует код приглашения. Обещание отключить приглашения после релиза является продуктовым планом, а не поведением текущего кода.
```
c7a5f1b3-8c64-47e2-9e3e-b7df6a2b021f
```
***
### Ограничения
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
Каждый код приглашения имеет:
* 🔹 **Ограниченное количество регистраций.**\
После достижения лимита использование кода становится невозможным.
* ⏳ **Ограниченный срок действия.**\
По истечении времени жизни код автоматически теряет актуальность.
### После официального релиза
После выхода **первой стабильной версии Говора** система кодов приглашений будет **отключена**, и регистрация станет **открытой для всех пользователей**.
Источник: [Govor.API/Program.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Program.cs).
+24 -18
View File
@@ -1,29 +1,35 @@
# Table of contents
* [The invitation code RU](README.md)
* [Govor.API — обзор](README.md)
* [Запуск и конфигурация](getting-started.md)
* [Архитектура и границы](architecture.md)
* [Диагностика и порядок исправлений](diagnostics.md)
## Endpoints
* [Authentication](endpoints/authentication/README.md)
* [AuthController](endpoints/authentication/authcontroller.md)
* [RefreshController](endpoints/authentication/refreshcontroller.md)
* [SessionController](endpoints/sessioncontroller.md)
* [FriendshipController](endpoints/friendshipcontroller.md)
* [FriendsRequestQueryController](endpoints/friendsrequestquerycontroller.md)
* [MediaController](endpoints/mediacontroller.md)
* [ChatLoadController](endpoints/chatloadcontroller.md)
* [OnlinePingingController(не работает)](endpoints/onlinepingingcontroller-ne-rabotaet.md)
* [Аутентификация](endpoints/authentication/README.md)
* [Регистрация и вход](endpoints/authentication/authcontroller.md)
* [Обновление токенов](endpoints/authentication/refreshcontroller.md)
* [Ключи сессий — экспериментальный API](endpoints/authentication/session-keys.md)
* [Сессии](endpoints/sessioncontroller.md)
* [Друзья и поиск](endpoints/friendshipcontroller.md)
* [Списки заявок в друзья](endpoints/friendsrequestquerycontroller.md)
* [Личные чаты](endpoints/private-chats.md)
* [Медиа](endpoints/mediacontroller.md)
* [История сообщений](endpoints/chatloadcontroller.md)
* [HTTP-присутствие — ограничения](endpoints/onlinepingingcontroller-ne-rabotaet.md)
* [Профиль и аватар](endpoints/profile.md)
* [Push-уведомления](endpoints/push.md)
* [Администрирование и незавершённые группы](endpoints/admin-and-groups.md)
## SignalR
* [PresenceHub](signalr/presencehub.md)
* [ChatHub](signalr/chathub.md)
***
* [FriendsHub](friendshub/README.md)
* [FriendsHub Client (Java)](friendshub/friendshub-client-java.md)
* [PresenceHub — online и offline](signalr/presencehub.md)
* [ChatsHub — сообщения](signalr/chathub.md)
* [ProfileHub — изменения профиля](signalr/profilehub.md)
* [FriendsHub — заявки](signalr/friendshub/README.md)
* [Клиент SignalR на C# для MAUI](signalr/friendshub/friendshub-client-java.md)
## Code Docs
* [HubResult\<T>](code-docs/hubresult-less-than-t-greater-than.md)
* [Ответы, ошибки и сериализация](code-docs/hubresult-less-than-t-greater-than.md)
+41
View File
@@ -0,0 +1,41 @@
# Архитектура и границы
## Поток запроса
MAUI → HTTP Controller / SignalR Hub → Application service → GovorDbContext → PostgreSQL. Медиа-сервис сохраняет бинарные данные через LocalStorageService; ChatNotificationService отправляет SignalR-события и push через Firebase.
| Проект | Ответственность сейчас |
| ----------------- | ------------------------------------------------------------ |
| Govor.API | Маршруты, хабы, авторизация, DI, преобразование ошибок и DTO |
| Govor.Application | Сценарии пользователей, друзей, сообщений, медиа и push |
| Govor.Contracts | HTTP/SignalR запросы, ответы и DTO |
| Govor.Domain | Сущности, DbContext, EF-конфигурации и миграции |
Это многослойное приложение, но Domain уже зависит от EF Core и содержит инфраструктуру БД. Не следует описывать его как полностью независимую доменную модель.
## Хранение и идентификаторы
PrivateChat связывает UserAId и UserBId. Message хранит SenderId и полиморфный RecipientId: ID PrivateChat для RecipientType.User или ID ChatGroup для RecipientType.Group. Ошибки возникают там, где этот ID сравнивают с ID пользователя.
Роль access token получается из приглашения пользователя (`Invite.IsAdmin`), хотя есть отдельная сущность Admin. Нужен один источник истины для ролей.
## Состояние соединений
ConnectionStore и OnlineUserStore — singleton в памяти одного процесса. Подключения автоматически вступают в группы пользователя, его чатов и групп. Перезапуск очищает это состояние; несколько инстансов без общего решения для SignalR и presence не имеют согласованного состояния.
## Рекомендуемые решения
1. Ввести общую проверку участия в конкретном чате и применять её к истории, Send, Read, медиа и событиям.
2. Разделить команды и чтение: создание чата и смена пароля не должны выполняться GET-запросами.
3. Возвращать только DTO, особенно для криптосессий и медиа.
4. Описать ошибки единым контрактом, сохранив совместимость с MAUI.
5. Для доставки отделить сохранение сообщения от внешних уведомлений: outbox и повторная доставка с дедупликацией.
6. Принять отдельное решение о E2EE: протокол, проверка ключей, несколько устройств, восстановление и миграция существующих сообщений.
Это предложения, они не внедрены в рамках переписывания документации.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
Источник: [Govor.Domain/GovorDbContext.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Domain/GovorDbContext.cs).
@@ -5,160 +5,51 @@ description: >-
messages. It supports various HTTP-like status cod
---
# HubResult\<T>
# Ответы, ошибки и сериализация
**Namespace**: `Govor.Contracts.Responses.SignalR`
## HTTP
### <mark style="color:$info;">Properties</mark>
ResultExtensions преобразует Result\<T, Error>: успешный T → 200 со значением; Unit → 204 без тела.
* **Status**: (`HubResultStatus`) Indicates the status of the hub operation, corresponding to HTTP-like status codes (e.g., Success, BadRequest).
* **Result**: (`T?`) The data returned by the hub operation, if applicable. Can be null for error cases or when no data is returned.
* **ErrorMessage**: (`string?`) A message describing the error, if the operation failed. Null for successful operations.
| ErrorType | HTTP |
| ------------------------------ | ---------------------------- |
| Validation | 400 |
| NotFound | 404 |
| Conflict | 409 |
| Unauthorized | 401 |
| Forbidden | 403 |
| Остальные, включая ServerError | 400 (текущий дефект mapping) |
### <mark style="color:$info;">Static Methods</mark>
Сервисная ошибка:
#### Ok
**Description**: Creates a successful result with an optional data payload.\
**Parameters**:
* `result`: (`T?`, optional) The data to include in the response (default: `null`).\
**Returns**: A `HubResult<T>` with `Status` set to `Success` (200) and the provided `result`.\
**Example**:
```csharp
HubResult<string> result = HubResult<string>.Ok("Operation completed");
```json
{"status":404,"title":"Not Found","detail":"<описание>","errorCode":"<код>"}
```
#### Created
errors добавляется при наличии. Автоматическая MVC-валидация, middleware авторизации и ручные BadRequest/StatusCode могут возвращать другую форму. Единого тела ошибки для всех маршрутов сейчас нет.
**Description**: Creates a result indicating a resource was created, with an optional data payload.\
**Parameters**:
В контроллерах встречается Forbid(ex.Message): строка трактуется как authentication scheme, а не тело ответа; результат может быть 500 вместо 403.
* `result`: (`T?`, optional) The data to include in the response (default: `null`).\
**Returns**: A `HubResult<T>` with `Status` set to `Created` (201) and the provided `result`.\
**Example**:
## SignalR HubResult
```csharp
HubResult<string> result = HubResult<string>.Created("Resource created");
```json
{"status":200,"result":null,"errorMessage":null}
```
#### NoContent
status — число внутри ответа команды, не HTTP-статус соединения. Значения: 200 Success, 201 Created, 204 NoContent, 400 BadRequest, 401 Unauthorized, 404 NotFound, 409 Conflict, 422 UnprocessableEntity, 500 ServerError.
**Description**: Creates a result indicating the operation was successful but no data is returned.\
**Parameters**: None\
**Returns**: A `HubResult<T>` with `Status` set to `NoContent` (204) and `Result` set to `null`.\
**Example**:
Static factories: Ok(result), Created(result), NoContent(), BadRequest(message, details), NotFound(message, details), Unauthorized(message), Conflict(message), UnprocessableEntity(message), Error(message).
```csharp
HubResult<string> result = HubResult<string>.NoContent();
```
Каждый хаб сам преобразует бизнес-ошибки; наличие enum не гарантирует точный status для каждого Failure. HubExceptionFilter возвращает Task.FromResult(errorResult) вместо объекта результата из InvokeMethodAsync; исключения вне локальных catch требуют исправления и проверки сериализации.
#### BadRequest
## JSON-контракт
**Description**: Creates a result indicating a client error due to invalid input.\
**Parameters**:
Стандартные ASP.NET настройки используют camelCase; enum передаются числами, Guid — строками, byte\[] — base64, даты — ISO 8601. StringEnumConverter явно не настроен.
* `message`: (`string`) The error message describing the issue.
* `details`: (`T?`, optional) Additional details about the error (default: `null`).\
**Returns**: A `HubResult<T>` with `Status` set to `BadRequest` (400), the provided `message`, and optional `details`.\
**Example**:
HTTP MessageResponse.id и SignalR UserMessageResponse.messageId отличаются. HTTP и SignalR вложения также имеют разные структуры. Клиент должен иметь явное преобразование; не подменяйте один DTO другим.
```csharp
HubResult<string> result = HubResult<string>.BadRequest("Invalid input provided");
```
***
#### NotFound
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
**Description**: Creates a result indicating a requested resource was not found.\
**Parameters**:
* `message`: (`string`) The error message describing the issue.
* `details`: (`T?`, optional) Additional details about the error (default: `null`).\
**Returns**: A `HubResult<T>` with `Status` set to `NotFound` (404), the provided `message`, and optional `details`.\
**Example**:
```csharp
HubResult<string> result = HubResult<string>.NotFound("User not found");
```
#### Unauthorized
**Description**: Creates a result indicating the client is not authorized to perform the operation.\
**Parameters**:
* `message`: (`string`) The error message describing the issue.\
**Returns**: A `HubResult<T>` with `Status` set to `Unauthorized` (401) and the provided `message`.\
**Example**:
```csharp
HubResult<string> result = HubResult<string>.Unauthorized("Authentication required");
```
#### Conflict
**Description**: Creates a result indicating a conflict, such as a duplicate resource.\
**Parameters**:
* `message`: (`string`) The error message describing the issue.\
**Returns**: A `HubResult<T>` with `Status` set to `Conflict` (409) and the provided `message`.\
**Example**:
```csharp
HubResult<string> result = HubResult<string>.Conflict("Resource already exists");
```
#### UnprocessableEntity
**Description**: Creates a result indicating the request could not be processed due to semantic errors.\
**Parameters**:
* `message`: (`string`) The error message describing the issue.\
**Returns**: A `HubResult<T>` with `Status` set to `UnprocessableEntity` (422) and the provided `message`.\
**Example**:
```csharp
HubResult<string> result = HubResult<string>.UnprocessableEntity("Invalid data format");
```
#### Error
**Description**: Creates a result indicating an internal server error.\
**Parameters**:
* `message`: (`string`) The error message describing the issue.\
**Returns**: A `HubResult<T>` with `Status` set to `ServerError` (500) and the provided `message`.\
**Example**:
```csharp
HubResult<string> result = HubResult<string>.Error("Unexpected server error");
```
### <mark style="color:$info;">Enum: HubResultStatus</mark>
**Description**: Enumerates the possible status codes for a `HubResult<T>` response, aligning with HTTP status codes for consistency in SignalR hub operations.
**Values**:
* <mark style="color:$success;">**Success**</mark> (200): The operation was successful.
* <mark style="color:$success;">**Created**</mark> (201): A resource was successfully created.
* <mark style="color:$success;">**NoContent**</mark> (204): The operation was successful, but no content is returned.
* <mark style="color:$danger;">**BadRequest**</mark> (400): The request was invalid or malformed.
* <mark style="color:$danger;">**Unauthorized**</mark> (401): The client is not authorized to perform the operation.
* <mark style="color:$danger;">**NotFound**</mark> (404): The requested resource was not found.
* <mark style="color:$danger;">**Conflict**</mark> (409): The request conflicts with an existing resource.
* <mark style="color:$danger;">**UnprocessableEntity**</mark> (422): The request could not be processed due to semantic errors.
* <mark style="color:$warning;">**ServerError**</mark> (500): An unexpected server error occurred.
### Example Usage
```csharp
// Successful operation with data
var successResult = HubResult<UserDto>.Ok(new UserDto { Id = Guid.NewGuid(), Username = "example" });
// Error due to invalid input
var errorResult = HubResult<UserDto>.BadRequest("Invalid username provided");
// Not found scenario
var notFoundResult = HubResult<UserDto>.NotFound("User not found in database");
```
Источник: [Govor.API/Common/Extensions/ResultExtensions.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Common/Extensions/ResultExtensions.cs).
+78
View File
@@ -0,0 +1,78 @@
# Диагностика и порядок исправлений
## Основание и пределы проверки
Проверен master Govor-team/Govor, commit 4603be9f714135e0af72d505d17f3d1709834bea (GitHub и локальный checkout совпали). Изучены контроллеры, хабы, сервисы, DTO, EF-модели, DI, запуск и часть MAUI-интеграции. Старый опубликованный GitBook оставался на ревизии 18.12.2025 и расходился с кодом.
Сборка API на SDK 10.0.400 успешна: первая сборка 90 предупреждений, 0 ошибок. Restore Govor.API.Tests неуспешен: NU1201, net8.0 → net10.0. Тесты не выполнены; утверждать, что они проходят, нельзя. Производственный сервер, БД, Firebase, Docker и UI на устройствах не проверялись.
Ниже «подтверждено» означает выявлено по конкретному коду или диагностике сборки, а не воспроизведено атакой на живой сервис.
## P0 — закрыть до публичного доступа
| Проблема | Доказательство | Последствие | Исправление |
| --------------------------------------------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------- |
| Административные приглашения доступны анонимно | InviteUserController: Authorize закомментирован; isAdmin принимается из запроса | Получение административной роли через собственное приглашение | Admin policy и серверная проверка права выдавать роль |
| Смена чужого пароля и выдача passwordHash обычному пользователю | UsersController: только Authorize; GET setpassword; BuildUserDtos включает PasswordHash | Захват аккаунтов, раскрытие хешей, пароль в URL | Admin policy, убрать hash из DTO, POST-команда, аудит и отзыв сессий |
| Чужая история и отправка в чужой личный чат | MessagesLoader игнорирует currentUser; Send проверяет только существование PrivateChat | Чтение и запись по чужому chatId | Общая проверка участия в конкретном чате |
| Неправильная авторизация Read | CanReadMessage проверяет любой PrivateChat пользователя | Отметки чужих сообщений прочитанными | Привязать проверку к message.RecipientId |
| Криптосессия выдаётся как EF-сущность с UserSession | SessionKeysReader Include(UserSession), контроллер Ok(keys) | Риск раскрытия внутренних полей и циклов JSON | PublicSessionKeysDto, проекция только публичных полей |
## P1 — восстановить корректность
| Проблема | Где | Действие |
| --------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- |
| rotate/used всегда обращаются к null | SessionKeysController.\_oneTimePreKeysRotator | Передать зависимость конструктору |
| online/status всегда падает | OnlinePingingController, две зависимости не присвоены | Исправить DI и проверку поведения |
| Вступление в группу неработоспособно | InviteController.\_currentUser и незарегистрированный IGroupService | Завершить сервис и инъекцию |
| HideForMe физически удаляет сообщение автора | MessageRemovingService игнорирует ForceRemove | Реализовать отдельную запись скрытия |
| Удаление группового сообщения сравнивает userId с groupId | MessageRemovingService | Проверять автора/администратора и участие |
| Собеседнику не приходят Edit/Remove/Read | NotifyParticipantsAsync адресует ID чата как группу пользователя | Определять обоих участников чата |
| Личные вложения недоступны получателю | AccesserToDownloadMediaService сравнивает RecipientId с userId | Проверять участников PrivateChat |
| Нет владения вложениями и аватаром | Send; ProfileHub.SetAvatar; OwnerType от клиента | Серверная политика ownership, лимиты и whitelist |
| EncryptedKey теряется | MediaService и MessageSendingService не сохраняют ключ | Выбрать и реализовать контракт хранения/доставки |
| Отзыв сессии не отзывает access/соединение | Program.cs; UserSessionRevoker | Проверять sid и закрывать соединения по политике |
| Refresh может повторяться/конфликтовать | JwtService без jti/sid; hash unique; неатомарная ротация | Случайный refresh, атомарная ротация и replay-политика |
| Ошибки превращаются в ложные статусы | ResultExtensions, Forbid(text), хабы, фильтр | Единый mapping, 500 для server errors, корректный объект из фильтра |
| Тестовая инфраструктура отстала | API.Tests net8, API net10; устаревшие проекты | Выровнять TFM/EF и восстановить CI |
| Контейнер не соответствует проекту | Dockerfile .NET 8, ссылки Core/Data | Обновить слои сборки и зависимости |
## P2 — надёжность и сопровождение
* Конкурентные регистрации могут превысить лимит приглашения; IsActive не проверяется. Нужна атомарная квота.
* Повторный Read конфликтует при гонке по unique(MessageId, UserId); требуется идемпотентная запись.
* Нет clientMessageId/outbox: после сохранения уведомление может упасть, а повторная отправка создаст дубль.
* Пагинация только по SentAt пропускает одинаковые timestamps; нужен стабильный курсор.
* Состояние соединений локально процессу; для нескольких инстансов требуется общее решение.
* CORS принимает любой origin с credentials; sensitive EF logging включён без ограничения окружения.
* Firebase обязателен даже для локального старта; внешние зависимости должны включаться явно.
* global.json содержит некорректную sdk/version; solution зависит от внешнего SmartRes, а API — от DLL в libs.
* Дубликат маппинга UserProfileDto, nullable выключен в API, а предупреждения CS0649 уже указывают реальные дефекты.
* Приглашение определяет роль одновременно с отдельной таблицей Admin; выбрать один источник.
* PrivacyUserSettings и Blocked-модель не означают, что приватность и блокировка покрывают все сценарии.
NuGet сообщил NU1903 для AutoMapper 16.0.0. [GHSA-rvv3-g6hj-g44x](https://github.com/advisories/GHSA-rvv3-g6hj-g44x) описывает DoS от рекурсивного mapping; исправленная версия ветки 16 — 16.1.1. Это подтверждение уязвимости зависимости; доступность конкретного exploit-пути в Govor отдельно не доказана.
## MAUI и стеклянный интерфейс
MessagesListController присваивает EncryptedContent = text; mapping читает его прямо в Text, а репозиторий редактирует как NewEncryptedContent = newText. Следовательно, в проверенном пути сообщения передаются обычным текстом. Хранение ключей на сервере не делает этот путь E2EE.
ChatHub клиента отбрасывает сообщения с пустым текстом, даже если есть вложение. Клиент подписан на MessageSent, которое сервер не отправляет. Перезапуск из Closed может конфликтовать с logout; refresh на любом HTTP-сбое очищает токены. MessagesListController.SendAsync возвращает Success(true), не проверяя результат SendMessageAsync; экран может считать неуспешную отправку успешной. Эти проблемы важнее полировки оформления.
В ChatPage.xaml есть слои с Opacity и Shadow. Визуально подтвердить эффект, FPS и поведение blur без запуска приложения нельзя. Рекомендуется отдельно измерить скролл длинного чата, работу клавиатуры, контраст текста на светлом/тёмном фоне и отключение тяжёлых эффектов. Полный UI-аудит не проводился.
## Последовательность работ
1. Закрыть P0, добавить проверки «пользователь C не может читать/писать/читать ключи чата A–B; User не управляет Admin».
2. Выровнять .NET и тесты; проверить реальные PostgreSQL-запросы и DI через старт приложения.
3. Исправить P1: события двух участников, HideForMe, медиа, ключи, logout.
4. Закрепить API контрактами и интеграционными тестами HTTP/SignalR, включая повторные и параллельные операции.
5. Решить E2EE и доставку; после этого расширять группы и оптимизировать визуальные эффекты.
Критерий готовности: воспроизводимый запуск, зелёные проверки доступа, согласованный MAUI-контракт и отсутствие известных неработающих методов. Архитектурная переработка должна опираться на эти проверки, а не начинаться с переписывания всего приложения.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
Источник: [Govor.API/Program.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Program.cs).
+35
View File
@@ -0,0 +1,35 @@
# Администрирование и незавершённые группы
## Административные маршруты
Следующая таблица показывает фактические атрибуты, а не требуемую безопасную политику.
| Метод | Маршрут | Защита сейчас |
| ----- | ------------------------------------------------- | -------------------------------------- |
| POST | /api/admin/InviteUser/Invitation | Без Authorize |
| GET | /api/admin/InviteUser | Без Authorize |
| GET | /api/admin/InviteUser/GetAllActiveInvitations | Без Authorize |
| GET | /api/admin/InviteUser/{id} | Без Authorize |
| GET | /api/admin/Users/all | Любой аутентифицированный пользователь |
| GET | /api/admin/Users/{id} | Любой аутентифицированный пользователь |
| GET | /api/admin/Users/user/{id}/setpassword/{password} | Любой аутентифицированный пользователь |
CreateInvitationRequest: endDate, maxParticipants, isAdmin, description. Генератор возвращает строковый код в JSON (200). Списки приглашений возвращают id, description, isAdmin, maxParticipants, code, createdAt, endAt, isActive, participantCount.
Users/all фактически ограничен 50 записями без стабильной пагинации. Ответ UserResponse включает passwordHash, что недопустимо для клиентского контракта. Смена пароля выполняется GET и кладёт пароль в URL.
Эти маршруты нужно закрыть ролью Admin до публичного использования. Создание административного приглашения вместе с регистрацией позволяет получить роль Admin. Не подключайте их к пользовательскому интерфейсу.
## Группы
GET /invite/{code} задуман как вход в группу и требует Authorize. IGroupService не зарегистрирован в AddServices, а \_currentUser не присваивается. Маршрут не является рабочим сценарием вступления.
GroupsHub пуст и не подключён MapHub. Административный FriendshipsController содержит только закомментированные действия, поэтому рабочих endpoints у него нет.
Наличие моделей ChatGroup/GroupMembership/GroupInvitation и проверки участия в групповом Send не подтверждает готовый продуктовый сценарий групп и каналов.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
Источник: [Govor.API/Controllers/AdminStuff/UsersController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/AdminStuff/UsersController.cs).
+19 -32
View File
@@ -3,43 +3,30 @@ description: How to work with jwt tokens
icon: user
---
# Authentication
# Аутентификация
### <mark style="color:$info;">Components</mark>
## Последовательность
* **AuthController**: Handles registration and login.
* **Route**: `/api/auth`
* **RefreshController**: Manages token refresh.
* **Route**: `/api/auth/token`
1. `POST /api/auth/register` либо `POST /api/auth/login` возвращает `{ refreshToken, accessToken }`.
2. HTTP-запросы передают `Authorization: Bearer <accessToken>`.
3. Для SignalR задайте AccessTokenProvider, который возвращает актуальный access token. Program.cs также принимает query `access_token` на путях /hubs.
4. `POST /api/auth/token/refresh` возвращает новую пару; клиент сохраняет новый refresh token.
5. Отзыв сессий выполняется методами /api/Session/close.
### <mark style="color:$info;">Authentication Process</mark>
Access token содержит `userId`, `sid` и роль User/Admin. Подпись HS256 проверяется, срок проверяется, issuer и audience не проверяются. Токены возвращаются JSON; сервер не устанавливает HttpOnly-cookie.
* **Registration**:
* **Endpoint**: `POST /api/auth/register`
* **Input**: `RegistrationRequest` (name, password, inviteLink, deviceInfo)
* **Output**: Access token
* **Action**: Validates invite, registers user, opens session.
* **Login**:
* **Endpoint**: `POST /api/auth/login`
* **Input**: `LoginRequest` (name, password, deviceInfo)
* **Output**: Access token
* **Action**: Authenticates user, opens session.
* **Token Refresh**:
* **Endpoint**: `POST /api/auth/token/refresh`
* **Input**: `RefreshTokenRequest` (refreshToken)
* **Output**: `RefreshTokenResponse` (accessToken, refreshToken)
* **Action**: Refreshes expired access token.
## Ограничения реализации
### <mark style="color:$info;">Token Usage</mark>
Отзыв сессии блокирует refresh, но Program.cs не проверяет IsRevoked при каждом использовании access token. Уже открытые SignalR-соединения явно не разрываются. Немедленный logout на всех устройствах не гарантирован.
* **Access Token**:
* **Request**: Obtain during registration or login.
* **Refresh**: Request via `/api/auth/token/refresh` when expired (e.g., 02:12 PM CEST, July 21, 2025).
* **Refresh Token**:
* **Request**: Received during registration or login.
* **Refresh**: Use to obtain new access token when current one expires.
Refresh JWT содержит userId и tokenType, но не случайный jti или sid. При выпуске одному пользователю в одну секунду возможны одинаковые токены, конфликтующие с уникальным RefreshTokenHash. Ротация не защищена атомарным compare-and-swap от параллельных запросов.
### Security
Не используйте refresh token как access token. В bearer-валидации нет явного требования tokenType=access; методы с одним Authorize требуют исправления разделения типов токенов.
* **Protocol**: Requires HTTPS.
* **Storage**: Store refresh token in HTTP-only cookie with `Secure` and `SameSite=Strict`.
На MAUI рекомендовано хранить refresh token в SecureStorage и выполнять обновление последовательно. Это рекомендация клиенту, а не свойство сервера.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
Источник: [Govor.Application/Authentication/JWT/JwtService.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Application/Authentication/JWT/JwtService.cs).
+29 -118
View File
@@ -4,138 +4,49 @@ description: >-
and login, with session management and invite-based registration.
---
# AuthController
# Регистрация и вход
### Controller Description
Оба метода доступны анонимно, Content-Type: application/json.
* **Route**: `api/auth`
* **Authorize**: Allows anonymous access (`[AllowAnonymous]`).
## POST /api/auth/register
### Endpoints
```json
{
"name": "Артём",
"password": "example-password",
"inviteLink": "<код приглашения>",
"deviceInfo": "Android test device"
}
```
#### <mark style="color:$info;">Register</mark>
Имя: 4–44 символа, только кириллица и цифры, первый символ — буква. Модерация запрещает зарезервированные имена, совпадения/подстроки из конфигурации и пять одинаковых символов подряд. Пароль: минимум 8 символов. DeviceInfo необязателен в запросе, но в БД ограничен 256 символами.
* **Description**: Registers a new user using a valid invite link and opens a user session, returning an authentication token.
* **Route**: `[POST] api/auth/register`
* **HTTP Method**: `POST`
* **Request**:
* **Content-Type**: `application/json`
* **Request Body**: `RegistrationRequest` object with the following structure:
Код создаётся как Guid.ToString("N"): 32 символа без дефисов. Поиск кода — по строковому равенству. InviteLink — код, а не URL.
```json
{
"name": "string",
"password": "string",
"inviteLink": "string",
"deviceInfo": "string"
}
```
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns the authentication token upon successful registration and session creation.
Проверяется существование приглашения, срок и число участников. Проверка IsActive отсутствует, лимит участников не защищён от конкурентной регистрации.
```json
{
"refreshToken": "string",
"accessToken": "string"
}
```
* <mark style="color:$danger;">**400 Bad Request**</mark>:
* If model validation fails.
* If the user already exists: `"Registration failed: user already exists."`
* If the invite link is invalid: `"Invite link invalid."`
* If the username is invalid: `"Invalid username: <error_message>"`
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
Успех 200:
```json
"An unexpected error occurred. Please try again later."
```
```json
{"refreshToken":"<token>","accessToken":"<token>"}
```
#### <mark style="color:$info;">Login</mark>
Конфликт имени — 409; ошибки валидации — 400; отсутствующее приглашение — 404. Тело сервисных ошибок — ProblemDetails с errorCode. Регистрация и открытие сессии — отдельные сохранения: ошибка открытия сессии не откатывает созданного пользователя.
* **Description**: Authenticates an existing user and opens a session, returning an authentication token.
* **Route**: `[POST] api/auth/login`
* **HTTP Method**: `POST`
* **Request**:
* **Content-Type**: `application/json`
* **Request Body**: `LoginRequest` object with the following structure:
## POST /api/auth/login
```json
{
"name": "string",
"password": "string",
"deviceInfo": "string"
}
```
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns the authentication token upon successful login and session creation.
```json
{"name":"Артём","password":"example-password","deviceInfo":"Android test device"}
```
```json
{
"refreshToken": "string",
"accessToken": "string"
}
```
* <mark style="color:$danger;">**400 Bad Request**</mark>:
* If model validation fails.
* If the user does not exist: `"Login failed: user does not exist."`
* If the username or password is incorrect: `"Login failed: username or password is incorrect."`
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
Успех 200 с той же парой токенов. Пользователь не найден — 404 (UserNotRegisteredException); неверный пароль — 400 (InvalidOperationException). Это текущее поведение, а не рекомендуемая политика ошибок входа: разные ответы раскрывают существование аккаунта.
```json
"An unexpected error occurred. Please try again later."
```
## Ограничения
### Data Models
Rate limiting и блокировка перебора в Program.cs не настроены. Для публичного запуска нужны единая ошибка входа, ограничение частоты и защита административных приглашений.
#### RegistrationRequest
***
* **Description**: Model for registration request data.
* **Structure**:
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
```json
{
"name": "string",
"password": "string",
"inviteLink": "string",
"deviceInfo": "string"
}
```
#### LoginRequest
* **Description**: Model for login request data.
* **Structure**:
```json
{
"name": "string",
"password": "string",
"deviceInfo": "string"
}
```
#### RefreshResult
* **Description**: Model for refresh token response data.
* **Structure**:
```json
{
"refreshToken": "string",
"accessToken": "string"
}
```
### Error Handling
* **Invalid User ID**: Not applicable (handled by session service).
* **Invalid Operations**: Registration fails if the user already exists, invite link is invalid, or username is invalid, returning `400 Bad Request`.
* **Unauthorized Access**: Not applicable (endpoint is `[AllowAnonymous]`).
* **Unexpected Errors**: General exceptions are caught, logged, and returned as `500 Internal Server Error`.
### Logging
* Logs successful registration and login events with username and user ID.
* Logs session opening events with username and user ID.
* Logs warnings for specific exceptions (e.g., user already exists, invalid invite link, login failures).
* Logs errors for unexpected exceptions during registration and login.
Источник: [Govor.API/Controllers/Authentication/AuthController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/Authentication/AuthController.cs).
@@ -4,87 +4,40 @@ description: >-
their access tokens using a valid refresh token.
---
# RefreshController
# Обновление токенов
### Controller Description
## POST /api/auth/token/refresh
* **Route**: `api/auth/token`
* **Authorize**: Allows anonymous access (`[AllowAnonymous]`).
Доступ анонимный. JSON:
### Endpoints
```json
{"refreshToken":"<последний сохранённый refresh token>"}
```
#### <mark style="color:$info;">Refresh</mark>
Сервис хеширует переданную строку и ищет UserSession по RefreshTokenHash. Проверяет IsRevoked и ExpiresAt, выпускает новую пару, заменяет хеш и продлевает ExpiresAt. CreatedAt также перезаписывается, поэтому после refresh это не исходная дата открытия сессии.
* **Description**: Refreshes an access token using a provided refresh token and returns a new access token and refresh token pair.
* **Route**: `[POST] api/auth/token/refresh`
* **HTTP Method**: `POST`
* **Request**:
* **Content-Type**: `application/json`
* **Request Body**: `RefreshTokenRequest` object with the following structure:
Успех 200:
```json
{
"refreshToken": "string"
}
```
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns a new access token and refresh token upon successful refresh.
```json
{"refreshToken":"<new token>","accessToken":"<new token>"}
```
```json
{
"accessToken": "string",
"refreshToken": "string"
}
```
* <mark style="color:$warning;">**400 Bad Request**</mark>: If model validation fails or the refresh token is empty.
| Случай | Текущий ответ |
| -------------------------- | -------------------------------- |
| Пустая строка | 400, errorCode Auth.EmptyToken |
| Хеш не найден | 400, errorCode Auth.InvalidToken |
| Истекшая/отозванная сессия | 400, errorCode Auth.InvalidToken |
```json
"Refresh token cant be empty."
```
* <mark style="color:$warning;">**401 Unauthorized**</mark>: If the refresh token is invalid or authorization fails.
Не документируйте неверный refresh как гарантированный 401: текущий Error.Failure преобразуется в 400.
```json
"Invalid refresh token"
```
* <mark style="color:$danger;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
## Клиент
```json
"An unexpected error occurred."
```
Сохраните оба новых токена и сериализуйте refresh-запросы. Ошибка сети не должна автоматически удалять авторизацию пользователя. При подтверждённо недействительном refresh требуется повторный вход.
### Data Models
Ротация сейчас не имеет защиты от конкурентного использования и истории повторного применения. Детали — в разделе «Аутентификация».
#### RefreshTokenRequest
***
* **Description**: Model for refresh token request data.
* **Structure**:
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
```json
{
"refreshToken": "string"
}
```
#### RefreshTokenResponse
* **Description**: Model for refresh token response data.
* **Structure**:
```json
{
"accessToken": "string",
"refreshToken": "string"
}
```
### Error Handling
* **Invalid User ID**: Not applicable (handled by session service).
* **Invalid Operations**: Returns `400 Bad Request` if the refresh token is empty or invalid.
* **Unauthorized Access**: Returns `401 Unauthorized` if the refresh token fails authorization.
* **Unexpected Errors**: General exceptions are caught, logged, and returned as `500 Internal Server Error`.
### Logging
* Logs warnings for invalid or failed refresh token attempts.
* Logs errors for unexpected exceptions during token refresh.
Источник: [Govor.Application/Users/UserSessions/UserSessionRefresher.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Application/Users/UserSessions/UserSessionRefresher.cs).
@@ -0,0 +1,33 @@
# Ключи сессий — экспериментальный API
RequireHttps и роль User/Admin обязательны.
| Метод | Маршрут | Назначение |
| ----- | --------------------------------- | ---------------------------------------- |
| POST | /api/session/keys | Привязать публичные ключи текущей сессии |
| GET | /api/session/users/{userId}/keys | Получить ключи друга |
| POST | /api/session/keys/rotate | Пополнить одноразовые ключи |
| GET | /api/session/keys/remaining | { remaining: число } |
| POST | /api/session/keys/{preKeyId}/used | Пометить собственный ключ использованным |
byte\[] в JSON передаются строкой base64. UploadKeysRequest содержит identityKey, signedPreKey, signedPreKeySignature и oneTimePreKeys (массив base64). За запрос допускается максимум 100 одноразовых ключей. Сервис запрещает повторную привязку ключей к сессии и проверяет владельца.
RotateOneTimePreKeysRequest содержит newOneTimePreKeys. В реализации ротация удаляет использованные записи и добавляет новые, не ограничивая общий размер набора.
## Неработающие и небезопасные части
\_oneTimePreKeysRotator не передан в конструктор SessionKeysController: rotate и used падают при обращении к null.
remaining считает все записи, включая IsUsed. Reader выдаёт все OneTimePreKeys и возвращает EF-сущности UserCryptoSession вместо PublicSessionKeysDto. Include(UserSession) может включить внутренние поля, а двусторонние навигации могут привести к циклу сериализации. SignedPreKey не включён явным Include.
Доступ к чужим ключам ограничен дружбой, но Forbid("текст") ошибочно используется как имя authentication scheme. Атомарной выдачи одного неиспользованного prekey потребителю нет: endpoint used относится к текущей сессии владельца.
## Статус E2EE
Это заготовка хранения ключей, не законченный криптографический протокол. Нет доказанной реализации обмена/проверки подписей, одноразового потребления, ratchet и поддержки шифрования на клиенте. Не используйте этот раздел как обещание сквозного шифрования.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
Источник: [Govor.API/Controllers/Authentication/SessionKeysController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/Authentication/SessionKeysController.cs).
+32 -242
View File
@@ -2,258 +2,48 @@
description: Controller for loading chat messages for users and groups with pagination.
---
# ChatLoadController
# История сообщений
### Controller Description
Требуется роль User/Admin.
* **Route**: `api/chats`
* **Authorize**: Requires authenticated user with roles "Admin" or "User" (`[Authorize(Roles = "Admin, User")]`).
| Метод | Маршрут | Идентификатор |
| ----- | ------------------------------ | -------------------------------------- |
| GET | /api/user/{userId}/messages | В userId передаётся **ID PrivateChat** |
| GET | /api/groups/{groupId}/messages | ID ChatGroup |
### Endpoints
Query: StartMessageId (Guid?, необязателен), Before=20, After=2. Before и After неотрицательные, сумма ≤100.
#### <mark style="color:$info;">GetGroupMessages</mark>
Без StartMessageId возвращаются последние Before сообщений, упорядоченные по SentAt по возрастанию; After не используется. С якорем возвращаются Before старых, якорное сообщение и After новых: максимум 101 запись. Неизвестный якорь — \[].
* **Description**: Retrieves messages from a specified group chat with pagination.
* **Route**: `[GET] api/chats/group-messages`
* **HTTP Method**: `GET`
* **Request**:
* **Path Parameter**: `chatId` (Guid, required): ID of the group chat.
* **Query Parameter**: `query` (`MessageQuery`, required) with:
* `startMessageId` (Guid?, optional): ID of the starting message.
* `before` (int, default=20): Number of messages before the start.
* `after` (int, default=2): Number of messages after the start.
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns a list of group chat messages.
Успех 200, MessageResponse\[]:
```json
[
{
"id": "Guid",
"senderId": "Guid",
"recipientId": "Guid",
"recipientType": "string",
"encryptedContent": "string",
"sentAt": "DateTime",
"isEdited": "boolean",
"editedAt": "DateTime?",
"replyToMessageId": "Guid?",
"mediaAttachments": [
{
"id": "Guid",
"messageId": "Guid",
"mediaFileId": "Guid"
}
],
"reactions": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"reactionCode": "string",
"reactedAt": "DateTime"
}
],
"messageViews": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"viewedAt": "DateTime"
}
]
}
]
```
* <mark style="color:$danger;">**400 Bad Request**</mark>:
* If `before` or `after` is negative or total exceeds 100: `"Values must be non-negative and total must not exceed 100."`
* If an argument or resource is invalid: `"string"`
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
```json
[{
"id":"11111111-1111-1111-1111-111111111111",
"senderId":"22222222-2222-2222-2222-222222222222",
"recipientId":"33333333-3333-3333-3333-333333333333",
"recipientType":0,
"encryptedContent":"<строка>",
"sentAt":"2026-10-03T00:00:00Z",
"isEdited":false,
"editedAt":null,
"replyToMessageId":null,
"mediaAttachments":[],
"reactions":[],
"messageViews":[]
}]
```
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
У HTTP-ответа поле id; у SignalR UserMessageResponse — messageId. Вложения HTTP имеют id, messageId, mediaFileId.
```json
"Unexpected Error! Please try again later."
```
## Известные проблемы
#### <mark style="color:$info;">GetUserMessages</mark>
Личный загрузчик принимает currentUser, но не проверяет участие в указанном чате. Это критичная ошибка доступа. Для группы участие проверяется; неучастнику возвращается \[].
* **Description**: Retrieves messages from a specified user chat with pagination.
* **Route**: `[GET] api/chats/user-messages`
* **HTTP Method**: `GET`
* **Request**:
* **Path Parameter**: `userId` (Guid, required): ID of the target user.
* **Query Parameter**: `query` (`MessageQuery`, required) with:
* `startMessageId` (Guid?, optional): ID of the starting message.
* `before` (int, default=20): Number of messages before the start.
* `after` (int, default=2): Number of messages after the start.
* **Responses**:
* **200 OK**: Returns a list of user chat messages.
Пагинация сравнивает только SentAt: сообщения с одинаковой датой могут выпадать вокруг якоря. Reactions и MessageViews не включаются явным Include, поэтому эти массивы не являются надёжным источником состояния. Нужны проверки доступа и стабильный курсор (SentAt, Id).
```json
[
{
"id": "Guid",
"senderId": "Guid",
"recipientId": "Guid",
"recipientType": "string",
"encryptedContent": "string",
"sentAt": "DateTime",
"isEdited": "boolean",
"editedAt": "DateTime?",
"replyToMessageId": "Guid?",
"mediaAttachments": [
{
"id": "Guid",
"messageId": "Guid",
"mediaFileId": "Guid"
}
],
"reactions": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"reactionCode": "string",
"reactedAt": "DateTime"
}
],
"messageViews": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"viewedAt": "DateTime"
}
]
}
]
```
* **400 Bad Request**:
* If `before` or `after` is negative or total exceeds 100: `"Values must be non-negative and total must not exceed 100."`
* If an operation or resource is invalid: `"string"`
* **403 Forbidden**: If user lacks authorization.
***
```json
"string"
```
* **500 Internal Server Error**: Indicates an unexpected error.
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
```json
"Unexpected Error! Please try again later."
```
### Data Models
#### MessageQuery
* **Description**: Model for pagination query parameters.
* **Structure**:
```json
{
"startMessageId": "Guid?",
"before": "int",
"after": "int"
}
```
#### MessageResponse
* **Description**: Data transfer object for chat message details.
* **Structure**:
```json
{
"id": "Guid",
"senderId": "Guid",
"recipientId": "Guid",
"recipientType": "string",
"encryptedContent": "string",
"sentAt": "DateTime",
"isEdited": "boolean",
"editedAt": "DateTime?",
"replyToMessageId": "Guid?",
"mediaAttachments": [
{
"id": "Guid",
"messageId": "Guid",
"mediaFileId": "Guid"
}
],
"reactions": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"reactionCode": "string",
"reactedAt": "DateTime"
}
],
"messageViews": [
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"viewedAt": "DateTime"
}
]
}
```
#### MediaAttachmentResponse
* **Description**: Data transfer object for media attachments in messages.
* **Structure**:
```json
{
"id": "Guid",
"messageId": "Guid",
"mediaFileId": "Guid"
}
```
#### MessageReactionResponse
* **Description**: Data transfer object for message reactions.
* **Structure**:
```json
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"reactionCode": "string",
"reactedAt": "DateTime"
}
```
#### MessageViewResponse
* **Description**: Data transfer object for message view tracking.
* **Structure**:
```json
{
"id": "Guid",
"messageId": "Guid",
"userId": "Guid",
"viewedAt": "DateTime"
}
```
### Error Handling
* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid.
* **Invalid Operations**: Returns `400 Bad Request` for negative values, total exceeding 100, or `InvalidOperationException`.
* **Unauthorized Access**: Returns `403 Forbidden` for `UnauthorizedAccessException`.
* **Resource Not Found**: Returns `400 Bad Request` for `NotFoundException`.
* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`.
### Logging
* Logs warnings for `UnauthorizedAccessException`, `NotFoundException`, `ArgumentException`, and `InvalidOperationException`.
* Logs errors for unexpected exceptions.
Источник: [Govor.Application/Messages/MessagesLoader.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Application/Messages/MessagesLoader.cs).
+22 -99
View File
@@ -4,111 +4,34 @@ description: >-
searching for users and retrieving the list of friends for the current user.
---
# FriendshipController
# Друзья и поиск
### Controller Description
Bearer token обязателен; отдельная роль в атрибуте не задана.
* **Route**: `api/friends`
* **Authorize**: Requires authenticated user (`[Authorize]`).
| Метод | Маршрут | Результат |
| ----- | ----------------------------- | ----------------------------- |
| GET | /api/friends | UserDto\[] друзей |
| GET | /api/friends/search?query=Арт | UserDto\[] результатов поиска |
### Endpoints
```json
[{
"id":"11111111-1111-1111-1111-111111111111",
"username":"Артём",
"description":"",
"wasOnline":"2026-10-03T00:00:00Z",
"iconId":"00000000-0000-0000-0000-000000000000",
"isOnline":false
}]
```
#### <mark style="color:$info;">Search</mark>
Пустой/пробельный query возвращает 400 строкой "Query cannot be empty". Успех — 200; серверные ошибки — 500 с объектом error. Не смешивайте UserDto и UserProfileDto: у второго нет wasOnline.
* **Description**: Searches for users based on a query string.
* **Route**: `[GET] api/friends/search?query=`
* **HTTP Method**: `GET`
* **Request**:
* **Query Parameter**: `query` (string, required)
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns a list of matching users.
Изменение заявок выполняется через FriendsHub. HTTP-контроллер не содержит команды отправки, принятия и отклонения.
```json
[
{
"id": "Guid",
"username": "string",
"description": "string",
"wasOnline": "DateTime",
"iconId": "Guid"
}
]
```
* <mark style="color:$danger;">**400 Bad Request**</mark>: If the query is empty.
Статус isOnline зависит от состояния процесса и подключения к presence. Он не является гарантией доставки сообщений или фоновой доступности устройства.
```json
"Query cannot be empty"
```
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
***
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
```json
{
"error": "Internal error during user search."
}
```
#### <mark style="color:$info;">GetFriends</mark>
* **Description**: Retrieves the list of friends for the authenticated user.
* **Route**: `[GET] api/friends`
* **HTTP Method**: `GET`
* **Request**: None
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns a list of the user's friends or an empty list if none.
```json
[
{
"id": "Guid",
"username": "string",
"description": "string",
"wasOnline": "DateTime",
"iconId": "Guid"
}
]
```
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
```json
{
"error": "Internal server error."
}
```
### Data Models
#### UserDto
* **Description**: Data transfer object for user information.
* **Structure**:
```json
{
"id": "Guid",
"username": "string",
"description": "string",
"wasOnline": "DateTime",
"iconId": "Guid"
}
```
### Error Handling
* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid.
* **Invalid Operations**: Returns `400 Bad Request` for empty query.
* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`.
### Logging
* Logs warnings for `SearchUsersException`.
* Logs errors for unexpected exceptions and `InvalidOperationException`.
Источник: [Govor.API/Controllers/Friends/FriendshipController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/Friends/FriendshipController.cs).
+19 -95
View File
@@ -4,106 +4,30 @@ description: >-
incoming friend requests and responses to sent friend requests.
---
# FriendsRequestQueryController
# Списки заявок в друзья
### Controller Description
Оба маршрута требуют Bearer token и возвращают 200 с FriendshipDto\[].
* **Route**: `api/friends`
* **Authorize**: Requires authenticated user (`[Authorize]`).
| Метод | Маршрут | Назначение |
| ----- | ---------------------- | --------------------------------------------------------------------- |
| GET | /api/friends/requests | Входящие заявки |
| GET | /api/friends/responses | Исходящие записи, кроме Accepted (включая Pending, Rejected, Blocked) |
### Endpoints
```json
[{
"id":"11111111-1111-1111-1111-111111111111",
"requesterId":"22222222-2222-2222-2222-222222222222",
"addresseeId":"33333333-3333-3333-3333-333333333333",
"status":0
}]
```
#### <mark style="color:$info;">GetIncomingRequests</mark>
FriendshipStatus сериализуется числом: Pending=0, Accepted=1, Rejected=2, Blocked=3. id — идентификатор заявки/дружбы; именно он передаётся в AcceptRequest и RejectRequest.
* **Description**: Retrieves a list of incoming friend requests for the authenticated user.
* **Route**: `[GET] api/friends/requests`
* **HTTP Method**: `GET`
* **Request**: None
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns a list of incoming friend requests or an empty list if none.
При отсутствии записей — пустой массив. Ошибки контроллера — 500 с {"error":"Internal server error."}. Для восстановления после reconnect перечитайте списки: события не являются журналом гарантированной доставки.
```json
[
{
"id": "Guid",
"senderId": "Guid",
"receiverId": "Guid",
"status": "string",
"createdAt": "DateTime"
}
]
```
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
***
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
```json
{
"error": "Internal server error."
}
```
#### <mark style="color:$info;">GetResponses</mark>
* **Description**: Retrieves a list of responses to the authenticated user's sent friend requests.
* **Route**: `[GET] api/friends/responses`
* **HTTP Method**: `GET`
* **Request**: None
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns a list of friend request responses or an empty list if none.
```json
[
{
"id": "Guid",
"senderId": "Guid",
"receiverId": "Guid",
"status": "string",
"createdAt": "DateTime"
}
]
```
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
```json
{
"error": "Internal server error."
}
```
### Data Models
#### FriendshipDto
* **Description**: Data transfer object for friend request information.
* **Structure**:
```json
{
"id": "Guid",
"senderId": "Guid",
"receiverId": "Guid",
"status": "string",
"createdAt": "DateTime"
}
```
### Error Handling
* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid.
* **Invalid Operations**: Returns `200 OK` with an empty list for `InvalidOperationException`.
* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`.
### Logging
* Logs warnings for `InvalidOperationException`.
* Logs information for successful response retrieval.
* Logs errors for unexpected exceptions.
Источник: [Govor.API/Controllers/Friends/FriendsRequestQueryController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/Friends/FriendsRequestQueryController.cs).
+26 -86
View File
@@ -2,106 +2,46 @@
description: Controller for uploading and downloading media files.
---
# MediaController
# Медиа
### Controller Description
Требуется роль User/Admin.
* **Route**: `api/media`
* **Authorize**: Requires authenticated user with roles "User" or "Admin" (`[Authorize(Roles = "User,Admin")]`).
## POST /api/media/upload
### Endpoints
Content-Type: multipart/form-data. Поля:
#### <mark style="color:$info;">Upload</mark>
| Поле | Тип | Назначение |
| ------------ | ----------- | ---------------------------------------------------------- |
| FromFile | файл | Непустое содержимое |
| Type | число | Image=0, Video=1, Audio=2, File=3, Voice=4 |
| MimeType | строка ≤255 | MIME типа файла |
| EncryptedKey | строка | Обязательное поле запроса; сохранение ключа не реализовано |
| OwnerType | число | Message=0, Avatar=1, GroupAvatar=2, System=3 |
* **Description**: Uploads a media file with associated metadata.
* **Route**: `[POST] api/media/upload`
* **HTTP Method**: `POST`
* **Request**:
* **Content-Type**: `multipart/form-data`
* **Request Body**: `MediaUploadRequest` object with the following structure:
Ограничение запроса — 20 000 000 байт, включая multipart; проверка файла также ≤20 000 000. Не следует обещать загрузку файла ровно этого размера: overhead тоже входит в лимит.
```json
{
"fromFile": "IFormFile",
"type": "MediaType",
"mimeType": "string",
"encryptedKey": "string"
}
```
* **Constraints**: File size limit of 20 MB.
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns the upload result.
Успех 200:
```json
"string" // Media ID or similar result
```
* <mark style="color:$danger;">**400 Bad Request**</mark>:
* If model validation fails.
* If no file is uploaded: `"No file uploaded"`
* If file exceeds 20 MB: `"File is too large"`
* If MIME type is missing: `"Missing MIME type"`
* If operation is invalid: `"string"`
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
```json
{"mediaId":"11111111-1111-1111-1111-111111111111","url":"2026/10/<имя файла>"}
```
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
url — относительный путь хранилища, не публичный URL. Для скачивания используйте endpoint.
```json
"Internal server error"
```
## GET /api/media/download/{id}
#### <mark style="color:$info;">Download</mark>
Проверяет HasAccessAsync, затем возвращает бинарный файл с MIME и Content-Disposition. Если доступа нет или запись не найдена — 403, потому что проверка доступа выполняется первой. Сервисные ошибки — через ResultExtensions.
* **Description**: Downloads a media file by its ID.
* **Route**: `[GET] api/media/download/{id}`
* **HTTP Method**: `GET`
* **Request**:
* **Path Parameter**: `id` (Guid, required): ID of the media file.
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns the media file as a stream.
* **Content-Type**: Matches `MimeType` of the media.
* **Content-Disposition**: Includes `filename` from `FileName`.
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks access.
* No body.
* <mark style="color:$danger;">**404 Not Found**</mark>: If media is not found.
## Ограничения
```json
"Media not found"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
Для личного сообщения accesser сравнивает Message.RecipientId с userId, хотя там ID чата: получатель может получить 403. При Send принадлежность вложения загрузившему пользователю не проверяется. OwnerType задаёт клиент, включая публично доступный System, — нужна серверная политика владения.
```json
"Internal server error"
```
EncryptedKey не хранится ни в MediaFile, ни в MediaAttachments. Нельзя обещать восстановление ключа из истории.
### Data Models
Файлы целиком буферизуются в памяти, MIME принимается от клиента. Запись файла и БД не атомарна: возможны файлы без записи. Очистка неиспользуемых загрузок и stream-based выдача требуют реализации.
#### MediaUploadRequest
***
* **Description**: Model for media upload request data.
* **Structure**:
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
```json
{
"fromFile": "IFormFile",
"type": "MediaType",
"mimeType": "string",
"encryptedKey": "string"
}
```
### Error Handling
* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid.
* **Invalid Operations**: Returns `400 Bad Request` for `InvalidOperationException`.
* **Unauthorized Access**: Returns `403 Forbidden` for `UnauthorizedAccessException`.
* **Resource Not Found**: Returns `404 Not Found` for `KeyNotFoundException`.
* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`.
### Logging
* Logs warnings for `UnauthorizedAccessException`, `InvalidOperationException`, and `KeyNotFoundException`.
* Logs information for successful file uploads.
* Logs errors for unexpected exceptions during upload and download.
Источник: [Govor.API/Controllers/MediaController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/MediaController.cs).
@@ -4,47 +4,23 @@ description: >-
ping requests.
---
# OnlinePingingController(не работает)
# HTTP-присутствие — ограничения
**Route**: `api/online`\
**Authorize**: Requires "User" or "Admin" role
Требуется роль User/Admin.
### <mark style="color:purple;">End Point {PATCH}</mark>
| Метод | Маршрут | Текущее поведение |
| ----- | --------------------------- | ----------------------------------------------- |
| PATCH | /api/online/ping | Вызывает PingHandlerService, успех 200 без тела |
| GET | /api/online/status/{userId} | Неработоспособен: 500 |
`[PATCH] api/online/ping`
В конструкторе не присваиваются \_userOnlineStore и \_presenceReader. GetStatus обращается к null; catch возвращает 500 "Internal server error.".
#### Description
Задуманное тело status — { isOnline, lastSeen }, но сейчас его нельзя считать рабочим контрактом.
Updates the online status of the current user by sending a ping request.
Для событий online/offline подключайтесь к /hubs/presence. Ping и наличие SignalR-подключения — разные механизмы; требуется единая политика lastSeen/TTL. Не считайте HTTP ping подтверждением активного presence-соединения.
**Request**
***
* **Content-Type**: `application/json`
* **Request Body**: None
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
**Responses**
* **200 OK**: Ping processed successfully.
```json
{}
```
* **400 Bad Request**: If the user cannot be found in the database.
```json
"User can't be found in our database."
```
* **403 Forbidden**: If the user is not authorized to perform the action.
```json
{
"error": "Not authorized to perform this action."
}
```
* **500 Internal Server Error**: Indicates an unexpected error.
```json
{
"error": "Failed to send friend request."
}
```
Источник: [Govor.API/Controllers/OnlinePingingController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/OnlinePingingController.cs).
+29
View File
@@ -0,0 +1,29 @@
# Личные чаты
Требуется роль User/Admin.
| Метод | Маршрут | Успех |
| ----- | --------------------------------- | ---------------------- |
| GET | /api/user/{friendId}/private-chat | 200, Guid чата в JSON |
| GET | /api/user/private-chats | 200, PrivateChatDto\[] |
Первый метод проверяет дружбу, возвращает существующий чат либо создаёт новый. Это побочный эффект GET; рекомендуемый будущий контракт — POST, но маршрут пока не изменён.
```json
[{
"chatId":"11111111-1111-1111-1111-111111111111",
"friendId":"22222222-2222-2222-2222-222222222222"
}]
```
При принятии заявки FriendRequestCommandService также создаёт личный чат и добавляет текущие соединения участников в SignalR-группу.
Используйте chatId в Send.recipientId и в /api/user/{userId}/messages. Несмотря на имя параметра userId, загрузчик ожидает ID PrivateChat.
Ошибки дружбы передаются через Forbid(ex.Message), что ошибочно трактует сообщение как имя схемы аутентификации и может дать 500. Параллельное создание и повторное присоединение после частичного сбоя требуют отдельной проверки.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
Источник: [Govor.API/Controllers/PrivateChatController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/PrivateChatController.cs).
+29
View File
@@ -0,0 +1,29 @@
# Профиль и аватар
Требуется роль User/Admin.
| Метод | Маршрут | Успех |
| ----- | -------------------------- | ------------------------------------------- |
| GET | /api/profile/download/me | 200, UserProfileDto текущего пользователя |
| GET | /api/profile/download/{id} | 200, UserProfileDto указанного пользователя |
| POST | /api/profile/avatar | 200, MediaUploadResult |
UserProfileDto: id, username, description (nullable), iconId (nullable), isOnline. Отсутствующий пользователь — 404 ProblemDetails.
Загрузка аватара: multipart/form-data с FromFile, Type, MimeType. В отличие от MediaController, отдельный лимит 20 MB не задан; действуют ограничения хоста. Контроллер сохраняет медиа с OwnerType.Avatar и устанавливает IconId.
Описание изменяется через ProfileHub.SetDescription. ProfileHub.SetAvatar принимает существующий iconId и рассылает AvatarUpdated.
## Ограничения
REST UploadAvatar не рассылает AvatarUpdated. Клиентам может потребоваться отдельное обновление данных. В ProfileHub.SetAvatar проверяется существование файла, но не его загрузчик/тип/владелец.
Хаб игнорирует Result от SetDescription и SetNewIcon, поэтому успех true не всегда подтверждает изменение. MappingProfile дважды регистрирует UserProfile → UserProfileDto; это нужно устранить и проверить isOnline.
Чтение чужого профиля не применяет PrivacyUserSettings. Наличие моделей приватности не означает действующую политику доступа.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
Источник: [Govor.API/Controllers/ProfileController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/ProfileController.cs).
+29
View File
@@ -0,0 +1,29 @@
# Push-уведомления
## POST /api/pushes/token/register
Требуется роль User/Admin. JSON:
```json
{"token":"<FCM registration token>","platform":"Android"}
```
Сервис связывает токен с userId и sid текущего access token, добавляет или обновляет запись. Успех Unit — 204. Пустой token/platform отклоняется 400; тело BadRequest(ModelState) не всегда содержит полезное объяснение.
При отзыве сессии связанные токены деактивируются. В DI зарегистрирован FirebasePushProvider; credentials читаются при старте приложения.
## Отправка
Личные сообщения вызывают отправку push собеседнику. title — имя отправителя; body — первые 40 символов EncryptedContent. Data содержит chatId и isGroup ("false"). Это текущая реализация: сервер не расшифровывает содержимое.
Для E2EE тело push должно быть нейтральным. Для текущего MAUI, отправляющего обычный текст, этот body раскрывает превью сообщения внешнему push-провайдеру.
## Доставка
Сохранение сообщения, SignalR и Firebase не образуют единую транзакцию. Ошибка после SaveChanges может дать ошибку Send, хотя сообщение уже записано. Автоматическое повторение без идентификатора клиентской операции может создать дубль. Нужны outbox, дедупликация и обработка недействительных FCM-токенов.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
Источник: [Govor.API/Hubs/Infrastructure/ChatNotificationService.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/Infrastructure/ChatNotificationService.cs).
+25 -140
View File
@@ -4,154 +4,39 @@ description: >-
sessions.
---
# SessionController
# Сессии
### Controller Description
Все методы требуют Bearer access token с ролью User или Admin.
* **Route**: `api/session`
* **Authorize**: Requires authenticated user with roles "Admin" or "User" (`[Authorize(Roles = "Admin,User")]`).
| Метод | Маршрут | Успех |
| ------ | ------------------------------ | ------------------------------------ |
| GET | /api/Session/all | 200, SessionDto\[] |
| DELETE | /api/Session/close/{sessionId} | 204, без тела |
| DELETE | /api/Session/close | 204, закрыть sid текущего токена |
| DELETE | /api/Session/close/all | 204, закрыть все сессии пользователя |
### Endpoints
```json
[{
"id":"11111111-1111-1111-1111-111111111111",
"deviceInfo":"Android test device",
"createdAt":"2026-10-03T00:00:00Z",
"expiresAt":"2026-10-10T00:00:00Z",
"isRevoked":false
}]
```
#### <mark style="color:$info;">GetAllSessions</mark>
Список фильтруется по UserId и !IsRevoked, но не по ExpiresAt; истекшие сессии могут присутствовать. CreatedAt меняется при refresh.
* **Description**: Retrieves all active sessions for the authenticated user.
* **Route**: `[GET] api/session/all`
* **HTTP Method**: `GET`
* **Request**: None
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Returns a list of user sessions.
Закрытие чужой, неизвестной или уже отозванной сессии возвращает 404 с errorCode UserSession.NotFoundOrUnauthorized. Guid.Empty возвращает 400. CloseAll без активных сессий тоже успешен.
```json
[
{
"id": "Guid",
"deviceInfo": "string",
"createdAt": "DateTime",
"expiresAt": "DateTime",
"isRevoked": "boolean"
}
]
```
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
Отзыв деактивирует связанные push-токены. Успех Unit преобразуется в 204, а не в 200.
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
## Ограничение logout
```json
"Unexpected Error! Please try again later."
```
IsRevoked проверяется при refresh; bearer middleware не сверяет текущий sid с БД. Access token может работать до окончания срока, а существующее соединение SignalR не закрывается этим контроллером.
#### <mark style="color:$info;">CloseSession</mark>
***
* **Description**: Closes a specific session for the authenticated user.
* **Route**: `[DELETE] api/session/close/{sessionId}`
* **HTTP Method**: `DELETE`
* **Request**:
* **Path Parameter**: `sessionId` (Guid, required): ID of the session to close.
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Indicates session was successfully closed.
* No body.
* <mark style="color:$danger;">**400 Bad Request**</mark>: If `sessionId` is invalid or operation fails.
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
```json
"string"
```
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
```json
"string"
```
* <mark style="color:$danger;">**404 Not Found**</mark>: If session is not found.
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
```json
"Unexpected Error! Please try again later."
```
#### <mark style="color:$info;">CloseSession</mark>
* **Description**: Closes a current session for the authenticated user.
* **Route**: `[DELETE] api/session/close/`
* **HTTP Method**: `DELETE`
* **Request**:
* No body.
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Indicates session was successfully closed.
* No body.
* <mark style="color:$danger;">**400 Bad Request**</mark>: If `sessionId` is invalid or operation fails.
```json
"string"
```
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
```json
"string"
```
* <mark style="color:$danger;">**404 Not Found**</mark>: If session is not found.
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
```json
"Unexpected Error! Please try again later."
```
#### <mark style="color:$info;">CloseAllSessions</mark>
* **Description**: Closes all active sessions for the authenticated user.
* **Route**: `[DELETE] api/session/close/all`
* **HTTP Method**: `DELETE`
* **Request**: None
* **Responses**:
* <mark style="color:$success;">**200 OK**</mark>: Indicates all sessions were successfully closed.
* No body.
* <mark style="color:$danger;">**403 Forbidden**</mark>: If user lacks authorization.
```json
"string"
```
* <mark style="color:$warning;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
```json
"Unexpected Error! Please try again later."
```
### Data Models
#### SessionDto
* **Description**: Data transfer object for session information.
* **Structure**:
```json
{
"id": "Guid",
"deviceInfo": "string",
"createdAt": "DateTime",
"expiresAt": "DateTime",
"isRevoked": "boolean"
}
```
### Error Handling
* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid.
* **Invalid Operations**: Returns `400 Bad Request` for `InvalidOperationException`.
* **Unauthorized Access**: Returns `403 Forbidden` for `UnauthorizedAccessException`.
* **Resource Not Found**: Returns `404 Not Found` for `NotFoundException`.
* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`.
### Logging
* Logs warnings for `UnauthorizedAccessException` and `NotFoundException`.
* Logs errors for `InvalidOperationException` and unexpected exceptions.
Источник: [Govor.API/Controllers/SessionController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/SessionController.cs).
-235
View File
@@ -1,235 +0,0 @@
---
description: >-
Description: SignalR hub for managing real-time friend request operations,
including sending, accepting, and rejecting friend requests.
icon: wifi
---
# FriendsHub
**Route** `hubs/friends`
**Authorize**: Requires authentication (user must be logged in)
### <mark style="color:$info;">Hub Methods</mark>
#### <mark style="color:$primary;">OnConnectedAsync</mark>
**Description**: Automatically invoked when a client establishes a connection to the hub. Adds the user to their personal group for receiving friend request notifications.
**Behavior**:
* Retrieves the user's ID from the connection context.
* If the user ID is invalid (`Guid.Empty`), logs a warning and aborts the connection.
* Adds the user to a group named after their user ID (e.g., `userId.ToString()`).
* Logs the connection event with the user ID and connection ID.
***
#### <mark style="color:$primary;">OnDisconnectedAsync</mark>
**Description**: Automatically invoked when a client disconnects from the hub. Removes the user from their personal group.
**Behavior**:
* Retrieves the user's ID from the connection context, suppressing exceptions if the ID is unavailable (e.g., due to an early abort).
* If the user ID is valid, removes the user from their personal group.
* Logs the disconnection event with the user ID and connection ID.
* If an exception occurs, logs it as a warning along with the connection ID.
* If no exception occurs but the user ID is invalid, logs the disconnection with the connection ID.
***
#### <mark style="color:$info;">SendRequest</mark>
**Description**: Sends a friend request to a specified user and notifies the recipient in real-time.
**Request**:
* **Method Name**: `SendRequest`
* **Parameters**:
* `targetUserId`: (`Guid`) The ID of the user to whom the friend request is sent.
**Responses**:
* <mark style="color:$success;">**Success (201 Created)**</mark>: Friend request sent successfully.
```json
{
"status": 201,
"result": null,
"errorMessage": null
}
```
* <mark style="color:$danger;">**400 Bad Request**</mark>: If the operation is invalid (e.g., sending a request to oneself).
```json
{
"status": 400,
"result": null,
"errorMessage": "<error_message>"
}
```
* <mark style="color:$danger;">**401 Unauthorized**</mark>: If the user is not authorized.
```json
{
"status": 401,
"result": null,
"errorMessage": "<error_message>"
}
```
* <mark style="color:$danger;">**409 Conflict**</mark>: If a friend request was already sent.
```json
{
"status": 409,
"result": null,
"errorMessage": "<error_message>"
}
```
* <mark style="color:$warning;">**500 Server Error**</mark>: Indicates an unexpected error.
```json
{
"status": 500,
"result": null,
"errorMessage": "Unexpected error! Please try later!"
}
```
**Client-Side Events**:
* **FriendRequestReceived**: Triggered on the recipient's client to notify them of a new friend request.
* Payload: `userId` (`Guid`) - The ID of the user who sent the request.
***
#### <mark style="color:purple;">AcceptRequest</mark>
**Description**: Accepts a friend request and notifies the user in real-time.
**Request**:
* **Method Name**: `AcceptRequest`
* **Parameters**:
* `friendshipId`: (`Guid`) The ID of the friend request to accept.
**Responses**:
* <mark style="color:$success;">**Success (200 OK)**</mark>: Friend request accepted successfully.
```json
{
"status": 200,
"result": null,
"errorMessage": null
}
```
* <mark style="color:$danger;">**400 Bad Request**</mark>: If the operation is invalid (e.g., invalid friendship ID).
```json
{
"status": 400,
"result": null,
"errorMessage": "<error_message>"
}
```
* <mark style="color:$danger;">**401 Unauthorized**</mark>: If the user is not authorized to accept the request.
```json
{
"status": 401,
"result": null,
"errorMessage": "<error_message>"
}
```
* <mark style="color:$warning;">**500 Server Error**</mark>: Indicates an unexpected error.
```json
{
"status": 500,
"result": null,
"errorMessage": "Unexpected error! Please try later!"
}
```
**Client-Side Events**:
* **FriendRequestAccepted**: Triggered on the user's client to confirm the friend request was accepted.
* Payload: `friendshipId` (`Guid`) - The ID of the accepted friend request.
***
#### <mark style="color:purple;">RejectRequest</mark>
**Description**: Rejects a friend request and notifies the user in real-time.
**Request**:
* **Method Name**: `RejectRequest`
* **Parameters**:
* `friendshipId`: (`Guid`) The ID of the friend request to reject.
**Responses**:
* <mark style="color:$success;">**Success (200 OK)**</mark>: Friend request rejected successfully.
```json
{
"status": 200,
"result": null,
"errorMessage": null
}
```
* <mark style="color:$danger;">**400 Bad Request**</mark>: If the operation is invalid (e.g., invalid friendship ID).
```json
{
"status": 400,
"result": null,
"errorMessage": "<error_message>"
}
```
* <mark style="color:$danger;">**401 Unauthorized**</mark>: If the user is not authorized to reject the request.
```json
{
"status": 401,
"result": null,
"errorMessage": "<error_message>"
}
```
* <mark style="color:$warning;">**500 Server Error**</mark>: Indicates an unexpected error.
```json
{
"status": 500,
"result": null,
"errorMessage": "Unexpected error! Please try later!"
}
```
**Client-Side Events**:
* **FriendRequestRejected**: Triggered on the user's client to confirm the friend request was rejected.
* Payload: `friendshipId` (`Guid`) - The ID of the rejected friend request.
***
### <mark style="color:$info;">Error Handling</mark>
* **Invalid User ID**: If the user ID is `Guid.Empty` during connection, the connection is aborted with a logged warning.
* **Invalid Operations**: Operations like sending a request to oneself or accepting/rejecting an invalid request return a `BadRequest` result.
* **Unauthorized Access**: Unauthorized actions return an `Unauthorized` result with a logged warning.
* **Conflicts**: Attempting to send a duplicate friend request returns a `Conflict` result.
* **Unexpected Errors**: General exceptions are caught, logged, and returned as a `ServerError` result.
***
### Logging
* Logs connection and disconnection events with user ID and connection ID.
* Logs friend request operations (send, accept, reject) with success or failure details for monitoring and debugging.
***
-384
View File
@@ -1,384 +0,0 @@
---
description: >-
Description: This sub-documentation provides example Java client code for
interacting with the FriendsHub SignalR hub using the microsoft/signalr
library. It covers connecting to the hub, handling con
icon: java
---
# FriendsHub Client (Java)
**Prerequisites**:
* Include the SignalR Java client library in your project. For Gradle, add the following dependency:
```gradle
implementation("com.microsoft.signalr:signalr:9.0.7")
```
* Ensure the client has a valid authentication token (JWT) for connecting to the hub, as it requires authentication.
**Hub Route**: `hubs/friends`\
**Authorize**: Requires a valid JWT token with a `userId` claim.
### <mark style="color:purple;">Setup and Connection</mark>
#### Connecting to the Hub
This example demonstrates how to establish a connection to the `FriendsHub` with authentication and handle connection events.
```java
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Single;
public class FriendsHubClient {
private final HubConnection hubConnection;
private final String accessToken; // JWT token with userId claim
public FriendsHubClient(String hubUrl, String accessToken) {
this.accessToken = accessToken;
this.hubConnection = HubConnectionBuilder.create(hubUrl)
.withAccessTokenProvider(Single.just(accessToken))
.build();
// Handle connection established
hubConnection.onConnected(() -> {
System.out.println("Connected to FriendsHub with connection ID: " + hubConnection.getConnectionId());
});
// Handle connection closed
hubConnection.onClosed((exception) -> {
if (exception != null) {
System.err.println("Connection closed with error: " + exception.getMessage());
} else {
System.out.println("Connection closed normally");
}
});
}
public Completable startConnection() {
return hubConnection.start();
}
public Completable stopConnection() {
return hubConnection.stop();
}
}
```
**Usage**:
```java
String hubUrl = "https://your-api-url/hubs/friends";
String jwtToken = "your-jwt-token-here";
FriendsHubClient client = new FriendsHubClient(hubUrl, jwtToken);
client.startConnection()
.blockingAwait(); // Wait for connection to establish
```
**Notes**:
* Replace `your-api-url` with the actual server URL.
* The `accessToken` must include a valid JWT with the `userId` claim to avoid connection abortion.
* Use `stopConnection()` to gracefully disconnect when done.
### <mark style="color:purple;">Subscribing to Hub Events</mark>
The `FriendsHub` sends three client-side events: `FriendRequestReceived`, `FriendRequestAccepted`, and `FriendRequestRejected`. Below is an example of subscribing to these events.
```java
public class FriendsHubClient {
// ... (constructor and connection methods as above)
public void subscribeToEvents() {
// Handle FriendRequestReceived event
hubConnection.on("FriendRequestReceived", (userId) -> {
System.out.println("Received friend request from user ID: " + userId);
// Handle the friend request (e.g., update UI or notify user)
}, String.class);
// Handle FriendRequestAccepted event
hubConnection.on("FriendRequestAccepted", (friendshipId) -> {
System.out.println("Friend request accepted, friendship ID: " + friendshipId);
// Update UI or local state to reflect new friendship
}, String.class);
// Handle FriendRequestRejected event
hubConnection.on("FriendRequestRejected", (friendshipId) -> {
System.out.println("Friend request rejected, friendship ID: " + friendshipId);
// Update UI or notify user of rejection
}, String.class);
}
}
```
**Usage**:
```java
FriendsHubClient client = new FriendsHubClient(hubUrl, jwtToken);
client.subscribeToEvents();
client.startConnection().blockingAwait();
```
**Notes**:
* The `userId` and `friendshipId` parameters are received as strings (representing `Guid` values) due to JSON serialization. Parse them to `UUID` if needed:
```java
UUID uuid = UUID.fromString(userId);
```
* Call `subscribeToEvents()` before starting the connection to ensure event handlers are registered.
### <mark style="color:purple;">Invoking Hub Methods</mark>
#### SendRequest
Sends a friend request to another user.
```java
public Completable sendFriendRequest(String targetUserId) {
return hubConnection.invoke(HubResult.class, "SendRequest", targetUserId)
.doOnSuccess(result -> {
switch (result.getStatus()) {
case 201: // Created
System.out.println("Friend request sent successfully");
break;
case 400: // BadRequest
System.err.println("Bad request: " + result.getErrorMessage());
break;
case 401: // Unauthorized
System.err.println("Unauthorized: " + result.getErrorMessage());
break;
case 409: // Conflict
System.err.println("Conflict: " + result.getErrorMessage());
break;
case 500: // ServerError
System.err.println("Server error: " + result.getErrorMessage());
break;
default:
System.err.println("Unexpected status: " + result.getStatus());
}
})
.ignoreElement();
}
```
**Usage**:
```java
client.sendFriendRequest("target-user-guid-here")
.blockingAwait();
```
**Notes**:
* The `targetUserId` should be a valid `Guid` string (e.g., "550e8400-e29b-41d4-a716-446655440000").
* The response is a `HubResult<object>` with a status code and optional error message.
#### AcceptRequest
Accepts a friend request by its friendship ID.
```java
public Completable acceptFriendRequest(String friendshipId) {
return hubConnection.invoke(HubResult.class, "AcceptRequest", friendshipId)
.doOnSuccess(result -> {
switch (result.getStatus()) {
case 200: // OK
System.out.println("Friend request accepted successfully");
break;
case 400: // BadRequest
System.err.println("Bad request: " + result.getErrorMessage());
break;
case 401: // Unauthorized
System.err.println("Unauthorized: " + result.getErrorMessage());
break;
case 500: // ServerError
System.err.println("Server error: " + result.getErrorMessage());
break;
default:
System.err.println("Unexpected status: " + result.getStatus());
}
})
.ignoreElement();
}
```
**Usage**:
```java
client.acceptFriendRequest("friendship-guid-here")
.blockingAwait();
```
#### RejectRequest
Rejects a friend request by its friendship ID.
```java
public Completable rejectFriendRequest(String friendshipId) {
return hubConnection.invoke(HubResult.class, "RejectRequest", friendshipId)
.doOnSuccess(result -> {
switch (result.getStatus()) {
case 200: // OK
System.out.println("Friend request rejected successfully");
break;
case 400: // BadRequest
System.err.println("Bad request: " + result.getErrorMessage());
break;
case 401: // Unauthorized
System.err.println("Unauthorized: " + result.getErrorMessage());
break;
case 500: // ServerError
System.err.println("Server error: " + result.getErrorMessage());
break;
default:
System.err.println("Unexpected status: " + result.getStatus());
}
})
.ignoreElement();
}
```
**Usage**:
```java
client.rejectFriendRequest("friendship-guid-here")
.blockingAwait();
```
### <mark style="color:purple;">Data Model</mark>
The client expects a `HubResult` response from hub methods, which is serialized as JSON:
```json
{
"status": "number", // Corresponds to HubResultStatus (e.g., 200, 400, 401, etc.)
"result": null, // Always null for FriendsHub methods
"errorMessage": "string" // Null for success, error message for failures
}
```
### <mark style="color:purple;">Error Handling</mark>
* **Connection Errors**: Handle connection failures in `onClosed` or by catching exceptions from `startConnection()`.
* **Invalid User ID**: If the JWT lacks a valid `userId` claim, the hub aborts the connection, and `onClosed` is triggered with an error.
* **Hub Method Errors**: Check the `status` and `errorMessage` fields in the `HubResult` response to handle specific errors (e.g., `BadRequest`, `Unauthorized`, `Conflict`).
### <mark style="color:purple;">Example Full Client</mark>
Below is a complete example combining connection, event subscription, and method invocation.
```java
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Single;
public class FriendsHubClient {
private final HubConnection hubConnection;
private final String accessToken;
public FriendsHubClient(String hubUrl, String accessToken) {
this.accessToken = accessToken;
this.hubConnection = HubConnectionBuilder.create(hubUrl)
.withAccessTokenProvider(Single.just(accessToken))
.build();
// Connection events
hubConnection.onConnected(() -> {
System.out.println("Connected to FriendsHub with connection ID: " + hubConnection.getConnectionId());
});
hubConnection.onClosed((exception) -> {
System.err.println(exception != null ? "Connection closed with error: " + exception.getMessage() : "Connection closed normally");
});
// Subscribe to hub events
hubConnection.on("FriendRequestReceived", (userId) -> {
System.out.println("Received friend request from user ID: " + userId);
}, String.class);
hubConnection.on("FriendRequestAccepted", (friendshipId) -> {
System.out.println("Friend request accepted, friendship ID: " + friendshipId);
}, String.class);
hubConnection.on("FriendRequestRejected", (friendshipId) -> {
System.out.println("Friend request rejected, friendship ID: " + friendshipId);
}, String.class);
}
public Completable startConnection() {
return hubConnection.start();
}
public Completable stopConnection() {
return hubConnection.stop();
}
public Completable sendFriendRequest(String targetUserId) {
return hubConnection.invoke(HubResult.class, "SendRequest", targetUserId)
.doOnSuccess(this::handleHubResult)
.ignoreElement();
}
public Completable acceptFriendRequest(String friendshipId) {
return hubConnection.invoke(HubResult.class, "AcceptRequest", friendshipId)
.doOnSuccess(this::handleHubResult)
.ignoreElement();
}
public Completable rejectFriendRequest(String friendshipId) {
return hubConnection.invoke(HubResult.class, "RejectRequest", friendshipId)
.doOnSuccess(this::handleHubResult)
.ignoreElement();
}
private void handleHubResult(HubResult result) {
switch (result.getStatus()) {
case 200:
System.out.println("Operation successful");
break;
case 201:
System.out.println("Resource created successfully");
break;
case 400:
System.err.println("Bad request: " + result.getErrorMessage());
break;
case 401:
System.err.println("Unauthorized: " + result.getErrorMessage());
break;
case 409:
System.err.println("Conflict: " + result.getErrorMessage());
break;
case 500:
System.err.println("Server error: " + result.getErrorMessage());
break;
default:
System.err.println("Unexpected status: " + result.getStatus());
}
}
public static void main(String[] args) {
String hubUrl = "https://your-api-url/hubs/friends";
String jwtToken = "your-jwt-token-here";
FriendsHubClient client = new FriendsHubClient(hubUrl, jwtToken);
// Start connection and send a friend request
client.startConnection()
.andThen(client.sendFriendRequest("550e8400-e29b-41d4-a716-446655440000"))
.blockingAwait();
// Simulate accepting a friend request
client.acceptFriendRequest("friendship-guid-here")
.blockingAwait();
// Stop connection
client.stopConnection().blockingAwait();
}
}
```
**Notes**:
* Replace `your-api-url` and `your-jwt-token-here` with actual values.
* The `main` method demonstrates a complete workflow, but in a real application, you would integrate this with your UI or event loop.
* Use `UUID.fromString()` to convert string GUIDs to `UUID` objects if needed for internal logic.
+56
View File
@@ -0,0 +1,56 @@
# Запуск и конфигурация
## Требования
.NET SDK 10 с корректной feature band, PostgreSQL, доступ к NuGet, файл `libs/SmartRes.dll`, каталог `Govor.API/configs` и Firebase service account в `Govor.API/secrets/firebase-adminsdk.json`.
В `global.json` записана некорректная версия SDK `10.0.0`; замените её в отдельном исправлении на установленную версию, например `10.0.400`. Во время диагностики SDK 10.0.400 всё же собрал отдельный проект API.
## Команды из корня репозитория
```powershell
dotnet restore Govor.API/Govor.API.csproj
dotnet build Govor.API/Govor.API.csproj --no-restore
dotnet ef database update --project Govor.Domain --startup-project Govor.API
dotnet run --project Govor.API/Govor.API.csproj
```
Команда миграции требует установленного инструмента dotnet-ef; она приведена как инструкция и не выполнялась на пользовательской БД. Перед обновлением существующей БД проверьте миграции и резервную копию.
## Конфигурация
| Ключ / ресурс | Назначение |
| ----------------------------------------- | ----------------------------------------------------------- |
| ConnectionStrings:GovorDbContext | PostgreSQL connection string |
| JwtAccessOption:SecretKey | Ключ подписи JWT |
| JwtAccessOption:Minutes | Срок access token в минутах |
| JwtRefreshOption:RefreshTokenLifetimeDays | Срок refresh-сессии |
| MessageEditingOptions:Enabled | Применять ли срок редактирования |
| MessageEditingOptions:MaxEditTimeMinutes | Срок редактирования; значение класса по умолчанию 15 |
| configs/ban\_usernames.json | UsernameModeration: BlockedExact, BlockedContains, Reserved |
| secrets/firebase-adminsdk.json | Обязательные учётные данные Firebase при старте |
| uploads/ | Файлы относительно ContentRootPath |
Не переносите реальные ключи, пароли и service account в документацию или Git. Не рассчитывайте только на переменные окружения: Program.cs повторно добавляет appsettings.json после стандартных провайдеров, поэтому JSON может перекрыть их значения. Это нужно исправить.
Firebase создаётся безусловно. Наличие NullPushProvider не даёт выключить Firebase конфигурацией в текущем DI.
## Развёртывание и проверка
Dockerfile устарел: использует .NET 8 и ссылается на удалённые Govor.Core/Govor.Data. Solution также ссылается на внешний проект SmartRes. До исправления используйте сборку конкретного API-проекта.
HTTPS redirection отключён; TLS и forwarded headers требуют отдельной настройки. SessionKeysController содержит RequireHttps, поэтому HTTP для его методов не подходит.
`GET /server/ping` — маршрут проверки доступности, но возвращает MVC OkResult из minimal API (предупреждение ASP0004); не считайте его полноценным health check БД и Firebase.
Swagger включён во всех окружениях. UseSwagger обслуживает документ через middleware; поздний MapSwagger.RequireAuthorization не является надёжным подтверждением защиты всех Swagger-маршрутов.
## Что проверено
Restore API-зависимостей и сборка API завершились. Первая сборка: 90 предупреждений, 0 ошибок. Restore Govor.API.Tests завершился NU1201: net8.0 не может ссылаться на net10.0. Сервер с БД и Firebase не запускался; контейнер и миграции не проверялись.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
Источник: [Govor.API/Program.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Program.cs).
+50 -143
View File
@@ -2,161 +2,68 @@
icon: wifi
---
# ChatHub
# ChatsHub — сообщения
**Route**: `hubs/chats`\
**Authorize**: Requires authentication (user must be logged in)
Подключение: /hubs/chats, Bearer access token. Серверный класс называется ChatsHub. Команды возвращают HubResult, события приходят независимо от ответа команды.
***
## Команды
### Hub Methods
| Имя | Запрос | Успешный Result |
| ------ | ---------------------------------- | ---------------------- |
| Send | MessageRequest | UserMessageResponse |
| Read | { messageId } | MessageReadResponse |
| Edit | { messageId, newEncryptedContent } | MessageEditResponse |
| Remove | { messageId, requestType } | MessageRemovedResponse |
#### <mark style="color:$primary;">OnConnectedAsync</mark>
**Description**: Automatically invoked when a client establishes a connection to the hub. Adds the user to their personal group for private messages and notifications.
**Behavior**:
* Retrieves the user's ID from the connection context.
* If the user ID is invalid (`Guid.Empty`), logs a warning and aborts the connection.
* Adds the user to a group named after their user ID (e.g., `userId.ToString()`).
* Logs the connection event with the user ID and connection ID.
**Notes**:
* Future enhancements may include adding the user to their chat groups (currently a TODO in the code).
***
#### <mark style="color:$primary;">OnDisconnectedAsync</mark>
**Description**: Automatically invoked when a client disconnects from the hub. Removes the user from their personal group.
**Behavior**:
* Retrieves the user's ID from the connection context, suppressing exceptions if the ID is unavailable (e.g., due to an early abort).
* If the user ID is valid, removes the user from their personal group.
* Logs the disconnection event with the user ID and connection ID.
* If an exception occurs, logs it as a warning along with the connection ID.
* If no exception occurs but the user ID is invalid, logs the disconnection with the connection ID.
**Notes**:
* Future enhancements may include removing the user from their chat groups (currently a TODO in the code).
***
#### <mark style="color:$info;">Send</mark>
**Description**: Allows a client to send a message to a recipient, which can be either a user or a group.
**Request**:
* **Method Name**: `Send`
* **Parameters**:
* `request`: An object of type `MessageRequest` with the following structure:
```json
{
"encryptedContent": "string",
"replyToMessageId": "Guid",
"recipientId": "Guid",
"recipientType": "string", // "User" or "Group"
"mediaAttachments": [
{
"mediaId": "Guid",
"encryptedKey": "string",
"type": "string",
"mimeType": "string"
}
]
}
```
**Responses**:
* <mark style="color:$success;">**Success**</mark>:
* Sends the message to the recipient (user or group) via the `ReceiveMessage` event.
* Notifies the sender with a confirmation via the `MessageSent` event.
* Logs the successful message send with the message ID, sender ID, recipient ID, and recipient type.
* <mark style="color:$danger;">**Error**</mark>:
* If the message is empty (no `encryptedContent` and no `mediaAttachments`), logs a warning and throws an `ArgumentException`.
* If the message fails to send (e.g., due to an internal error), logs the error and throws a `HubException`.
**Client-Side Events**:
* <mark style="color:$primary;">**ReceiveMessage**</mark>: Triggered on the recipient's client(s) to deliver the message.
* Payload: `UserMessageResponse` object.
* <mark style="color:$primary;">**MessageSent**</mark>: Triggered on the sender's client to confirm the message was sent.
* Payload: `UserMessageResponse` object.
**Notes**:
* The message must contain either `encryptedContent` or `mediaAttachments`; otherwise, it is invalid.
* The recipient is determined by `recipientType`:
* `"User"`: Sends to the recipient’s personal group (e.g., `recipientId.ToString()`).
* `"Group"`: Sends to all members of the group (e.g., `group_{recipientId}`).
***
### Data Models
#### MessageRequest
MessageRequest:
```json
{
"encryptedContent": "string",
"replyToMessageId": "Guid",
"recipientId": "Guid",
"recipientType": "string", // "User" or "Group"
"mediaAttachments": [
{
"mediaId": "Guid",
"encryptedKey": "string",
"type": "string",
"mimeType": "string"
}
]
"recipientId":"11111111-1111-1111-1111-111111111111",
"recipientType":0,
"encryptedContent":"<содержимое>",
"replyToMessageId":null,
"mediaAttachments":[]
}
```
#### UserMessageResponse
RecipientType.User=0 означает **личный чат**, recipientId — PrivateChat.Id. Group=1 означает ChatGroup.Id. Вложение: { mediaId, encryptedKey }.
```json
{
"messageId": "Guid",
"senderId": "Guid",
"recipientId": "Guid",
"recipientType": "string",
"encryptedContent": "string",
"sentAt": "DateTime",
"isEdited": "bool",
"mediaAttachments": [
{
"mediaId": "Guid",
"encryptedKey": "string",
"type": "string",
"mimeType": "string"
}
],
"replyToMessageId": "Guid"
}
```
Содержимое или вложение обязательно. Хаб ограничивает текст 50 000 символами, хотя атрибут DTO указывает 100 000. SignalR не выполняет MVC DataAnnotations автоматически; транспортный лимит входящего сообщения отдельно ограничивает размер JSON. При null encryptedContent с вложением возможна ошибка на Length.
## События
| Имя события (точно) | Payload |
| ------------------- | ---------------------- |
| ReceiveMessage | UserMessageResponse |
| MessageEdited | MessageEditResponse |
| MessageRemoved | MessageRemovedResponse |
| MessageReaded | MessageReadResponse |
Опечатка MessageReaded является текущим именем wire-контракта. Константа MessageSent есть, но отправка этого события закомментирована; не ожидайте его.
UserMessageResponse: messageId, senderId, recipientId, recipientType, encryptedContent, replyToMessageId, sentAt, isEdited, mediaAttachments. mediaAttachments — список MediaFile, не HTTP MediaAttachmentResponse; навигация MediaFile после Send явно не загружается и элементы могут быть null.
MessageEditResponse: messageId, editorId, recipientId, recipientType, newEncryptedContent, editedAt. MessageReadResponse: viewId, messageId, readerId, recipientId, whenWas, recipientType. MessageRemovedResponse: messageId, senderId, recipientId, requestType, recipientType.
## Семантика и ошибки
Edit проверяет автора и срок из MessageEditingOptions (по умолчанию 15 минут при Enabled=true), но не применяет лимит текста Send. Многие сервисные ошибки хаб превращает в InvalidOperationException и возвращает status=500, теряя исходный код.
RemoveMessageRequestType: HideForMe=0, ForceRemove=1. **HideForMe сейчас не реализован**: если автор вызывает Remove, сервис физически удаляет сообщение независимо от флага. Групповое удаление сравнивает DeleterId с ID группы вместо автора/прав администратора.
Read проверяет наличие у пользователя любого личного чата вместо участия в чате сообщения. Для групп прочтение не реализовано; хаб может упасть на First при отсутствии MessageView. Параллельные Read могут конфликтовать по уникальному индексу (MessageId, UserId).
Уведомления Edit/Remove/Read в личных чатах отправляются инициатору и группе с именем ID чата, хотя второй адресат должен быть участником. Поэтому собеседник может не получить событие.
Send для личного чата проверяет только его существование, не участие отправителя. Исправление доступа обязательно.
## Доставка
Успех сохранения и доставка события — разные этапы. После reconnect загрузите историю через HTTP, объединяйте ответ Send и ReceiveMessage по messageId. Без clientMessageId/idempotency-key повтор Send после сбоя может создать дубль.
***
### Error Handling
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
* **Invalid User ID**: If the user ID is `Guid.Empty` during connection, the connection is aborted with a logged warning.
* **Empty Message**: If a message lacks both content and attachments, an `ArgumentException` is thrown with a logged warning.
* **Message Send Failure**: If sending fails (e.g., due to a service error), a `HubException` is thrown with the error logged.
***
### Logging
* Logs connection events with user ID and connection ID.
* Logs disconnection events, including exceptions if present.
* Logs message send attempts, successes, and failures for monitoring and debugging.
***
Источник: [Govor.API/Hubs/ChatsHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/ChatsHub.cs).
+51
View File
@@ -0,0 +1,51 @@
---
description: >-
Description: SignalR hub for managing real-time friend request operations,
including sending, accepting, and rejecting friend requests.
icon: wifi
---
# FriendsHub — заявки
Подключение: /hubs/friends с access token, содержащим userId. Атрибут Authorize у класса отсутствует; HubUserAccessor читает claim и бросает исключение при его отсутствии. Это не следует считать полноценной endpoint-политикой авторизации: её нужно добавить явно.
## Команды
| Команда | Аргумент | Успех |
| ------------- | ----------------- | ----------------------- |
| SendRequest | Guid targetUserId | status 201, result null |
| AcceptRequest | Guid friendshipId | status 200, result null |
| RejectRequest | Guid friendshipId | status 200, result null |
SendRequest запрещает заявку себе и повтор при Pending/Accepted/Blocked. После Rejected запись переиспользуется. Accept разрешён только адресату и только Pending; после сохранения дружбы создаётся личный чат. Reject разрешён адресату для Pending/Rejected.
## Все события
| Событие | Кому |
| ------------------------- | --------------------------- |
| FriendRequestReceived | Адресату новой заявки |
| YourFriendRequestReceived | Отправителю |
| FriendRequestAccepted | Принимающему адресату |
| YourFriendRequestAccepted | Отправителю исходной заявки |
| FriendRequestRejected | Отклоняющему адресату |
| YourFriendRequestRejected | Отправителю исходной заявки |
Каждое событие передаёт **FriendshipDto**, не строку Guid:
```json
{"id":"11111111-1111-1111-1111-111111111111","requesterId":"22222222-2222-2222-2222-222222222222","addresseeId":"33333333-3333-3333-3333-333333333333","status":0}
```
Status: Pending=0, Accepted=1, Rejected=2, Blocked=3.
## Ошибки и восстановление
Сервисные Failure в SendRequest преобразуются в status 500; Accept/Reject — в 400. Поэтому не обещайте 409/403/404 для всех соответствующих бизнес-ошибок.
Дружба сохраняется до создания чата/рассылки; сбой может оставить частично завершённый сценарий. На reconnect перечитывайте /api/friends, /requests, /responses и /api/user/private-chats. Клиенту нужны дедупликация и обновление cache по id.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
Источник: [Govor.API/Hubs/FriendsHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/FriendsHub.cs).
@@ -0,0 +1,67 @@
---
description: >-
Description: This sub-documentation provides example Java client code for
interacting with the FriendsHub SignalR hub using the microsoft/signalr
library. It covers connecting to the hub, handling con
icon: java
---
# Клиент SignalR на C# для MAUI
Эта страница заменяет устаревший Java-пример: он принимал FriendshipDto как String и не соответствовал серверу. Ниже минимальный пример подключения C#; это пример интеграции, а не проверенный end-to-end тест.
Используйте Microsoft.AspNetCore.SignalR.Client и Govor.Contracts либо эквивалентные DTO с теми же полями.
```csharp
using Govor.Contracts.DTOs;
using Govor.Contracts.Responses.SignalR;
using Microsoft.AspNetCore.SignalR.Client;
var connection = new HubConnectionBuilder()
.WithUrl($"{baseUrl.TrimEnd('/')}/hubs/friends", options =>
{
options.AccessTokenProvider = async () =>
await jwtProvider.GetAccessTokenAsync();
})
.WithAutomaticReconnect()
.Build();
using var received = connection.On<FriendshipDto>(
"FriendRequestReceived", dto =>
{
MainThread.BeginInvokeOnMainThread(() => ApplyFriendship(dto));
});
using var accepted = connection.On<FriendshipDto>(
"YourFriendRequestAccepted", dto =>
{
MainThread.BeginInvokeOnMainThread(() => ApplyFriendship(dto));
});
await connection.StartAsync();
var response = await connection.InvokeAsync<HubResult<object>>(
"SendRequest", targetUserId);
if (response.Status != HubResultStatus.Created)
ShowError(response.ErrorMessage);
```
baseUrl, jwtProvider, ApplyFriendship, ShowError и targetUserId предоставляет приложение. Зарегистрируйте остальные четыре события аналогично с FriendshipDto. AcceptRequest/RejectRequest получают friendshipId.
## Жизненный цикл MAUI
1. Подпишитесь на события до подключения.
2. Первоначальный StartAsync требует собственной обработки повторов; automatic reconnect относится к потерянному соединению.
3. После Reconnected перечитайте HTTP-списки, чтобы восстановить пропущенные события.
4. Изменяйте ObservableCollection на MainThread.
5. Отменяйте повторные попытки при logout и DisposeAsync; не запускайте бесконечный StartAsync из Closed после намеренного StopAsync.
6. AccessTokenProvider должен получать актуальный access token; refresh должен быть сериализован.
В текущем Govor.Mobile ChatHub фильтрует ReceiveMessage по непустому encryptedContent, поэтому сообщение только с вложением может игнорироваться. Closed пытается перезапуститься даже после намеренного DisconnectAsync. JwtProviderService очищает токены при любом неуспешном HTTP-refresh, включая временную ошибку сервера: это следует исправить отдельно.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
Источник: [Govor.API/Hubs/FriendsHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/FriendsHub.cs).
+16 -36
View File
@@ -3,51 +3,31 @@ description: SignalR hub for managing user online presence and notifications.
icon: wifi
---
# PresenceHub
# PresenceHub — online и offline
### Controller Description
Подключение: /hubs/presence. Требуется роль User/Admin.
* **Route**: `hubs/presence`
* **Authorize**: Requires authenticated user with roles "Admin" or "User" (`[Authorize(Roles = "Admin, User")]`).
Публичных команд у хаба нет. На подключении сервер добавляет connectionId в OnlineUserStore и группу userId. Первая связь пользователя вызывает событие UserOnline; отключение последней — UserOffline.
### Hub Methods
| Событие | Payload |
| ----------- | ----------------- |
| UserOnline | Guid пользователя |
| UserOffline | Guid пользователя |
#### <mark style="color:$info;">OnConnectedAsync</mark>
Получатели определяются IUserNotificationScopeService. Несколько соединений одного пользователя учитываются отдельно.
* **Description**: Invoked when a client connects, updates online status and notifies friends.
* **Behavior**:
* Retrieves user ID from context.
* Aborts connection if user ID is `Guid.Empty` or user does not exist.
* Adds user to online store and their personal group.
* Notifies friends of user going online via `UserOnline` event.
* **Client-Side Events**:
* **UserOnline**: Triggered for friends with payload `userId` (Guid).
* **Responses**: None (connection aborted on invalid user ID).
## Ограничения
#### <mark style="color:$info;">OnDisconnectedAsync</mark>
OnlineUserStore хранится в памяти одного процесса. Перезапуск теряет состояние; несколько серверов не согласованы. Online означает наличие соединения этого хаба, не доступность устройства для push.
* **Description**: Invoked when a client disconnects, updates offline status and notifies friends.
* **Behavior**:
* Retrieves user ID from context, suppressing exceptions.
* Removes user from personal group if ID is valid.
* Updates user's `WasOnline` timestamp.
* Sets user as offline in store.
* Notifies friends of user going offline via `UserOffline` event.
* **Client-Side Events**:
* **UserOffline**: Triggered for friends with payload `userId` (Guid).
* **Responses**: None.
PresenceHub не сохраняет lastSeen в БД при отключении. Для него есть отдельный HTTP ping; нужна единая политика обновления lastSeen.
### Data Models
Для первоначального экрана получайте доступные данные профиля/друзей; события только изменяют локальный cache. После reconnect перечитайте состояние. HTTP /api/online/status сейчас сломан из-за отсутствующих зависимостей.
* **N/A**: No specific data models defined for hub methods.
Обработчики должны быть зарегистрированы до StartAsync. Не используйте события присутствия как гарантированный журнал активности.
### Error Handling
***
* **Invalid User ID**: Aborts connection with logged warning if `Guid.Empty` or user not found.
* **Unexpected Errors**: Logged, but no specific response (handled by base method).
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
### Logging
* Logs warnings for invalid user ID on connection.
* Logs information for disconnections with user ID and connection ID.
* Logs errors for unexpected exceptions during disconnection.
Источник: [Govor.API/Hubs/PresenceHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/PresenceHub.cs).
+29
View File
@@ -0,0 +1,29 @@
# ProfileHub — изменения профиля
Подключение: /hubs/profiles; требуется Authorize.
| Метод | Аргумент | Успех |
| -------------- | ------------------ | ---------------------------------- |
| SetDescription | string description | HubResult, status=200, result=true |
| SetAvatar | Guid iconId | HubResult, status=200, result=true |
Описание не может быть null, переносы строк нормализуются, длина после нормализации ≤500; пустая строка допустима для очистки. Avatar требует непустой Guid и существующую запись медиа.
| Событие | Payload |
| ------------------ | ----------------------- |
| DescriptionUpdated | { userId, description } |
| AvatarUpdated | { userId, iconId } |
Получатели: пользователь, друзья и потенциальные друзья согласно IFriendshipService. Группы имеют префикс user:.
## Ограничения
Result от записи профиля не проверяется хабом, поэтому true не всегда подтверждает запись. Ошибка рассылки логируется, но не меняет успешный ответ.
SetAvatar не проверяет владельца файла. REST UploadAvatar не отправляет AvatarUpdated. Политика приватности не применяется к этой рассылке. После reconnect перечитайте профиль; события не гарантированно сохраняются.
***
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался.
Источник: [Govor.API/Hubs/ProfileHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/ProfileHub.cs).