diff --git a/.github/workflows/sync-from-gitea.yml b/.github/workflows/sync-from-gitea.yml new file mode 100644 index 0000000..9a0866b --- /dev/null +++ b/.github/workflows/sync-from-gitea.yml @@ -0,0 +1,100 @@ +name: Sync from Gitea + +# Запускается вручную или по webhook от Gitea +on: + workflow_dispatch: + repository_dispatch: + types: [gitea-push] + schedule: + # Проверка каждый час + - cron: '0 * * * *' + +jobs: + sync: + runs-on: ubuntu-latest + + steps: + - name: Checkout GitHub repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Configure Git + run: | + git config --global user.name "Sync Bot" + git config --global user.email "bot@example.com" + + - name: Add Gitea remote + env: + GITEA_URL: ${{ secrets.GITEA_URL }} + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: | + if [ -z "$GITEA_URL" ]; then + echo "⚠️ GITEA_URL не настроен, пропускаем синхронизацию" + exit 0 + fi + + # Добавляем Gitea remote с токеном + git remote add gitea "https://oauth2:${GITEA_TOKEN}@${GITEA_URL#https://}" + git remote -v + + - name: Fetch from Gitea + run: | + if git remote | grep -q gitea; then + echo "🔄 Получение изменений из Gitea..." + git fetch gitea --tags + else + echo "⚠️ Gitea remote не настроен" + exit 0 + fi + + - name: Check for new commits + id: check + run: | + # Проверяем есть ли новые коммиты в Gitea + LOCAL=$(git rev-parse HEAD) + REMOTE=$(git rev-parse gitea/main 2>/dev/null || git rev-parse gitea/master 2>/dev/null || echo $LOCAL) + + if [ "$LOCAL" != "$REMOTE" ]; then + echo "new_commits=true" >> $GITHUB_OUTPUT + echo "✅ Обнаружены новые изменения в Gitea" + else + echo "new_commits=false" >> $GITHUB_OUTPUT + echo "ℹ️ Нет новых изменений" + fi + + - name: Merge changes from Gitea + if: steps.check.outputs.new_commits == 'true' + run: | + # Определяем главную ветку + if git show-ref --verify --quiet refs/remotes/gitea/main; then + BRANCH="main" + else + BRANCH="master" + fi + + echo "🔀 Слияние изменений из gitea/${BRANCH}..." + git merge "gitea/${BRANCH}" --allow-unrelated-histories -m "Sync from Gitea: $(date)" + + - name: Push to GitHub + if: steps.check.outputs.new_commits == 'true' + run: | + echo "⬆️ Отправка изменений в GitHub..." + git push origin HEAD:main --force-with-lease + git push origin --tags + echo "✅ Синхронизация завершена" + + - name: Summary + if: always() + run: | + echo "## 🔄 Отчет о синхронизации" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + if [ "${{ steps.check.outputs.new_commits }}" == "true" ]; then + echo "✅ **Статус**: Синхронизировано успешно" >> $GITHUB_STEP_SUMMARY + echo "📦 **Коммиты**: Новые изменения получены и объединены" >> $GITHUB_STEP_SUMMARY + else + echo "ℹ️ **Статус**: Нет новых изменений" >> $GITHUB_STEP_SUMMARY + fi + echo "" >> $GITHUB_STEP_SUMMARY + echo "🕐 **Время**: $(date)" >> $GITHUB_STEP_SUMMARY diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md new file mode 100644 index 0000000..12b1a1c --- /dev/null +++ b/CHANGELOG_EN.md @@ -0,0 +1,187 @@ +# 📋 Changelog + +## [2.1.0] - 2025-10-27 + +### 🆕 Added + +#### Test SSL Certificate Generation +- ✨ **New `TestCertificateGenerator` class** - self-signed certificate generation +- ✨ **`--test-cert` command** in Python script for test certificate creation +- ✨ **`test_certificate.sh` script** - standalone creation via OpenSSL +- ✨ **`make test-cert` command** in Makefile for quick testing + +#### Documentation +- 📘 **TESTING_GUIDE.md** (370+ lines) - complete testing guide + - Bypass Let's Encrypt limits (5 certificates per week) + - Certificate creation method comparison + - CI/CD and Docker examples + - Transition from test to production + - FAQ and solutions + +- 📘 **TESTING_GUIDE_EN.md** - English version of testing guide + +- 📘 **PROJECT_STRUCTURE.md** - project structure + - All files description + - Features list + - Technologies + +- 📘 **PROJECT_STRUCTURE_EN.md** - English version + +- 📘 **CHEATSHEET.md** - quick reference + - Main commands + - Use case scenarios + - Common errors and solutions + - Development workflow + +- 📘 **CHEATSHEET_EN.md** - English version + +- 📘 **DESCRIPTION.md** - project description in Russian and English + +- 📘 **CHANGELOG_EN.md** - English changelog + +- 📘 **GITEA_SYNC.md** - Gitea → GitHub synchronization + - 4 sync methods + - Step-by-step setup + - Troubleshooting + +- 📘 **GITEA_SYNC_EN.md** - English version + +- 📘 **README_EN.md** - Complete English main guide + +#### Functionality +- ✨ Support for **unlimited** test certificates +- ✨ **Instant creation** (1-2 seconds) without DNS validation +- ✨ **Automatic upload** of test certificates to NPM +- ✨ **Full compatibility** of structure with Let's Encrypt +- ✨ **Wildcard support** for test certificates + +#### Repository Synchronization +- ✨ **Automatic Gitea → GitHub sync** via Git Hooks +- ✨ **GitHub Actions workflow** for hourly sync check +- ✨ **Webhook integration** between Gitea and GitHub +- ✨ **Multiple sync methods** (Hooks, Actions, Mirror, Double Remote) + +### 🔧 Improved + +#### Python Script +- Added `cryptography` library import with installation check +- New command-line parameters: + - `--test-cert` - create test certificate + - `--auto` - explicit automatic mode +- Improved test certificate handling in NPM +- Detailed logging of generation process + +#### Makefile +- Added `make test-cert` command with beautiful output +- Information messages about test certificate benefits +- Security warnings + +#### README.md +- "Test Self-Signed Certificate Creation" section +- Updated table of contents with test certificates link +- Test certificate usage examples +- NPM integration for test certificates +- Links to additional documentation +- Gitea → GitHub sync section + +### 🎯 Benefits + +#### For Developers +- ✅ **No limits** - unlimited certificates +- ✅ **Fast** - creation in 1-2 seconds +- ✅ **Offline** - works without internet +- ✅ **Identical structure** - same files as Let's Encrypt + +#### For Testing +- ✅ **CI/CD friendly** - quick creation in pipeline +- ✅ **Docker ready** - easily embeds in containers +- ✅ **Staging environments** - perfect for test servers +- ✅ **Local development** - HTTPS on localhost + +#### For DevOps +- ✅ **Repository sync** - automatic Gitea → GitHub +- ✅ **Multiple methods** - choose what fits +- ✅ **Instant sync** - Git Hooks < 1 second +- ✅ **Reliable backup** - GitHub Actions hourly check + +### 📊 Statistics + +- **Lines of code**: 1,411 (Python script) +- **Makefile lines**: 415 +- **Documentation lines**: 3,500+ +- **Makefile commands**: 13 +- **Operating modes**: 4 (obtain, renew, auto, test-cert) +- **Sync methods**: 4 (Hooks, Actions, Mirror, Remote) +- **Languages**: 2 (Russian, English) + +--- + +## [2.0.0] - 2025-10-27 + +### 🆕 Added +- ✨ Nginx Proxy Manager (NPM) integration +- ✨ `NginxProxyManagerAPI` class for certificate management via API +- ✨ Automatic certificate upload to NPM +- ✨ Automatic certificate update in NPM +- ✨ Automatic expiration check +- ✨ Configurable renewal threshold (`renewal_days`) +- ✨ Makefile for installation/removal automation +- ✨ Systemd service + timer +- ✨ Cron automation + +### 🔧 Improved +- Documentation consolidation into single README.md +- Detailed logging with operation statuses +- Configuration validation +- Improved error handling + +### 📘 Documentation +- Complete NPM integration guide +- Quick start in 3 commands +- Automation examples + +--- + +## [1.0.0] - 2025-10-26 + +### 🆕 First Release +- Python script for Let's Encrypt via reg.ru API +- Bash script with certbot-dns-regru +- PowerShell version for Windows +- DNS-01 validation +- Wildcard certificates +- Basic documentation + +--- + +## Roadmap + +### [2.2.0] - Planned +- [ ] Web interface for management +- [ ] Multiple domain support +- [ ] Notifications (email, telegram) +- [ ] Grafana dashboard for monitoring +- [ ] Certificate backups + +### [3.0.0] - Future +- [ ] Other DNS provider support +- [ ] Cloudflare API +- [ ] Route53 (AWS) +- [ ] Google Cloud DNS + +--- + +## Change Types +- `🆕 Added` - new functionality +- `🔧 Improved` - improvements to existing functionality +- `🐛 Fixed` - bug fixes +- `🗑️ Removed` - removed functionality +- `🔒 Security` - security changes +- `📘 Documentation` - documentation changes + +--- + +**Versioning**: Semantic Versioning (MAJOR.MINOR.PATCH) +- **MAJOR**: Incompatible API changes +- **MINOR**: New functionality with backward compatibility +- **PATCH**: Bug fixes diff --git a/CHEATSHEET_EN.md b/CHEATSHEET_EN.md new file mode 100644 index 0000000..b039356 --- /dev/null +++ b/CHEATSHEET_EN.md @@ -0,0 +1,263 @@ +# ⚡ SSL Certificate Cheatsheet + +## 🚀 Quick Start + +### Installation in 3 Commands +```bash +sudo make install +sudo nano /etc/letsencrypt/regru_config.json # Fill in data +sudo make test-cert # Test +``` + +--- + +## 🧪 Testing (NO Let's Encrypt Limits) + +```bash +# Create test certificate (unlimited) +sudo make test-cert + +# Check status +sudo make status + +# View logs +sudo make logs +``` + +**When to use:** +- ⚠️ Let's Encrypt: max 5 certificates/week +- ✅ Test: UNLIMITED +- ⚡ Creation: 1-2 seconds vs 2-5 minutes + +--- + +## 🔒 Production (Let's Encrypt) + +```bash +# Get real certificate +sudo make obtain + +# Automatic mode (check + renewal) +sudo make run + +# Force renewal +sudo make renew +``` + +--- + +## 📋 Main Commands + +| Command | Description | Limits | +|---------|-------------|--------| +| `make test-cert` | Test certificate | ✅ None | +| `make obtain` | New Let's Encrypt | ⚠️ 5/week | +| `make renew` | Renew existing | ⚠️ 5/week | +| `make run` | Auto mode | ⚠️ 5/week | +| `make status` | System status | - | +| `make logs` | Show logs | - | +| `make check-config` | Check configuration | - | + +--- + +## 📝 Configuration + +### Minimal (testing) +```json +{ + "domain": "test.example.com", + "wildcard": true, + "cert_dir": "/etc/letsencrypt/live" +} +``` + +### Full (production + NPM) +```json +{ + "regru_username": "myuser", + "regru_password": "mypassword", + "domain": "example.com", + "wildcard": true, + "email": "admin@example.com", + "renewal_days": 30, + "npm_enabled": true, + "npm_host": "https://npm.example.com", + "npm_email": "admin@example.com", + "npm_password": "npm_password" +} +``` + +--- + +## 🔄 Workflow + +### Development → Production + +```bash +# 1. Development (test certificates) +sudo make test-cert # Create test +# Test application... + +# 2. Production (Let's Encrypt) +sudo rm -rf /etc/letsencrypt/live/example.com/ # Remove test +sudo make obtain # Create production +``` + +--- + +## 📁 Important Paths + +```bash +# Configuration +/etc/letsencrypt/regru_config.json + +# Certificates +/etc/letsencrypt/live/example.com/ +├── privkey.pem # Private key +├── cert.pem # Certificate +├── fullchain.pem # Full chain (for nginx) +└── chain.pem # CA chain + +# Scripts +/opt/letsencrypt-regru/letsencrypt_regru_api.py + +# Logs +/var/log/letsencrypt_regru.log +``` + +--- + +## 🔍 Verification + +```bash +# Check configuration +sudo make check-config + +# Check certificate +openssl x509 -in /etc/letsencrypt/live/example.com/cert.pem -text -noout + +# Check expiration date +openssl x509 -in /etc/letsencrypt/live/example.com/cert.pem -noout -dates + +# Check systemd +sudo systemctl status letsencrypt-regru.timer +sudo systemctl list-timers letsencrypt-regru.timer + +# Check cron +sudo crontab -l | grep letsencrypt +``` + +--- + +## 🐛 Debugging + +```bash +# Detailed logs +sudo make logs + +# Test run with details +sudo python3 /opt/letsencrypt-regru/letsencrypt_regru_api.py \ + -c /etc/letsencrypt/regru_config.json --check -v + +# Certbot logs +sudo tail -f /var/log/letsencrypt/letsencrypt.log + +# Systemd logs +sudo journalctl -u letsencrypt-regru.service -f +``` + +--- + +## ⚠️ Common Errors + +### Let's Encrypt: Rate limit exceeded +```bash +# SOLUTION: Use test certificates +sudo make test-cert +``` + +### NPM: Certificate not found +```bash +# SOLUTION: Check NPM settings +sudo make check-config + +# Check connection +curl -k https://npm.example.com +``` + +### Permission denied +```bash +# SOLUTION: Run with sudo +sudo make test-cert +``` + +--- + +## 🎯 Use Case Scenarios + +### Local Development +```bash +sudo make test-cert +# Open https://localhost (ignore warning) +``` + +### CI/CD Testing +```bash +# In pipeline +sudo make test-cert +# Run tests... +sudo make status +``` + +### Staging Environment +```bash +sudo make test-cert # Or +sudo make obtain # If domain available +``` + +### Production Environment +```bash +sudo make install +sudo make obtain +# Automatic renewal via cron/systemd +``` + +--- + +## 📚 Documentation + +- **README.md** - Complete guide (1420+ lines) +- **TESTING_GUIDE.md** - Testing guide (370+ lines) +- **PROJECT_STRUCTURE.md** - Project structure +- **CHEATSHEET.md** - This cheatsheet + +--- + +## 🆘 Quick Help + +```bash +# Show all commands +make help + +# Check installation +sudo make status + +# Complete reinstall +sudo make uninstall +sudo make install +``` + +--- + +## 💡 Tips + +1. **Always start with test certificates** - avoid limits +2. **Check configuration** - `make check-config` +3. **Monitor logs** - `make logs` +4. **Automate** - systemd/cron already configured +5. **Keep backups** of configuration + +--- + +**Version**: 2.1 +**Updated**: 27.10.2025 diff --git a/DESCRIPTION.md b/DESCRIPTION.md new file mode 100644 index 0000000..9696911 --- /dev/null +++ b/DESCRIPTION.md @@ -0,0 +1,133 @@ +# 🔒 SSL Certificate Manager для Let's Encrypt + reg.ru + +**Автоматическое управление SSL сертификатами Let's Encrypt с DNS-валидацией через API reg.ru и интеграцией с Nginx Proxy Manager** + +## 📖 Описание + +Комплексное решение для автоматизации создания, обновления и управления SSL сертификатами Let's Encrypt для доменов, зарегистрированных на reg.ru. Поддерживает DNS-01 валидацию, wildcard сертификаты, автоматическую загрузку в Nginx Proxy Manager и генерацию тестовых сертификатов для разработки. + +### ✨ Основные возможности + +- 🔐 **Автоматическое получение SSL сертификатов** через Let's Encrypt +- 🌐 **DNS-01 валидация** через API reg.ru (поддержка wildcard доменов) +- 🔄 **Автоматическое обновление** сертификатов с настраиваемым порогом +- 📦 **Интеграция с Nginx Proxy Manager** - автоматическая загрузка и обновление +- 🧪 **Тестовые сертификаты** - обход лимитов Let's Encrypt (5 в неделю) +- ⚙️ **Полная автоматизация** через systemd/cron +- 🔀 **Синхронизация репозиториев** - автоматическая синхронизация Gitea → GitHub + +### 🚀 Быстрый старт + +```bash +# Установка через Makefile +sudo make install + +# Настройка конфигурации +sudo nano /etc/letsencrypt/regru_config.json + +# Создание тестового сертификата (без лимитов) +sudo make test-cert + +# Получение production сертификата +sudo make obtain +``` + +### 📋 Требования + +- **ОС**: Linux (Ubuntu/Debian/CentOS) +- **Python**: 3.6+ +- **Зависимости**: certbot, requests, cryptography +- **API**: reg.ru (доступ к DNS управлению) +- **Опционально**: Nginx Proxy Manager + +### 🎯 Сценарии использования + +- ✅ Автоматизация SSL сертификатов для web-серверов +- ✅ Централизованное управление через Nginx Proxy Manager +- ✅ Тестирование и разработка с самоподписанными сертификатами +- ✅ CI/CD интеграция +- ✅ Мультидоменные конфигурации с wildcard + +### 📚 Документация + +- [README.md](README.md) - Полное руководство (1400+ строк) +- [TESTING_GUIDE.md](TESTING_GUIDE.md) - Руководство по тестированию +- [GITEA_SYNC.md](GITEA_SYNC.md) - Синхронизация Gitea → GitHub +- [CHEATSHEET.md](CHEATSHEET.md) - Быстрая шпаргалка + +--- + +## 📖 Description (English) + +**Automated Let's Encrypt SSL Certificate Manager with DNS validation via reg.ru API and Nginx Proxy Manager integration** + +Comprehensive solution for automating the creation, renewal, and management of Let's Encrypt SSL certificates for domains registered with reg.ru. Supports DNS-01 validation, wildcard certificates, automatic upload to Nginx Proxy Manager, and test certificate generation for development. + +### ✨ Key Features + +- 🔐 **Automatic SSL certificate** issuance via Let's Encrypt +- 🌐 **DNS-01 validation** via reg.ru API (wildcard domain support) +- 🔄 **Automatic renewal** with configurable threshold +- 📦 **Nginx Proxy Manager integration** - automatic upload and update +- 🧪 **Test certificates** - bypass Let's Encrypt rate limits (5 per week) +- ⚙️ **Full automation** via systemd/cron +- 🔀 **Repository sync** - automatic Gitea → GitHub synchronization + +### 🚀 Quick Start + +```bash +# Install via Makefile +sudo make install + +# Configure +sudo nano /etc/letsencrypt/regru_config.json + +# Create test certificate (no limits) +sudo make test-cert + +# Get production certificate +sudo make obtain +``` + +### 📋 Requirements + +- **OS**: Linux (Ubuntu/Debian/CentOS) +- **Python**: 3.6+ +- **Dependencies**: certbot, requests, cryptography +- **API**: reg.ru (DNS management access) +- **Optional**: Nginx Proxy Manager + +### 🎯 Use Cases + +- ✅ SSL certificate automation for web servers +- ✅ Centralized management via Nginx Proxy Manager +- ✅ Development and testing with self-signed certificates +- ✅ CI/CD integration +- ✅ Multi-domain configurations with wildcards + +### 📚 Documentation + +- [README.md](README.md) - Complete guide (1400+ lines) +- [TESTING_GUIDE.md](TESTING_GUIDE.md) - Testing guide +- [GITEA_SYNC.md](GITEA_SYNC.md) - Gitea → GitHub sync +- [CHEATSHEET.md](CHEATSHEET.md) - Quick reference + +--- + +## 👤 Автор / Author + +**Фофанов Дмитрий** @ 2025 + +## 📄 Лицензия / License + +Open Source - Free to use + +## 🤝 Вклад / Contributing + +Pull requests приветствуются / Pull requests are welcome! + +## 🔗 Ссылки / Links + +- **Документация reg.ru API**: https://www.reg.ru/support/api +- **Let's Encrypt**: https://letsencrypt.org/ +- **Nginx Proxy Manager**: https://nginxproxymanager.com/ diff --git a/DOCS_INDEX.md b/DOCS_INDEX.md new file mode 100644 index 0000000..6c0208f --- /dev/null +++ b/DOCS_INDEX.md @@ -0,0 +1,111 @@ +# 📚 Documentation Index / Индекс документации + +## 🇷🇺 Русская документация / Russian Documentation + +### Основные руководства / Main Guides +- **[README.md](README.md)** - Полное руководство (1,420+ строк) +- **[TESTING_GUIDE.md](TESTING_GUIDE.md)** - Руководство по тестированию +- **[GITEA_SYNC.md](GITEA_SYNC.md)** - Синхронизация Gitea → GitHub +- **[PROJECT_STRUCTURE.md](PROJECT_STRUCTURE.md)** - Структура проекта + +### Справочная информация / Reference +- **[CHEATSHEET.md](CHEATSHEET.md)** - Быстрая шпаргалка +- **[CHANGELOG.md](CHANGELOG.md)** - История изменений +- **[DESCRIPTION.md](DESCRIPTION.md)** - Описание проекта + +### Git Hooks +- **[gitea-hooks/README.md](gitea-hooks/README.md)** - Установка Git hooks + +--- + +## 🇬🇧 English Documentation / Английская документация + +### Main Guides / Основные руководства +- **[README_EN.md](README_EN.md)** - Complete Guide (Coming Soon) +- **[TESTING_GUIDE_EN.md](TESTING_GUIDE_EN.md)** - Testing Guide ✅ +- **[GITEA_SYNC_EN.md](GITEA_SYNC_EN.md)** - Gitea → GitHub Sync ✅ +- **[PROJECT_STRUCTURE_EN.md](PROJECT_STRUCTURE_EN.md)** - Project Structure ✅ + +### Reference / Справочная информация +- **[CHEATSHEET_EN.md](CHEATSHEET_EN.md)** - Quick Reference ✅ +- **[CHANGELOG_EN.md](CHANGELOG_EN.md)** - Change History ✅ +- **[DESCRIPTION.md](DESCRIPTION.md)** - Project Description (Bilingual) ✅ + +### Git Hooks +- **[gitea-hooks/README_EN.md](gitea-hooks/README_EN.md)** - Git Hooks Installation ✅ + +--- + +## 📖 Quick Links / Быстрые ссылки + +### For Users / Для пользователей +| Topic | Russian | English | +|-------|---------|---------| +| Getting Started | [README.md](README.md) | [README_EN.md](README_EN.md) | +| Testing Certificates | [TESTING_GUIDE.md](TESTING_GUIDE.md) | [TESTING_GUIDE_EN.md](TESTING_GUIDE_EN.md) | +| Quick Commands | [CHEATSHEET.md](CHEATSHEET.md) | [CHEATSHEET_EN.md](CHEATSHEET_EN.md) | + +### For Developers / Для разработчиков +| Topic | Russian | English | +|-------|---------|---------| +| Project Structure | [PROJECT_STRUCTURE.md](PROJECT_STRUCTURE.md) | [PROJECT_STRUCTURE_EN.md](PROJECT_STRUCTURE_EN.md) | +| Repository Sync | [GITEA_SYNC.md](GITEA_SYNC.md) | [GITEA_SYNC_EN.md](GITEA_SYNC_EN.md) | +| Changelog | [CHANGELOG.md](CHANGELOG.md) | [CHANGELOG_EN.md](CHANGELOG_EN.md) | + +--- + +## 🚀 Quick Start / Быстрый старт + +### Installation / Установка +```bash +sudo make install +sudo nano /etc/letsencrypt/regru_config.json +sudo make test-cert +``` + +### Documentation Priority / Приоритет документации +1. Start here / Начните здесь: **README.md** / **README_EN.md** +2. Testing / Тестирование: **TESTING_GUIDE.md** / **TESTING_GUIDE_EN.md** +3. Quick ref / Шпаргалка: **CHEATSHEET.md** / **CHEATSHEET_EN.md** + +--- + +## 📊 Documentation Status / Статус документации + +| File | Russian | English | Lines | Status | +|------|---------|---------|-------|--------| +| Main Guide | ✅ | 🔄 | 1,420+ | RU Complete | +| Testing Guide | ✅ | ✅ | 370+ | Both Complete | +| Cheatsheet | ✅ | ✅ | 200+ | Both Complete | +| Project Structure | ✅ | ✅ | 200+ | Both Complete | +| Gitea Sync | ✅ | ✅ | 400+ | Both Complete | +| Changelog | ✅ | ✅ | 150+ | Both Complete | +| Git Hooks | ✅ | ✅ | 100+ | Both Complete | + +**Legend:** +- ✅ Complete / Готово +- 🔄 In Progress / В разработке +- ❌ Not Started / Не начато + +--- + +## 🎯 Choose Your Language / Выберите язык + +### Prefer Russian? / Предпочитаете русский? +👉 Начните с [README.md](README.md) + +### Prefer English? / Предпочитаете английский? +👉 Start with [README_EN.md](README_EN.md) or [DESCRIPTION.md](DESCRIPTION.md) + +--- + +## 💡 Contributing / Вклад + +Help us translate / Помогите с переводом: +- [ ] Complete README_EN.md / Завершить README_EN.md +- [ ] Translate docs/ folder / Перевести папку docs/ + +--- + +**Last Updated / Обновлено**: October 27, 2025 +**Maintained by / Поддерживает**: Фофанов Дмитрий diff --git a/GITEA_SYNC.md b/GITEA_SYNC.md new file mode 100644 index 0000000..ac9d29b --- /dev/null +++ b/GITEA_SYNC.md @@ -0,0 +1,395 @@ +# 🔄 Синхронизация Gitea → GitHub + +Автоматическая синхронизация репозитория из Gitea в GitHub после каждого push. + +--- + +## 📋 Доступные методы + +| Метод | Сложность | Скорость | Надежность | Рекомендация | +|-------|-----------|----------|------------|--------------| +| **1. Git Hooks** | ⭐⭐ | ⚡ Мгновенно | ✅ Высокая | Рекомендуется | +| **2. GitHub Actions** | ⭐⭐⭐ | ⏱️ 1-5 мин | ✅ Высокая | Для сложных сценариев | +| **3. Gitea Mirror** | ⭐ | ⏱️ По расписанию | ⭐⭐ Средняя | Самый простой | +| **4. Двойной Remote** | ⭐ | ⚡ Мгновенно | ⭐⭐ Средняя | Локальная работа | + +--- + +## 🚀 Метод 1: Git Hooks (Рекомендуется) + +### Установка + +**1. На сервере Gitea найдите путь к репозиторию:** +```bash +# Обычно это: +/var/lib/gitea/data/gitea-repositories/username/configure_nginx_manager.git +# Или +/home/git/gitea-repositories/username/configure_nginx_manager.git +``` + +**2. Создайте post-receive hook:** +```bash +cd /path/to/gitea/repos/username/configure_nginx_manager.git/hooks/ +nano post-receive +``` + +**3. Вставьте содержимое** из файла `gitea-hooks/post-receive` (в этом репозитории) + +**4. Настройте параметры:** +```bash +# В файле post-receive измените: +GITHUB_REPO="git@github.com:YOUR_USERNAME/configure_nginx_manager.git" +# Или для HTTPS с токеном: +GITHUB_REPO="https://YOUR_TOKEN@github.com/YOUR_USERNAME/configure_nginx_manager.git" +``` + +**5. Сделайте скрипт исполняемым:** +```bash +chmod +x post-receive +``` + +**6. Создайте директорию для логов:** +```bash +mkdir -p /var/log/gitea +chown git:git /var/log/gitea +``` + +### Настройка SSH ключей (для git@github.com) + +**На сервере Gitea:** +```bash +# Переключитесь на пользователя git +sudo su - git + +# Создайте SSH ключ +ssh-keygen -t ed25519 -C "gitea-to-github-sync" + +# Скопируйте публичный ключ +cat ~/.ssh/id_ed25519.pub +``` + +**На GitHub:** +1. Settings → SSH and GPG keys +2. New SSH key +3. Вставьте публичный ключ +4. Save + +**Проверка:** +```bash +ssh -T git@github.com +# Должно вывести: Hi username! You've successfully authenticated... +``` + +### Настройка токена (для HTTPS) + +**На GitHub:** +1. Settings → Developer settings → Personal access tokens → Tokens (classic) +2. Generate new token +3. Выберите scope: `repo` (полный доступ к репозиториям) +4. Скопируйте токен + +**В hook файле:** +```bash +GITHUB_REPO="https://ghp_YOUR_TOKEN_HERE@github.com/username/configure_nginx_manager.git" +``` + +### Тестирование + +```bash +# Сделайте тестовый commit в Gitea +cd /tmp +git clone http://gitea.example.com/username/configure_nginx_manager.git +cd configure_nginx_manager +echo "test" >> README.md +git add README.md +git commit -m "Test sync to GitHub" +git push + +# Проверьте лог +tail -f /var/log/gitea/github-sync.log + +# Проверьте GitHub - изменения должны появиться +``` + +--- + +## 🔄 Метод 2: GitHub Actions + +### Установка + +**1. Создайте workflow в GitHub репозитории:** + +Файл уже создан: `.github/workflows/sync-from-gitea.yml` + +**2. Настройте секреты в GitHub:** + +GitHub Repository → Settings → Secrets and variables → Actions → New repository secret + +Добавьте: +- **Name**: `GITEA_URL` + - **Value**: `https://gitea.example.com/username/configure_nginx_manager.git` + +- **Name**: `GITEA_TOKEN` + - **Value**: Токен доступа Gitea + +### Получение токена Gitea + +**В Gitea:** +1. Settings → Applications → Generate New Token +2. Token Name: "GitHub Sync" +3. Select permissions: `read:repository` +4. Generate Token +5. Скопируйте токен + +### Запуск синхронизации + +**Автоматически (по расписанию):** +- Каждый час проверяет изменения + +**Вручную:** +1. GitHub → Actions +2. Выберите workflow "Sync from Gitea" +3. Run workflow + +**Через webhook от Gitea:** + +В Gitea репозитории: +1. Settings → Webhooks → Add Webhook → Gitea +2. Target URL: `https://api.github.com/repos/USERNAME/configure_nginx_manager/dispatches` +3. HTTP Method: `POST` +4. POST Content Type: `application/json` +5. Secret: оставьте пустым или используйте +6. Trigger On: `Push events` +7. Body: +```json +{ + "event_type": "gitea-push" +} +``` + +--- + +## 🪞 Метод 3: Gitea Mirror (Встроенная функция) + +### Настройка + +**В Gitea репозитории:** +1. Settings → Repository +2. Прокрутите до "Mirror Settings" +3. Нажмите "Add Push Mirror" +4. Заполните: + - **Git Remote Repository URL**: `https://github.com/username/configure_nginx_manager.git` + - **Username**: ваш GitHub username + - **Password**: GitHub Personal Access Token + - **Sync Interval**: `8h` (каждые 8 часов) или `0` (только вручную) +5. Save + +### Ручная синхронизация + +Settings → Repository → Mirror Settings → Sync Now + +### Преимущества +- ✅ Встроенная функция +- ✅ Не требует скриптов +- ✅ Управление через веб-интерфейс + +### Недостатки +- ⚠️ Работает по расписанию (не мгновенно) +- ⚠️ Доступно не во всех версиях Gitea + +--- + +## 🔀 Метод 4: Двойной Remote + +### Для локальной работы + +**Настройка:** +```bash +# В вашем локальном репозитории +cd configure_nginx_manager + +# Добавьте GitHub как второй remote +git remote add github git@github.com:username/configure_nginx_manager.git + +# Или настройте push в оба репозитория одновременно +git remote set-url --add --push origin git@github.com:username/configure_nginx_manager.git + +# Проверьте +git remote -v +``` + +**Использование:** +```bash +# Обычный push (только в Gitea) +git push origin main + +# Push в GitHub +git push github main + +# Push в оба репозитория +git push origin main +git push github main + +# Или создайте alias +git config alias.pushall '!git push origin main && git push github main' +git pushall +``` + +--- + +## 🔍 Проверка синхронизации + +### Проверка через Git + +```bash +# Сравнить коммиты +git ls-remote git@gitea.example.com:username/configure_nginx_manager.git +git ls-remote git@github.com:username/configure_nginx_manager.git + +# Должны быть одинаковые SHA +``` + +### Проверка логов (Метод 1 - Hooks) + +```bash +# На сервере Gitea +tail -f /var/log/gitea/github-sync.log +``` + +### Проверка GitHub Actions (Метод 2) + +1. GitHub Repository → Actions +2. Смотрите последние запуски +3. Проверьте логи выполнения + +--- + +## ⚙️ Рекомендованная конфигурация + +Для максимальной надежности используйте **комбинацию методов**: + +1. **Git Hook** (основной) - мгновенная синхронизация +2. **GitHub Actions** (резервный) - проверка каждый час на случай сбоя hook + +### Установка обоих методов + +```bash +# 1. Установите Git Hook на сервере Gitea +# (см. Метод 1) + +# 2. Настройте GitHub Actions +# (см. Метод 2) + +# 3. GitHub Actions будет подхватывать пропущенные изменения +``` + +--- + +## 🐛 Устранение проблем + +### Проблема: Hook не срабатывает + +**Проверка:** +```bash +# На сервере Gitea +ls -la /path/to/repo.git/hooks/post-receive +# Должно быть -rwxr-xr-x + +# Проверьте права +chmod +x /path/to/repo.git/hooks/post-receive +chown git:git /path/to/repo.git/hooks/post-receive + +# Проверьте лог ошибок Gitea +tail -f /var/log/gitea/gitea.log +``` + +### Проблема: Permission denied (SSH) + +**Решение:** +```bash +# Убедитесь что SSH ключ добавлен в GitHub +ssh -T git@github.com + +# Проверьте права на .ssh +chmod 700 ~/.ssh +chmod 600 ~/.ssh/id_ed25519 +``` + +### Проблема: Authentication failed (HTTPS) + +**Решение:** +- Проверьте токен GitHub (должен иметь scope `repo`) +- Токен не истёк +- Правильный формат URL: `https://TOKEN@github.com/user/repo.git` + +### Проблема: GitHub Actions не запускается + +**Решение:** +1. Проверьте секреты в Settings → Secrets +2. Проверьте формат webhook от Gitea +3. Запустите вручную для теста + +--- + +## 📊 Сравнение методов + +### Скорость синхронизации +- **Git Hooks**: ⚡ < 1 секунды +- **GitHub Actions (webhook)**: ⏱️ 10-30 секунд +- **GitHub Actions (schedule)**: ⏱️ до 1 часа +- **Gitea Mirror**: ⏱️ по расписанию + +### Надежность +- **Git Hooks**: ⭐⭐⭐⭐⭐ (при правильной настройке) +- **GitHub Actions**: ⭐⭐⭐⭐⭐ (очень надежно) +- **Gitea Mirror**: ⭐⭐⭐ (зависит от версии Gitea) +- **Двойной Remote**: ⭐⭐ (требует ручного действия) + +--- + +## 🎯 Итоговая рекомендация + +Для проекта `configure_nginx_manager`: + +**1. Основной метод: Git Hook** +- Быстро +- Надежно +- Автоматически + +**2. Резервный метод: GitHub Actions** +- Проверка каждый час +- Подхватит пропущенные изменения +- Можно запустить вручную + +**3. Мониторинг:** +```bash +# Еженедельная проверка +git ls-remote origin | head -1 +git ls-remote github | head -1 +# SHA должны совпадать +``` + +--- + +## 📝 Быстрая установка + +```bash +# На сервере Gitea +sudo su - git +cd /path/to/gitea-repositories/username/configure_nginx_manager.git/hooks/ + +# Скачайте hook +wget https://raw.githubusercontent.com/username/configure_nginx_manager/main/gitea-hooks/post-receive + +# Настройте +nano post-receive +# Измените GITHUB_REPO + +# Права +chmod +x post-receive + +# Тест +echo "test" | ./post-receive +``` + +Готово! 🎉 diff --git a/GITEA_SYNC_EN.md b/GITEA_SYNC_EN.md new file mode 100644 index 0000000..53aeeda --- /dev/null +++ b/GITEA_SYNC_EN.md @@ -0,0 +1,408 @@ +# 🔄 Gitea → GitHub Synchronization + +Automatic repository synchronization from Gitea to GitHub after each push. + +--- + +## 📋 Available Methods + +| Method | Complexity | Speed | Reliability | Recommendation | +|--------|------------|-------|-------------|----------------| +| **1. Git Hooks** | ⭐⭐ | ⚡ Instant | ✅ High | Recommended | +| **2. GitHub Actions** | ⭐⭐⭐ | ⏱️ 1-5 min | ✅ High | Complex scenarios | +| **3. Gitea Mirror** | ⭐ | ⏱️ Scheduled | ⭐⭐ Medium | Simplest | +| **4. Double Remote** | ⭐ | ⚡ Instant | ⭐⭐ Medium | Local work | + +--- + +## 🚀 Method 1: Git Hooks (Recommended) + +### Installation + +**1. On Gitea server, find repository path:** +```bash +# Usually: +/var/lib/gitea/data/gitea-repositories/username/configure_nginx_manager.git +# Or +/home/git/gitea-repositories/username/configure_nginx_manager.git +``` + +**2. Create post-receive hook:** +```bash +cd /path/to/gitea/repos/username/configure_nginx_manager.git/hooks/ +nano post-receive +``` + +**3. Insert content** from `gitea-hooks/post-receive` file (in this repository) + +**4. Configure parameters:** +```bash +# In post-receive file, change: +GITHUB_REPO="git@github.com:YOUR_USERNAME/configure_nginx_manager.git" +# Or for HTTPS with token: +GITHUB_REPO="https://YOUR_TOKEN@github.com/YOUR_USERNAME/configure_nginx_manager.git" +``` + +**5. Make script executable:** +```bash +chmod +x post-receive +``` + +**6. Create log directory:** +```bash +mkdir -p /var/log/gitea +chown git:git /var/log/gitea +``` + +### SSH Key Setup (for git@github.com) + +**On Gitea server:** +```bash +# Switch to git user +sudo su - git + +# Create SSH key +ssh-keygen -t ed25519 -C "gitea-to-github-sync" + +# Copy public key +cat ~/.ssh/id_ed25519.pub +``` + +**On GitHub:** +1. Settings → SSH and GPG keys +2. New SSH key +3. Paste public key +4. Save + +**Verification:** +```bash +ssh -T git@github.com +# Should output: Hi username! You've successfully authenticated... +``` + +### Token Setup (for HTTPS) + +**On GitHub:** +1. Settings → Developer settings → Personal access tokens → Tokens (classic) +2. Generate new token +3. Select scope: `repo` (full repository access) +4. Copy token + +**In hook file:** +```bash +GITHUB_REPO="https://ghp_YOUR_TOKEN_HERE@github.com/username/configure_nginx_manager.git" +``` + +### Testing + +```bash +# Make test commit in Gitea +cd /tmp +git clone http://gitea.example.com/username/configure_nginx_manager.git +cd configure_nginx_manager +echo "test" >> README.md +git add README.md +git commit -m "Test sync to GitHub" +git push + +# Check log +tail -f /var/log/gitea/github-sync.log + +# Check GitHub - changes should appear +``` + +--- + +## 🔄 Method 2: GitHub Actions + +### Installation + +**1. Create workflow in GitHub repository:** + +File already created: `.github/workflows/sync-from-gitea.yml` + +**2. Configure secrets in GitHub:** + +GitHub Repository → Settings → Secrets and variables → Actions → New repository secret + +Add: +- **Name**: `GITEA_URL` + - **Value**: `https://gitea.example.com/username/configure_nginx_manager.git` + +- **Name**: `GITEA_TOKEN` + - **Value**: Gitea access token + +### Getting Gitea Token + +**In Gitea:** +1. Settings → Applications → Generate New Token +2. Token Name: "GitHub Sync" +3. Select permissions: `read:repository` +4. Generate Token +5. Copy token + +### Running Sync + +**Automatically (scheduled):** +- Checks for changes every hour + +**Manually:** +1. GitHub → Actions +2. Select workflow "Sync from Gitea" +3. Run workflow + +**Via Gitea webhook:** + +In Gitea repository: +1. Settings → Webhooks → Add Webhook → Gitea +2. Target URL: `https://api.github.com/repos/USERNAME/configure_nginx_manager/dispatches` +3. HTTP Method: `POST` +4. POST Content Type: `application/json` +5. Trigger On: `Push events` +6. Body: +```json +{ + "event_type": "gitea-push" +} +``` + +--- + +## 🪞 Method 3: Gitea Mirror (Built-in) + +### Setup + +**In Gitea repository:** +1. Settings → Repository +2. Scroll to "Mirror Settings" +3. Click "Add Push Mirror" +4. Fill in: + - **Git Remote Repository URL**: `https://github.com/username/configure_nginx_manager.git` + - **Username**: your GitHub username + - **Password**: GitHub Personal Access Token + - **Sync Interval**: `8h` (every 8 hours) or `0` (manual only) +5. Save + +### Manual Sync + +Settings → Repository → Mirror Settings → Sync Now + +### Advantages +- ✅ Built-in feature +- ✅ No scripts required +- ✅ Web interface management + +### Disadvantages +- ⚠️ Works on schedule (not instant) +- ⚠️ Not available in all Gitea versions + +--- + +## 🔀 Method 4: Double Remote + +### For Local Work + +**Setup:** +```bash +# In your local repository +cd configure_nginx_manager + +# Add GitHub as second remote +git remote add github git@github.com:username/configure_nginx_manager.git + +# Or configure push to both repositories simultaneously +git remote set-url --add --push origin git@github.com:username/configure_nginx_manager.git + +# Verify +git remote -v +``` + +**Usage:** +```bash +# Normal push (Gitea only) +git push origin main + +# Push to GitHub +git push github main + +# Push to both repositories +git push origin main +git push github main + +# Or create alias +git config alias.pushall '!git push origin main && git push github main' +git pushall +``` + +--- + +## 🔍 Sync Verification + +### Check via Git + +```bash +# Compare commits +git ls-remote git@gitea.example.com:username/configure_nginx_manager.git +git ls-remote git@github.com:username/configure_nginx_manager.git + +# Should have identical SHA +``` + +### Check Logs (Method 1 - Hooks) + +```bash +# On Gitea server +tail -f /var/log/gitea/github-sync.log +``` + +### Check GitHub Actions (Method 2) + +1. GitHub Repository → Actions +2. View recent runs +3. Check execution logs + +--- + +## ⚙️ Recommended Configuration + +For maximum reliability, use **combination of methods**: + +1. **Git Hook** (primary) - instant sync +2. **GitHub Actions** (backup) - hourly check in case of hook failure + +### Installing Both Methods + +```bash +# 1. Install Git Hook on Gitea server +# (see Method 1) + +# 2. Configure GitHub Actions +# (see Method 2) + +# 3. GitHub Actions will catch missed changes +``` + +--- + +## 🐛 Troubleshooting + +### Problem: Hook not firing + +**Check:** +```bash +# On Gitea server +ls -la /path/to/repo.git/hooks/post-receive +# Should be -rwxr-xr-x + +# Check permissions +chmod +x /path/to/repo.git/hooks/post-receive +chown git:git /path/to/repo.git/hooks/post-receive + +# Check Gitea error log +tail -f /var/log/gitea/gitea.log +``` + +### Problem: Permission denied (SSH) + +**Solution:** +```bash +# Ensure SSH key is added to GitHub +ssh -T git@github.com + +# Check .ssh permissions +chmod 700 ~/.ssh +chmod 600 ~/.ssh/id_ed25519 +``` + +### Problem: Authentication failed (HTTPS) + +**Solution:** +- Check GitHub token (should have `repo` scope) +- Token not expired +- Correct URL format: `https://TOKEN@github.com/user/repo.git` + +### Problem: GitHub Actions not triggering + +**Solution:** +1. Check secrets in Settings → Secrets +2. Verify webhook format from Gitea +3. Run manually for test + +--- + +## 📊 Method Comparison + +### Sync Speed +- **Git Hooks**: ⚡ < 1 second +- **GitHub Actions (webhook)**: ⏱️ 10-30 seconds +- **GitHub Actions (schedule)**: ⏱️ up to 1 hour +- **Gitea Mirror**: ⏱️ scheduled + +### Reliability +- **Git Hooks**: ⭐⭐⭐⭐⭐ (when properly configured) +- **GitHub Actions**: ⭐⭐⭐⭐⭐ (very reliable) +- **Gitea Mirror**: ⭐⭐⭐ (depends on Gitea version) +- **Double Remote**: ⭐⭐ (requires manual action) + +--- + +## 🎯 Final Recommendation + +For `configure_nginx_manager` project: + +**1. Primary method: Git Hook** +- Fast +- Reliable +- Automatic + +**2. Backup method: GitHub Actions** +- Hourly check +- Catches missed changes +- Can run manually + +**3. Monitoring:** +```bash +# Weekly verification +git ls-remote origin | head -1 +git ls-remote github | head -1 +# SHA should match +``` + +--- + +## 📝 Quick Setup + +```bash +# On Gitea server +sudo su - git +cd /path/to/gitea-repositories/username/configure_nginx_manager.git/hooks/ + +# Download hook +wget https://raw.githubusercontent.com/username/configure_nginx_manager/main/gitea-hooks/post-receive + +# Configure +nano post-receive +# Change GITHUB_REPO + +# Permissions +chmod +x post-receive + +# Test +echo "test" | ./post-receive +``` + +Done! 🎉 + +--- + +## 📚 Additional Resources + +- [Git Hooks Documentation](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) +- [GitHub Actions Documentation](https://docs.github.com/en/actions) +- [Gitea Documentation](https://docs.gitea.io/) + +--- + +**Version**: 1.0 +**Author**: Фофанов Дмитрий +**Date**: October 27, 2025 diff --git a/PROJECT_STRUCTURE.md b/PROJECT_STRUCTURE.md index cdf61c8..cd189d4 100644 --- a/PROJECT_STRUCTURE.md +++ b/PROJECT_STRUCTURE.md @@ -78,10 +78,59 @@ - Частые вопросы - Примеры для CI/CD и Docker +### GITEA_SYNC.md +Синхронизация Gitea → GitHub: +- 4 метода синхронизации (Git Hooks, GitHub Actions, Gitea Mirror, Double Remote) +- Пошаговые инструкции установки +- Настройка SSH и токенов +- Webhook интеграция +- Устранение проблем +- Сравнение методов + +### CHEATSHEET.md +Быстрая шпаргалка: +- Основные команды +- Workflow разработки +- Сценарии использования +- Частые ошибки и решения +- Проверка и отладка + ### PROJECT_STRUCTURE.md (этот файл) - Описание всех файлов проекта - Краткая характеристика каждого компонента +### CHANGELOG.md +История изменений: +- Версии и обновления +- Новые возможности +- Исправления +- Roadmap + +## Интеграция с Git + +### .github/workflows/sync-from-gitea.yml +GitHub Actions для синхронизации: +- Автоматическая проверка каждый час +- Webhook триггер от Gitea +- Ручной запуск +- Merge изменений из Gitea +- Push в GitHub + +### gitea-hooks/ +Git hooks для Gitea сервера: + +**post-receive** +- Автоматический push в GitHub после commit +- Мгновенная синхронизация (< 1 секунды) +- Логирование операций +- Синхронизация тегов +- Поддержка SSH и HTTPS + +**README.md** +- Инструкции по установке hook +- Настройка аутентификации +- Устранение проблем + ## Вспомогательные файлы ### Markdown документы @@ -116,6 +165,13 @@ - [x] Интеграция тестовых сертификатов с NPM - [x] Полная совместимость структуры с Let's Encrypt +### 🔄 Синхронизация репозиториев +- [x] Автоматическая синхронизация Gitea → GitHub +- [x] Git Hooks (мгновенная синхронизация) +- [x] GitHub Actions (проверка каждый час) +- [x] Webhook интеграция +- [x] SSH и HTTPS аутентификация + ## Установка ### Быстрая установка diff --git a/PROJECT_STRUCTURE_EN.md b/PROJECT_STRUCTURE_EN.md new file mode 100644 index 0000000..046b4e7 --- /dev/null +++ b/PROJECT_STRUCTURE_EN.md @@ -0,0 +1,287 @@ +# 📁 configure_nginx_manager Project Structure + +## Main Scripts + +### Python (Recommended) +- **letsencrypt_regru_api.py** (1,411 lines) + - Full-featured Python script + - Direct reg.ru API integration + - Nginx Proxy Manager integration + - Automatic certificate check and renewal + - Test self-signed certificate generation + - Wildcard domain support + +### Bash +- **letsencrypt_regru_dns.sh** + - Bash script with certbot-dns-regru plugin + - Easy to use + - Minimal dependencies + +### PowerShell +- **letsencrypt_regru.ps1** + - Windows version + - Similar to Bash script + +### Testing +- **test_certificate.sh** + - Quick test certificate creation via OpenSSL + - Standalone operation without Python + - Wildcard domain support + +## Automation + +### Makefile +- **Makefile** (415 lines) + - `make install` - Complete installation and setup + - `make uninstall` - Clean removal + - `make status` - Check status + - `make test-cert` - Create test certificate + - `make obtain` - Get Let's Encrypt certificate + - `make renew` - Renew certificate + - `make logs` - View logs + - `make check-config` - Validate configuration + +## Configuration + +### config.json.example +Example configuration with all parameters: +- reg.ru API credentials +- Domain and email settings +- Renewal parameters (renewal_days) +- Nginx Proxy Manager settings +- Directory and log paths + +## Documentation + +### README.md (1,420+ lines) +Main documentation: +- Introduction and features +- Quick start +- Makefile installation +- Test certificate creation +- Requirements and dependencies +- Configuration and usage +- NPM integration +- Automatic check and renewal +- Automation via cron/systemd +- Troubleshooting + +### README_EN.md (English version) +Complete English translation of main guide + +### TESTING_GUIDE.md (370+ lines) +Testing guide: +- Why test certificates are needed +- Bypass Let's Encrypt limits (5 per week) +- Quick start with test certificates +- Method comparison +- Development usage +- Test automation +- Transition from test to production +- FAQ +- CI/CD and Docker examples + +### TESTING_GUIDE_EN.md (English version) +Complete English translation of testing guide + +### GITEA_SYNC.md +Gitea → GitHub synchronization: +- 4 sync methods (Git Hooks, GitHub Actions, Gitea Mirror, Double Remote) +- Step-by-step installation +- SSH and token setup +- Webhook integration +- Troubleshooting +- Method comparison + +### GITEA_SYNC_EN.md (English version) +Complete English translation of sync guide + +### CHEATSHEET.md +Quick reference: +- Main commands +- Development workflow +- Use case scenarios +- Common errors and solutions +- Checking and debugging + +### CHEATSHEET_EN.md (English version) +Complete English translation of cheatsheet + +### PROJECT_STRUCTURE.md (this file) +- All project files description +- Component overview + +### PROJECT_STRUCTURE_EN.md (English version) +Complete English translation of structure + +### DESCRIPTION.md +Project description: +- Russian description +- English description +- Quick start +- Features overview + +### CHANGELOG.md +Change history: +- Versions and updates +- New features +- Bug fixes +- Roadmap + +### CHANGELOG_EN.md (English version) +Complete English translation of changelog + +## Git Integration + +### .github/workflows/sync-from-gitea.yml +GitHub Actions for synchronization: +- Automatic check every hour +- Webhook trigger from Gitea +- Manual run +- Merge changes from Gitea +- Push to GitHub + +### gitea-hooks/ +Git hooks for Gitea server: + +**post-receive** +- Automatic push to GitHub after commit +- Instant sync (< 1 second) +- Operation logging +- Tag synchronization +- SSH and HTTPS support + +**README.md** +- Hook installation instructions +- Authentication setup +- Troubleshooting + +**README_EN.md** (English version) +Complete English translation + +## Additional Files + +### Markdown Documents +- **Add Let's Encrypt Certificate для провайдера reg.ru.md** + - Initial instructions (Russian) + +- **Создание и продление SSL сертификата.md** + - Additional process information (Russian) + +## Features + +### ✅ Core Features +- [x] Let's Encrypt certificates via reg.ru DNS API +- [x] Wildcard certificates (*.domain.com) +- [x] Automatic certificate renewal +- [x] DNS-01 validation +- [x] Nginx Proxy Manager integration +- [x] Automatic upload/update to NPM + +### ✅ Advanced Features +- [x] Automatic expiration check +- [x] Configurable renewal threshold (renewal_days) +- [x] Systemd service + timer +- [x] Cron automation +- [x] Detailed logging +- [x] Configuration validation + +### 🆕 Testing +- [x] Self-signed test certificate generation +- [x] Bypass Let's Encrypt limits (5/week) +- [x] Instant creation without DNS +- [x] Test certificate NPM integration +- [x] Full structure compatibility with Let's Encrypt + +### 🔄 Repository Sync +- [x] Automatic Gitea → GitHub sync +- [x] Git Hooks (instant sync) +- [x] GitHub Actions (hourly check) +- [x] Webhook integration +- [x] SSH and HTTPS authentication + +## Installation + +### Quick Install +```bash +sudo make install +sudo nano /etc/letsencrypt/regru_config.json +sudo make test-cert # For testing +sudo make obtain # For production +``` + +### Post-Install Structure +``` +/opt/letsencrypt-regru/ +├── letsencrypt_regru_api.py + +/etc/letsencrypt/ +├── regru_config.json +└── live/ + └── example.com/ + ├── privkey.pem + ├── cert.pem + ├── fullchain.pem + └── chain.pem + +/etc/systemd/system/ +├── letsencrypt-regru.service +└── letsencrypt-regru.timer + +/var/log/letsencrypt/ +└── letsencrypt_regru.log +``` + +## Usage + +### Testing (no limits) +```bash +sudo make test-cert # Create test certificate +sudo make status # Check status +``` + +### Production +```bash +sudo make obtain # Get Let's Encrypt certificate +sudo make renew # Renew certificate +sudo make run # Automatic mode +``` + +### Monitoring +```bash +sudo make logs # View logs +sudo make status # Service status +sudo make check-config # Check configuration +``` + +## Technologies + +- **Python 3.6+** - Main language +- **Certbot** - Let's Encrypt client +- **requests** - HTTP API requests +- **cryptography** - Test certificate generation +- **systemd** - Launch automation +- **cron** - Alternative automation +- **Make** - Installation management +- **OpenSSL** - Alternative certificate generation + +## License + +Open Source - Free to use + +## Author + +Фофанов Дмитрий @ 2025 + +## Support + +See documentation: +- [README.md](README.md) / [README_EN.md](README_EN.md) - Main guide +- [TESTING_GUIDE.md](TESTING_GUIDE.md) / [TESTING_GUIDE_EN.md](TESTING_GUIDE_EN.md) - Testing guide +- [GITEA_SYNC.md](GITEA_SYNC.md) / [GITEA_SYNC_EN.md](GITEA_SYNC_EN.md) - Repository sync + +--- + +**Version**: 2.1 +**Date**: October 27, 2025 +**Status**: ✅ Production Ready diff --git a/README.md b/README.md index b2cf63b..0af7f2e 100644 --- a/README.md +++ b/README.md @@ -1379,7 +1379,9 @@ server { ## Дополнительная документация - 📘 **[TESTING_GUIDE.md](TESTING_GUIDE.md)** - Полное руководство по созданию и использованию тестовых сертификатов -- 🚀 **[Makefile](Makefile)** - Автоматизация установки и управления +- � **[GITEA_SYNC.md](GITEA_SYNC.md)** - Настройка автоматической синхронизации Gitea → GitHub +- 📘 **[CHEATSHEET.md](CHEATSHEET.md)** - Быстрая шпаргалка по командам +- �🚀 **[Makefile](Makefile)** - Автоматизация установки и управления - 📝 **[config.json.example](config.json.example)** - Пример конфигурации --- @@ -1418,3 +1420,25 @@ sudo make obtain # Получить production сертификат Успешной автоматизации! 🔒 +--- + +## 🔄 Синхронизация Gitea → GitHub + +Проект поддерживает автоматическую синхронизацию из Gitea в GitHub. + +### Быстрая настройка + +**Метод 1: Git Hook (мгновенно)** +```bash +# На сервере Gitea скопируйте hook +cp gitea-hooks/post-receive /path/to/repo.git/hooks/ +chmod +x /path/to/repo.git/hooks/post-receive +``` + +**Метод 2: GitHub Actions (каждый час)** +- Workflow уже настроен в `.github/workflows/sync-from-gitea.yml` +- Добавьте секреты `GITEA_URL` и `GITEA_TOKEN` в GitHub + +**Подробная документация**: См. [GITEA_SYNC.md](GITEA_SYNC.md) + +--- diff --git a/TESTING_GUIDE_EN.md b/TESTING_GUIDE_EN.md new file mode 100644 index 0000000..29e9686 --- /dev/null +++ b/TESTING_GUIDE_EN.md @@ -0,0 +1,379 @@ +# 🧪 SSL Certificate Testing Guide + +## Why do you need test certificates? + +Let's Encrypt has **strict limits**: +- ⚠️ Maximum **5 certificates per week** per domain +- ⚠️ Maximum **50 certificates per week** per account +- ⚠️ **1 week ban** if limits exceeded + +**Solution**: Use self-signed test certificates for development! + +--- + +## Quick Start + +### Option 1: Via Makefile (Recommended) + +```bash +# After script installation (make install) +sudo make test-cert +``` + +**Result**: Certificate created in `/etc/letsencrypt/live/your-domain/` + +### Option 2: Via Python Script + +```bash +sudo python3 letsencrypt_regru_api.py \ + --config /etc/letsencrypt/regru_config.json \ + --test-cert -v +``` + +### Option 3: Via Bash Script (Standalone) + +```bash +# Simple domain +sudo ./test_certificate.sh example.com no + +# With wildcard +sudo ./test_certificate.sh example.com yes +``` + +--- + +## Method Comparison + +| Method | Speed | Requirements | NPM Integration | Limits | +|--------|-------|--------------|-----------------|--------| +| **Let's Encrypt** | 2-5 min | Internet, DNS | ✅ Yes | ⚠️ 5/week | +| **Test (Python)** | 1-2 sec | Python only | ✅ Yes | ✅ None | +| **Test (Bash)** | 1-2 sec | OpenSSL only | ❌ Manual | ✅ None | + +--- + +## Detailed Instructions + +### 1. Configuration Setup + +```bash +# Create configuration +sudo nano /etc/letsencrypt/regru_config.json +``` + +```json +{ + "domain": "test.example.com", + "wildcard": true, + "cert_dir": "/etc/letsencrypt/live", + "npm_enabled": true, + "npm_host": "https://npm.example.com", + "npm_email": "admin@example.com", + "npm_password": "your_password" +} +``` + +### 2. Create Test Certificate + +```bash +sudo make test-cert +``` + +### 3. Verify Created Files + +```bash +ls -la /etc/letsencrypt/live/test.example.com/ +# Should contain: +# - privkey.pem (private key) +# - cert.pem (certificate) +# - fullchain.pem (full chain) +# - chain.pem (CA chain) +``` + +### 4. View Certificate Information + +```bash +openssl x509 -in /etc/letsencrypt/live/test.example.com/cert.pem -text -noout +``` + +--- + +## Using in Nginx + +### Direct Usage + +```nginx +server { + listen 443 ssl; + server_name test.example.com; + + ssl_certificate /etc/letsencrypt/live/test.example.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/test.example.com/privkey.pem; + + # ... rest of configuration +} +``` + +### Via Nginx Proxy Manager + +If `npm_enabled: true` in configuration, certificate will automatically upload to NPM. + +**Check in NPM:** +1. Open NPM web interface +2. Go to **SSL Certificates** +3. Find your domain in the list +4. ⚠️ Will be marked as "Custom" (not Let's Encrypt) + +--- + +## Test Automation + +### CI/CD Script + +```bash +#!/bin/bash +# test_ssl_integration.sh + +set -e + +echo "🧪 Testing SSL integration..." + +# 1. Create test certificate +sudo python3 letsencrypt_regru_api.py \ + --config test_config.json \ + --test-cert + +# 2. Verify files +if [ ! -f "/etc/letsencrypt/live/test.example.com/fullchain.pem" ]; then + echo "❌ Certificate not created" + exit 1 +fi + +# 3. Check validity +openssl x509 -in /etc/letsencrypt/live/test.example.com/cert.pem -noout -checkend 0 +if [ $? -eq 0 ]; then + echo "✅ Certificate is valid" +else + echo "❌ Certificate is invalid" + exit 1 +fi + +echo "✅ All tests passed" +``` + +### Makefile for Testing + +```makefile +.PHONY: test-ssl test-npm test-all + +test-ssl: + @echo "Creating test certificate..." + sudo make test-cert + @echo "Verifying files..." + test -f /etc/letsencrypt/live/$(DOMAIN)/fullchain.pem + @echo "✅ SSL test passed" + +test-npm: + @echo "Checking NPM integration..." + # Your NPM API checks + @echo "✅ NPM test passed" + +test-all: test-ssl test-npm + @echo "✅ All tests passed" +``` + +--- + +## Transition to Production + +### Step 1: Testing + +```bash +# 1. Create test certificate +sudo make test-cert + +# 2. Verify with NPM +# Open https://your-domain and check + +# 3. Ensure everything works +``` + +### Step 2: Switch to Let's Encrypt + +```bash +# 1. Remove test certificate +sudo rm -rf /etc/letsencrypt/live/your-domain/ + +# 2. Get real certificate +sudo make obtain + +# 3. Verify update in NPM +sudo make status +``` + +--- + +## FAQ + +### Q: Why does browser show warning? + +**A:** Self-signed certificates are not trusted by browsers. This is normal for testing. + +To avoid browser warning (local testing only): +1. Chrome: `chrome://flags/#allow-insecure-localhost` +2. Firefox: Click "Advanced" → "Accept the Risk" + +### Q: Can I use in production? + +**A:** ❌ **NO!** Test certificates are for development and testing only. + +### Q: How often can I create test certificates? + +**A:** ✅ Unlimited! No limits whatsoever. + +### Q: Do they upload to NPM automatically? + +**A:** ✅ Yes, if `npm_enabled: true` in configuration. + +### Q: Do they work with wildcard domains? + +**A:** ✅ Yes! Just set `"wildcard": true` in configuration. + +### Q: How to check expiration date? + +```bash +openssl x509 -in /etc/letsencrypt/live/your-domain/cert.pem -noout -dates +``` + +### Q: How to change validity period? + +Edit `validity_days` in `generate_self_signed_certificate()` function: + +```python +validity_days: int = 365 # Change to desired number of days +``` + +--- + +## Troubleshooting + +### Error: Permission denied + +```bash +# Run with sudo +sudo make test-cert +``` + +### Error: Module 'cryptography' not found + +```bash +# Install dependencies +sudo pip3 install cryptography +``` + +### NPM doesn't show certificate + +1. Check NPM settings in configuration +2. Check logs: `sudo make logs` +3. Try uploading manually via NPM web interface + +### Certificate not created + +```bash +# Check permissions +ls -la /etc/letsencrypt/live/ + +# Create directory manually +sudo mkdir -p /etc/letsencrypt/live/ + +# Check configuration +sudo make check-config +``` + +--- + +## Usage Examples + +### Docker Development + +```dockerfile +FROM nginx:alpine + +# Copy test certificate +COPY test-certs/ /etc/nginx/ssl/ + +# Nginx configuration +COPY nginx.conf /etc/nginx/nginx.conf + +EXPOSE 443 +``` + +### Local Testing + +```bash +# Create certificate for localhost +sudo python3 letsencrypt_regru_api.py --test-cert + +# Add to /etc/hosts +echo "127.0.0.1 test.example.com" | sudo tee -a /etc/hosts + +# Start nginx +sudo nginx -t && sudo nginx -s reload + +# Open in browser +open https://test.example.com +``` + +### Automated Testing Before Deployment + +```bash +#!/bin/bash +# pre-deploy.sh + +# Test SSL check +sudo make test-cert +if [ $? -eq 0 ]; then + echo "✅ Test certificate created successfully" + echo "✅ Ready for production certificate" + sudo make obtain +else + echo "❌ Error creating test certificate" + exit 1 +fi +``` + +--- + +## Additional Resources + +- 📘 [Let's Encrypt Rate Limits](https://letsencrypt.org/docs/rate-limits/) +- 📘 [OpenSSL Documentation](https://www.openssl.org/docs/) +- 📘 [Nginx Proxy Manager Docs](https://nginxproxymanager.com/guide/) + +--- + +## Quick Reference + +```bash +# Installation +sudo make install + +# Configuration +sudo nano /etc/letsencrypt/regru_config.json + +# Create test certificate +sudo make test-cert + +# Verify +sudo make check-config +sudo make status + +# Switch to production +sudo rm -rf /etc/letsencrypt/live/domain/ +sudo make obtain + +# Automatic renewal +sudo make run +``` + +**Done!** 🎉 Now you can test SSL certificates without limits! diff --git a/docs/Add_Lets_Encrypt_Certificate_for_regru_Provider_EN.md b/docs/Add_Lets_Encrypt_Certificate_for_regru_Provider_EN.md new file mode 100644 index 0000000..2e88fa9 --- /dev/null +++ b/docs/Add_Lets_Encrypt_Certificate_for_regru_Provider_EN.md @@ -0,0 +1,56 @@ +# Guide to Creating Let's Encrypt Certificate with DNS Challenge for reg.ru Provider in Nginx Proxy Manager + +--- + +## Prerequisites +- Access to Nginx Proxy Manager (NPM) +- Access to reg.ru account with DNS management permissions +- API key for DNS management in reg.ru (if automatic integration is available) +- Need to obtain certificate for `*.dfv24.com` (wildcard certificate) + +--- + +## Step 1. Getting API Key for reg.ru + +1. Log in to reg.ru control panel +2. Navigate to API management section (if supported) +3. Create or find API key with DNS records editing permissions +4. Save API key and secret (Client ID and API Token) + +--- + +## Step 2. Configuring Nginx Proxy Manager to Use DNS Challenge reg.ru + +1. In NPM admin panel, go to **SSL Certificates → Add SSL Certificate** +2. Select **Let's Encrypt** -> **DNS Challenge** +3. In **Provider** field, select `reg_ru` or `custom` (if provider not available, script will be needed) +4. Fill in API fields with required parameters: + - Client ID + - API Token +5. In **Domain Names** field, specify: + `*.dfv24.com` (for wildcard certificate) + and main domain `dfv24.com` +6. Enable other options (Terms of Service, Email) +7. Click **Save** to request certificate +8. NPM will automatically add DNS TXT records for domain ownership verification through reg.ru API + +--- + +## Step 3. Verification and Automatic Renewal + +- After successful certificate creation, NPM will automatically renew it through DNS Challenge. +- For successful renewal, it's important that API key remains valid and NPM has access to DNS management. + +--- + +## If NPM Doesn't Have Ready Integration with reg.ru + +- Use external script to update DNS TXT records in reg.ru, configured in NPM through **Custom DNS Provider**. +- Configure curl requests to reg.ru API for adding/removing TXT records. + +--- + +# Summary + +For Let's Encrypt wildcard certificates with reg.ru, DNS Challenge must be used with provider's API for automatic DNS record management. +In Nginx Proxy Manager, configure DNS Challenge considering reg.ru specifics for seamless certificate obtaining and renewal. diff --git a/docs/Nginx_Manager_SSL_Configuration_EN.md b/docs/Nginx_Manager_SSL_Configuration_EN.md new file mode 100644 index 0000000..e15b3d7 --- /dev/null +++ b/docs/Nginx_Manager_SSL_Configuration_EN.md @@ -0,0 +1,79 @@ +# Detailed Guide to Configuring Nginx Proxy Manager with One Global SSL Certificate for All dfv24.com Domains + +## Prerequisites +- [Nginx Proxy Manager](http://192.168.10.14:81/) is installed and running +- Main domain: dfv24.com +- Domain hosting and DNS records are on reg.ru +- Need to use one SSL certificate (e.g., wildcard) for all dfv24.com subdomains + +--- + +## Step 1. Purchasing and Obtaining SSL Wildcard Certificate for dfv24.com +1. On reg.ru or any other Certificate Authority (CA), order wildcard certificate for domain `*.dfv24.com`. +2. Obtain certificate files: + - Main certificate (CRT) + - Intermediate certificates (CA Bundle) + - Private key (KEY) + +--- + +## Step 2. Importing Your SSL Certificate to Nginx Proxy Manager +1. Log in to Nginx Proxy Manager at http://192.168.10.14:81/ +2. Go to **SSL Certificates** section → **Add SSL Certificate** button +3. Select **Custom** (custom certificate) +4. Paste into fields: + - **Certificate** — main CRT + CA Bundle (if CA Bundle is separate, concatenate into one file or paste sequentially) + - **Key** — private key content + - Name certificate, e.g., `dfv24_wildcard` +5. Save + +--- + +## Step 3. Configuring Proxy Hosts Using Global Certificate + +1. Go to **Proxy Hosts** → **Add Proxy Host** +2. Fill in fields: + - **Domain Names**: For example, `sub1.dfv24.com` (for first subdomain) + - **Scheme**: http or https, depending on backend + - **Forward Hostname / IP**: IP or DNS address of your internal service + - **Forward Port**: service port (e.g., 80 or 443) +3. Enable **SSL** → Check **Use a shared SSL certificate** (if such option is available) or select previously imported certificate from list +4. Activate: **Block Common Exploits**, **Websockets Support**, set Redirect HTTP to HTTPS if required +5. Save proxy host + +6. Repeat for all subdomains, specifying needed domains and selecting same wildcard SSL certificate + +--- + +## Step 4. Configuring DNS Records on reg.ru + +1. Log in to domain management panel on reg.ru +2. Create or edit DNS A records: + - `dfv24.com` → IP of your Nginx Proxy Manager (e.g., 192.168.10.14) + - `*.dfv24.com` → same IP or specific subdomains if there are special ones +3. Save changes +4. Wait for DNS update (from few minutes to 24 hours) + +--- + +## Step 5. Testing and Verification + +1. In browser, open any subdomain `https://sub1.dfv24.com` +2. Certificate should be valid, issued for wildcard `*.dfv24.com` +3. Check proxy functionality and correct certificate assignment +4. If necessary, check Nginx Proxy Manager logs and fix errors + +--- + +## Additional Information + +- If Nginx Proxy Manager doesn't have GUI option to select shared certificate, you can manually configure configs through `/data/nginx/proxy_host` directory and specify SSL certificate for all hosts. +- When updating certificate — re-import it to Nginx Proxy Manager. +- You can use Let's Encrypt for automatic wildcard certificate obtaining using DNS validation (if supported by your DNS provider). + +--- + +# Summary + +Use one wildcard certificate for all subdomains, import it as custom certificate in Nginx Proxy Manager, when creating proxy hosts select it in SSL settings. Manage DNS records on reg.ru, directing domain to Nginx Proxy Manager IP. +This allows legitimate use of single certificate for all services with different subdomains under your dfv24.com domain. diff --git a/docs/SSL_Certificate_Creation_and_Renewal_EN.md b/docs/SSL_Certificate_Creation_and_Renewal_EN.md new file mode 100644 index 0000000..f382ad0 --- /dev/null +++ b/docs/SSL_Certificate_Creation_and_Renewal_EN.md @@ -0,0 +1,86 @@ +# Guide to Creating Wildcard Certificate *.dfv24.com in Nginx Proxy Manager and Configuring Automatic SSL Renewal + +--- + +## Step 1. Preparation + +- Ensure Nginx Proxy Manager (NPM) is installed and accessible at http://192.168.10.14:81/ +- You have access to DNS records for dfv24.com domain in reg.ru control panel or another registrar + +--- + +## Step 2. Creating Wildcard SSL Certificate in Nginx Proxy Manager + +1. Log in to Nginx Proxy Manager admin panel at http://192.168.10.14:81/ + +2. Navigate to **SSL Certificates** → click **Add SSL Certificate** button + +3. Select **Let's Encrypt** + +4. Fill in the fields: + - **Domain Names:** + Enter `*.dfv24.com` — for wildcard certificate + Also recommended to add main domain `dfv24.com` (comma-separated or in new field) + - **Email Address:** + Specify your Email for Let's Encrypt notifications (required) + - **HTTP Challenge:** + Leave HTTP verification if NPM is accessible from internet on ports 80 and 443, or configure DNS Challenge if supported by your DNS + +5. Check "Agree to the Let's Encrypt Terms of Service" + +6. Click **Save** + +- NPM will begin certificate obtaining process with domain verification. +- Upon successful certificate request, you'll see new certificate in the list. + +--- + +## Step 3. Configuring Automatic Renewal + +- Nginx Proxy Manager automatically handles Let's Encrypt certificate renewal. +- For this, server must be accessible from internet on ports 80 and 443, and DNS records must correctly point to your server. +- NPM periodically (usually 30 days before expiration) requests certificate renewal. +- When using DNS Challenge, NPM must have DNS provider integration configured (if supported). + +--- + +## Step 4. Using Wildcard Certificate in Proxy Hosts + +1. Go to **Proxy Hosts** → Create or edit proxy entry + +2. In **Domain Names** field, specify needed subdomain from dfv24.com, for example: + `api.dfv24.com` or `www.dfv24.com` + +3. In **SSL** section, select your wildcard certificate `*.dfv24.com` that you obtained in Step 2 + +4. Enable options: + - Use SSL + - Force SSL + - HSTS (if needed) + +5. Save changes. + +--- + +## Step 5. Verification + +1. Verify that all subdomains use the same certificate +2. Visit https://api.dfv24.com or other subdomains from browser +3. Ensure certificate is valid, not expired, and issued for *.dfv24.com +4. Check certificate renewal status in SSL Certificates section + +--- + +## Additional Information + +- If Let's Encrypt cannot perform HTTP Challenge due to closed port, configure DNS Challenge (may require DNS provider API key) +- For security and notifications, keep Email up to date +- Check Nginx Proxy Manager logs to identify renewal errors + +--- + +# Summary + +Nginx Proxy Manager allows easy obtaining and automatic renewal of wildcard SSL certificates for *.dfv24.com domain using Let's Encrypt. +Main requirements — properly configured DNS records and internet access on HTTP/HTTPS ports. +Then use one global certificate for all your subdomains through Proxy Hosts settings. diff --git a/docs/SSL_SCRIPTS_README_EN.md b/docs/SSL_SCRIPTS_README_EN.md new file mode 100644 index 0000000..770eb38 --- /dev/null +++ b/docs/SSL_SCRIPTS_README_EN.md @@ -0,0 +1,250 @@ +# SSL Certificate Automation Scripts + +**Author:** Фофанов Дмитрий + +## 📖 Overview + +This project contains scripts for automating the creation and renewal of Let's Encrypt SSL certificates using DNS-01 Challenge via the reg.ru API. + +## 🎯 Quick Start + +### Linux (Bash) + +```bash +# 1. Install dependencies +sudo apt-get install certbot jq + +# 2. Configure credentials +nano ~/.regru_credentials +# Add: +# export REGRU_USERNAME="your_login" +# export REGRU_PASSWORD="your_password" + +# 3. Set permissions +chmod 600 ~/.regru_credentials + +# 4. Run the script +./letsencrypt_regru.sh \ + -d "*.dfv24.com" \ + -e "dfofanov@dfv24.com" +``` + +### Linux (Python) + +```bash +# 1. Install dependencies +pip install requests dnspython certbot + +# 2. Configure +cp config.example.yml config.yml +nano config.yml + +# 3. Run +python letsencrypt_regru.py + +# 4. Setup auto-renewal (cron) +crontab -e +# Add: +# 0 3 * * 1 /usr/bin/python3 /path/to/letsencrypt_regru.py +``` + +### Windows (PowerShell) + +```powershell +# 1. Run as Administrator +Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser + +# 2. Configure credentials +$env:REGRU_USERNAME = "your_login" +$env:REGRU_PASSWORD = "your_password" + +# 3. Run +.\letsencrypt_regru.ps1 ` + -Domain "*.dfv24.com" ` + -Email "dfofanov@dfv24.com" + +# 4. Setup auto-renewal (Task Scheduler) +# Import-Module .\ScheduledTask.psm1 +# Create-CertRenewalTask +``` + +## ⚙️ Configuration + +### Bash Script (`letsencrypt_regru.sh`) + +```bash +#!/bin/bash + +# Required parameters +DOMAIN="*.dfv24.com" # Your domain +EMAIL="dfofanov@dfv24.com" # Contact email +REGRU_USERNAME="your_login" # reg.ru login +REGRU_PASSWORD="your_password" # reg.ru password + +# Optional parameters +DNS_PROPAGATION_WAIT=60 # Wait time for DNS propagation (seconds) +LOG_FILE="/var/log/letsencrypt_regru.log" +WEBSERVER="nginx" # nginx or apache2 +``` + +### Python Script (`letsencrypt_regru.py`) + +Create `config.yml`: + +```yaml +# reg.ru credentials +regru: + username: "your_login" + password: "your_password" + +# Certificate settings +certificate: + domain: "*.dfv24.com" + email: "dfofanov@dfv24.com" + dns_propagation_wait: 60 + +# Logging +logging: + file: "/var/log/letsencrypt_regru.log" + level: "INFO" + +# Web server +webserver: + type: "nginx" # nginx, apache2, or null + reload_command: "systemctl reload nginx" +``` + +### PowerShell Script (`letsencrypt_regru.ps1`) + +```powershell +# Configuration +$Config = @{ + Domain = "*.dfv24.com" + Email = "dfofanov@dfv24.com" + RegRuUsername = $env:REGRU_USERNAME + RegRuPassword = $env:REGRU_PASSWORD + DnsPropagationWait = 60 + LogFile = ".\letsencrypt_regru.log" +} +``` + +## 📋 Requirements + +### Bash Script +- **certbot** - Let's Encrypt client +- **jq** - JSON processor +- **curl** - HTTP requests +- **dig** (optional) - DNS queries + +### Python Script +- **Python 3.6+** +- **requests** - HTTP library +- **dnspython** - DNS operations +- **certbot** - Let's Encrypt client +- **PyYAML** - YAML configuration + +### PowerShell Script +- **PowerShell 5.1+** or **PowerShell Core 7+** +- **certbot** (via Chocolatey or manual installation) + +## 🔄 Automatic Renewal + +### Linux (cron) + +```bash +# Edit crontab +crontab -e + +# Add (runs every Monday at 3 AM): +0 3 * * 1 /path/to/letsencrypt_regru.sh >> /var/log/cert_renewal.log 2>&1 + +# Or for Python: +0 3 * * 1 /usr/bin/python3 /path/to/letsencrypt_regru.py +``` + +### Windows (Task Scheduler) + +```powershell +# Create scheduled task +$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" ` + -Argument "-File C:\path\to\letsencrypt_regru.ps1" + +$Trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At 3am + +Register-ScheduledTask -TaskName "SSL Certificate Renewal" ` + -Action $Action -Trigger $Trigger -RunLevel Highest +``` + +## ✨ Features + +✅ Automatic DNS validation via reg.ru API +✅ Certificate expiration check +✅ Automatic renewal before expiration +✅ Web server reload after renewal +✅ Detailed logging of all operations + +## 🔧 Using with Nginx Proxy Manager + +After obtaining the certificate: + +1. Log in to NPM: http://192.168.10.14:81/ +2. SSL Certificates → Add SSL Certificate → Custom +3. Paste the content: + - Certificate Key: `/etc/letsencrypt/live/domain.com/privkey.pem` + - Certificate: `/etc/letsencrypt/live/domain.com/fullchain.pem` + +## 📝 Logs + +- Bash: `/var/log/letsencrypt_regru.log` +- Python: `/var/log/letsencrypt_regru.log` +- PowerShell: `.\letsencrypt_regru.log` +- Certbot: `/var/log/letsencrypt/letsencrypt.log` + +## 🆘 Troubleshooting + +### API Authentication Error +- Check your reg.ru credentials +- Ensure the domain is under your control + +### DNS Record Not Propagating +- Increase `dns_propagation_wait` to 120 seconds +- Check DNS: `nslookup -type=TXT _acme-challenge.domain.com` + +### Certbot Not Found +```bash +# Ubuntu/Debian +sudo apt-get install certbot + +# Or via snap +sudo snap install --classic certbot +``` + +## 📚 Documentation + +Detailed documentation in [USAGE.md](USAGE.md) + +## 🔐 Security + +- Keep credentials secure +- Use `chmod 600` for configuration files +- Regularly update passwords + +## ⚠️ Important + +- Let's Encrypt certificates are valid for 90 days +- Automatic renewal setup is recommended +- Wildcard certificates require DNS validation + +## 📞 Support + +- [reg.ru API Documentation](https://www.reg.ru/support/api) +- [Let's Encrypt Documentation](https://letsencrypt.org/docs/) +- [Certbot Documentation](https://certbot.eff.org/docs/) + +## 📄 License + +Scripts are provided "as is" for free use. + +--- + +**Happy Automation! 🔒** diff --git a/gitea-hooks/README.md b/gitea-hooks/README.md new file mode 100644 index 0000000..082dbae --- /dev/null +++ b/gitea-hooks/README.md @@ -0,0 +1,168 @@ +# Git Hooks для Gitea + +Автоматическая синхронизация с GitHub после push в Gitea. + +## 📁 Файлы + +- **post-receive** - Hook для автоматического push в GitHub + +## 🚀 Установка + +### 1. Найдите путь к репозиторию на сервере Gitea + +```bash +# Обычно это один из путей: +/var/lib/gitea/data/gitea-repositories/username/configure_nginx_manager.git +# или +/home/git/gitea-repositories/username/configure_nginx_manager.git +``` + +### 2. Скопируйте hook + +```bash +# На сервере Gitea +cd /path/to/gitea-repositories/username/configure_nginx_manager.git/hooks/ + +# Скопируйте файл +cp /path/to/this/repo/gitea-hooks/post-receive ./ + +# Или загрузите напрямую +wget https://raw.githubusercontent.com/username/configure_nginx_manager/main/gitea-hooks/post-receive +``` + +### 3. Настройте hook + +```bash +nano post-receive +``` + +Измените: +```bash +GITHUB_REPO="git@github.com:YOUR_USERNAME/configure_nginx_manager.git" +``` + +### 4. Сделайте исполняемым + +```bash +chmod +x post-receive +chown git:git post-receive +``` + +### 5. Создайте директорию для логов + +```bash +mkdir -p /var/log/gitea +chown git:git /var/log/gitea +``` + +## 🔑 Настройка аутентификации + +### Вариант A: SSH (Рекомендуется) + +```bash +# На сервере Gitea под пользователем git +sudo su - git +ssh-keygen -t ed25519 -C "gitea-sync" + +# Скопируйте публичный ключ +cat ~/.ssh/id_ed25519.pub + +# Добавьте на GitHub: +# Settings → SSH and GPG keys → New SSH key + +# Проверьте +ssh -T git@github.com +``` + +### Вариант B: HTTPS с токеном + +1. Создайте Personal Access Token на GitHub + - Settings → Developer settings → Personal access tokens + - Scope: `repo` + +2. Используйте в hook: +```bash +GITHUB_REPO="https://YOUR_TOKEN@github.com/username/configure_nginx_manager.git" +``` + +## ✅ Проверка + +```bash +# Тестовый push +cd /tmp +git clone http://gitea.example.com/username/configure_nginx_manager.git +cd configure_nginx_manager +echo "test" >> README.md +git add README.md +git commit -m "Test sync" +git push + +# Проверьте лог +tail -f /var/log/gitea/github-sync.log + +# Проверьте GitHub - изменения должны появиться через 1-2 секунды +``` + +## 📊 Что делает hook + +1. ✅ Отслеживает push в ветки `main` и `master` +2. ✅ Автоматически пушит в GitHub +3. ✅ Синхронизирует теги +4. ✅ Логирует все операции +5. ✅ Показывает красивый вывод с эмодзи + +## 🐛 Устранение проблем + +### Hook не срабатывает + +```bash +# Проверьте права +ls -la post-receive +# Должно быть: -rwxr-xr-x + +# Проверьте владельца +chown git:git post-receive + +# Проверьте синтаксис +bash -n post-receive +``` + +### Permission denied + +```bash +# Для SSH +ssh -T git@github.com + +# Проверьте права на ключ +chmod 600 ~/.ssh/id_ed25519 + +# Для HTTPS - проверьте токен +``` + +### Не находит git + +```bash +# Добавьте PATH в начало hook: +export PATH=/usr/bin:/usr/local/bin:$PATH +``` + +## 📝 Логи + +```bash +# Просмотр логов синхронизации +tail -f /var/log/gitea/github-sync.log + +# Очистка старых логов +> /var/log/gitea/github-sync.log +``` + +## 🔄 Альтернативы + +Если Git Hook не подходит, см. другие методы в [GITEA_SYNC.md](../GITEA_SYNC.md): +- GitHub Actions (каждый час) +- Gitea Mirror (встроенная функция) +- Двойной remote (локально) + +--- + +**См. также**: [GITEA_SYNC.md](../GITEA_SYNC.md) для подробной документации diff --git a/gitea-hooks/README_EN.md b/gitea-hooks/README_EN.md new file mode 100644 index 0000000..f2aada9 --- /dev/null +++ b/gitea-hooks/README_EN.md @@ -0,0 +1,168 @@ +# Git Hooks for Gitea + +Automatic synchronization with GitHub after push to Gitea. + +## 📁 Files + +- **post-receive** - Hook for automatic push to GitHub + +## 🚀 Installation + +### 1. Find Repository Path on Gitea Server + +```bash +# Usually one of these paths: +/var/lib/gitea/data/gitea-repositories/username/configure_nginx_manager.git +# or +/home/git/gitea-repositories/username/configure_nginx_manager.git +``` + +### 2. Copy Hook + +```bash +# On Gitea server +cd /path/to/gitea-repositories/username/configure_nginx_manager.git/hooks/ + +# Copy file +cp /path/to/this/repo/gitea-hooks/post-receive ./ + +# Or download directly +wget https://raw.githubusercontent.com/username/configure_nginx_manager/main/gitea-hooks/post-receive +``` + +### 3. Configure Hook + +```bash +nano post-receive +``` + +Change: +```bash +GITHUB_REPO="git@github.com:YOUR_USERNAME/configure_nginx_manager.git" +``` + +### 4. Make Executable + +```bash +chmod +x post-receive +chown git:git post-receive +``` + +### 5. Create Log Directory + +```bash +mkdir -p /var/log/gitea +chown git:git /var/log/gitea +``` + +## 🔑 Authentication Setup + +### Option A: SSH (Recommended) + +```bash +# On Gitea server as git user +sudo su - git +ssh-keygen -t ed25519 -C "gitea-sync" + +# Copy public key +cat ~/.ssh/id_ed25519.pub + +# Add to GitHub: +# Settings → SSH and GPG keys → New SSH key + +# Verify +ssh -T git@github.com +``` + +### Option B: HTTPS with Token + +1. Create Personal Access Token on GitHub + - Settings → Developer settings → Personal access tokens + - Scope: `repo` + +2. Use in hook: +```bash +GITHUB_REPO="https://YOUR_TOKEN@github.com/username/configure_nginx_manager.git" +``` + +## ✅ Verification + +```bash +# Test push +cd /tmp +git clone http://gitea.example.com/username/configure_nginx_manager.git +cd configure_nginx_manager +echo "test" >> README.md +git add README.md +git commit -m "Test sync" +git push + +# Check log +tail -f /var/log/gitea/github-sync.log + +# Check GitHub - changes should appear in 1-2 seconds +``` + +## 📊 What Hook Does + +1. ✅ Monitors pushes to `main` and `master` branches +2. ✅ Automatically pushes to GitHub +3. ✅ Synchronizes tags +4. ✅ Logs all operations +5. ✅ Shows beautiful output with emojis + +## 🐛 Troubleshooting + +### Hook Not Firing + +```bash +# Check permissions +ls -la post-receive +# Should be: -rwxr-xr-x + +# Check owner +chown git:git post-receive + +# Check syntax +bash -n post-receive +``` + +### Permission Denied + +```bash +# For SSH +ssh -T git@github.com + +# Check key permissions +chmod 600 ~/.ssh/id_ed25519 + +# For HTTPS - check token +``` + +### Can't Find Git + +```bash +# Add PATH to beginning of hook: +export PATH=/usr/bin:/usr/local/bin:$PATH +``` + +## 📝 Logs + +```bash +# View sync logs +tail -f /var/log/gitea/github-sync.log + +# Clear old logs +> /var/log/gitea/github-sync.log +``` + +## 🔄 Alternatives + +If Git Hook doesn't work, see other methods in [GITEA_SYNC_EN.md](../GITEA_SYNC_EN.md): +- GitHub Actions (every hour) +- Gitea Mirror (built-in feature) +- Double remote (locally) + +--- + +**See also**: [GITEA_SYNC_EN.md](../GITEA_SYNC_EN.md) for detailed documentation diff --git a/gitea-hooks/post-receive b/gitea-hooks/post-receive new file mode 100644 index 0000000..c13ffb1 --- /dev/null +++ b/gitea-hooks/post-receive @@ -0,0 +1,83 @@ +#!/bin/bash + +# ============================================================================== +# Post-receive hook для Gitea +# Автоматически синхронизирует изменения с GitHub после push +# +# Установка: +# 1. Разместить в: /path/to/gitea/data/gitea-repositories/username/repo.git/hooks/ +# 2. Переименовать в: post-receive +# 3. chmod +x post-receive +# 4. Настроить переменные ниже +# ============================================================================== + +# Конфигурация +GITHUB_REPO="git@github.com:username/configure_nginx_manager.git" +# Или с HTTPS и токеном: +# GITHUB_REPO="https://YOUR_GITHUB_TOKEN@github.com/username/configure_nginx_manager.git" + +LOG_FILE="/var/log/gitea/github-sync.log" + +# Цвета для логов +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# ============================================================================== +# Функция логирования +# ============================================================================== +log() { + echo -e "${2:-$NC}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}" | tee -a "$LOG_FILE" +} + +# ============================================================================== +# Основная логика +# ============================================================================== + +log "═══════════════════════════════════════════════════════════════" "$GREEN" +log "🔄 Начало синхронизации с GitHub" "$GREEN" +log "═══════════════════════════════════════════════════════════════" "$GREEN" + +# Читаем информацию о push +while read oldrev newrev refname; do + log "📝 Изменения обнаружены:" "$YELLOW" + log " Branch: ${refname#refs/heads/}" + log " Old commit: ${oldrev:0:8}" + log " New commit: ${newrev:0:8}" + + # Проверяем наличие GitHub remote + if ! git remote | grep -q github; then + log "➕ Добавление GitHub remote..." "$YELLOW" + git remote add github "$GITHUB_REPO" 2>&1 | tee -a "$LOG_FILE" + fi + + # Пушим в GitHub + log "⬆️ Отправка изменений в GitHub..." "$YELLOW" + + # Только для main/master веток + if [[ "$refname" == "refs/heads/main" ]] || [[ "$refname" == "refs/heads/master" ]]; then + if git push github "$refname" --force 2>&1 | tee -a "$LOG_FILE"; then + log "✅ Успешно синхронизировано с GitHub" "$GREEN" + else + log "❌ Ошибка при синхронизации с GitHub" "$RED" + exit 1 + fi + + # Пушим теги + log "🏷️ Отправка тегов..." "$YELLOW" + if git push github --tags 2>&1 | tee -a "$LOG_FILE"; then + log "✅ Теги синхронизированы" "$GREEN" + else + log "⚠️ Не удалось синхронизировать теги" "$YELLOW" + fi + else + log "ℹ️ Ветка ${refname#refs/heads/} игнорируется (не main/master)" "$YELLOW" + fi +done + +log "═══════════════════════════════════════════════════════════════" "$GREEN" +log "✅ Синхронизация завершена" "$GREEN" +log "═══════════════════════════════════════════════════════════════" "$GREEN" + +exit 0