Skip to content

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) or config.php (scheduler/index.php).
    • Developers & CI/Design Sync: Run scripts/sync-brand.sh and docker compose up -d --build.

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; parses KEY=VALUE, skips # comments, trims quotes, does not overwrite existing $_ENV[$k]).
    • Auto-starts PHP session PLANOVI_MS (when PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_NONE && !headers_sent()) with lifetime=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-time hash_equals().
    • verify_turnstile(string $token, string $secret): fails closed (false) on empty token/secret, HTTP failure, or missing success truthy flag; posts to Cloudflare Turnstile siteverify (timeout=8s, uses HTTP_CF_CONNECTING_IP ?? REMOTE_ADDR, prefers cURL with file_get_contents fallback).
  • Feature B: Environment Auto-Detection (config.php)
    • Reads $_SERVER['HTTP_HOST'] ?? 'localhost':
      • Contains localhost or 127.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.
    • Currently only scheduler/index.php:2 includes config.php, and none of its URL constants are even referenced inside scheduler/index.php.
  • Feature C: Brand Kit Sync (scripts/sync-brand.sh + assets/brand/* + BRANDING_GUIDE.md)
    • Shallow-clones PA-IDEAS/planovi-docs via gh repo clone into mktemp -d, copies brand-kit/BRANDING_GUIDE.md to ./BRANDING_GUIDE.md and brand-kit/assets/. into ${1:-assets/brand}, cleans up temp dir on EXIT trap.
  • 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 on host.docker.internal:54322, exposes Nginx on localhost:8000 (root /var/www/public), and runs Mailpit (1025 SMTP, 8025 Web UI).

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

  • BR-INF-01 (Turnstile Fails Closed): verify_turnstile() (includes/security.php:89-133) returns false unless Cloudflare returns JSON with truthy success. Network timeout is 8 seconds; logs 'verify_turnstile: no response from Cloudflare' via error_log().
  • BR-INF-02 (CSRF Entropy & Timing Safety): CSRF tokens are 256-bit (random_bytes(32) → 64 hex chars) and verified exclusively with hash_equals() (includes/security.php:67, 81).
  • BR-INF-03 (PHP Compile-Time Hoisting Dependency): dealflow/offer.php:13-16 calls require_once '../includes/security.php' before declaring function planovi_load_env(...). This executes cleanly solely because PHP hoists top-level function declarations at compile time before require_once evaluates if (!function_exists('planovi_load_env')).
  • BR-INF-04 (Production Error Suppression Only When config.php Included): Only scheduler/index.php includes config.php (error_reporting(0); ini_set('display_errors', 0) in prod). Other PHP entrypoints rely on server php.ini defaults (except scheduler/backend/api.php:5 which explicitly sets ini_set('display_errors', '0')).
  • BR-INF-05 (Cookie Banner Partial Duplication): dealflow/cookie-banner.php and scheduler/cookie-banner.php are functionally identical (differ only in whitespace/formatting), store acceptance in localStorage['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

CallerCalleeProtocol & AuthExact Endpoint / Contract
scripts/sync-brand.shPA-IDEAS/planovi-docsGit/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 .env Parsers Duplicated Across 8 Files: Because microservices evolved as standalone PHP files without a Composer autoloader at root (only scheduler/ has Composer), nearly every entrypoint implements its own .env reader — causing subtle inconsistencies (quote stripping vs non-stripping).
  • Database Drivers in Docker (README.md:59): CACHE_DRIVER, QUEUE_CONNECTION, and SESSION_DRIVER are set to database because 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 MessageRoot Cause in CodeHow to Verify / Exact Log or QueryFix
http://localhost:8000 returns 404/403 after docker compose uplaravel-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 errorsagreements/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 errorgh CLI not authenticated to PA-IDEAS/planovi-docs.Run gh auth status.Run gh auth login before running ./scripts/sync-brand.sh.