# ========================================
# FLYING BOOK CREATOR - SECURITE .HTACCESS
# SMG Studio v2.0 - Protection Anti-Fouineurs
# ========================================

# ========== PROTECTION GENERALE ==========

# Empêcher le listing des répertoires
Options -Indexes

# Masquer la signature Apache
ServerTokens Prod
ServerSignature Off

# Protection contre les injections
<IfModule mod_rewrite.c>
    RewriteEngine On
    
    # Bloquer les tentatives d'injection SQL
    RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
    RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2}) [OR]
    RewriteCond %{QUERY_STRING} proc/self/environ [OR]
    RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
    RewriteCond %{QUERY_STRING} base64_(en|de)code[^(]*\([^)]*\) [OR]
    RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} (\<|%3C).*iframe.*(\>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} (<|%3C)([^e]*e)+mbed.*(>|%3E) [NC]
    RewriteRule ^(.*)$ - [F,L]
</IfModule>

# ========== PROTECTION FICHIERS SENSIBLES ==========

# Protéger les fichiers de configuration
<FilesMatch "^(\.env|\.env\.php|config\.php|database\.php|wp-config\.php|configuration\.php)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

# Protéger les logs et sauvegardes
<FilesMatch "\.(log|sql|bak|backup|old|tmp|temp)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

# Protéger les fichiers système
<FilesMatch "^(\.htaccess|\.htpasswd|\.git|\.svn|readme\.txt|license\.txt|changelog\.txt)">
    Order Allow,Deny
    Deny from all
</FilesMatch>

# Empêcher l'accès aux dossiers sensibles
RedirectMatch 404 /\.git
RedirectMatch 404 /\.svn
RedirectMatch 404 /vendor
RedirectMatch 404 /node_modules
RedirectMatch 404 /env

# ========== PROTECTION FLYING BOOK ==========

# Protéger le dossier uploads (sauf images autorisées)
<Directory "uploads">
    Options -Indexes
    
    # Autoriser seulement les médias
    <FilesMatch "\.(jpg|jpeg|png|gif|webp|mp4|webm|mov|mp3|wav|ogg|pdf)$">
        Order Allow,Deny
        Allow from all
    </FilesMatch>
    
    # Bloquer tout le reste
    <FilesMatch "\.">
        Order Allow,Deny
        Deny from all
    </FilesMatch>
</Directory>

# Protéger les dossiers d'administration
<Directory "admin">
    Options -Indexes
    
    # Restriction IP pour admin (adapter vos IPs)
    Order Deny,Allow
    Deny from all
    # Allow from 127.0.0.1
    # Allow from 192.168.1
    # Allow from VOTRE_IP_PUBLIQUE
</Directory>

# Protéger les backups et exports
<Directory "backups">
    Options -Indexes
    Order Allow,Deny
    Deny from all
</Directory>

<Directory "exports">
    Options -Indexes
    Order Allow,Deny
    Deny from all
</Directory>

# ========== SECURITY HEADERS ==========

<IfModule mod_headers.c>
    # Protection XSS
    Header always set X-XSS-Protection "1; mode=block"
    
    # Empêcher le MIME sniffing
    Header always set X-Content-Type-Options nosniff
    
    # Protection contre le clickjacking
    Header always set X-Frame-Options SAMEORIGIN
    
    # Politique de référent stricte
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # Content Security Policy pour Flying Book
    Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; img-src 'self' data: https:; font-src 'self' https://cdnjs.cloudflare.com; connect-src 'self'; media-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'"
    
    # HSTS (SSL uniquement)
    # Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</IfModule>

# ========== BLOQUER USER AGENTS SUSPECTS ==========

<IfModule mod_rewrite.c>
    RewriteEngine On
    
    # Bloquer les bots malveillants
    RewriteCond %{HTTP_USER_AGENT} ^$ [OR]
    RewriteCond %{HTTP_USER_AGENT} (nikto|sqlmap|fimap|nessus|openvas|nmap|masscan) [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} (wget|curl|libwww|python|perl|java|winhttp) [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} (scanner|bot|spider|crawl|scraper) [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} (havij|union|select|insert|cast|set|declare|drop|update|md5|benchmark) [NC]
    RewriteRule .* - [F,L]
</IfModule>

# ========== LIMITATION TAUX DE REQUETES ==========

<IfModule mod_limitipconn.c>
    # Limiter à 20 connexions par IP
    MaxConnPerIP 20
</IfModule>

# ========== PROTECTION HOTLINKING ==========

<IfModule mod_rewrite.c>
    RewriteEngine On
    
    # Empêcher le hotlinking des images (sauf domaines autorisés)
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{HTTP_REFERER} !^https?://(www\.)?votre-domaine\.com [NC]
    RewriteCond %{HTTP_REFERER} !^https?://(www\.)?smgstudio\.fr [NC]
    RewriteCond %{REQUEST_URI} \.(jpe?g|png|gif|webp|mp4|webm|mp3)$ [NC]
    RewriteRule .* - [F,L]
