# VibeChat API Documentation ## 📚 Обзор **VibeChat** — безопасный мессенджер с End-to-End шифрованием, группами, каналами и кроссплатформенной поддержкой. **Стек:** - Бэкенд: Node.js (native http, без зависимостей) - Хранение: JSON файлы - Шифрование: AES-256-GCM (crypto module) - Аутентификация: JWT-like токены на HMAC-SHA256 --- ## 🔐 Безопасность ### End-to-End Шифрование Каждое сообщение шифруется на клиенте перед отправкой: ```javascript // Ключ генерируется из email + ID пользователя const userKey = hashPassword(user.email + user.id); // Шифрование (AES-256-GCM) function encryptMessage(text, key) { const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv("aes-256-gcm", key, iv); let encrypted = cipher.update(text, "utf8", "hex"); encrypted += cipher.final("hex"); const authTag = cipher.getAuthTag().toString("hex"); return { iv, encrypted, authTag }; } ``` **В базе данных хранится:** ```json { "text": "Исходный текст (виден только отправителю)", "encrypted": { "iv": "...", "encrypted": "...", "authTag": "..." } } ``` Получатель расшифровывает своим ключом на клиенте. --- ## 🚀 API Endpoints ### AUTH #### Регистрация ``` POST /api/auth/register Content-Type: application/json { "username": "john", "email": "john@example.com", "password": "secure123" } Response: { "ok": true, "token": "eyJhbGc...", "user": { "id": 1234567890, "username": "john", "email": "john@example.com", "avatar": "https://api.dicebear.com/7.x/avataaars/svg?seed=john" } } ``` #### Вход ``` POST /api/auth/login Content-Type: application/json { "email": "john@example.com", "password": "secure123" } Response: { "ok": true, "token": "eyJhbGc...", "user": { ... } } ``` #### Выход ``` POST /api/auth/logout Authorization: Bearer Response: { "ok": true } ``` #### Получить текущий профиль ``` GET /api/auth/me Authorization: Bearer Response: { "ok": true, "user": { "id": 123, "username": "john", "email": "john@example.com", "avatar": "...", "bio": "О себе" } } ``` --- ### USERS #### Список пользователей ``` GET /api/users Authorization: Bearer Response: { "ok": true, "users": [ { "id": 456, "username": "jane", "avatar": "..." } ] } ``` #### Обновить профиль ``` PUT /api/users/me Authorization: Bearer Content-Type: application/json { "username": "newname", "bio": "Новое описание", "avatar": "https://..." } Response: { "ok": true, "user": { ... } } ``` --- ### CHATS #### Получить все чаты ``` GET /api/chats Authorization: Bearer Response: { "ok": true, "chats": [ { "id": 789, "type": "private", "name": "jane", "avatar": "...", "participants": [123, 456], "lastMessage": { "text": "Привет!", "createdAt": "2026-08-17T10:30:00Z" } } ] } ``` #### Создать чат ``` POST /api/chats Authorization: Bearer Content-Type: application/json // Приватный чат { "type": "private", "participantId": 456 } // Группа { "type": "group", "name": "Моя группа" } // Канал { "type": "channel", "name": "Мой канал" } Response: { "ok": true, "chat": { ... } } ``` #### Получить сообщения ``` GET /api/chats/:id/messages Authorization: Bearer Response: { "ok": true, "messages": [ { "id": 111, "chatId": 789, "senderId": 456, "senderName": "jane", "senderAvatar": "...", "text": "Привет!", // Уже расшифровано "type": "text", "createdAt": "2026-08-17T10:30:00Z" } ] } ``` #### Отправить сообщение ``` POST /api/chats/:id/messages Authorization: Bearer Content-Type: application/json { "text": "Привет!", "type": "text" // или "emoji", "sticker" } Response: { "ok": true, "message": { ... } } ``` --- ### GROUPS #### Добавить участника в группу ``` POST /api/groups/:id/members Authorization: Bearer Content-Type: application/json { "userId": 789 } Response: { "ok": true, "group": { ... } } ``` --- ### CHANNELS #### Подписаться на канал ``` POST /api/channels/:id/subscribe Authorization: Bearer Response: { "ok": true, "channel": { ... } } ``` --- ## 📊 Структура данных ### User ```json { "id": 1234567890, "username": "john", "email": "john@example.com", "passwordHash": "sha256...", "avatar": "https://...", "bio": "О себе", "createdAt": "2026-08-17T10:00:00Z" } ``` ### Chat ```json { "id": 789, "type": "private|group|channel", "participants": [123, 456], "name": "Группа", "avatar": "https://...", "ownerId": 123, "createdAt": "2026-08-17T10:00:00Z" } ``` ### Message ```json { "id": 111, "chatId": 789, "senderId": 123, "senderName": "john", "senderAvatar": "...", "text": "Привет!", "encrypted": { "iv": "...", "encrypted": "...", "authTag": "..." }, "type": "text|emoji|sticker", "createdAt": "2026-08-17T10:30:00Z" } ``` --- ## 🏗 Архитектура сервера ``` server.js ├── Crypto Utils │ ├── hashPassword() │ ├── generateToken() │ ├── verifyToken() │ ├── encryptMessage() │ └── decryptMessage() │ ├── Routes │ ├── AUTH │ │ ├── POST /api/auth/register │ │ ├── POST /api/auth/login │ │ ├── POST /api/auth/logout │ │ └── GET /api/auth/me │ │ │ ├── USERS │ │ ├── GET /api/users │ │ └── PUT /api/users/me │ │ │ ├── CHATS │ │ ├── GET /api/chats │ │ ├── POST /api/chats │ │ ├── GET /api/chats/:id/messages │ │ └── POST /api/chats/:id/messages │ │ │ ├── GROUPS │ │ └── POST /api/groups/:id/members │ │ │ └── CHANNELS │ └── POST /api/channels/:id/subscribe │ └── Static Files ├── index.html (лендинг + auth) ├── app.html (мессенджер) ├── landing.css ├── landing.js ├── app.css └── app.js ``` --- ## 📱 Мобильное приложение (Future) API полностью готов для подключения мобильного приложения: ### React Native / Flutter интеграция ```javascript // Пример для React Native const API_BASE = 'https://your-domain.com'; async function login(email, password) { const res = await fetch(`${API_BASE}/api/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }); const json = await res.json(); if (json.ok) { await AsyncStorage.setItem('token', json.token); return json.user; } throw new Error(json.error); } async function getChats(token) { const res = await fetch(`${API_BASE}/api/chats`, { headers: { 'Authorization': `Bearer ${token}` } }); const json = await res.json(); return json.chats; } ``` --- ## 🔒 Безопасность (Production Checklist) Для продакшена добавить: - [ ] HTTPS (TLS 1.3) - [ ] Rate limiting (100 req/min на IP) - [ ] Helmet.js для security headers - [ ] Валидация входных данных (Joi/Zod) - [ ] 2FA (TOTP) - [ ] Сессионные токены с refresh - [ ] Блокировка при подозрительной активности - [ ] Аудит логов - [ ] GDPR compliance --- ## 🧪 Тестирование API ```bash # Регистрация curl -X POST http://localhost:3000/api/auth/register \ -H "Content-Type: application/json" \ -d '{"username":"test","email":"test@test.com","password":"123456"}' # Вход curl -X POST http://localhost:3000/api/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"test@test.com","password":"123456"}' # Получить профиль curl -X GET http://localhost:3000/api/auth/me \ -H "Authorization: Bearer YOUR_TOKEN" # Создать чат curl -X POST http://localhost:3000/api/chats \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"type":"group","name":"Test Group"}' ``` --- ## 📈 Масштабирование ### Текущая архитектура (JSON файлы) - ✅ Подходит для: до 1000 пользователей, до 10K сообщений - ⚠️ Ограничения: нет real-time, нет шардирования ### Roadmap для продакшена 1. **База данных:** PostgreSQL + Prisma 2. **Real-time:** WebSocket (Socket.io) 3. **Кеширование:** Redis (сессии, последние сообщения) 4. **Файлы:** S3-compatible storage (аватарки, файлы) 5. **Очереди:** RabbitMQ/Kafka для асинхронных задач 6. **Мониторинг:** Prometheus + Grafana 7. **Контейнеризация:** Docker + Kubernetes --- ## 📞 Поддержка API Version: 1.0.0 Last Updated: 2026-08-17