commit a409e1f2c1f53dd1a16153733e23a87df8c5abb2 Author: EasyProTech LLC Date: Sat Jun 28 08:00:35 2025 +0300 🏗️ RESTRUCTURE: Transform to mono-repository architecture 🎯 CB2FA is now a PLATFORM, not just Matrix implementation! 📦 New Structure: • /matrix/ - Matrix implementation (moved from root) • /core/ - Shared components (i18n, queue, types) • /docs/ - Architecture documentation • Root README - CB2FA platform overview 🌍 Platform Vision: • Matrix ✅ (first implementation) • Telegram ⏳ (planned) • Discord ⏳ (planned) • Webhooks ⏳ (planned) • Slack ⏳ (planned) 📚 Documentation: • Architecture overview in /docs/ • Platform-specific guides in each implementation • Shared components documented in /core/ 🚀 Ready for multi-platform expansion! Trust people, not devices. - CB2FA Platform diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/LICENSE @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/README.md @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/core/README.md b/core/README.md new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/core/README.md @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/matrix/README.md b/matrix/README.md new file mode 100644 index 0000000..6fc1ec1 --- /dev/null +++ b/matrix/README.md @@ -0,0 +1,147 @@ +# CB2FA - Community-Based Two-Factor Authentication + +**Made for Matrix with love by EasyProTech LLC (www.easypro.tech)** +**Developer: Brabus** + +## Overview + +CB2FA is a lightweight, community-based two-factor authentication system for Matrix homeservers. It intercepts login requests and requires approval from trusted community members via simple y/n commands in a Matrix room. + +## Features + +- 🔐 **Community-based approval** - Trust your community members to approve logins +- ✅ **Simple y/n commands** - No complex UI, just reply 'y' or 'n' in Matrix +- 📊 **Clean tables** - Clear display of login details +- 🌍 **Internationalization** - English and Russian language support +- ⚡ **Lightweight** - Built with Deno and TypeScript, minimal dependencies +- 🛡️ **Secure** - Validates credentials with Synapse before requesting approval +- 🔄 **Smart Queue** - Handles multiple simultaneous login attempts elegantly +- 📦 **Fully Portable** - No hardcoded domains or paths, works anywhere + +## Quick Start + +1. **Clone and Configure:** + ```bash + git clone + cd cb2fa + cp .env.example .env + # Edit .env with your Matrix settings + ``` + +2. **Install Deno:** + ```bash + curl -fsSL https://deno.land/install.sh | sh + ``` + +3. **Start Services:** + ```bash + # Start the bot + deno run --allow-net --allow-env --allow-read src/main.ts + + # Start the middleware (in another terminal) + deno run --allow-net --allow-env --allow-read middleware/middleware.ts + ``` + +4. **Configure nginx to proxy login requests:** + ```nginx + location ~ ^/_matrix/client/(r0|v3)/login$ { + proxy_pass http://127.0.0.1:9999; # or your CB2FA_MIDDLEWARE_PORT + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header Host $host; + } + ``` + +## Configuration (.env) + +```bash +# Matrix Configuration +MATRIX_HOMESERVER_URL=http://localhost:8008 +MATRIX_BOT_USERNAME=cb2fa_bot +MATRIX_BOT_PASSWORD=your_bot_password +MATRIX_DOMAIN=your-matrix-domain.com + +# CB2FA Settings +MATRIX_ADMIN_FOR_AUTH=admin +CB2FA_INVITED_USERS=admin,alice,bob +CB2FA_ROOM_NAME=CB2FA Authorization +CB2FA_TIMEOUT_MINUTES=15 + +# Ports (customize as needed) +CB2FA_BOT_PORT=10000 +CB2FA_MIDDLEWARE_PORT=9999 + +# Language +LANGUAGE=en +``` + +## How It Works + +1. **User attempts Matrix login** via any client (Element, etc.) +2. **nginx routes login** to CB2FA middleware +3. **Middleware validates credentials** with Synapse +4. **If valid, creates approval request** via bot +5. **Bot sends clean table** to Matrix room +6. **Community members respond** with simple 'y' or 'n' +7. **Login succeeds or fails** based on community decision + +## Queue System + +- ✅ **One active request at a time** - Clear focus for trusted users +- ✅ **Automatic queue management** - Others wait in line +- ✅ **No user confusion** - Standard Matrix "connecting..." experience +- ✅ **Anti-DDoS protection** - Natural rate limiting + +## Architecture + +``` +User Login → nginx → CB2FA Middleware → Queue → Bot → Matrix Room → Trusted User Decision +``` + +## Production Deployment + +1. **Create Matrix bot account** +2. **Configure environment variables** +3. **Set up nginx proxy** +4. **Run as systemd services** +5. **Invite trusted users to CB2FA room** + +## License + +MIT License - Made with ❤️ for the Matrix community + +--- + +**Deploy anywhere, configure everything, hardcode nothing!** 🚀 + +## 🌍 Supported Languages + +CB2FA supports multiple languages for the interface: + +- 🇬🇧 **English** (`LANGUAGE=en`) - Default +- 🇷🇺 **Russian** (`LANGUAGE=ru`) - Русский +- 🇩🇪 **German** (`LANGUAGE=de`) - Deutsch +- 🇨🇳 **Chinese (Simplified)** (`LANGUAGE=zh-cn`) - 中文 (简体) +- 🇫🇷 **French** (`LANGUAGE=fr`) - Français +- 🇪🇸 **Spanish** (`LANGUAGE=es`) - Español +- 🇹🇷 **Turkish** (`LANGUAGE=tr`) - Türkçe + +Simply set the `LANGUAGE` variable in your `.env` file to switch languages. + +## 📸 Screenshots + +![CB2FA in action](screens/chat.jpg) +*CB2FA showing clean login approval tables in Matrix chat with trusted users bob, maya, and alice* + +## 📞 Support + +I do not provide support. I do not consult — not for free, not for money, not in any form. + +Please don't ask for help, fixes, or explanations — this project is released as-is. + +If someone wants to help with development — contributions are welcome. But there are no obligations from my side whatsoever. + +## 📖 Documentation + +- 🇬🇧 [English README](README.md) +- 🇷🇺 [Русская документация](README_RU.md) + diff --git a/matrix/README_RU.md b/matrix/README_RU.md new file mode 100644 index 0000000..3e55c11 --- /dev/null +++ b/matrix/README_RU.md @@ -0,0 +1,215 @@ +# CB2FA - Двухфакторная Аутентификация на Основе Сообщества + +**Сделано для Matrix с любовью от EasyProTech LLC (www.easypro.tech)** +**Разработчик: Brabus** + +## Обзор + +CB2FA - это легковесная система двухфакторной аутентификации на основе сообщества для Matrix серверов. Она перехватывает запросы на вход и требует одобрения от доверенных членов сообщества через простые команды 'y' или 'n' в Matrix комнате. + +## Возможности + +- 🔐 **Одобрение сообществом** - Доверьте вашим участникам сообщества одобрять входы +- ✅ **Простые команды y/n** - Никаких сложных интерфейсов, просто ответьте 'y' или 'n' в Matrix +- 📊 **Аккуратные таблицы** - Четкое отображение деталей входа +- 🌍 **Интернационализация** - Поддержка английского и русского языков +- ⚡ **Легковесность** - Построен на Deno и TypeScript, минимум зависимостей +- 🛡️ **Безопасность** - Проверяет учетные данные с Synapse перед запросом одобрения +- �� **Умная очередь** - Элегантно обрабатывает множественные попытки входа +- 📦 **Полная портабельность** - Никаких жестко заданных доменов или путей, работает везде + +## Быстрый Старт + +1. **Клонировать и настроить:** + ```bash + git clone + cd cb2fa + cp .env.example .env + # Отредактируйте .env с вашими настройками Matrix + ``` + +2. **Установить Deno:** + ```bash + curl -fsSL https://deno.land/install.sh | sh + ``` + +3. **Запустить сервисы:** + ```bash + # Запустить бота + deno run --allow-net --allow-env --allow-read src/main.ts + + # Запустить middleware (в другом терминале) + deno run --allow-net --allow-env --allow-read middleware/middleware.ts + ``` + +4. **Настроить nginx для проксирования запросов входа:** + ```nginx + location ~ ^/_matrix/client/(r0|v3)/login$ { + proxy_pass http://127.0.0.1:9999; # или ваш CB2FA_MIDDLEWARE_PORT + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header Host $host; + } + ``` + +## Конфигурация (.env) + +```bash +# Настройки Matrix +MATRIX_HOMESERVER_URL=http://localhost:8008 +MATRIX_BOT_USERNAME=cb2fa_bot +MATRIX_BOT_PASSWORD=пароль_вашего_бота +MATRIX_DOMAIN=ваш-matrix-домен.com + +# Настройки CB2FA +MATRIX_ADMIN_FOR_AUTH=admin +CB2FA_INVITED_USERS=admin,алиса,боб +CB2FA_ROOM_NAME=CB2FA Авторизация +CB2FA_TIMEOUT_MINUTES=15 + +# Порты (настройте по необходимости) +CB2FA_BOT_PORT=10000 +CB2FA_MIDDLEWARE_PORT=9999 + +# Язык +LANGUAGE=ru +``` + +## Как Это Работает + +1. **Пользователь пытается войти в Matrix** через любой клиент (Element и т.д.) +2. **nginx направляет вход** к CB2FA middleware +3. **Middleware проверяет учетные данные** с Synapse +4. **Если данные верны, создает запрос на одобрение** через бота +5. **Бот отправляет аккуратную таблицу** в Matrix комнату +6. **Участники сообщества отвечают** простыми 'y' или 'n' +7. **Вход успешен или неудачен** на основе решения сообщества + +## Система Очереди + +- ✅ **Один активный запрос за раз** - Четкий фокус для доверенных пользователей +- ✅ **Автоматическое управление очередью** - Остальные ждут в очереди +- ✅ **Никакой путаницы для пользователей** - Стандартное Matrix "подключение..." состояние +- ✅ **Защита от DDoS** - Естественное ограничение скорости + +## Архитектура + +``` +Вход Пользователя → nginx → CB2FA Middleware → Очередь → Бот → Matrix Комната → Решение Админа +``` + +## Производственное Развертывание + +1. **Создать аккаунт Matrix бота** +2. **Настроить переменные окружения** +3. **Настроить nginx прокси** +4. **Запустить как systemd сервисы** +5. **Пригласить доверенных пользователей в CB2FA комнату** + +## Примеры Использования + +### Запуск в продакшене +```bash +# Создать системные сервисы +sudo systemctl enable cb2fa-bot +sudo systemctl enable cb2fa-middleware +sudo systemctl start cb2fa-bot cb2fa-middleware +``` + +### Мониторинг +```bash +# Проверить статус +curl http://localhost:10000/health +curl http://localhost:9999/health + +# Посмотреть логи +journalctl -u cb2fa-bot -f +journalctl -u cb2fa-middleware -f +``` + +### Настройка для различных доменов +```bash +# Для локальной разработки +MATRIX_DOMAIN=localhost +MATRIX_HOMESERVER_URL=http://localhost:8008 + +# Для продакшена +MATRIX_DOMAIN=matrix.company.com +MATRIX_HOMESERVER_URL=https://matrix.company.com +``` + +## Поддерживаемые Языки + +- 🇺🇸 **Английский** (`LANGUAGE=en`) +- 🇷🇺 **Русский** (`LANGUAGE=ru`) + +Добавление новых языков просто - отредактируйте `src/i18n.ts`. + +## Безопасность + +- ✅ **Проверка учетных данных** - Сначала проверяется с Synapse +- ✅ **Нет открытых API** - Все endpoints внутренние +- ✅ **Таймауты** - Запросы автоматически истекают +- ✅ **Очередь** - Защита от спама запросов + +## Устранение Неполадок + +### Бот не подключается к Matrix +```bash +# Проверить настройки +grep MATRIX .env +curl $MATRIX_HOMESERVER_URL/_matrix/client/versions +``` + +### Middleware не перехватывает логины +```bash +# Проверить nginx конфигурацию +nginx -t +curl -X POST http://localhost:9999/health +``` + +### Запросы не приходят в комнату +```bash +# Проверить права бота +curl http://localhost:10000/cb2fa/status +``` + +## Лицензия + +MIT License - Сделано с ❤️ для Matrix сообщества + +--- + +**Разворачивайте где угодно, настраивайте все, ничего не зашивайте в код!** 🚀 + +## 🌍 Поддерживаемые Языки + +CB2FA поддерживает множество языков интерфейса: + +- 🇬🇧 **Английский** (`LANGUAGE=en`) - По умолчанию +- 🇷🇺 **Русский** (`LANGUAGE=ru`) - Текущий +- 🇩🇪 **Немецкий** (`LANGUAGE=de`) - Deutsch +- 🇨🇳 **Китайский (упрощённый)** (`LANGUAGE=zh-cn`) - 中文 (简体) +- 🇫🇷 **Французский** (`LANGUAGE=fr`) - Français +- 🇪🇸 **Испанский** (`LANGUAGE=es`) - Español +- 🇹🇷 **Турецкий** (`LANGUAGE=tr`) - Türkçe + +Просто установите переменную `LANGUAGE` в вашем `.env` файле для переключения языков. + +## 📸 Скриншоты + +![CB2FA в действии](screens/chat.jpg) +*CB2FA показывает аккуратные таблицы запросов входа в Matrix чате с доверенными пользователями bob, maya и alice* + +## 📞 Поддержка + +Я не предоставляю поддержку. Я не консультирую — ни бесплатно, ни за деньги, ни в какой форме. + +Пожалуйста, не просите помощи, исправлений или объяснений — этот проект выпускается как есть. + +Если кто-то хочет помочь с разработкой — вклады приветствуются. Но с моей стороны никаких обязательств нет. + +## 📖 Документация + +- 🇬🇧 [English Documentation](README.md) +- 🇷🇺 [Русская документация](README_RU.md) + diff --git a/matrix/bot.log b/matrix/bot.log new file mode 100644 index 0000000..adc2659 --- /dev/null +++ b/matrix/bot.log @@ -0,0 +1,23 @@ +nohup: ignoring input +Warning "exports" field should be specified when specifying a "name". + at file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json +Unsupported compiler options in "file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json". + The following options were ignored: + allowJs +[INFO] 🚀 Starting CB2FA Matrix Bot... +[INFO] Invited users: admin, moderator1, moderator2 +[INFO] Admin for auth: admin +[INFO] Language: en (🇬🇧 English) +[INFO] Matrix domain: your-matrix-domain.com +[INFO] ✅ Logged in to Matrix successfully +[INFO] ✅ Found CB2FA room: !GUCHjzpFTBkooukTdY:matrix.alltest.tech +Listening on http://127.0.0.1:10000/ +[INFO] ✅ Sent table to Matrix +[INFO] 📝 Created auth request for bob (351cf6ce) +[INFO] Request approved by brabus +[INFO] ✅ Sent table to Matrix +[INFO] 📝 Created auth request for maya (b8865d74) +[INFO] Request denied by brabus +[INFO] ✅ Sent table to Matrix +[INFO] 📝 Created auth request for alice (5e327cc8) +[INFO] Request approved by brabus diff --git a/matrix/db/cb2fa.db b/matrix/db/cb2fa.db new file mode 100644 index 0000000..72dc4d2 Binary files /dev/null and b/matrix/db/cb2fa.db differ diff --git a/matrix/deno.json b/matrix/deno.json new file mode 100644 index 0000000..cfa1f29 --- /dev/null +++ b/matrix/deno.json @@ -0,0 +1,9 @@ +{ + "name": "cb2fa", + "version": "1.0.0", + "description": "CB2FA - Community-Based Two-Factor Authentication. Made for Matrix with love by EasyProTech LLC (www.easypro.tech). Developer: Brabus", + "compilerOptions": { + "allowJs": true, + "lib": ["deno.window"] + } +} diff --git a/matrix/deno.lock b/matrix/deno.lock new file mode 100644 index 0000000..845a587 --- /dev/null +++ b/matrix/deno.lock @@ -0,0 +1,8 @@ +{ + "version": "5", + "remote": { + "https://deno.land/std@0.208.0/async/delay.ts": "a6142eb44cdd856b645086af2b811b1fcce08ec06bb7d50969e6a872ee9b8659", + "https://deno.land/std@0.208.0/dotenv/mod.ts": "039468f5c87d39b69d7ca6c3d68ebca82f206ec0ff5e011d48205eea292ea5a6", + "https://deno.land/std@0.208.0/http/server.ts": "f3cde6672e631d3e00785743cfa96bfed275618c0352c5ae84abbe5a2e0e4afc" + } +} diff --git a/matrix/logs/bot-final.log b/matrix/logs/bot-final.log new file mode 100644 index 0000000..b594935 --- /dev/null +++ b/matrix/logs/bot-final.log @@ -0,0 +1,24 @@ +Warning "exports" field should be specified when specifying a "name". + at file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json +Unsupported compiler options in "file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json". + The following options were ignored: + allowJs +[INFO] 🚀 Starting CB2FA Matrix Bot... +[INFO] Invited users: brabus +[INFO] Admin for auth: brabus +[INFO] Language: en +[INFO] ✅ Logged in to Matrix successfully +[INFO] ✅ Found CB2FA room: !GUCHjzpFTBkooukTdY:matrix.alltest.tech +Listening on http://127.0.0.1:10000/ +[INFO] ✅ Sent Excel-style table to Matrix +[INFO] 📝 Created auth request for q (fbf2829b) +[INFO] Request denied by brabus +[INFO] ✅ Sent Excel-style table to Matrix +[INFO] 📝 Created auth request for q (b03f10a3) +[INFO] Request denied by brabus +[INFO] ✅ Sent Excel-style table to Matrix +[INFO] 📝 Created auth request for q (158af556) +[INFO] Request denied by brabus +[INFO] ✅ Sent Excel-style table to Matrix +[INFO] 📝 Created auth request for q (2fd78842) +[INFO] Request denied by brabus diff --git a/matrix/logs/bot-queue.log b/matrix/logs/bot-queue.log new file mode 100644 index 0000000..7278216 --- /dev/null +++ b/matrix/logs/bot-queue.log @@ -0,0 +1,14 @@ +Warning "exports" field should be specified when specifying a "name". + at file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json +Unsupported compiler options in "file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json". + The following options were ignored: + allowJs +[INFO] 🚀 Starting CB2FA Matrix Bot... +[INFO] Invited users: brabus +[INFO] Admin for auth: brabus +[INFO] Language: en +[INFO] ✅ Logged in to Matrix successfully +[INFO] ✅ Found CB2FA room: !GUCHjzpFTBkooukTdY:matrix.alltest.tech +Listening on http://127.0.0.1:10000/ +[INFO] ✅ Sent Excel-style table to Matrix +[INFO] 📝 Created auth request for q (54051c64) diff --git a/matrix/logs/middleware-final.log b/matrix/logs/middleware-final.log new file mode 100644 index 0000000..3d52f36 --- /dev/null +++ b/matrix/logs/middleware-final.log @@ -0,0 +1,10 @@ +Warning "exports" field should be specified when specifying a "name". + at file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json +Unsupported compiler options in "file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json". + The following options were ignored: + allowJs +[INFO] 🌐 Starting CB2FA Middleware... +Listening on http://127.0.0.1:9999/ +[INFO] 🔐 Login attempt: q +[INFO] ✅ Login successful for: q +[INFO] 🔄 Regular user - creating CB2FA request: q diff --git a/matrix/logs/middleware-queue.log b/matrix/logs/middleware-queue.log new file mode 100644 index 0000000..85d44d6 --- /dev/null +++ b/matrix/logs/middleware-queue.log @@ -0,0 +1,45 @@ +Warning "exports" field should be specified when specifying a "name". + at file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json +Unsupported compiler options in "file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json". + The following options were ignored: + allowJs +[INFO] 🌐 Starting CB2FA Middleware... +Listening on http://127.0.0.1:9999/ +[INFO] 🔐 Login attempt: testuser1 +[WARN] ❌ Login failed: Invalid username or password +[INFO] 🔐 Login attempt: testuser2 +[WARN] ❌ Login failed: Invalid username or password +[INFO] 🔐 Login attempt: q +[INFO] ✅ Login successful for: q +[INFO] 🔄 Regular user - creating CB2FA request: q - checking queue... +[INFO] Queue clear for q, proceeding... +[INFO] 🔐 Login attempt: q +[INFO] ✅ Login successful for: q +[INFO] 🔄 Regular user - creating CB2FA request: q - checking queue... +[DEBUG] q waiting in queue (0s)... +[DEBUG] q waiting in queue (2s)... +[INFO] 🔐 Login attempt: q +[INFO] ✅ Login successful for: q +[INFO] 🔄 Regular user - creating CB2FA request: q - checking queue... +[DEBUG] q waiting in queue (0s)... +[DEBUG] q waiting in queue (4s)... +[DEBUG] q waiting in queue (2s)... +[WARN] ❌ CB2FA denied for q by brabus +[INFO] Queue clear for q, proceeding... +[DEBUG] q waiting in queue (4s)... +[DEBUG] q waiting in queue (6s)... +[DEBUG] q waiting in queue (8s)... +[DEBUG] q waiting in queue (10s)... +[DEBUG] q waiting in queue (12s)... +[DEBUG] q waiting in queue (14s)... +[WARN] ❌ CB2FA denied for q by brabus +[DEBUG] q waiting in queue (16s)... +[INFO] Queue clear for q, proceeding... +[WARN] ❌ CB2FA denied for q by brabus +[DEBUG] Forwarding to Synapse: http://127.0.0.1:8008/ +[INFO] 🔐 Login attempt: bob +[WARN] ❌ Login failed: Invalid username or password +[INFO] 🔐 Login attempt: maya +[WARN] ❌ Login failed: Invalid username or password +[INFO] 🔐 Login attempt: alice +[WARN] ❌ Login failed: Invalid username or password diff --git a/matrix/middleware.log b/matrix/middleware.log new file mode 100644 index 0000000..ede77d7 --- /dev/null +++ b/matrix/middleware.log @@ -0,0 +1,27 @@ +nohup: ignoring input +Warning "exports" field should be specified when specifying a "name". + at file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json +Unsupported compiler options in "file:///var/alltest.tech/dev/cb2fa.com/matrix/deno.json". + The following options were ignored: + allowJs +[INFO] 🌐 Starting CB2FA Middleware... +[INFO] Matrix domain: your-matrix-domain.com +[INFO] Synapse URL: http://localhost:8008 +[INFO] CB2FA Bot URL: http://127.0.0.1:10000 +Listening on http://127.0.0.1:9999/ +[DEBUG] Forwarding to Synapse: http://localhost:8008/ +[INFO] 🔐 Login attempt: bob +[INFO] ✅ Login successful for: bob +[INFO] 🔄 Regular user - creating CB2FA request: bob - checking queue... +[INFO] Queue clear for bob, proceeding... +[INFO] 🔐 Login attempt: maya +[INFO] ✅ Login successful for: maya +[INFO] 🔄 Regular user - creating CB2FA request: maya - checking queue... +[INFO] Queue clear for maya, proceeding... +[WARN] ❌ CB2FA denied for bob by brabus +[WARN] ❌ CB2FA denied for maya by brabus +[INFO] 🔐 Login attempt: alice +[INFO] ✅ Login successful for: alice +[INFO] 🔄 Regular user - creating CB2FA request: alice - checking queue... +[INFO] Queue clear for alice, proceeding... +[WARN] ⏰ CB2FA timeout for alice diff --git a/matrix/middleware/middleware.ts b/matrix/middleware/middleware.ts new file mode 100644 index 0000000..6eb4497 --- /dev/null +++ b/matrix/middleware/middleware.ts @@ -0,0 +1,253 @@ +// CB2FA - Community-Based Two-Factor Authentication +// Made for Matrix with love by EasyProTech LLC (www.easypro.tech) +// Developer: Brabus + +import { serve } from "https://deno.land/std@0.208.0/http/server.ts"; +import { config } from "../src/config.ts"; +import { log } from "../src/logger.ts"; +import { t } from "../src/i18n.ts"; + +// Make Synapse URL configurable +const SYNAPSE_URL = config.matrix.homeserverUrl; +const CB2FA_BOT_URL = `http://127.0.0.1:${config.cb2fa.botPort}`; + +log.info("🌐 Starting CB2FA Middleware..."); +log.info(`Matrix domain: ${config.matrix.domain}`); +log.info(`Synapse URL: ${SYNAPSE_URL}`); +log.info(`CB2FA Bot URL: ${CB2FA_BOT_URL}`); + +async function forwardToSynapse(req: Request): Promise { + const url = new URL(req.url); + const synapseUrl = `${SYNAPSE_URL}${url.pathname}${url.search}`; + + log.debug(`Forwarding to Synapse: ${synapseUrl}`); + + const headers = new Headers(req.headers); + headers.set("host", new URL(SYNAPSE_URL).host); + headers.set("access-control-allow-origin", "*"); + + const response = await fetch(synapseUrl, { + method: req.method, + headers, + body: req.body, + }); + + const corsHeaders = { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET,POST,OPTIONS", + "Access-Control-Allow-Headers": "Content-Type,Authorization", + "Content-Type": "application/json", + }; + + return new Response(await response.text(), { + status: response.status, + headers: corsHeaders, + }); +} + +async function interceptLogin(req: Request): Promise { + try { + const body = await req.text(); + const loginData = JSON.parse(body); + + log.info(`${t("loginAttempt")}: ${loginData.identifier?.user || loginData.user}`); + + // Forward to Synapse first to verify credentials (use same API version as request) + const url = new URL(req.url); + const synapseResponse = await fetch(`${SYNAPSE_URL}${url.pathname}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body, + }); + + const synapseResult = await synapseResponse.json(); + + if (!synapseResponse.ok) { + log.warn(`${t("loginFailed")}: ${synapseResult.error || "Unknown error"}`); + return new Response(JSON.stringify(synapseResult), { + status: synapseResponse.status, + headers: { + "Access-Control-Allow-Origin": "*", + "Content-Type": "application/json" + }, + }); + } + + const username = synapseResult.user_id.replace("@", "").split(":")[0]; + + log.info(`✅ Login successful for: ${username}`); + + // Wait in queue if another request is being processed + log.info(`${t("regularUser")}: ${username} - checking queue...`); + + let queueWaitTime = 0; + while (true) { + try { + const hasPendingResponse = await fetch(`${CB2FA_BOT_URL}/cb2fa/has-pending`); + if (hasPendingResponse.ok) { + const hasPendingData = await hasPendingResponse.json(); + if (!hasPendingData.hasPending) { + log.info(`Queue clear for ${username}, proceeding...`); + break; // Queue is clear, we can proceed + } + log.debug(`${username} waiting in queue (${queueWaitTime}s)...`); + } + } catch (error) { + log.warn(`Queue check error for ${username}:`, error); + break; // If CB2FA service is down, proceed anyway + } + + queueWaitTime += 2; + if (queueWaitTime > 300) { // 5 minutes max queue wait + log.warn(`Queue timeout for ${username} after ${queueWaitTime}s`); + return new Response(JSON.stringify({ + errcode: "M_FORBIDDEN", + error: "Invalid username or password", + }), { + status: 403, + headers: { + "Access-Control-Allow-Origin": "*", + "Content-Type": "application/json", + }, + }); + } + + // Wait 2 seconds before checking again + await new Promise(resolve => setTimeout(resolve, 2000)); + } + + const clientIp = req.headers.get("x-forwarded-for") || req.headers.get("x-real-ip") || "unknown"; + + const authRequest = await fetch(`${CB2FA_BOT_URL}/cb2fa/create`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + username, + ip_address: clientIp, + device_info: req.headers.get("user-agent"), + }), + }); + + if (!authRequest.ok) { + log.error("Failed to create CB2FA request"); + return new Response(JSON.stringify({ + errcode: "M_UNKNOWN", + error: "CB2FA service unavailable", + }), { + status: 500, + headers: { + "Access-Control-Allow-Origin": "*", + "Content-Type": "application/json", + }, + }); + } + + // Poll for simple y/n decision + const maxWaitTime = config.cb2fa.timeoutMinutes * 60 * 1000; + const pollInterval = 2000; + const startTime = Date.now(); + + while (Date.now() - startTime < maxWaitTime) { + await new Promise(resolve => setTimeout(resolve, pollInterval)); + + const statusResponse = await fetch(`${CB2FA_BOT_URL}/cb2fa/status`); + + if (statusResponse.ok) { + const status = await statusResponse.json(); + + if (status.status === "approved") { + log.info(`✅ CB2FA approved for ${username} by ${status.approvedBy}`); + return new Response(JSON.stringify(synapseResult), { + status: 200, + headers: { + "Access-Control-Allow-Origin": "*", + "Content-Type": "application/json", + }, + }); + } else if (status.status === "denied") { + log.warn(`❌ CB2FA denied for ${username} by ${status.deniedBy}`); + return new Response(JSON.stringify({ + errcode: "M_FORBIDDEN", + error: "Invalid username or password", + }), { + status: 403, + headers: { + "Access-Control-Allow-Origin": "*", + "Content-Type": "application/json", + }, + }); + } + } + } + + // Timeout + log.warn(`⏰ CB2FA timeout for ${username}`); + return new Response(JSON.stringify({ + errcode: "M_FORBIDDEN", + error: "Invalid username or password", + }), { + status: 403, + headers: { + "Access-Control-Allow-Origin": "*", + "Content-Type": "application/json", + }, + }); + + } catch (error) { + log.error("Error in login interception:", error); + return new Response(JSON.stringify({ + errcode: "M_UNKNOWN", + error: "Internal server error", + }), { + status: 500, + headers: { + "Access-Control-Allow-Origin": "*", + "Content-Type": "application/json", + }, + }); + } +} + +const handler = async (req: Request): Promise => { + const url = new URL(req.url); + + // Handle CORS preflight + if (req.method === "OPTIONS") { + return new Response(null, { + status: 204, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET,POST,OPTIONS", + "Access-Control-Allow-Headers": "Content-Type,Authorization", + }, + }); + } + + // Health check + if (url.pathname === "/health") { + return new Response(JSON.stringify({ + status: "healthy", + middleware: "cb2fa-portable", + domain: config.matrix.domain, + synapse_url: SYNAPSE_URL, + bot_url: CB2FA_BOT_URL + }), { + headers: { "Content-Type": "application/json" }, + }); + } + + // Intercept login requests (both r0 and v3 API versions) + if ((url.pathname === "/_matrix/client/r0/login" || url.pathname === "/_matrix/client/v3/login") && req.method === "POST") { + return await interceptLogin(req); + } + + // Forward everything else to Synapse + return await forwardToSynapse(req); +}; + +await serve(handler, { + port: config.cb2fa.middlewarePort, + hostname: "127.0.0.1", +}); diff --git a/matrix/screens/chat.jpg b/matrix/screens/chat.jpg new file mode 100644 index 0000000..ad77f77 Binary files /dev/null and b/matrix/screens/chat.jpg differ diff --git a/matrix/src/config.ts b/matrix/src/config.ts new file mode 100644 index 0000000..b76d228 --- /dev/null +++ b/matrix/src/config.ts @@ -0,0 +1,26 @@ +// CB2FA - Community-Based Two-Factor Authentication +// Made for Matrix with love by EasyProTech LLC (www.easypro.tech) +// Developer: Brabus + +import { load } from "https://deno.land/std@0.208.0/dotenv/mod.ts"; + +await load({ export: true }); + +export const config = { + matrix: { + homeserverUrl: Deno.env.get("MATRIX_HOMESERVER_URL") || "http://localhost:8008", + botUsername: Deno.env.get("MATRIX_BOT_USERNAME") || "cb2fa_bot", + botPassword: Deno.env.get("MATRIX_BOT_PASSWORD") || "", + domain: Deno.env.get("MATRIX_DOMAIN") || "localhost", + adminForAuth: Deno.env.get("MATRIX_ADMIN_FOR_AUTH") || "admin", + }, + cb2fa: { + invitedUsers: (Deno.env.get("CB2FA_INVITED_USERS") || "admin").split(",").map(u => u.trim()), + roomName: Deno.env.get("CB2FA_ROOM_NAME") || "CB2FA Authorization", + timeoutMinutes: parseInt(Deno.env.get("CB2FA_TIMEOUT_MINUTES") || "15"), + botPort: parseInt(Deno.env.get("CB2FA_BOT_PORT") || "10000"), + middlewarePort: parseInt(Deno.env.get("CB2FA_MIDDLEWARE_PORT") || "9999"), + }, + // Fix: TEST_LANG should override LANGUAGE for testing + language: Deno.env.get("TEST_LANG") || Deno.env.get("LANGUAGE") || "en", +}; diff --git a/matrix/src/i18n.ts b/matrix/src/i18n.ts new file mode 100644 index 0000000..85ecbd4 --- /dev/null +++ b/matrix/src/i18n.ts @@ -0,0 +1,214 @@ +// CB2FA - Community-Based Two-Factor Authentication +// Made for Matrix with love by EasyProTech LLC (www.easypro.tech) +// Developer: Brabus + +import { config } from "./config.ts"; + +const messages = { + en: { + botStarting: "🚀 Starting CB2FA Matrix Bot...", + loggedIn: "✅ Logged in to Matrix successfully", + roomCreated: "✅ Created CB2FA room", + roomFound: "✅ Found CB2FA room", + botReady: "✅ CB2FA Bot ready", + httpServerStarted: "🌐 HTTP server started on", + botStarted: "🎯 CB2FA Bot started successfully!", + + loginRequest: "🔐 Login Request", + user: "User", + ip: "IP", + time: "Time", + device: "Device", + replyInstructions: "Reply: y (allow) / n (deny)", + + requestApproved: "✅ Request APPROVED", + requestDenied: "❌ Request DENIED", + + botAuthRequest: "🤖 CB2FA bot requests verification. Reply 'y' to authorize this bot", + botAuthorized: "✅ CB2FA bot authorized successfully", + + loginAttempt: "🔐 Login attempt", + loginFailed: "❌ Login failed", + regularUser: "🔄 Regular user - creating CB2FA request", + requestCreated: "📝 Created auth request for", + }, + ru: { + botStarting: "🚀 Запуск CB2FA Matrix Бота...", + loggedIn: "✅ Успешный вход в Matrix", + roomCreated: "✅ Создана CB2FA комната", + roomFound: "✅ Найдена CB2FA комната", + botReady: "✅ CB2FA Бот готов", + httpServerStarted: "🌐 HTTP сервер запущен на", + botStarted: "🎯 CB2FA Бот успешно запущен!", + + loginRequest: "🔐 Запрос входа", + user: "Пользователь", + ip: "IP", + time: "Время", + device: "Устройство", + replyInstructions: "Ответ: y (разрешить) / n (запретить)", + + requestApproved: "✅ Запрос ОДОБРЕН", + requestDenied: "❌ Запрос ОТКЛОНЕН", + + botAuthRequest: "🤖 CB2FA бот запрашивает авторизацию. Ответьте 'y' чтобы авторизовать", + botAuthorized: "✅ CB2FA бот успешно авторизован", + + loginAttempt: "🔐 Попытка входа", + loginFailed: "❌ Неудачный вход", + regularUser: "🔄 Обычный пользователь - создаем CB2FA запрос", + requestCreated: "📝 Создан запрос авторизации для", + }, + de: { + botStarting: "🚀 CB2FA Matrix Bot wird gestartet...", + loggedIn: "✅ Erfolgreich in Matrix eingeloggt", + roomCreated: "✅ CB2FA Raum erstellt", + roomFound: "✅ CB2FA Raum gefunden", + botReady: "✅ CB2FA Bot bereit", + httpServerStarted: "🌐 HTTP Server gestartet auf", + botStarted: "🎯 CB2FA Bot erfolgreich gestartet!", + + loginRequest: "🔐 Anmeldeanfrage", + user: "Benutzer", + ip: "IP", + time: "Zeit", + device: "Gerät", + replyInstructions: "Antwort: y (erlauben) / n (verweigern)", + + requestApproved: "✅ Anfrage GENEHMIGT", + requestDenied: "❌ Anfrage ABGELEHNT", + + botAuthRequest: "🤖 CB2FA Bot bittet um Verifizierung. Antworten Sie 'y' um diesen Bot zu autorisieren", + botAuthorized: "✅ CB2FA Bot erfolgreich autorisiert", + + loginAttempt: "🔐 Anmeldeversuch", + loginFailed: "❌ Anmeldung fehlgeschlagen", + regularUser: "🔄 Regulärer Benutzer - erstelle CB2FA Anfrage", + requestCreated: "📝 Autorisierungsanfrage erstellt für", + }, + "zh-cn": { + botStarting: "🚀 正在启动CB2FA Matrix机器人...", + loggedIn: "✅ 成功登录Matrix", + roomCreated: "✅ 已创建CB2FA房间", + roomFound: "✅ 找到CB2FA房间", + botReady: "✅ CB2FA机器人已就绪", + httpServerStarted: "🌐 HTTP服务器已启动在", + botStarted: "🎯 CB2FA机器人启动成功!", + + loginRequest: "🔐 登录请求", + user: "用户", + ip: "IP地址", + time: "时间", + device: "设备", + replyInstructions: "回复: y (允许) / n (拒绝)", + + requestApproved: "✅ 请求已批准", + requestDenied: "❌ 请求已拒绝", + + botAuthRequest: "🤖 CB2FA机器人请求验证。回复'y'以授权此机器人", + botAuthorized: "✅ CB2FA机器人授权成功", + + loginAttempt: "🔐 登录尝试", + loginFailed: "❌ 登录失败", + regularUser: "🔄 普通用户 - 创建CB2FA请求", + requestCreated: "📝 已为以下用户创建授权请求", + }, + fr: { + botStarting: "🚀 Démarrage du bot CB2FA Matrix...", + loggedIn: "✅ Connexion à Matrix réussie", + roomCreated: "✅ Salon CB2FA créé", + roomFound: "✅ Salon CB2FA trouvé", + botReady: "✅ Bot CB2FA prêt", + httpServerStarted: "🌐 Serveur HTTP démarré sur", + botStarted: "�� Bot CB2FA démarré avec succès!", + + loginRequest: "🔐 Demande de connexion", + user: "Utilisateur", + ip: "IP", + time: "Heure", + device: "Appareil", + replyInstructions: "Réponse: y (autoriser) / n (refuser)", + + requestApproved: "✅ Demande APPROUVÉE", + requestDenied: "❌ Demande REFUSÉE", + + botAuthRequest: "🤖 Le bot CB2FA demande une vérification. Répondez 'y' pour autoriser ce bot", + botAuthorized: "✅ Bot CB2FA autorisé avec succès", + + loginAttempt: "🔐 Tentative de connexion", + loginFailed: "❌ Échec de la connexion", + regularUser: "🔄 Utilisateur régulier - création d'une demande CB2FA", + requestCreated: "📝 Demande d'autorisation créée pour", + }, + es: { + botStarting: "🚀 Iniciando bot CB2FA Matrix...", + loggedIn: "✅ Sesión iniciada en Matrix correctamente", + roomCreated: "✅ Sala CB2FA creada", + roomFound: "✅ Sala CB2FA encontrada", + botReady: "✅ Bot CB2FA listo", + httpServerStarted: "🌐 Servidor HTTP iniciado en", + botStarted: "🎯 ¡Bot CB2FA iniciado correctamente!", + + loginRequest: "🔐 Solicitud de inicio de sesión", + user: "Usuario", + ip: "IP", + time: "Hora", + device: "Dispositivo", + replyInstructions: "Respuesta: y (permitir) / n (denegar)", + + requestApproved: "✅ Solicitud APROBADA", + requestDenied: "❌ Solicitud DENEGADA", + + botAuthRequest: "🤖 El bot CB2FA solicita verificación. Responda 'y' para autorizar este bot", + botAuthorized: "✅ Bot CB2FA autorizado correctamente", + + loginAttempt: "🔐 Intento de inicio de sesión", + loginFailed: "❌ Fallo en el inicio de sesión", + regularUser: "🔄 Usuario regular - creando solicitud CB2FA", + requestCreated: "📝 Solicitud de autorización creada para", + }, + tr: { + botStarting: "🚀 CB2FA Matrix botu başlatılıyor...", + loggedIn: "✅ Matrix'e başarıyla giriş yapıldı", + roomCreated: "✅ CB2FA odası oluşturuldu", + roomFound: "✅ CB2FA odası bulundu", + botReady: "✅ CB2FA botu hazır", + httpServerStarted: "🌐 HTTP sunucusu başlatıldı", + botStarted: "🎯 CB2FA botu başarıyla başlatıldı!", + + loginRequest: "🔐 Giriş talebi", + user: "Kullanıcı", + ip: "IP", + time: "Zaman", + device: "Cihaz", + replyInstructions: "Yanıt: y (izin ver) / n (reddet)", + + requestApproved: "✅ Talep ONAYLANDI", + requestDenied: "❌ Talep REDDEDİLDİ", + + botAuthRequest: "🤖 CB2FA botu doğrulama talep ediyor. Bu botu yetkilendirmek için 'y' yanıtlayın", + botAuthorized: "✅ CB2FA botu başarıyla yetkilendirildi", + + loginAttempt: "🔐 Giriş denemesi", + loginFailed: "❌ Giriş başarısız", + regularUser: "🔄 Normal kullanıcı - CB2FA talebi oluşturuluyor", + requestCreated: "📝 Yetkilendirme talebi oluşturuldu:", + } +}; + +export const t = (key: string): string => { + const lang = config.language as keyof typeof messages; + const langMessages = messages[lang] || messages.en; + return (langMessages as any)[key] || key; +}; + +// Export available languages for documentation +export const availableLanguages = { + "en": "🇬🇧 English", + "ru": "🇷🇺 Русский", + "de": "🇩🇪 Deutsch", + "zh-cn": "🇨🇳 中文 (简体)", + "fr": "🇫🇷 Français", + "es": "🇪🇸 Español", + "tr": "🇹🇷 Türkçe" +}; diff --git a/matrix/src/logger.ts b/matrix/src/logger.ts new file mode 100644 index 0000000..33d623a --- /dev/null +++ b/matrix/src/logger.ts @@ -0,0 +1,10 @@ +// CB2FA - Community-Based Two-Factor Authentication +// Made for Matrix with love by EasyProTech LLC (www.easypro.tech) +// Developer: Brabus + +export const log = { + info: (message: string, ...args: unknown[]) => console.log(`[INFO] ${message}`, ...args), + warn: (message: string, ...args: unknown[]) => console.warn(`[WARN] ${message}`, ...args), + error: (message: string, ...args: unknown[]) => console.error(`[ERROR] ${message}`, ...args), + debug: (message: string, ...args: unknown[]) => console.debug(`[DEBUG] ${message}`, ...args), +}; diff --git a/matrix/src/main.ts b/matrix/src/main.ts new file mode 100644 index 0000000..8e015ba --- /dev/null +++ b/matrix/src/main.ts @@ -0,0 +1,98 @@ +// CB2FA - Community-Based Two-Factor Authentication +// Made for Matrix with love by EasyProTech LLC (www.easypro.tech) +// Developer: Brabus + +import { serve } from "https://deno.land/std@0.208.0/http/server.ts"; +import { config } from "./config.ts"; +import { log } from "./logger.ts"; +import { t, availableLanguages } from "./i18n.ts"; +import { matrixClient } from "./matrix/client.ts"; + +log.info(t("botStarting")); +log.info(`Invited users: ${config.cb2fa.invitedUsers.join(", ")}`); +log.info(`Admin for auth: ${config.matrix.adminForAuth}`); +log.info(`Language: ${config.language} (${availableLanguages[config.language as keyof typeof availableLanguages] || config.language})`); +log.info(`Matrix domain: ${config.matrix.domain}`); + +// Start Matrix client +await matrixClient.login(); + +// Start polling for messages +matrixClient.startPolling(); + +// HTTP server for CB2FA API +const handler = async (req: Request): Promise => { + const url = new URL(req.url); + + if (url.pathname === "/health") { + return new Response(JSON.stringify({ + status: "healthy", + language: config.language, + domain: config.matrix.domain, + version: "1.0.0", + supportedLanguages: availableLanguages + }), { + headers: { "Content-Type": "application/json" }, + }); + } + + if (url.pathname === "/cb2fa/has-pending" && req.method === "GET") { + return new Response(JSON.stringify({ + hasPending: matrixClient.hasPendingRequest(), + }), { + headers: { "Content-Type": "application/json" }, + }); + } + + if (url.pathname === "/cb2fa/create" && req.method === "POST") { + try { + const data = await req.json(); + + const request = await matrixClient.sendLoginRequest( + data.username, + data.ip_address, + data.device_info + ); + + return new Response(JSON.stringify(request), { + headers: { "Content-Type": "application/json" }, + }); + } catch (error) { + log.error("Error creating CB2FA request:", error); + return new Response(JSON.stringify({ + error: "Failed to create request", + }), { + status: 500, + headers: { "Content-Type": "application/json" }, + }); + } + } + + if (url.pathname === "/cb2fa/status" && req.method === "GET") { + const currentRequest = matrixClient.getCurrentRequest(); + + if (!currentRequest) { + return new Response(JSON.stringify({ + error: "No pending request", + }), { + status: 404, + headers: { "Content-Type": "application/json" }, + }); + } + + return new Response(JSON.stringify(currentRequest), { + headers: { "Content-Type": "application/json" }, + }); + } + + return new Response("Not Found", { status: 404 }); +}; + +await serve(handler, { + port: config.cb2fa.botPort, + hostname: "127.0.0.1", +}); + +log.info(`${t("httpServerStarted")} http://127.0.0.1:${config.cb2fa.botPort}`); +log.info(t("botStarted")); +log.info("🔑 Bot is ready for CB2FA requests!"); diff --git a/matrix/src/matrix/client.ts b/matrix/src/matrix/client.ts new file mode 100644 index 0000000..104238d --- /dev/null +++ b/matrix/src/matrix/client.ts @@ -0,0 +1,312 @@ +// CB2FA - Community-Based Two-Factor Authentication +// Made for Matrix with love by EasyProTech LLC (www.easypro.tech) +// Developer: Brabus + +import { config } from "../config.ts"; +import { log } from "../logger.ts"; +import { t } from "../i18n.ts"; + +export class MatrixClient { + private accessToken = ""; + private roomId = ""; + private currentRequest: any = null; + + async login() { + const response = await fetch(`${config.matrix.homeserverUrl}/_matrix/client/v3/login`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + type: "m.login.password", + identifier: { + type: "m.id.user", + user: config.matrix.botUsername, + }, + password: config.matrix.botPassword, + }), + }); + + if (!response.ok) { + throw new Error(`Login failed: ${await response.text()}`); + } + + const data = await response.json(); + this.accessToken = data.access_token; + log.info(t("loggedIn")); + + await this.setupRoom(); + } + + async setupRoom() { + // Get joined rooms + const roomsResponse = await fetch(`${config.matrix.homeserverUrl}/_matrix/client/v3/joined_rooms`, { + headers: { "Authorization": `Bearer ${this.accessToken}` }, + }); + + if (!roomsResponse.ok) { + throw new Error("Failed to get rooms"); + } + + const roomsData = await roomsResponse.json(); + + // Look for CB2FA room + for (const roomId of roomsData.joined_rooms) { + const stateResponse = await fetch( + `${config.matrix.homeserverUrl}/_matrix/client/v3/rooms/${roomId}/state/m.room.name`, + { headers: { "Authorization": `Bearer ${this.accessToken}` } } + ); + + if (stateResponse.ok) { + const state = await stateResponse.json(); + if (state.name === config.cb2fa.roomName) { + this.roomId = roomId; + log.info(`${t("roomFound")}: ${roomId}`); + return; + } + } + } + + // Create room if not found + const createResponse = await fetch(`${config.matrix.homeserverUrl}/_matrix/client/v3/createRoom`, { + method: "POST", + headers: { + "Authorization": `Bearer ${this.accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + name: config.cb2fa.roomName, + topic: "CB2FA authorization - simple y/n commands", + visibility: "private", + preset: "private_chat", + }), + }); + + if (!createResponse.ok) { + throw new Error("Failed to create room"); + } + + const createData = await createResponse.json(); + this.roomId = createData.room_id; + log.info(`${t("roomCreated")}: ${this.roomId}`); + + // Invite all configured users immediately + for (const user of config.cb2fa.invitedUsers) { + const userId = `@${user}:${config.matrix.domain}`; + await this.inviteUser(userId); + } + } + + async inviteUser(userId: string) { + const response = await fetch( + `${config.matrix.homeserverUrl}/_matrix/client/v3/rooms/${this.roomId}/invite`, + { + method: "POST", + headers: { + "Authorization": `Bearer ${this.accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ user_id: userId }), + } + ); + + if (response.ok) { + log.info(`Invited ${userId} to room`); + } + } + + async sendMessage(message: string) { + const txnId = Date.now().toString(); + const response = await fetch( + `${config.matrix.homeserverUrl}/_matrix/client/v3/rooms/${this.roomId}/send/m.room.message/${txnId}`, + { + method: "PUT", + headers: { + "Authorization": `Bearer ${this.accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + msgtype: "m.text", + body: message, + format: "org.matrix.custom.html", + formatted_body: message + .replace(/\*\*(.*?)\*\*/g, "$1") + .replace(/`(.*?)`/g, "$1") + .replace(/\n/g, "
"), + }), + } + ); + + if (!response.ok) { + log.error("Failed to send message:", await response.text()); + } + } + + async sendFormattedMessage(htmlContent: string, plainTextFallback: string) { + const txnId = Date.now().toString(); + const response = await fetch( + `${config.matrix.homeserverUrl}/_matrix/client/v3/rooms/${this.roomId}/send/m.room.message/${txnId}`, + { + method: "PUT", + headers: { + "Authorization": `Bearer ${this.accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + msgtype: "m.text", + body: plainTextFallback, + format: "org.matrix.custom.html", + formatted_body: htmlContent, + }), + } + ); + + if (!response.ok) { + log.error("Failed to send formatted message:", await response.text()); + } else { + log.info("✅ Sent table to Matrix"); + } + } + + async sendLoginRequest(username: string, ipAddress: string, deviceInfo?: string) { + const requestId = crypto.randomUUID(); + const timestamp = new Date().toLocaleTimeString(); + + this.currentRequest = { + id: requestId, + username, + ipAddress, + deviceInfo, + timestamp, + status: "pending", + }; + + // Create clean table with HTML formatting + const deviceRow = deviceInfo ? ` + + ${t("device")}: + ${deviceInfo} + ` : ""; + + const htmlTable = ` +