</IfModule>

# ========== CACHE ET PERFORMANCE ==========

<IfModule mod_expires.c>
    ExpiresActive On
    
    # Cache des médias Flying Book
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/webp "access plus 1 month"
    ExpiresByType video/mp4 "access plus 1 month"
    ExpiresByType video/webm "access plus 1 month"
    ExpiresByType audio/mp3 "access plus 1 month"
    ExpiresByType audio/wav "access plus 1 month"
    
    # Cache des assets
    ExpiresByType text/css "access plus 7 days"
    ExpiresByType application/javascript "access plus 7 days"
    ExpiresByType application/pdf "access plus 1 month"
    
    # Pas de cache pour les pages dynamiques
    ExpiresByType text/html "access plus 2 hours"
    ExpiresByType application/json "access plus 1 hour"
</IfModule>

# ========== COMPRESSION ==========

<IfModule mod_deflate.c>
    # Activer la compression
    SetOutputFilter DEFLATE
    
    # Types de fichiers à compresser
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/json
    
    # Exclure les binaires
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|swf|woff|woff2)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
</IfModule>

# ========== REGLES SPECIFIQUES FLYING BOOK ==========

<IfModule mod_rewrite.c>
    RewriteEngine On
    
    # Forcer HTTPS (décommenter si SSL actif)
    # RewriteCond %{HTTPS} off
    # RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # Redirection propre pour les Flying Books publiés
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^flyingbook/([a-zA-Z0-9-]+)/?$ flying_book_viewer.php?slug=$1 [L,QSA]
    
    # API REST pour Flying Book
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^api/v1/(.*)$ api/index.php?endpoint=$1 [L,QSA]
    
    # Bloquer l'accès direct aux fichiers PHP sensibles
    RewriteRule ^(includes|vendor|node_modules)/ - [F,L]
    
    # Empêcher l'accès aux fichiers temporaires
    RewriteRule \.(tmp|temp|bak|backup|swp|old)$ - [F,L]
</IfModule>

# ========== PAGES D'ERREUR PERSONNALISEES ==========

ErrorDocument 400 /errors/400.html
ErrorDocument 401 /errors/401.html
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html
ErrorDocument 503 /errors/503.html

# ========== LOGS DE SECURITE ==========

<IfModule mod_log_config.c>
    # Log des tentatives de sécurité
    LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-For}i\"" flying_book_security
    
    # Activer si besoin de logs détaillés
    # CustomLog /var/log/apache2/flying_book_security.log flying_book_security env=suspicious
</IfModule>

# ========== CONFIGURATION PHP ==========

<IfModule mod_php.c>
    # Désactiver les fonctions dangereuses
    php_admin_value disable_functions "exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source,file_get_contents,fopen,fwrite,file_put_contents"
    
    # Limites de sécurité
    php_value max_execution_time 30
    php_value max_input_time 60
    php_value memory_limit 256M
    php_value post_max_size 100M
    php_value upload_max_filesize 50M
    php_value max_file_uploads 20
    
    # Masquer la version PHP
    php_flag expose_php off
    
    # Session sécurisée
    php_value session.cookie_httponly 1
    php_value session.cookie_secure 1
    php_value session.use_only_cookies 1
    php_value session.cookie_samesite "Strict"
</IfModule>

# ========== MONITORING INTRUSION ==========

<IfModule mod_rewrite.c>
    # Détecter les tentatives d'intrusion
    RewriteCond %{QUERY_STRING} (union.*select|insert.*into|delete.*from|drop.*table) [NC]
    RewriteRule .* /security/intrusion_detected.php [L]
    
    # Bloquer les tentatives de path traversal
    RewriteCond %{THE_REQUEST} \s/+[^\s]*\.(php|asp|jsp|cgi|pl)\?[^\s]*\.\.[^\s]* [NC,OR]
    RewriteCond %{REQUEST_URI} \.\./
    RewriteRule .* - [F,L]
</IfModule>

# ========== MAINTENANCE MODE ==========

# Décommenter pour activer le mode maintenance
# <IfModule mod_rewrite.c>
#     RewriteEngine On
#     RewriteCond %{REQUEST_URI} !/maintenance.html$
#     RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1
#     RewriteCond %{REMOTE_ADDR} !^VOTRE_IP_PUBLIQUE
#     RewriteRule .* /maintenance.html [R=503,L]
# </IfModule>

# ========== FIN CONFIGURATION ==========
# SMG Studio v2.0 - Flying Book Creator
# Configuration sécurisée anti-fouineurs ✅