videotomp3transcriptor/docs/DEPLOYMENT.md
StillHammer c0cfc4c28e Add API security with token authentication and localStorage management
- Add API token authentication middleware (X-API-Key header)
- Add CORS configuration with ALLOWED_ORIGINS
- Add security HTTP headers (X-Frame-Options, CSP, etc.)
- Add web interface for API token configuration with localStorage
- Add toggle visibility for token input
- Add connection status indicator
- Add auto-save token functionality
- Update API documentation with authentication examples
- Add deployment guides (OVH specific and general)
- Add local testing guide

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 12:01:19 +08:00

700 lines
14 KiB
Markdown

# Guide de Déploiement - Video to MP3 Transcriptor
Ce guide vous accompagne pour déployer l'API de manière sécurisée sur un serveur de production.
## Table des matières
1. [Prérequis](#prérequis)
2. [Configuration de sécurité](#configuration-de-sécurité)
3. [Déploiement sur VPS/Serveur](#déploiement-sur-vpsserveur)
4. [Déploiement avec Docker](#déploiement-avec-docker)
5. [Nginx Reverse Proxy](#nginx-reverse-proxy)
6. [SSL/HTTPS avec Let's Encrypt](#sslhttps-avec-lets-encrypt)
7. [Surveillance et logs](#surveillance-et-logs)
8. [Sécurité avancée](#sécurité-avancée)
---
## Prérequis
### Serveur
- Linux (Ubuntu 20.04+ / Debian 11+ recommandé)
- Minimum 2 GB RAM
- 10 GB espace disque
- Node.js 18+ ou Docker
### Dépendances système
```bash
# Ubuntu/Debian
sudo apt update
sudo apt install -y ffmpeg python3
# Pour téléchargement YouTube
sudo curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp
sudo chmod a+rx /usr/local/bin/yt-dlp
```
### Domaine et DNS
- Un nom de domaine pointant vers votre serveur
- Accès aux paramètres DNS
---
## Configuration de sécurité
### 1. Générer un token API sécurisé
**Sur votre serveur:**
```bash
# Générer un token de 64 caractères
openssl rand -hex 32
# Ou utiliser cette commande alternative
head /dev/urandom | tr -dc A-Za-z0-9 | head -c 64
```
Copiez le token généré, vous en aurez besoin pour le `.env`.
### 2. Configurer les variables d'environnement
Créez/éditez le fichier `.env` sur le serveur:
```bash
cd /path/to/videotoMP3Transcriptor
nano .env
```
Configuration minimale de production:
```env
# ========================================
# SÉCURITÉ - PRODUCTION
# ========================================
# Token API (REMPLACEZ PAR VOTRE TOKEN GÉNÉRÉ)
API_TOKEN=votre_token_securise_de_64_caracteres
# Origines CORS autorisées (vos domaines uniquement)
ALLOWED_ORIGINS=https://yourdomain.com,https://api.yourdomain.com
# ========================================
# CONFIGURATION SERVEUR
# ========================================
# Port interne (Nginx fera le reverse proxy)
PORT=8888
# Répertoire de sortie
OUTPUT_DIR=/var/www/videotoMP3Transcriptor/output
# ========================================
# API KEYS
# ========================================
# OpenAI API Key (OBLIGATOIRE)
OPENAI_API_KEY=sk-...
# ========================================
# ENVIRONNEMENT
# ========================================
NODE_ENV=production
```
### 3. Permissions du fichier .env
```bash
# Sécuriser le fichier .env
chmod 600 .env
chown www-data:www-data .env # ou votre utilisateur système
```
---
## Déploiement sur VPS/Serveur
### 1. Installation de Node.js
```bash
# Installation de Node.js 20 LTS
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
# Vérification
node --version # devrait afficher v20.x
npm --version
```
### 2. Cloner et installer l'application
```bash
# Créer le répertoire
sudo mkdir -p /var/www/videotoMP3Transcriptor
sudo chown $USER:$USER /var/www/videotoMP3Transcriptor
# Cloner (ou copier) votre code
cd /var/www/videotoMP3Transcriptor
# git clone ... ou upload manuel
# Installer les dépendances
npm ci --only=production
# Créer le répertoire de sortie
mkdir -p output
chmod 755 output
```
### 3. Utiliser PM2 pour la gestion des processus
PM2 est un gestionnaire de processus pour Node.js qui redémarre automatiquement votre app en cas de crash.
```bash
# Installer PM2 globalement
sudo npm install -g pm2
# Démarrer l'application
pm2 start src/server.js --name "video-transcriptor"
# Configurer PM2 pour démarrer au boot
pm2 startup systemd
pm2 save
# Commandes utiles
pm2 status # Voir le statut
pm2 logs video-transcriptor # Voir les logs
pm2 restart video-transcriptor # Redémarrer
pm2 stop video-transcriptor # Arrêter
```
### 4. Configuration PM2 avancée (optionnelle)
Créez un fichier `ecosystem.config.js`:
```javascript
module.exports = {
apps: [{
name: 'video-transcriptor',
script: './src/server.js',
instances: 1,
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'production',
PORT: 8888
},
error_file: '/var/log/pm2/video-transcriptor-error.log',
out_file: '/var/log/pm2/video-transcriptor-out.log',
log_date_format: 'YYYY-MM-DD HH:mm:ss Z'
}]
};
```
Démarrer avec:
```bash
pm2 start ecosystem.config.js
```
---
## Déploiement avec Docker
### 1. Créer un Dockerfile
Créez `Dockerfile` à la racine du projet:
```dockerfile
FROM node:20-slim
# Installer les dépendances système
RUN apt-get update && apt-get install -y \
ffmpeg \
python3 \
curl \
&& rm -rf /var/lib/apt/lists/*
# Installer yt-dlp
RUN curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp \
&& chmod a+rx /usr/local/bin/yt-dlp
# Créer le répertoire de l'app
WORKDIR /app
# Copier package.json et installer les dépendances
COPY package*.json ./
RUN npm ci --only=production
# Copier le code source
COPY . .
# Créer le répertoire de sortie
RUN mkdir -p /app/output && chmod 755 /app/output
# Exposer le port
EXPOSE 8888
# Variables d'environnement par défaut
ENV NODE_ENV=production
ENV PORT=8888
ENV OUTPUT_DIR=/app/output
# Démarrer l'application
CMD ["node", "src/server.js"]
```
### 2. Créer docker-compose.yml
```yaml
version: '3.8'
services:
video-transcriptor:
build: .
container_name: video-transcriptor
restart: unless-stopped
ports:
- "8888:8888"
volumes:
- ./output:/app/output
- ./.env:/app/.env:ro
environment:
- NODE_ENV=production
networks:
- transcriptor-network
networks:
transcriptor-network:
driver: bridge
```
### 3. Lancer avec Docker Compose
```bash
# Build et démarrer
docker-compose up -d
# Voir les logs
docker-compose logs -f
# Arrêter
docker-compose down
# Reconstruire après modification
docker-compose up -d --build
```
---
## Nginx Reverse Proxy
### 1. Installer Nginx
```bash
sudo apt update
sudo apt install -y nginx
```
### 2. Configuration Nginx
Créez `/etc/nginx/sites-available/video-transcriptor`:
```nginx
# Rate limiting
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
listen 80;
server_name api.yourdomain.com;
# Logs
access_log /var/log/nginx/video-transcriptor-access.log;
error_log /var/log/nginx/video-transcriptor-error.log;
# Rate limiting
limit_req zone=api_limit burst=20 nodelay;
# Augmenter les timeouts pour les longs traitements
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
# Augmenter la taille max des uploads
client_max_body_size 500M;
location / {
proxy_pass http://localhost:8888;
proxy_http_version 1.1;
# Headers
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Pour Server-Sent Events (SSE)
proxy_cache_bypass $http_upgrade;
proxy_buffering off;
proxy_cache off;
}
# Headers de sécurité supplémentaires
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
}
```
### 3. Activer le site
```bash
# Créer un lien symbolique
sudo ln -s /etc/nginx/sites-available/video-transcriptor /etc/nginx/sites-enabled/
# Tester la configuration
sudo nginx -t
# Recharger Nginx
sudo systemctl reload nginx
```
---
## SSL/HTTPS avec Let's Encrypt
### 1. Installer Certbot
```bash
sudo apt install -y certbot python3-certbot-nginx
```
### 2. Obtenir un certificat SSL
```bash
# Obtenir et installer automatiquement le certificat
sudo certbot --nginx -d api.yourdomain.com
# Suivez les instructions à l'écran
```
### 3. Renouvellement automatique
```bash
# Tester le renouvellement
sudo certbot renew --dry-run
# Le renouvellement automatique est configuré via cron
# Vérifier: sudo systemctl status certbot.timer
```
Après SSL, votre configuration Nginx sera automatiquement mise à jour pour HTTPS.
---
## Surveillance et logs
### 1. Logs de l'application
```bash
# Avec PM2
pm2 logs video-transcriptor
# Avec Docker
docker-compose logs -f video-transcriptor
# Logs Nginx
sudo tail -f /var/log/nginx/video-transcriptor-access.log
sudo tail -f /var/log/nginx/video-transcriptor-error.log
```
### 2. Monitoring avec PM2 (optionnel)
```bash
# Installer PM2 monitoring
pm2 install pm2-logrotate
# Configurer la rotation des logs
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
```
### 3. Monitoring système
```bash
# Installer htop pour surveiller les ressources
sudo apt install -y htop
# Lancer htop
htop
# Voir l'utilisation disque
df -h
# Voir l'utilisation mémoire
free -h
```
---
## Sécurité avancée
### 1. Firewall (UFW)
```bash
# Installer UFW
sudo apt install -y ufw
# Autoriser SSH (IMPORTANT AVANT D'ACTIVER!)
sudo ufw allow ssh
sudo ufw allow 22/tcp
# Autoriser HTTP et HTTPS
sudo ufw allow 'Nginx Full'
# Activer le firewall
sudo ufw enable
# Vérifier le statut
sudo ufw status
```
### 2. Fail2Ban (protection contre brute force)
```bash
# Installer Fail2Ban
sudo apt install -y fail2ban
# Créer une configuration pour Nginx
sudo nano /etc/fail2ban/jail.local
```
Ajouter:
```ini
[nginx-limit-req]
enabled = true
filter = nginx-limit-req
port = http,https
logpath = /var/log/nginx/video-transcriptor-error.log
maxretry = 5
findtime = 600
bantime = 3600
```
```bash
# Redémarrer Fail2Ban
sudo systemctl restart fail2ban
# Vérifier le statut
sudo fail2ban-client status nginx-limit-req
```
### 3. Limitations supplémentaires
**Limiter les tailles de fichiers uploadés** - Déjà configuré dans Nginx (`client_max_body_size 500M`)
**Rate limiting par IP** - Déjà configuré dans Nginx (`limit_req_zone`)
### 4. Sauvegardes automatiques
```bash
# Créer un script de backup
sudo nano /usr/local/bin/backup-video-transcriptor.sh
```
```bash
#!/bin/bash
BACKUP_DIR="/backup/video-transcriptor"
APP_DIR="/var/www/videotoMP3Transcriptor"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR
# Backup de la configuration
tar -czf $BACKUP_DIR/config_$DATE.tar.gz \
$APP_DIR/.env \
$APP_DIR/ecosystem.config.js
# Backup des fichiers de sortie (optionnel, peut être volumineux)
# tar -czf $BACKUP_DIR/output_$DATE.tar.gz $APP_DIR/output
# Garder seulement les 7 derniers backups
find $BACKUP_DIR -name "config_*.tar.gz" -mtime +7 -delete
echo "Backup completed: $DATE"
```
```bash
# Rendre exécutable
sudo chmod +x /usr/local/bin/backup-video-transcriptor.sh
# Ajouter au crontab (backup quotidien à 2h du matin)
sudo crontab -e
# Ajouter: 0 2 * * * /usr/local/bin/backup-video-transcriptor.sh
```
---
## Checklist finale de déploiement
Avant de mettre en production, vérifiez:
- [ ] **Sécurité**
- [ ] Token API fort généré (`API_TOKEN`)
- [ ] CORS configuré avec vos domaines (`ALLOWED_ORIGINS`)
- [ ] Fichier `.env` avec permissions 600
- [ ] HTTPS configuré et fonctionnel
- [ ] Firewall UFW activé
- [ ] **Configuration**
- [ ] `OPENAI_API_KEY` valide et fonctionnelle
- [ ] `NODE_ENV=production`
- [ ] Répertoire `output/` créé et accessible
- [ ] FFmpeg et yt-dlp installés
- [ ] **Infrastructure**
- [ ] PM2 ou Docker en cours d'exécution
- [ ] Nginx reverse proxy configuré
- [ ] SSL/TLS actif (Let's Encrypt)
- [ ] Rate limiting activé
- [ ] **Monitoring**
- [ ] Logs accessibles
- [ ] PM2 startup configuré (redémarrage auto)
- [ ] Fail2Ban actif
- [ ] Backups automatiques configurés
- [ ] **Tests**
- [ ] Endpoint `/health` accessible
- [ ] Test d'authentification (avec et sans token)
- [ ] Test d'upload de fichier
- [ ] Test de téléchargement YouTube
---
## Tests post-déploiement
### 1. Test de santé
```bash
curl https://api.yourdomain.com/health
# Devrait retourner: {"status":"ok","timestamp":"..."}
```
### 2. Test d'authentification
```bash
# Sans token (devrait échouer avec 401)
curl https://api.yourdomain.com/info?url=https://www.youtube.com/watch?v=dQw4w9WgXcQ
# Avec token (devrait réussir)
curl -H "X-API-Key: VOTRE_TOKEN" \
"https://api.yourdomain.com/info?url=https://www.youtube.com/watch?v=dQw4w9WgXcQ"
```
### 3. Test de download
```bash
curl -H "X-API-Key: VOTRE_TOKEN" \
-X POST https://api.yourdomain.com/download \
-H "Content-Type: application/json" \
-d '{"url":"https://www.youtube.com/watch?v=dQw4w9WgXcQ"}'
```
---
## Dépannage
### L'API ne démarre pas
```bash
# Vérifier les logs PM2
pm2 logs video-transcriptor
# Vérifier les variables d'environnement
pm2 env video-transcriptor
# Redémarrer
pm2 restart video-transcriptor
```
### Erreurs 502 Bad Gateway (Nginx)
```bash
# Vérifier que l'app tourne
pm2 status
# Vérifier les logs Nginx
sudo tail -f /var/log/nginx/error.log
# Vérifier que le port 8888 est ouvert
sudo netstat -tlnp | grep 8888
```
### Problèmes SSL
```bash
# Vérifier le certificat
sudo certbot certificates
# Renouveler manuellement
sudo certbot renew --force-renewal
# Tester la configuration Nginx
sudo nginx -t
```
### Mémoire insuffisante
```bash
# Vérifier l'utilisation mémoire
free -h
# Créer un swap file (si nécessaire)
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
```
---
## Mises à jour
### Mise à jour de l'application
```bash
cd /var/www/videotoMP3Transcriptor
# Sauvegarder la config
cp .env .env.backup
# Pull des nouvelles versions (git)
git pull
# Mettre à jour les dépendances
npm ci --only=production
# Redémarrer
pm2 restart video-transcriptor
# Ou avec Docker
docker-compose down
docker-compose up -d --build
```
---
## Support et ressources
- **Documentation API**: [docs/API.md](./API.md)
- **CLAUDE.md**: [CLAUDE.md](../CLAUDE.md) - Instructions pour Claude
- **PM2 Documentation**: https://pm2.keymetrics.io/
- **Nginx Documentation**: https://nginx.org/en/docs/
- **Let's Encrypt**: https://letsencrypt.org/
---
**Bon déploiement ! 🚀**