project

module
v0.0.0-...-a679988 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: MIT

README

FitPulse — Интеллектуальная платформа персонализированных тренировок

Build Status Kubernetes Security Go Version Node Version React Version

FitPulse — микросервисная платформа для персонализированных тренировок, ML-анализа биометрии и интеграции с носимыми устройствами.


Документация

Полная документация разделена по назначению:

Документ Описание
Техническое задание Полное ТЗ с требованиями, стадиями разработки и критериями приемки
Архитектура Инфраструктура, наблюдаемость, безопасность, релизный процесс
API Reference Полная спецификация REST/gRPC endpoints
ML Specification Архитектура классификатора, правила, ML модель, порог переключения
Security Policy Меры безопасности, compliance, аудит
Architecture Decision Records Обоснование архитектурных решений
UI Specification Спецификация мобильного веб-интерфейса
Accessibility (a11y) Доступность интерфейса (WCAG 2.1 AA)
Runbooks Операционные инструкции и response playbooks
Phase 2 Roadmap Бэклог инфраструктуры (план на Phase 2)
Bug Bounty Scope Условия программы Bug Bounty, scope, severity tiers
Contributing Guide Как внести вклад, стандарты кода, тестирование

Возможности платформы

Для пользователей:

  • Персонализированные тренировочные планы (template-based engine)
  • Интеграция с носимыми устройствами
  • ML-классификация состояния (7 классов)
  • Мониторинг биометрии в реальном времени

Для администраторов:

  • Регистрация через invite-коды
  • Управление пользователями
  • Мониторинг и аудит

Подробные таблицы: Возможности • API Endpoints • ML логика


Безопасность

FitPulse реализует комплексные меры безопасности:

  • JWT (ES256) + Refresh Token rotation
  • Argon2id хеширование паролей (memory 64 MB, iterations 3, parallelism 1)
  • Content Security Policy (nonce-based)
  • Rate limiting (token bucket)
  • Сетевая сегментация (Kubernetes Network Policies)
  • mTLS для внутренних коммуникаций (TLS 1.3, mutual auth через Kubernetes Secret)
  • Соответствие 152-ФЗ

Полный список мер: Security Policy • ADR-0006


API Endpoints

Публичные (без auth)
Метод Путь Описание
POST /api/v1/register Регистрация пользователя
POST /api/v1/register/invite Регистрация через invite-код
POST /api/v1/invite/validate Проверка invite-кода
POST /api/v1/login Вход
POST /api/v1/auth/confirm Подтверждение email
GET /api/v1/auth/verify-status Проверка статуса подтверждения email
GET /api/v1/auth/yandex Yandex ID логин
GET /api/v1/auth/yandex/callback Yandex ID callback
POST /api/v1/auth/2fa/verify Проверка TOTP после логина
POST /api/v1/auth/refresh Ротация refresh token
GET /.well-known/jwks.json JWKS endpoint для JWT публичного ключа
GET /health Health check
GET /confirm Страница подтверждения email
Защищённые (JWT required)
Метод Путь Описание
POST /api/v1/logout Выход с инвалидацией сессии
POST /api/v1/auth/critical-session Получить critical session token для защищённых действий
POST /api/v1/auth/2fa/setup Настройка TOTP
POST /api/v1/auth/2fa/confirm Подтверждение TOTP
GET /api/v1/auth/2fa/status Статус TOTP
POST /api/v1/auth/2fa/disable Отключение TOTP
GET /api/v1/profile Получить профиль
PUT /api/v1/profile Обновить профиль
DELETE /api/v1/profile Удалить профиль
POST /api/v1/biometrics Добавить биометрию
GET /api/v1/biometrics Получить биометрию
GET /api/v1/health/conditions Список заболеваний
POST /api/v1/health/conditions Добавить заболевание
DELETE /api/v1/health/conditions/{condition_id} Удалить заболевание
GET /api/v1/health/body-composition Состав тела
POST /api/v1/health/body-composition Добавить запись состава тела
GET /api/v1/health/menstrual-cycles Менструальные циклы
POST /api/v1/health/menstrual-cycles Добавить цикл
PUT /api/v1/health/menstrual-cycles/{cycle_id} Обновить цикл
DELETE /api/v1/health/menstrual-cycles/{cycle_id} Удалить цикл
GET /api/v1/training/plans Список планов
GET /api/v1/training/plans/{plan_id} Получить план по ID
POST /api/v1/training/generate Сгенерировать план
POST /api/v1/training/complete Завершить тренировку
GET /api/v1/training/progress Прогресс
POST /api/v1/chat FAQ/чат (rule-based)
POST /api/v1/devices/register Регистрация устройства
POST /api/v1/devices/{device_id}/ingest Приём данных с устройства
GET /api/v1/devices Список устройств
GET /api/v1/devices/providers Список провайдеров устройств
GET /metrics Prometheus метрики
Админ (JWT + role=admin)
Метод Путь Описание
GET /api/v1/admin/users Список пользователей
GET /api/v1/admin/invites Список invite-кодов
POST /api/v1/admin/invites Создать invite-код
POST /api/v1/admin/invites/{code}/revoke Отозвать invite-код

Полная спецификация: docs/API.md

Подробная инструкция: docs/DEPLOYMENT.md


Инфраструктура

Секреты

Секреты приложения создаются декларативно при деплое скриптом scripts/ci/lib/secrets.sh (обычные kubectl create secret) из GitHub Secrets репозитория: app-secrets (PostgreSQL, JWT, SMTP, Yandex ID, Valkey, RabbitMQ), captcha-secrets, rabbitmq-secret, minio-credentials.

Манифесты Vault и External Secrets Operator удалены как неиспользуемые: в кластере они не разворачивались, а секреты создавал secrets.sh. Если вернётесь к динамическим credentials с ротацией — это отдельная задача с восстановлением манифестов.

