7. Shared Runtime Security, Environment Config, Brand Kit & Local Scaffold
Repository:
Microservices (planovi-microservices)• Rule Prefix:BR-INF• Documented Rules: 5 • Open[TEAM_WHY_NEEDED]Questions: 2
1. Business Purpose & Actors
- Problem Solved: Provides shared PHP runtime utilities (session/CSRF/Turnstile/env loading), host-based environment detection, official synced Planovi branding assets, and the local Docker + Nginx + Mailpit container stack for the planned Laravel 11 migration.
- Actors:
- Microservice PHP Scripts: Include
includes/security.php(dealflow/offer.php,dealflow/api/save_response.php,scheduler/backend/api.php) orconfig.php(scheduler/index.php). - Developers & CI/Design Sync: Run
scripts/sync-brand.shanddocker compose up -d --build.
- Microservice PHP Scripts: Include
2. All Features & End-to-End Flows (Happy Path + Error Paths)
- Feature A: Shared Security Library (
includes/security.php)- Idempotent include guard
PLANOVI_SECURITY_LOADED. - Conditional
planovi_load_env(string $path)(defined only if not already declared; parsesKEY=VALUE, skips#comments, trims quotes, does not overwrite existing$_ENV[$k]). - Auto-starts PHP session
PLANOVI_MS(whenPHP_SAPI !== 'cli' && session_status() === PHP_SESSION_NONE && !headers_sent()) withlifetime=0,path=/,secure=true,httponly=true,samesite=None. get_csrf_token(): lazily generates 64-char hex token (bin2hex(random_bytes(32))) in$_SESSION['csrf_token'].verify_csrf_token($token): requires active session and constant-timehash_equals().verify_turnstile(string $token, string $secret): fails closed (false) on empty token/secret, HTTP failure, or missingsuccesstruthy flag; posts to Cloudflare Turnstilesiteverify(timeout=8s, usesHTTP_CF_CONNECTING_IP ?? REMOTE_ADDR, prefers cURL withfile_get_contentsfallback).
- Idempotent include guard
- Feature B: Environment Auto-Detection (
config.php)- Reads
$_SERVER['HTTP_HOST'] ?? 'localhost':- Contains
localhostor127.0.0.1→ENVIRONMENT='local',BASE_URL='http://localhost/planovi',error_reporting(E_ALL),display_errors=1. - Contains
dev-→ENVIRONMENT='staging',BASE_URL='https://dev-webpage.planovi.app',SCHEDULER_URL='https://dev-scheduler.planovi.app',DEALFLOW_URL='https://dev-dealflow.planovi.app',display_errors=1. - Otherwise →
ENVIRONMENT='production',BASE_URL='https://planovi.app',SCHEDULER_URL='https://scheduler.planovi.app',DEALFLOW_URL='https://dealflow.planovi.app',error_reporting(0),display_errors=0.
- Contains
- Currently only
scheduler/index.php:2includesconfig.php, and none of its URL constants are even referenced insidescheduler/index.php.
- Reads
- Feature C: Brand Kit Sync (
scripts/sync-brand.sh+assets/brand/*+BRANDING_GUIDE.md)- Shallow-clones
PA-IDEAS/planovi-docsviagh repo cloneintomktemp -d, copiesbrand-kit/BRANDING_GUIDE.mdto./BRANDING_GUIDE.mdandbrand-kit/assets/.into${1:-assets/brand}, cleans up temp dir onEXITtrap.
- Shallow-clones
- Feature D: Local Laravel/Docker Scaffold (
Dockerfile.local,docker-compose.yml,nginx.local.conf,laravel-app/.env.example)- Builds PHP 8.2-FPM container mounting
./laravel-app:/var/www, connects to host Supabase PostgreSQL onhost.docker.internal:54322, exposes Nginx onlocalhost:8000(root/var/www/public), and runs Mailpit (1025SMTP,8025Web UI).
- Builds PHP 8.2-FPM container mounting
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-INF-01(Turnstile Fails Closed):verify_turnstile()(includes/security.php:89-133) returnsfalseunless Cloudflare returns JSON with truthysuccess. Network timeout is8seconds; logs'verify_turnstile: no response from Cloudflare'viaerror_log().BR-INF-02(CSRF Entropy & Timing Safety): CSRF tokens are 256-bit (random_bytes(32)→ 64 hex chars) and verified exclusively withhash_equals()(includes/security.php:67, 81).BR-INF-03(PHP Compile-Time Hoisting Dependency):dealflow/offer.php:13-16callsrequire_once '../includes/security.php'before declaringfunction planovi_load_env(...). This executes cleanly solely because PHP hoists top-level function declarations at compile time beforerequire_onceevaluatesif (!function_exists('planovi_load_env')).BR-INF-04(Production Error Suppression Only Whenconfig.phpIncluded): Onlyscheduler/index.phpincludesconfig.php(error_reporting(0); ini_set('display_errors', 0)in prod). Other PHP entrypoints rely on serverphp.inidefaults (exceptscheduler/backend/api.php:5which explicitly setsini_set('display_errors', '0')).BR-INF-05(Cookie Banner Partial Duplication):dealflow/cookie-banner.phpandscheduler/cookie-banner.phpare functionally identical (differ only in whitespace/formatting), store acceptance inlocalStorage['planovi_cookies_accepted'] = 'true', link to broken relative path/assets/for_preview/index.php, and use legacy neon-blue styling (#4169e1→#00d9ff).
4. State Machines & Data Lifecycle
Not applicable (stateless infrastructure/helpers; PHP session PLANOVI_MS has browser-session lifetime 0).
5. Technical Contract (Inputs → Processing → Side Effects)
- PHP Functions Exported (
includes/security.php):planovi_load_env(string $path): void,get_csrf_token(): string,verify_csrf_token($token): bool,verify_turnstile(string $token, string $secret): bool. - PHP Constants Exported (
config.php):ENVIRONMENT,BASE_URL,SCHEDULER_URL,DEALFLOW_URL,IS_LOCAL,IS_STAGING,IS_PRODUCTION,ASSETS_URL,CSS_URL,JS_URL,IMG_URL. - Docker Ports Exposed (
docker-compose.yml):8000(Nginx),1025(Mailpit SMTP),8025(Mailpit UI).
6. Cross-Repository Dependencies
| Caller | Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|---|
scripts/sync-brand.sh | PA-IDEAS/planovi-docs | Git/GitHub CLI (gh repo clone, user auth) | brand-kit/BRANDING_GUIDE.md & brand-kit/assets/ |
docker-compose.yml (app) | Local Supabase CLI (planovi-backend) | TCP PostgreSQL (host.docker.internal:54322) | Local Postgres DB for Laravel scaffold |
7. Why It Works This Way (Decisions, Trade-offs & Workarounds)
- Inline
.envParsers Duplicated Across 8 Files: Because microservices evolved as standalone PHP files without a Composer autoloader at root (onlyscheduler/has Composer), nearly every entrypoint implements its own.envreader — causing subtle inconsistencies (quote stripping vs non-stripping). - Database Drivers in Docker (
README.md:59):CACHE_DRIVER,QUEUE_CONNECTION, andSESSION_DRIVERare set todatabasebecause production has no Redis instance. [TEAM_WHY_NEEDED: What is the current status and timeline of the Laravel 11 migration (laravel-app/ has only .env.example)? Should new features and branding fixes target the plain PHP files, Laravel, or both?][TEAM_WHY_NEEDED: Why does README.md list an offers/ microservice (offers.planovi.app) and Python runtime when no offers/ directory or Python files exist in this repository?]
8. Debugging, Logs & Common Failure Modes
| Symptom / Error Message | Root Cause in Code | How to Verify / Exact Log or Query | Fix |
|---|---|---|---|
http://localhost:8000 returns 404/403 after docker compose up | laravel-app/public/index.php does not exist in git (only .env.example is committed). | ls -la laravel-app/ | Initialize/checkout Laravel app code into laravel-app/, or serve legacy PHP microservices with php -S localhost:8080. |
.env values contain literal quotes causing 401/URL errors | agreements/sign.php, dealflow/sign.php, dealflow/inquiry.php, dealflow/inquiry-success.php, and dealflow/payment-success.php do NOT strip quotes from .env values. | Check whether .env uses KEY="value" syntax. | Standardize all PHP entrypoints to require_once __DIR__ . '/../includes/security.php' and call planovi_load_env(). |
scripts/sync-brand.sh fails with permission/auth error | gh CLI not authenticated to PA-IDEAS/planovi-docs. | Run gh auth status. | Run gh auth login before running ./scripts/sync-brand.sh. |