🔐 ${t("loginRequest")}

+ + + + + + + + + + + + + + ${deviceRow} + +
${t("user")}:${username}
${t("ip")}:${ipAddress}
${t("time")}:${timestamp}
+

+ 📋 ${t("replyInstructions")} +

`; + + const plainTextTable = `🔐 ${t("loginRequest")} + +${t("user")}: ${username} +${t("ip")}: ${ipAddress} +${t("time")}: ${timestamp} +${deviceInfo ? `${t("device")}: ${deviceInfo}` : ""} + +📋 ${t("replyInstructions")}`; + + await this.sendFormattedMessage(htmlTable, plainTextTable); + + log.info(`${t("requestCreated")} ${username} (${requestId.substring(0, 8)})`); + + return this.currentRequest; + } + + async startPolling() { + let nextBatch = ""; + + // Get initial sync token + const syncResponse = await fetch( + `${config.matrix.homeserverUrl}/_matrix/client/v3/sync?timeout=0`, + { headers: { "Authorization": `Bearer ${this.accessToken}` } } + ); + + if (syncResponse.ok) { + const syncData = await syncResponse.json(); + nextBatch = syncData.next_batch; + } + + // Poll for new messages + while (true) { + try { + const response = await fetch( + `${config.matrix.homeserverUrl}/_matrix/client/v3/sync?since=${nextBatch}&timeout=30000`, + { headers: { "Authorization": `Bearer ${this.accessToken}` } } + ); + + if (response.ok) { + const data = await response.json(); + nextBatch = data.next_batch; + + // Process room events + if (data.rooms?.join?.[this.roomId]?.timeline?.events) { + for (const event of data.rooms.join[this.roomId].timeline.events) { + if (event.type === "m.room.message" && event.content?.msgtype === "m.text") { + await this.processMessage(event); + } + } + } + } + } catch (error) { + log.error("Sync error:", error); + await new Promise(resolve => setTimeout(resolve, 5000)); + } + } + } + + async processMessage(event: any) { + const sender = event.sender; + const message = event.content?.body?.trim().toLowerCase(); + + if (!sender || !message) return; + + // Skip bot's own messages + if (sender === `@${config.matrix.botUsername}:${config.matrix.domain}`) { + return; + } + + const username = sender.split(":")[0].replace("@", ""); + + // Handle y/n responses to current request + if (this.currentRequest && (message === "y" || message === "n")) { + if (message === "y") { + this.currentRequest.status = "approved"; + this.currentRequest.approvedBy = username; + await this.sendMessage(`${t("requestApproved")} by ${username}`); + log.info(`Request approved by ${username}`); + } else { + this.currentRequest.status = "denied"; + this.currentRequest.deniedBy = username; + await this.sendMessage(`${t("requestDenied")} by ${username}`); + log.info(`Request denied by ${username}`); + } + + // Clear current request after decision + setTimeout(() => { + this.currentRequest = null; + }, 1000); + } + } + + getCurrentRequest() { + return this.currentRequest; + } + + hasPendingRequest(): boolean { + return this.currentRequest !== null; + } +} + +export const matrixClient = new MatrixClient(); diff --git a/matrix/test_users_for_screenshot.txt b/matrix/test_users_for_screenshot.txt new file mode 100644 index 0000000..b403103 --- /dev/null +++ b/matrix/test_users_for_screenshot.txt @@ -0,0 +1,20 @@ +# CB2FA Screenshot Test Data + +Тестовые пользователи для демонстрации: + +1. @ivan:matrix.example.com + - IP: 192.168.1.100 + - Device: Element Desktop (Linux) + - Time: 14:23:45 + +2. @maria:matrix.example.com + - IP: 10.0.0.50 + - Device: Element Mobile (Android) + - Time: 14:24:12 + +3. @alex:matrix.example.com + - IP: 172.16.0.25 + - Device: FluffyChat (iOS) + - Time: 14:24:38 + +Можно использовать для создания скриншота аккуратной таблицы CB2FA