Skip to content

2. Internationalization (i18n) & Security Hardening Layer

Repository: Webpage (planovi-webpage) • Rule Prefix: BR-SEC • Documented Rules: 9 • Open [TEAM_WHY_NEEDED] Questions: 2

1. Business Purpose & Actors

  • Problem solved: Delivers bilingual Polish (pl, default) and English (en) copy with persistent language selection, while applying baseline HTTP security headers, Open Redirect protection, PostgREST query injection mitigation, slug validation, and HTML sanitization for CMS-authored blog posts.
  • Actors: All website visitors switching between PL/EN; CMS/n8n authors whose HTML is sanitized at render time; security scanners/browsers enforcing response headers.

2. All Features & End-to-End Flows

  • Flow A — Security Header & Session Initialization (i18n.php:1-15, includes/security.php:14-23):
    • Trigger: Any page executing require_once 'i18n.php'.
    • Processing: Calls send_security_headers() emitting 5 headers (if !headers_sent()). Starts PHP session (session_status() === PHP_SESSION_NONE) with cookie_httponly=1, cookie_samesite=Lax, and cookie_secure=1 when $_SERVER['HTTPS'] is non-empty and not 'off'.
  • Flow B — Language Switch via Query Parameter (i18n.php:20-54):
    • Trigger: Request with ?lang=pl or ?lang=en.
    • Validation: Strict allowlist check in_array($_GET['lang'], ['pl', 'en'], true). Invalid values are ignored.
    • State Change: Writes $_SESSION['lang'] and sets cookie lang (expires = time() + 2592000, path = '/', httponly = true, samesite = 'Lax', secure = HTTPS).
    • Response: Strips lang from query string (preserving other query params like slug, category, q), validates path starts with / and not // (otherwise resets to /), responds HTTP 302 Location: <redirectUrl>, and exits.
  • Flow C — Language Resolution & Dictionary Load (i18n.php:56-98):
    • Resolution order: $_SESSION['lang'] → $_COOKIE['lang'] (if in ['pl', 'en'], also backfills $_SESSION['lang']) → $default_lang = 'pl'.
    • Loads lang/{$current_lang}.json into global $translations.
    • __(string $key, array $replacements = []): Traverses dot-separated segments on $translations. Returns raw $key if path missing or non-string. Replaces :name tokens via str_replace.
  • Flow D — Blog HTML Sanitization (includes/security.php:33-143):
    • Trigger: blog-post.php:252 passes $post['content'] to sanitize_blog_html().
    • Processing: Loads HTML wrapped in <?xml encoding="UTF-8"><div>...</div> via DOMDocument::loadHTML(..., LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD). Recursively traverses DOM: unwraps disallowed tags, strips on* event attributes, enforces per-tag/global attribute allowlists, strips javascript:/vbscript:/data: URIs on href/src/poster, forces rel="noopener noreferrer" on a[target="_blank"]. Falls back to htmlspecialchars() if root <div> is missing.
  • Flow E — PostgREST Filter Sanitization & Slug Validation (includes/security.php:152-176):
    • sanitize_postgrest_query($input): Removes [(),.*%\\] and trims.
    • validate_slug($slug): Trims and matches /^[a-z0-9]+(?:-[a-z0-9]+)*$/ with strlen($slug) <= 150; returns false on failure.

