mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-17 04:58:46 +00:00
Add reactions, reliable push & session checks
Implements message reactions and reaction packs (domain models, services, admin HTTP API, media processing via ImageSharp and limits) and adds reliable push delivery (ChatPushNotification, ChatPushDispatcher, ChatPushWorker, improved ChatNotificationService). Enhances message reading (ReadChat API, unread counts, concurrency-safe receipts) and tightens session security (access-token session validation in JWT, hub filter, SessionAuthorization). Improves SignalR behavior (session groups, reaction/channel events, hub/error mappings). Adds EF migrations, many controller fixes (Forbid handling, password API), tests (Govor.Server.Tests), docs, CI and tooling updates (Dockerfile → .NET 10, GH Actions matrix for sqlite/postgres, Govor.Server.slnx, global.json), and small infra changes (AutoMapper bump, NullPushProvider, storage/token handling).
This commit is contained in:
@@ -1,45 +1,26 @@
|
||||
# Аутентификация
|
||||
|
||||
## Последовательность
|
||||
|
||||
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.
|
||||
|
||||
Access token содержит `userId`, `sid` и роль User/Admin. Подпись HS256 проверяется, срок проверяется, issuer и audience не проверяются. Токены возвращаются JSON; сервер не устанавливает HttpOnly-cookie.
|
||||
|
||||
## Ограничения реализации
|
||||
|
||||
Отзыв сессии блокирует refresh, но Program.cs не проверяет IsRevoked при каждом использовании access token. Уже открытые SignalR-соединения явно не разрываются. Немедленный logout на всех устройствах не гарантирован.
|
||||
|
||||
Refresh JWT содержит userId и tokenType, но не случайный jti или sid. При выпуске одному пользователю в одну секунду возможны одинаковые токены, конфликтующие с уникальным RefreshTokenHash. Ротация не защищена атомарным compare-and-swap от параллельных запросов.
|
||||
|
||||
Не используйте refresh token как access token. В bearer-валидации нет явного требования tokenType=access; методы с одним Authorize требуют исправления разделения типов токенов.
|
||||
|
||||
На MAUI рекомендовано хранить refresh token в SecureStorage и выполнять обновление последовательно. Это рекомендация клиенту, а не свойство сервера.
|
||||
|
||||
---
|
||||
description: How to work with jwt tokens
|
||||
icon: user
|
||||
---
|
||||
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
|
||||
|
||||
# Authentication
|
||||
|
||||
### <mark style="color:$info;">Components</mark>
|
||||
|
||||
* **AuthController**: Handles registration and login.
|
||||
* **Route**: `/api/auth`
|
||||
* **RefreshController**: Manages token refresh.
|
||||
* **Route**: `/api/auth/token`
|
||||
|
||||
### <mark style="color:$info;">Authentication Process</mark>
|
||||
|
||||
* **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>
|
||||
|
||||
* **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.
|
||||
|
||||
### Security
|
||||
|
||||
* **Protocol**: Requires HTTPS.
|
||||
* **Storage**: Store refresh token in HTTP-only cookie with `Secure` and `SameSite=Strict`.
|
||||
Источник: [Govor.Application/Authentication/JWT/JwtService.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Application/Authentication/JWT/JwtService.cs).
|
||||
|
||||
@@ -1,141 +1,45 @@
|
||||
# Регистрация и вход
|
||||
|
||||
Оба метода доступны анонимно, Content-Type: application/json.
|
||||
|
||||
## POST /api/auth/register
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Артём",
|
||||
"password": "example-password",
|
||||
"inviteLink": "<код приглашения>",
|
||||
"deviceInfo": "Android test device"
|
||||
}
|
||||
```
|
||||
|
||||
Имя: 4–44 символа, только кириллица и цифры, первый символ — буква. Модерация запрещает зарезервированные имена, совпадения/подстроки из конфигурации и пять одинаковых символов подряд. Пароль: минимум 8 символов. DeviceInfo необязателен в запросе, но в БД ограничен 256 символами.
|
||||
|
||||
Код создаётся как Guid.ToString("N"): 32 символа без дефисов. Поиск кода — по строковому равенству. InviteLink — код, а не URL.
|
||||
|
||||
Проверяется существование приглашения, срок и число участников. Проверка IsActive отсутствует, лимит участников не защищён от конкурентной регистрации.
|
||||
|
||||
Успех 200:
|
||||
|
||||
```json
|
||||
{"refreshToken":"<token>","accessToken":"<token>"}
|
||||
```
|
||||
|
||||
Конфликт имени — 409; ошибки валидации — 400; отсутствующее приглашение — 404. Тело сервисных ошибок — ProblemDetails с errorCode. Регистрация и открытие сессии — отдельные сохранения: ошибка открытия сессии не откатывает созданного пользователя.
|
||||
|
||||
## POST /api/auth/login
|
||||
|
||||
```json
|
||||
{"name":"Артём","password":"example-password","deviceInfo":"Android test device"}
|
||||
```
|
||||
|
||||
Успех 200 с той же парой токенов. Пользователь не найден — 404 (UserNotRegisteredException); неверный пароль — 400 (InvalidOperationException). Это текущее поведение, а не рекомендуемая политика ошибок входа: разные ответы раскрывают существование аккаунта.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Rate limiting и блокировка перебора в Program.cs не настроены. Для публичного запуска нужны единая ошибка входа, ограничение частоты и защита административных приглашений.
|
||||
|
||||
---
|
||||
description: >-
|
||||
Controller for handling user authentication operations, including registration
|
||||
and login, with session management and invite-based registration.
|
||||
---
|
||||
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
|
||||
|
||||
# AuthController
|
||||
|
||||
### Controller Description
|
||||
|
||||
* **Route**: `api/auth`
|
||||
* **Authorize**: Allows anonymous access (`[AllowAnonymous]`).
|
||||
|
||||
### Endpoints
|
||||
|
||||
#### <mark style="color:$info;">Register</mark>
|
||||
|
||||
* **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:
|
||||
|
||||
```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.
|
||||
|
||||
```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.
|
||||
|
||||
```json
|
||||
"An unexpected error occurred. Please try again later."
|
||||
```
|
||||
|
||||
#### <mark style="color:$info;">Login</mark>
|
||||
|
||||
* **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:
|
||||
|
||||
```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
|
||||
{
|
||||
"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.
|
||||
|
||||
```json
|
||||
"An unexpected error occurred. Please try again later."
|
||||
```
|
||||
|
||||
### Data Models
|
||||
|
||||
#### RegistrationRequest
|
||||
|
||||
* **Description**: Model for registration request data.
|
||||
* **Structure**:
|
||||
|
||||
```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).
|
||||
|
||||
@@ -1,90 +1,36 @@
|
||||
# Обновление токенов
|
||||
|
||||
## POST /api/auth/token/refresh
|
||||
|
||||
Доступ анонимный. JSON:
|
||||
|
||||
```json
|
||||
{"refreshToken":"<последний сохранённый refresh token>"}
|
||||
```
|
||||
|
||||
Сервис хеширует переданную строку и ищет UserSession по RefreshTokenHash. Проверяет IsRevoked и ExpiresAt, выпускает новую пару, заменяет хеш и продлевает ExpiresAt. CreatedAt также перезаписывается, поэтому после refresh это не исходная дата открытия сессии.
|
||||
|
||||
Успех 200:
|
||||
|
||||
```json
|
||||
{"refreshToken":"<new token>","accessToken":"<new token>"}
|
||||
```
|
||||
|
||||
| Случай | Текущий ответ |
|
||||
| --- | --- |
|
||||
| Пустая строка | 400, errorCode Auth.EmptyToken |
|
||||
| Хеш не найден | 400, errorCode Auth.InvalidToken |
|
||||
| Истекшая/отозванная сессия | 400, errorCode Auth.InvalidToken |
|
||||
|
||||
Не документируйте неверный refresh как гарантированный 401: текущий Error.Failure преобразуется в 400.
|
||||
|
||||
## Клиент
|
||||
|
||||
Сохраните оба новых токена и сериализуйте refresh-запросы. Ошибка сети не должна автоматически удалять авторизацию пользователя. При подтверждённо недействительном refresh требуется повторный вход.
|
||||
|
||||
Ротация сейчас не имеет защиты от конкурентного использования и истории повторного применения. Детали — в разделе «Аутентификация».
|
||||
|
||||
---
|
||||
description: >-
|
||||
Controller for managing token refresh operations, allowing users to refresh
|
||||
their access tokens using a valid refresh token.
|
||||
---
|
||||
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
|
||||
|
||||
# RefreshController
|
||||
|
||||
### Controller Description
|
||||
|
||||
* **Route**: `api/auth/token`
|
||||
* **Authorize**: Allows anonymous access (`[AllowAnonymous]`).
|
||||
|
||||
### Endpoints
|
||||
|
||||
#### <mark style="color:$info;">Refresh</mark>
|
||||
|
||||
* **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:
|
||||
|
||||
```json
|
||||
{
|
||||
"refreshToken": "string"
|
||||
}
|
||||
```
|
||||
* **Responses**:
|
||||
* <mark style="color:$success;">**200 OK**</mark>: Returns a new access token and refresh token upon successful refresh.
|
||||
|
||||
```json
|
||||
{
|
||||
"accessToken": "string",
|
||||
"refreshToken": "string"
|
||||
}
|
||||
```
|
||||
* <mark style="color:$warning;">**400 Bad Request**</mark>: If model validation fails or the refresh token is empty.
|
||||
|
||||
```json
|
||||
"Refresh token cant be empty."
|
||||
```
|
||||
* <mark style="color:$warning;">**401 Unauthorized**</mark>: If the refresh token is invalid or authorization fails.
|
||||
|
||||
```json
|
||||
"Invalid refresh token"
|
||||
```
|
||||
* <mark style="color:$danger;">**500 Internal Server Error**</mark>: Indicates an unexpected error.
|
||||
|
||||
```json
|
||||
"An unexpected error occurred."
|
||||
```
|
||||
|
||||
### Data Models
|
||||
|
||||
#### RefreshTokenRequest
|
||||
|
||||
* **Description**: Model for refresh token request data.
|
||||
* **Structure**:
|
||||
|
||||
```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).
|
||||
|
||||
Reference in New Issue
Block a user