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) withcookie_httponly=1,cookie_samesite=Lax, andcookie_secure=1when$_SERVER['HTTPS']is non-empty and not'off'.
- Trigger: Any page executing
- Flow B — Language Switch via Query Parameter (
i18n.php:20-54):- Trigger: Request with
?lang=plor?lang=en. - Validation: Strict allowlist check
in_array($_GET['lang'], ['pl', 'en'], true). Invalid values are ignored. - State Change: Writes
$_SESSION['lang']and sets cookielang(expires = time() + 2592000,path = '/',httponly = true,samesite = 'Lax',secure = HTTPS). - Response: Strips
langfrom query string (preserving other query params likeslug,category,q), validates path starts with/and not//(otherwise resets to/), respondsHTTP 302 Location: <redirectUrl>, and exits.
- Trigger: Request with
- 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}.jsoninto global$translations. __(string $key, array $replacements = []): Traverses dot-separated segments on$translations. Returns raw$keyif path missing or non-string. Replaces:nametokens viastr_replace.
- Resolution order:
- Flow D — Blog HTML Sanitization (
includes/security.php:33-143):- Trigger:
blog-post.php:252passes$post['content']tosanitize_blog_html(). - Processing: Loads HTML wrapped in
<?xml encoding="UTF-8"><div>...</div>viaDOMDocument::loadHTML(..., LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD). Recursively traverses DOM: unwraps disallowed tags, stripson*event attributes, enforces per-tag/global attribute allowlists, stripsjavascript:/vbscript:/data:URIs onhref/src/poster, forcesrel="noopener noreferrer"ona[target="_blank"]. Falls back tohtmlspecialchars()if root<div>is missing.
- Trigger:
- 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]+)*$/withstrlen($slug) <= 150; returnsfalseon 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):
langcookie persists for86400 * 30seconds (30 days),Path=/,HttpOnly,SameSite=Lax,Secureonly 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()emitsX-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, andwaitlist-qualify-handler.phpdo NOT invokesend_security_headers(). NoContent-Security-PolicyorStrict-Transport-Securityheader 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 attributesid,classplus tag-specific attributes fora, 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$parentand$cleanNodeimmediatelyreturns. Because$parentsnapshotted$childrenbefore iterating (lines 123-129), hoisted child elements are NEVER sanitized. A payload such as<svg><img src="x" onerror="alert(1)"></svg>preserves theonerrorattribute 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 PostgRESTeq.andor=(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]+)*$/, max150bytes;includes/security.php:167-176). However,.htaccess:29,router.php:21,index.php:12, andblog-post.php:9match[a-zA-Z0-9_\-]+, causing slugs with uppercase letters or underscores to route intoblog-post.phpand fail with HTTP404. - BR-SEC-09 (Explicit vs. Session Translation Split):
i18n.php’s__(...)always reads the active session/cookie dictionary ($current_lang), whereasincludes/waitlist.php:59-74’swl_t($lang, $key)loadslang/{$lang}.jsoninto 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 with302redirect.
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=via302prevents 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.phpintentionally avoidsi18n.phpso JSON API calls stay stateless and respect the JSONlangfield 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 Message | Root Cause in Code | How to Verify | Fix |
|---|---|---|---|
Literal key like blog.title rendered in HTML | Missing 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 proxy | Reverse proxy strips HTTPS var or browser blocks insecure cookie; check Set-Cookie header | curl -I 'https://planovi.app/?lang=en' | Ensure Nginx passes fastcgi_param HTTPS on; |
| Blog article with underscores or capital letters in slug returns 404 | validate_slug() (includes/security.php:172) only permits [a-z0-9] and - | Check website.blog_posts.slug in Supabase | Normalize DB slug to lowercase kebab-case |