3. Hard Business Rules, Validations, Calculations & Edge Cases

  • BR-SEC-01 (Allowed Locales & Default): Only 'pl' and 'en' are accepted; default is 'pl' (i18n.php:17-18).
  • BR-SEC-02 (Language Cookie TTL & Flags): lang cookie persists for 86400 * 30 seconds (30 days), Path=/, HttpOnly, SameSite=Lax, Secure only when $_SERVER['HTTPS'] is non-empty and !== 'off' (i18n.php:26-32).
  • BR-SEC-03 (Open Redirect Guard on Language Switch): Redirect path must satisfy str_starts_with($path, '/') && !str_starts_with($path, '//'), otherwise coerced to '/'; scheme/host are dropped by taking only $parts['path'] and $parts['query'] (i18n.php:36-43).
  • BR-SEC-04 (Baseline Security Headers Coverage Gap): send_security_headers() emits X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN, Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy: geolocation=(), microphone=(), camera=(), X-XSS-Protection: 1; mode=block (includes/security.php:14-23). Edge Case: sitemap.php, waitlist-handler.php, and waitlist-qualify-handler.php do NOT invoke send_security_headers(). No Content-Security-Policy or Strict-Transport-Security header is emitted by PHP.
  • BR-SEC-05 (Blog HTML Tag & Attribute Allowlist): sanitize_blog_html() permits exactly 36 HTML tags (p, h1-h6, br, hr, strong, b, em, i, u, s, small, sub, sup, ul, ol, li, blockquote, pre, code, a, img, video, source, figure, figcaption, table, thead, tbody, tr, th, td, span, div) and global attributes id, class plus tag-specific attributes for a, img, video, source, table, pre, code, span, div (includes/security.php:38-57).
  • BR-SEC-06 (DOM-Unwrapping XSS Bypass Vulnerability in sanitize_blog_html): When a disallowed tag is encountered (includes/security.php:72-79), its child nodes are hoisted into $parent and $cleanNode immediately returns. Because $parent snapshotted $children before iterating (lines 123-129), hoisted child elements are NEVER sanitized. A payload such as <svg><img src="x" onerror="alert(1)"></svg> preserves the onerror attribute in the output. Furthermore, <script>...</script> unwraps its text node into visible HTML rather than deleting the subtree, and URI scheme checks (line 104) do not strip leading control characters/entities before checking ^(javascript|vbscript|data):.
  • BR-SEC-07 (PostgREST Operator Injection Filter): sanitize_postgrest_query() strips (, ), ,, ., *, %, and \ before interpolating into PostgREST eq. and or=(title.ilike.*...*) query strings (includes/security.php:152-159).
  • BR-SEC-08 (Slug Validation vs. Router Regex Mismatch): validate_slug() requires strictly lowercase ASCII alphanumeric segments separated by single hyphens (/^[a-z0-9]+(?:-[a-z0-9]+)*$/, max 150 bytes; includes/security.php:167-176). However, .htaccess:29, router.php:21, index.php:12, and blog-post.php:9 match [a-zA-Z0-9_\-]+, causing slugs with uppercase letters or underscores to route into blog-post.php and fail with HTTP 404.
  • BR-SEC-09 (Explicit vs. Session Translation Split): i18n.php’s __(...) always reads the active session/cookie dictionary ($current_lang), whereas includes/waitlist.php:59-74’s wl_t($lang, $key) loads lang/{$lang}.json into a static cache for an explicit request language without starting a PHP session.

4. State Machines & Data Lifecycle

Language state transitions: Default ('pl') → [?lang=en] → Session + Cookie ('en', 30d TTL) + 302 Redirect → [?lang=pl] → Session + Cookie ('pl', 30d TTL) + 302 Redirect.

5. Technical Contract (Inputs → Processing → Side Effects)

  • Inputs: $_GET['lang'], $_COOKIE['lang'], $_SESSION['lang'], lang/pl.json, lang/en.json, raw HTML/query/slug strings.
  • Processing: Header emission, session start, JSON decode, DOMDocument sanitization, regex validation.
  • Side Effects: Sends HTTP headers and Set-Cookie: lang=... / PHPSESSID; writes PHP session file on server; may terminate request with 302 redirect.

6. Cross-Repository Dependencies

None (self-contained local JSON dictionaries and PHP standard library).

7. Why It Works This Way (Decisions, Trade-offs & Workarounds)

  • PRG (Post/Redirect/Get-style) ?lang= redirect: Stripping ?lang= via 302 prevents duplicate indexed URLs and keeps shareable links clean while persisting choice in cookie + session (i18n.php:34-53).
  • No session in waitlist API endpoints: includes/waitlist.php intentionally avoids i18n.php so JSON API calls stay stateless and respect the JSON lang field directly (includes/waitlist.php:58).
  • [TEAM_WHY_NEEDED: Behind Hostinger VPS Nginx TLS termination, is HTTPS=on forwarded to PHP-FPM so i18n.php sets the Secure flag on PHPSESSID and lang cookies?]
  • [TEAM_WHY_NEEDED: Why does lang/pl.json:105 have truncated "most_popular": "Najczęściej " (missing "wybierany"), and why are pricing bullets in index.php:362-401 and maintenance timestamps in status.php:221-222 hardcoded in Polish instead of using i18n keys?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to VerifyFix
Literal key like blog.title rendered in HTMLMissing key in lang/{lang}.json or malformed JSON causing json_decode to return null (i18n.php:71,85)php -r 'json_decode(file_get_contents("lang/pl.json"), true, 512, JSON_THROW_ON_ERROR);'Fix JSON syntax or add missing key in both pl.json and en.json
Language resets after browser restart on HTTPS reverse proxyReverse proxy strips HTTPS var or browser blocks insecure cookie; check Set-Cookie headercurl -I 'https://planovi.app/?lang=en'Ensure Nginx passes fastcgi_param HTTPS on;
Blog article with underscores or capital letters in slug returns 404validate_slug() (includes/security.php:172) only permits [a-z0-9] and -Check website.blog_posts.slug in SupabaseNormalize DB slug to lowercase kebab-case