# .htaccess - ADVANCED SECURITY CONFIGURATION - VERSÃO 1.0
# Leotofalo - Python Full Stack Developer
# Last Updated: 2025-12-10
# Correções: Removido bloqueio de imagens, ícones e arquivos estáticos

# ============================
# EXCEÇÃO CRÍTICA: ARQUIVOS ESTÁTICOS
# ============================
# IMPORTANTE: Esta regra DEVE vir ANTES de qualquer outra regra de reescrita
# Permite acesso direto a imagens, ícones, CSS, JS, fontes sem processamento
RewriteCond %{REQUEST_URI} \.(jpg|jpeg|png|gif|webp|svg|ico|bmp|tiff|css|js|woff|woff2|ttf|eot|otf|pdf|mp4|webm|ogg)$ [NC]
RewriteRule .* - [L]

# ============================
# REWRITE ENGINE & REDIRECTS
# ============================
RewriteEngine On


# Force HTTPS redirect
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Remove www prefix
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# ============================
# URL REWRITING - REMOVE EXTENSIONS
# ============================

# Remove .html extension from URLs (external redirect)
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1? [NC,L,R=301]

# Remove .php extension from URLs (external redirect)
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1? [NC,L,R=301]

# Remove .htm extension from URLs (external redirect)
RewriteCond %{THE_REQUEST} /([^.]+)\.htm [NC]
RewriteRule ^ /%1? [NC,L,R=301]

# Internal rewrite - serve .html files for extensionless URLs
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^.]+)$ $1.html [L]

# Internal rewrite - serve .php files for extensionless URLs
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)$ $1.php [L]

# Internal rewrite - serve .htm files for extensionless URLs
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.htm -f
RewriteRule ^([^.]+)$ $1.htm [L]

# Handle index files in subdirectories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ $1/index.html [L]

# ============================
# ADVANCED SECURITY HEADERS
# ============================
<IfModule mod_headers.c>
    # Prevent clickjacking
    Header always set X-Frame-Options "DENY"
    
    # Prevent MIME type sniffing
    Header always set X-Content-Type-Options "nosniff"
    
    # XSS Protection
    Header always set X-XSS-Protection "1; mode=block"
    
    # Referrer Policy
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # Permissions Policy (formerly Feature Policy)
    Header always set Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), speaker=()"
    
    # Strict Transport Security (HSTS) - Force HTTPS for 2 years
    Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
    
    # Content Security Policy - CORRIGIDO PARA PERMITIR GOOGLE APPS SCRIPT + CHART.JS
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com https://unpkg.com https://cdn.tailwindcss.com https://cdn.jsdelivr.net https://fonts.googleapis.com https://www.google-analytics.com https://www.googletagmanager.com https://www.gstatic.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdnjs.cloudflare.com https://unpkg.com https://cdn.tailwindcss.com; font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com data:; img-src * data: blob: 'self'; connect-src 'self' https://www.google-analytics.com https://analytics.google.com https://script.google.com https://script.googleusercontent.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self' https://script.google.com"    
    # Remove server information
    Header always unset Server
    Header always unset X-Powered-By
    
    # Prevent information disclosure
    Header always set X-Robots-Tag "index, follow"
    
    # Expect-CT header for certificate transparency
    Header always set Expect-CT "max-age=86400, enforce"
</IfModule>

# ============================
# CORS AJUSTADO PARA IMAGENS
# ============================
# CORREÇÃO: Permite que imagens sejam carregadas de qualquer origem
<FilesMatch "\.(jpg|jpeg|png|gif|webp|svg|ico|bmp|tiff)$">
    <IfModule mod_headers.c>
        Header always set Access-Control-Allow-Origin "*"
        Header always set Access-Control-Allow-Methods "GET, OPTIONS"
        Header always set Access-Control-Allow-Headers "Content-Type, Authorization"
    </IfModule>
</FilesMatch>

# CORS para fontes
<FilesMatch "\.(woff|woff2|ttf|eot|otf)$">
    <IfModule mod_headers.c>
        Header always set Access-Control-Allow-Origin "*"
    </IfModule>
</FilesMatch>

# ============================
# FILE ACCESS RESTRICTIONS
# ============================

# Block access to sensitive files
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|sql|conf|bak|backup|swp|tmp|env|git|svn|bzr|hg)$">
    Require all denied
</FilesMatch>

# Block access to version control directories
RedirectMatch 404 /\.git
RedirectMatch 404 /\.svn
RedirectMatch 404 /\.hg
RedirectMatch 404 /\.bzr

# Protect wp-config if WordPress is ever added
<Files wp-config.php>
    Require all denied