Текущий сервер
Параметр Значение
CPU 2 vCPU
RAM 4 ГБ
Storage 60 ГБ SSD
Виртуализация KVM
ОС Ubuntu 26.04 LTS
Локальная разработка

Для запуска всего стека локально используйте Docker Compose:

docker compose up --build

Сервисы:

Production домен: https://fitpulse.tail6f5dca.ts.net

Переменные окружения для локального запуска описаны в docker-compose.yml.

Frontend Stack
  • Framework: React 19.2+ with Vite 8
  • Routing: React Router v7
  • Styling: Plain CSS with CSS Variables
  • State: React Context API
  • Testing: Vitest + React Testing Library + Playwright
  • Linting/formatting: Biome

Подробнее: docs/ARCHITECTURE.md


Как внести вклад

См. CONTRIBUTING.md — ветвление, код-стайл, тесты, PR процесс.


Лицензия

MIT

Directories

Path Synopsis
api
cmd
admin-cli command
classifier command
data-processor command
gan-service command
gateway command
gateway/ports
Package ports defines the authentication port for the gateway service.
Package ports defines the authentication port for the gateway service.
hash-password command
Command hash-password prints the Argon2id PHC string for a password read from stdin.
Command hash-password prints the Argon2id PHC string for a password read from stdin.
user-service command
user-service/ports
Package ports defines the authentication port for the user service.
Package ports defines the authentication port for the user service.
internal
apperrors
Package apperrors provides structured application errors.
Package apperrors provides structured application errors.
audit
Package audit provides structured audit logging for 152-ФЗ compliance.
Package audit provides structured audit logging for 152-ФЗ compliance.
auth/claims
Package claims provides domain types for JWT authentication.
Package claims provides domain types for JWT authentication.
auth/jwt
Package jwt provides infrastructure utilities for JWT token generation, parsing, JWKS conversion, and a shared JWTAdapter implementation.
Package jwt provides infrastructure utilities for JWT token generation, parsing, JWKS conversion, and a shared JWTAdapter implementation.
auth/password
Package password implements the Argon2id password hashing format used by the user service: a PHC string with m=65536, t=3, p=1, a 16-byte salt and a 32-byte hash, both encoded with unpadded standard base64.
Package password implements the Argon2id password hashing format used by the user service: a PHC string with m=65536, t=3, p=1, a 16-byte salt and a 32-byte hash, both encoded with unpadded standard base64.
cache
Package cache provides a type-safe, observable caching abstraction over Valkey.
Package cache provides a type-safe, observable caching abstraction over Valkey.
chat
Package chat provides rule-based FAQ and chat functionality.
Package chat provides rule-based FAQ and chat functionality.
config
Package config provides configuration utilities and typed config structs.
Package config provides configuration utilities and typed config structs.
crypto
Package crypto provides AES-GCM encryption helpers.
Package crypto provides AES-GCM encryption helpers.
db
Package db provides database connection utilities.
Package db provides database connection utilities.
domain/entity
Package entity defines core domain entities.
Package entity defines core domain entities.
domain/port
Package port defines repository and service interfaces.
Package port defines repository and service interfaces.
domain/service
Package service defines application service interfaces.
Package service defines application service interfaces.
grpc
Package grpc provides gRPC server utilities with optional mutual TLS.
Package grpc provides gRPC server utilities with optional mutual TLS.
logger
Package logger provides structured logging utilities.
Package logger provides structured logging utilities.
metrics
Package metrics provides Prometheus metrics collection and RPC instrumentation.
Package metrics provides Prometheus metrics collection and RPC instrumentation.
middleware
Package middleware provides HTTP middleware for authentication, logging, and security.
Package middleware provides HTTP middleware for authentication, logging, and security.
planner
Package planner generates training plans from templates.
Package planner generates training plans from templates.
profanity
Package profanity provides a basic RU/EN profanity check for user-supplied names (nickname, full_name).
Package profanity provides a basic RU/EN profanity check for user-supplied names (nickname, full_name).
queue
Package queue provides message queue interfaces and implementations.
Package queue provides message queue interfaces and implementations.
repository/pgx
Package pgx provides PostgreSQL repository implementations using pgx.
Package pgx provides PostgreSQL repository implementations using pgx.
repository/postgres
Package postgres provides PostgreSQL repository implementations.
Package postgres provides PostgreSQL repository implementations.
repository/shared
Package shared contains reusable biometric queries.
Package shared contains reusable biometric queries.
resilience
Package resilience provides circuit breaker and retry utilities for external service calls.
Package resilience provides circuit breaker and retry utilities for external service calls.
sanitize
Package sanitize provides input sanitization utilities for security.
Package sanitize provides input sanitization utilities for security.
server
Package server provides HTTP server lifecycle management.
Package server provides HTTP server lifecycle management.
telemetry
Package telemetry provides OpenTelemetry tracing for gRPC and HTTP services.
Package telemetry provides OpenTelemetry tracing for gRPC and HTTP services.
templates
Package templates provides training templates for plan generation.
Package templates provides training templates for plan generation.
testcontainers
Package testcontainers provides helpers for spinning up ephemeral infrastructure containers in integration and smoke tests.
Package testcontainers provides helpers for spinning up ephemeral infrastructure containers in integration and smoke tests.
totp
Package totp provides TOTP secret generation, validation, and backup-code helpers.
Package totp provides TOTP secret generation, validation, and backup-code helpers.
validator
Package validator provides input validation utilities for API requests.
Package validator provides input validation utilities for API requests.
webhook
Package webhook provides Open Wearables webhook handling.
Package webhook provides Open Wearables webhook handling.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL