# / .htaccess

# 1. Disable directory listing (Security)
Options -Indexes

# Block direct access to dotfiles (.env, .htaccess, .gitignore, .aiexclude …) and the .git
# directory, plus VCS/backup/source artefacts. Without this, Apache serves these as plain
# static files because they exist on disk (the SPA reroute below only catches *missing* paths).
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  # 403 any request whose path has a segment starting with a dot (e.g. /.env, /.git/config),
  # except /.well-known/ which must stay reachable for ACME/TLS challenges.
  RewriteCond %{REQUEST_URI} !^/\.well-known/
  RewriteCond %{REQUEST_URI} (^|/)\. [NC]
  RewriteRule ^ - [F,L]
</IfModule>

# Defense-in-depth for when mod_rewrite is unavailable. Apache 2.4 syntax.
<FilesMatch "^\.">
  Require all denied
</FilesMatch>
<FilesMatch "\.(env|sql|sqlite|log|bak|orig|ini|sh|lock|dist)$">
  Require all denied
</FilesMatch>

# An archive is never a page, and the deny-lists above and below do not cover one. Rule 4 at the
# bottom only routes paths that do NOT exist (!-f), so any real file Apache can find is served
# verbatim — which is how a signed module package left in modules/ during a manual update was
# downloadable in full over the open web (confirmed 200 on a live install, 2026-09-08; that is
# paid module source, and manual file-copy updates are the documented procedure until the release
# pipeline lands). Extension-based, so it holds in every directory, including site/themes/ and
# uploads/, and it needs no mod_rewrite. Nothing this product serves is an archive: the updater
# fetches packages from updates.tilspire.com, whose docroot is the separate Tilspire/updates repo
# and does not carry this file. Key and signature material is here for the same reason — a
# keypair copied into the docroot by accident should 403, not download.
<FilesMatch "\.(zip|tar|gz|tgz|bz2|xz|rar|7z|pem|key|crt|p12|pfx|asc|sig)$">
  Require all denied
</FilesMatch>

# Markdown is never served over HTTP. CLAUDE.md and .docs/ are tracked in git (so they reach the
# server via the Plesk pull) but must not be readable by the public — they carry architecture
# notes, internal IPs and schema detail. The dot-segment rewrite above already covers /.docs/*;
# this catches root-level CLAUDE.md and any other .md that lands in the docroot.
<FilesMatch "\.md$">
  Require all denied
</FilesMatch>

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # 1a. Hand the Authorization header to PHP. Apache withholds it from PHP run as CGI or FastCGI,
    # so an Operator API bearer sent that way would silently vanish and every credential would be
    # refused. The API reads X-Api-Token first for the same reason; this keeps Bearer working too,
    # and the suite asserts the rule is still here.
    RewriteCond %{HTTP:Authorization} .
    RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # 1b. Block dot-segments (/.env, /.git/config, /.docs/*) — except ACME challenges.
    RewriteCond %{REQUEST_URI} !^/\.well-known/
    RewriteCond %{REQUEST_URI} (^|/)\. [NC]
    RewriteRule ^ - [F,L]

    # 2. Hard-Block direct access to the engine and configuration
    # EXEMPTIONS: Allow public access to assets and action endpoints
    RewriteCond %{REQUEST_URI} !^/core/admin/assets/ [NC]
    RewriteCond %{REQUEST_URI} !^/core/assets/ [NC]
    RewriteCond %{REQUEST_URI} !^/core/actions/ [NC]
    RewriteRule ^core/ - [F,L]
    
    RewriteRule ^site/config/ - [F,L]

    # Runtime state under site/ is never web-readable. Backup filenames are
    # <name>-backup-YYYYMMDD-HHMMSS.json — date-guessable, so no directory listing is
    # needed — and a backup JSON carries the whole settings table, i.e. SMTP credentials
    # and API secrets on any configured install. Confirmed served 200 on a real install
    # 2026-08-26. site/cache/ holds rendered pages and the updater's extracted staging
    # tree. site/sessions/ holds every visitor's session, each file named after the session id
    # (1.14.0). site/drafts/ holds images an Operator API draft proposed and files an approved
    # deletion kept to restore from (1.15.0): neither may be served before a person decides, or
    # after. Backed up by the per-directory .htaccess Security::ensureDirGuard() writes when the
    # app creates each directory. An nginx vhost needs the same four in its own deny rule.
    RewriteRule ^site/(backups|cache|sessions|drafts)/ - [F,L]

    # Developer tooling is never packaged (tools/ is outside Updater::MANAGED), but on a
    # dev box the repo IS the docroot, so every script under it was one request away —
    # tools/release/build.php answered 200 until 2026-09-18. Each script also refuses a
    # non-CLI SAPI itself: that in-file guard is the layer that survives nginx.
    RewriteRule ^tools/ - [F,L]

    # Theme PHP is include-only. A partial is a REAL file, so the !-f master rewrite at
    # the bottom never sees it and Apache hands it straight to PHP: header.php starts a
    # session and mints a CSRF token before it fatals, and the fatal prints the absolute
    # filesystem path. Matches .php ONLY, so theme assets (css/js/images) are untouched.
    # Backed up by `defined('CMS_NAME') || exit;` inside each partial — the only layer
    # that survives an nginx-fronted install, where .htaccess is inert.
    RewriteRule ^site/themes/.*\.php$ - [F,L]
    
    # Block execution of any script that might get uploaded maliciously. The path is
    # /uploads/ (media/ + tickets/) — the old rule pointed at ^site/uploads/, which has
    # never existed in this layout, so the guard matched nothing. Backed up by the
    # per-directory .htaccess in uploads/media/ and uploads/tickets/.
    RewriteRule ^uploads/.*\.(php|php\.|phtml|phps|php[0-9]|cgi|pl|py|jsp|asp|aspx|shtml|sh)$ - [F,L,NC]

    # 2b. Modules live under the web root: allow their static assets + AJAX action
    # endpoints, but block direct access to source, views, migrations and manifests
    # (those are only ever included server-side by the kernel/router).
    RewriteCond %{REQUEST_URI} !^/modules/[^/]+/actions/ [NC]
    RewriteRule ^modules/[^/]+/.*\.(php|json|sql|md|lock)$ - [F,L]

    # 2c. Media fallback (1.19.0): a new upload lives in uploads/media/YYYY/MM/, and a theme may still
    # build /uploads/media/<name>. A FLAT name there that is no file goes to index.php, which answers
    # 301 to the file's month-folder address or routes on to the 404 (Core\Lib\MediaFallback). Ahead
    # of rule 3, which would hand a missing image to Apache's own 404. Nothing else under uploads/ is
    # routed, and never a script extension: the rule above refuses those first, and this pattern and
    # MediaFallback::claims() refuse them again. nginx: the try_files line in site-install.md.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !\.(php|php\.|phtml|phps|php[0-9]|cgi|pl|py|jsp|asp|aspx|shtml|sh)$ [NC]
    RewriteRule ^uploads/media/([A-Za-z0-9][A-Za-z0-9._-]*)$ index.php?url=uploads/media/$1 [QSA,L]

    # 2d. An imported file's old address (1.20.2): the two folders the Importer's sources kept their files in, at any
    # depth because the old site may have lived under a path. Without this, rule 3 hands a missing image to Apache's own
    # 404 and no old address could ever answer. Only a name that is no file, only an image, so a missing image anywhere
    # else stays the cheap 404 it was. index.php answers 301 from the import's map, or the site's 404
    # (Core\Lib\OldFileAddress). On nginx this file is inert: importer.md says what that means.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^((?:[^/]+/)*(?:site/assets/files/[0-9]+|wp-content/uploads(?:/[0-9]{4}/[0-9]{2})?)/[^/]+\.(?:jpe?g|png|gif|webp))$ index.php?url=$1 [NC,QSA,L]

    # 3. Allow direct access to static assets (CSS, JS, Images, Fonts)
    RewriteCond %{REQUEST_URI} \.(css|js|jpg|jpeg|png|gif|svg|woff|woff2|ttf|eot|ico)$ [NC]
    RewriteRule ^ - [L]

    # 4. Master Routing: Send everything else to index.php
    # If the request is not a real file or a real directory, route it!
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

# 5. Browser and CDN lifetimes for static files (1.18.0). Every directive sits in an <IfModule>,
# so a host without the module (or nginx, where this file is inert) serves exactly what it did.
# Scoped by FILENAME, never by the query alone: a page or PHP endpoint is rewritten to index.php,
# which this pattern never matches, so `/?v=1` or `/account?v=1` can never come back `public`.
# A `?v=` URL changes whenever its file does (Template::assetVersion(), the module and core
# versions, Image::versioned()), so a week is safe; anything unversioned is stale for an hour at
# most. Uploads carry s-maxage=300 (HttpCache::CDN_MAX_AGE): no CDN keeps a taken-down image longer
# than it may keep a page. Ticket attachments are personal and get nothing (uploads/tickets/
# denies or forces a download on its own).
<IfModule mod_headers.c>
    <FilesMatch "\.(css|js|woff2?|ttf|svg|png|jpe?g|gif|webp|avif|ico)$">
        <If "%{REQUEST_URI} =~ m#^/uploads/(?!tickets/)#i && %{QUERY_STRING} =~ /(^|&)v=/">
            Header set Cache-Control "public, max-age=604800, s-maxage=300"
        </If>
        <ElseIf "%{REQUEST_URI} =~ m#^/uploads/(?!tickets/)#i">
            Header set Cache-Control "public, max-age=3600, s-maxage=300"
        </ElseIf>
        <ElseIf "%{REQUEST_URI} !~ m#^/uploads/#i && %{QUERY_STRING} =~ /(^|&)v=/">
            Header set Cache-Control "public, max-age=604800"
        </ElseIf>
        <ElseIf "%{REQUEST_URI} !~ m#^/uploads/#i">
            Header set Cache-Control "public, max-age=3600"
        </ElseIf>
    </FilesMatch>
</IfModule>

# 6. Compression of text responses where the host has not done it (a host that
# compresses already, like Plesk's nginx, is untouched). Brotli first, so a browser that takes it
# gets it; each module skips a response another has already encoded. PHP never compresses: it
# would replace a host's brotli with gzip and spend CPU on every hit.
<IfModule mod_filter.c>
    <IfModule mod_brotli.c>
        AddOutputFilterByType BROTLI_COMPRESS text/html text/css text/plain text/xml text/javascript application/javascript application/json application/xml application/rss+xml image/svg+xml
    </IfModule>
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/javascript application/javascript application/json application/xml application/rss+xml image/svg+xml
    </IfModule>
</IfModule>