</Files>

# Block PHP execution in uploads directory (if created)
<Directory "uploads">
    <Files *.php>
        Require all denied
    </Files>
</Directory>

# ============================
# BOT & CRAWLER PROTECTION
# ============================

# CORREÇÃO: Não aplicar bloqueio de bots para arquivos estáticos
<RequireAll>
    Require all granted
    Require not env bad_bot
</RequireAll>

SetEnvIf User-Agent "(Wget|wget)" bad_bot
SetEnvIf User-Agent "(libwww-perl|LWP)" bad_bot
SetEnvIf User-Agent "(curl|Curl)" bad_bot
SetEnvIf User-Agent "(PHP)" bad_bot
SetEnvIf User-Agent "(Jakarta)" bad_bot
SetEnvIf User-Agent "(WinHttp)" bad_bot
SetEnvIf User-Agent "(Bot|bot|BOT)" !search_bot
SetEnvIf User-Agent "(Googlebot|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|facebookexternalhit|Twitterbot|LinkedInBot|WhatsApp)" search_bot

# EXCEÇÃO: Remover bloqueio de user-agent vazio para arquivos estáticos
RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|png|gif|webp|svg|ico|css|js|woff|woff2|ttf|eot|otf|pdf)$ [NC]
RewriteCond %{HTTP_USER_AGENT} ^-?$
RewriteRule ^.* - [F]

# EXCEÇÃO: Não bloquear query strings em arquivos estáticos
RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|png|gif|webp|svg|ico|css|js|woff|woff2|ttf|eot|pdf)$ [NC]
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).*iframe.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*object.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*embed.*(\>|%3E) [NC]
RewriteRule ^.* - [F]

# ============================
# IP PROTECTION & RATE LIMITING
# ============================

# Block known malicious IP ranges (update as needed)
# Require not ip 192.168.1.100
# Require not ip 10.0.0.0/8

# Simple rate limiting - max 200 requests per minute per IP
# NOTA: Esta regra pode não funcionar em todos os servidores
# RewriteMap requests "txt:/tmp/requests.txt"
# RewriteCond ${requests:%{REMOTE_ADDR}|0} ^([0-9]+)
# RewriteCond %1 >200
# RewriteRule .* - [F,L]

# ============================
# SQL INJECTION PROTECTION
# ============================

# EXCEÇÃO: Não bloquear SQL injection em arquivos estáticos
RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|png|gif|webp|svg|ico|css|js|woff|woff2|ttf|eot|pdf)$ [NC]
RewriteCond %{QUERY_STRING} ([0-9]+)=([0-9]+)--
RewriteRule ^.* - [F]

RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|png|gif|webp|svg|ico|css|js|woff|woff2|ttf|eot|pdf)$ [NC]
RewriteCond %{QUERY_STRING} \b(union|select|insert|delete|drop|create|update|exec)\b [NC]
RewriteRule ^.* - [F]

# ============================
# DIRECTORY TRAVERSAL PROTECTION
# ============================

# Block directory traversal attacks
RewriteCond %{THE_REQUEST} \s/+(.*?)/{2,}([^\s]*) [NC]
RewriteRule .* /%2 [R=301,L]

RewriteCond %{REQUEST_URI} \.\./ [NC,OR]
RewriteCond %{REQUEST_URI} \.(php|pl|py|jsp|asp|aspx|cgi|sh)\$ [NC]
RewriteRule .* - [F]

# ============================
# CACHE & PERFORMANCE
# ============================

<IfModule mod_expires.c>
    ExpiresActive On
    
    # HTML
    ExpiresByType text/html "access plus 1 hour"
    
    # CSS and JavaScript
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    ExpiresByType text/javascript "access plus 1 year"
    
    # Images
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType image/x-icon "access plus 1 year"
    
    # Fonts
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType font/woff "access plus 1 year"
    ExpiresByType application/font-woff2 "access plus 1 year"
    ExpiresByType application/font-woff "access plus 1 year"
</IfModule>

# GZIP Compression
<IfModule mod_deflate.c>
    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
    AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>

# ============================
# ERROR PAGES
# ============================
ErrorDocument 400 /error/400.html
ErrorDocument 401 /error/401.html
ErrorDocument 403 /error/403.html
ErrorDocument 404 /error/404.html
ErrorDocument 500 /error/500.html

# ============================
# MISC SECURITY
# ============================

# Remove server signature
ServerSignature Off

# Disable server-side includes
Options -Includes -ExecCGI

# Disable directory browsing
Options -Indexes

# Turn off ETags
FileETag None

# Limit file upload size (if forms are used)
LimitRequestBody 10485760