# TechTalks — Full-Stack Kits & AI Security Masterclasses
> Canonical Website: https://techtalks.itsumarfarooq.com
> Author: Umar Farooq (Senior Full-Stack & Security Engineer)
> Portfolio: https://itsumarfarooq.com
> GitHub: https://github.com/Umar-444
> GitHub Repository: https://github.com/Umar-444/Techtalks-stack-kits
> LinkedIn: https://linkedin.com/in/umar444
> X / Twitter: https://x.com/@umartechtalks
> Email: contact@itsumarfarooq.com
## About TechTalks
TechTalks is an open-source engineering knowledge platform providing production-tested full-stack project setups with pre-wired AI agent rules (transpiled to 6 native dialects: Cursor, Claude Code, Copilot, Cline, Codex, Antigravity) alongside comprehensive threat models and verified security masterclasses.
===============================================================================
## Master Stack Kits Catalogue (18 Kits & Layers in 5 Tiers)
### Tier 1: Laravel Ecosystem
- [Laravel 13 + Filament 4 + PostgreSQL](https://techtalks.itsumarfarooq.com/kits/laravel-filament-postgresql/) — `Complete & Verified`. PHP 8.4, Filament 4, PostgreSQL 16+. UUID v7, BOLA authorization policies, zero plaintext credentials.
- [Laravel 12 + Livewire 4 + PostgreSQL](https://techtalks.itsumarfarooq.com/kits/laravel-livewire-postgresql/) — `Complete & Verified`. PHP 8.3+, Livewire 4, Flux UI, Volt single-file components, Folio routing.
- [Laravel 12 + MongoDB NoSQL](https://techtalks.itsumarfarooq.com/kits/laravel-mongodb/) — `Complete & Verified`. PHP 8.3+, MongoDB 7.0+, mongodb/laravel-mongodb Eloquent driver, NoSQL injection defenses.
- [Laravel + MySQL Dashboard](https://techtalks.itsumarfarooq.com/kits/laravel-mysql/) — `Blueprint (Build Next)`. PHP 8.4, MySQL 8, Larastan Level 8, Pest Arch tests, high-concurrency indexing.
- **Laravel + Filament + MySQL** — `Planned`. Enterprise admin architecture tailored for existing MySQL infrastructure.
- **Laravel API + Sanctum** — `Planned`. Pure headless API architecture, sliding tokens, rate limiting, and OpenAPI schema generators.
### Tier 2: JavaScript & TypeScript
- [Next.js 15+ + Supabase + shadcn/ui](https://techtalks.itsumarfarooq.com/kits/nextjs-approuter-supabase/) — `Complete & Verified`. Next.js 15, React 19, Supabase RLS, Server Actions with Zod validation.
- **Next.js 15 + Prisma + PostgreSQL** — `Planned`. Type-safe ORM integration, automated schema migrations, and connection pooling.
- **Next.js AI Chatbot** — `Planned`. Vercel AI SDK, streaming UI, prompt safety guardrails, and token-cost fences.
### Tier 3: Python Web & API
- [Django 5+ + Tailwind + PostgreSQL](https://techtalks.itsumarfarooq.com/kits/django-tailwind-postgresql/) — `Blueprint`. Python 3.12+, Django 5, Celery background queues, django-tailwind, custom user model auth.
- [Flask 3 + HTMX + Alpine.js](https://techtalks.itsumarfarooq.com/kits/flask-htmx-sqlite/) — `Blueprint`. Lightweight hypermedia stack, partial HTML over the wire, zero heavy JS build tooling.
- **FastAPI Modern Backend** — `Planned`. Python 3.12+, async endpoints, Pydantic v2 schemas, automated OpenAPI documentation, and JWT security gates.
### Tier 4: AI & Agentic Systems
- [Production RAG Stack](https://techtalks.itsumarfarooq.com/kits/rag-fastapi-qdrant/) — `Blueprint`. Python 3.12+, FastAPI, Qdrant / Chroma, multi-tenant vector isolation, Ragas evaluation benchmark.
- [Autonomous Multi-Agent System](https://techtalks.itsumarfarooq.com/kits/agentic-langgraph-crewai/) — `Blueprint`. LangGraph, CrewAI, Docker sandboxing, human-in-the-loop approvals, and tool execution fences.
- **MCP Tools Kit** — `Planned`. Standard Model Context Protocol servers for secure local agent tooling and database introspection.
- **Laravel AI Features** — `Planned`. Native Laravel integration of prompt injection defense, dual-LLM arbiters, and PII redaction from the masterclass.
### Tier 5: Foundation Layers
- **DESIGN.md Design System Library** — Canonical visual design tokens, contrast ratios, and layout invariants enforced across agent prompts.
- [Reverse Engineering & Security Agent Stack](https://techtalks.itsumarfarooq.com/kits/reverse-engineering-security/) — `Blueprint`. GhidraMCP, Radare2, Semgrep AST analysis, firmware decompilation pipelines.
===============================================================================
# COMPLETE STACK KITS SPECIFICATIONS & AGENT BUILD STEPS
===============================================================================
## KIT SPECIFICATION: laravel-filament-postgresql
# Laravel 12/13 + Filament 4/3 + PostgreSQL — TechTalks Stack Kit
[](https://techtalks.itsumarfarooq.com/kits/laravel-filament-postgresql/)
[](https://techtalks.itsumarfarooq.com/kits/laravel-filament-postgresql/)
[](LICENSE)
Official TechTalks Flagship Stack Kit for **Laravel 12/13 + Filament 4/3 + PostgreSQL 16+**. A production-ready, verified project setup combining an opinionated starter, multi-agent rules transpiled to 8 dialect targets, specialized skills, a comprehensive `DESIGN.md`, and automated security guardrails.
- **Kit Slug:** `laravel-filament-postgresql`
- **Documentation & Catalog:** [techtalks.itsumarfarooq.com/kits/laravel-filament-postgresql/](https://techtalks.itsumarfarooq.com/kits/laravel-filament-postgresql/)
- **Repository:** [github.com/Umar-444/Techtalks-stack-kits](https://github.com/Umar-444/Techtalks-stack-kits)
---
## What is Inside This Kit
| Component | Path | Description |
|---|---|---|
| **Starter Skeleton** | `starter/` | Clean PHP 8.4 + Laravel 12/13 project, multi-stage Docker Compose (PostgreSQL 16, Redis 7, Mailpit, Horizon). |
| **Agent Rules** | `rules/source/` | Single-source rules transpiled to Cursor, Claude Code, Codex, Copilot, Antigravity, and Windsurf formats. |
| **Specialized Skills** | `skills/` | Standardized agent workflows (`make-filament-resource`, `pest-arch-test`). |
| **Design System** | `DESIGN.md` | Concrete tokens, typography, Filament table and form layouts, WCAG AA contrast rules. |
| **Security Standard** | `SECURITY.md` | Automated Gitleaks scanning, Semgrep AST rules, Spatie RBAC, and Pest Arch regression tests. |
| **Agent Build Steps** | `steps/agent-build-steps.md` | 10 linear agent tasks with self-verification commands. |
---
## Quickstart
### 1. Clone Repository
```bash
git clone https://github.com/Umar-444/Techtalks-stack-kits.git
cd Techtalks-stack-kits/kits/laravel-filament-postgresql
```
### 2. Configure Environment & Launch Docker
```bash
cp starter/.env.example starter/.env
cd starter
docker compose up -d --build
docker compose exec app composer install
docker compose exec app php artisan migrate --seed
```
### 3. Transpile Agent Rules (if editing rules)
```bash
# Transpiles rules/source/*.md into 6 agent formats with drift validation
python ../../tools/transpiler.py kits/laravel-filament-postgresql
```
---
## Agent Prompt Kickoff
Paste this prompt into your AI coding assistant (Claude, Cursor, Codex, or Antigravity):
```text
You are an expert full-stack engineer building with the TechTalks "laravel-filament-postgresql" kit.
Read kit.yaml, AGENTS.md, DESIGN.md, and steps/agent-build-steps.md before executing any actions.
Adhere strictly to:
1. PHP 8.4 typed properties and Laravel 12/13 conventions.
2. Filament navigation organized by workflow, not raw database tables.
3. Every resource action must have an explicit Policy check ($this->authorize).
4. All database queries must be parameterized via PDO / Eloquent.
Follow steps/agent-build-steps.md sequentially and report in: Done, Files, Verified, Not verified.
```
### laravel-filament-postgresql Agent Build Steps
# Agent Build Steps — Laravel 12/13 + Filament 4/3 + PostgreSQL
# Linear, self-verifying implementation prompts for AI agents.
Follow each step sequentially. Run the verification command after completing each step. If verification fails, fix the issue before proceeding to the next step.
---
### Step 1: Environment & Container Initialization
**Action:** Copy `.env.example` to `.env`. Configure PostgreSQL 16 connection parameters (`DB_CONNECTION=pgsql`, `DB_HOST=postgres`, `DB_PORT=5432`, `DB_DATABASE=app_production`, `DB_USERNAME=app_user`). Start the multi-container environment with Docker Compose.
**Verification:**
```bash
docker compose ps
docker compose exec app php artisan db:monitor
```
*Expected: Containers healthy, database connected.*
---
### Step 2: Base Migrations & PostgreSQL Schemas
**Action:** Configure PostgreSQL UUID extension (`uuid-ossp` or `gen_random_uuid()`). Ensure all primary keys use UUIDs. Apply initial database migrations for users, sessions, cache, and queue jobs.
**Verification:**
```bash
docker compose exec app php artisan migrate:status
```
*Expected: All core migrations have status 'Ran'.*
---
### Step 3: Filament Admin Panel Installation
**Action:** Register Filament admin panel in SPA mode (`->spa()`). Apply custom branding matching `DESIGN.md` (primary color `#E85D26`, navigation grouping, favicon).
**Verification:**
```bash
docker compose exec app php artisan filament:upgrade
curl -s http://localhost:8000/admin/login | grep -q "Filament"
```
*Expected: Filament assets published and login page returns HTTP 200.*
---
### Step 4: Spatie RBAC & Seeded Roles
**Action:** Install and configure Spatie Laravel Permission. Create seeded roles (`Superadmin`, `Admin`, `Auditor`). Enforce that the Superadmin bypasses permissions via `Gate::before`.
**Verification:**
```bash
docker compose exec app php artisan db:seed --class=RoleAndPermissionSeeder
```
*Expected: Roles and permissions created without errors.*
---
### Step 5: User Management Resource & Policies
**Action:** Create a Filament resource for User management with view, edit, and role assignment. Generate a strict `UserPolicy` ensuring only Superadmins can assign the Superadmin role.
**Verification:**
```bash
docker compose exec app php artisan test --filter=UserResourceTest
```
*Expected: Resource tests pass with 100% assertion success.*
---
### Step 6: Multi-Tenant Schema or Role Scoping
**Action:** Configure tenant scoping or team scoping so records created by a team cannot be accessed or modified by unauthorized users (BOLA defense).
**Verification:**
```bash
docker compose exec app php artisan test --filter=TenantIsolationTest
```
*Expected: Unauthorized cross-tenant queries return 403 Forbidden.*
---
### Step 7: Queue Worker & Redis Horizon
**Action:** Configure Redis 7 for cache and queue. Set up Laravel Horizon dashboard protected by `can:viewHorizon` gate.
**Verification:**
```bash
docker compose exec app php artisan horizon:status
```
*Expected: Horizon is running and healthy.*
---
### Step 8: Pest Architecture Tests
**Action:** Implement Pest architecture tests in `tests/ArchTest.php` asserting:
1. Controllers do not directly invoke `DB::raw()`.
2. All models use UUID traits and guard against mass assignment.
3. No debugging statements (`dd`, `dump`, `ray`) exist in codebase.
**Verification:**
```bash
docker compose exec app ./vendor/bin/pest tests/ArchTest.php
```
*Expected: All architectural assertions pass.*
---
### Step 9: Static Analysis & Style Linting
**Action:** Run Larastan at Level 8 and Laravel Pint to enforce strict types and style standards.
**Verification:**
```bash
docker compose exec app ./vendor/bin/phpstan analyse
docker compose exec app ./vendor/bin/pint --test
```
*Expected: Zero errors found at Level 8.*
---
### Step 10: Full Security Scan & Git Integrity
**Action:** Run Gitleaks and Semgrep static analysis across the entire project repository.
**Verification:**
```bash
gitleaks detect --source . --verbose
semgrep scan --config "p/php" --config "p/owasp-top-ten"
```
*Expected: Zero plaintext credentials and zero OWASP Top 10 vulnerabilities detected.*
## KIT SPECIFICATION: laravel-livewire-postgresql
# Laravel 12 + Livewire 4 + PostgreSQL — TechTalks Stack Kit
[](https://techtalks.itsumarfarooq.com/kits/laravel-livewire-postgresql/)
[](https://techtalks.itsumarfarooq.com/kits/laravel-livewire-postgresql/)
Official TechTalks Stack Kit for **Laravel 12 + Livewire 4 + Flux UI + PostgreSQL 16+**. Reactive full-stack architecture using Volt single-file components and Folio page-based routing.
## What is Inside
- **Starter Skeleton:** Clean PHP 8.4 + Laravel 12 project with PostgreSQL Docker Compose.
- **Rules (Transpiled):** Single-source rules for Volt, Folio, Flux UI, and Livewire security invariants.
- **Skills:** `skills/flux-component/SKILL.md` for scaffolding reactive components.
- **Design:** `DESIGN.md` with Flux UI tokens and dark mode support.
- **Security:** `SECURITY.md` covering Livewire property locking, CSRF, and authorization.
### laravel-livewire-postgresql Agent Build Steps
# Agent Build Steps — Laravel 12 + Livewire 4 + PostgreSQL
### Step 1: Environment Setup
Configure `.env` for PostgreSQL 16 and launch Docker containers.
*Verification:* `docker compose ps`
### Step 2: Livewire 4 & Volt Installation
Install Livewire 4 and configure Volt single-file component discovery.
*Verification:* `php artisan volt:install`
### Step 3: Flux UI Integration
Publish Flux UI component views and apply DESIGN.md color tokens.
*Verification:* `php artisan test --filter=FluxTest`
### Step 4: Security Verification
Verify all Livewire components enforce `#[Locked]` on immutable state and check policies.
*Verification:* `vendor/bin/pest tests/Feature/LivewireSecurityTest.php`
## KIT SPECIFICATION: laravel-mongodb
# Laravel 12 + MongoDB (NoSQL) — TechTalks Stack Kit
[](https://techtalks.itsumarfarooq.com/kits/laravel-mongodb/)
[](https://techtalks.itsumarfarooq.com/kits/laravel-mongodb/)
Official TechTalks Empty-Market Pioneer Kit for **Laravel 12 + MongoDB 7+ + React/Inertia**. Combines the official `mongodb/laravel-mongodb` package, embedded documents, and custom dashboard components.
## What is Inside
- **Starter Skeleton:** Clean PHP 8.4 + Laravel 12 project with MongoDB 7 Docker Compose.
- **Rules (Transpiled):** Single-source rules for MongoDB Eloquent, aggregation pipelines, and NoSQL injection security.
- **Skills:** `skills/mongodb-aggregation/SKILL.md` for writing aggregation queries.
- **Design:** `DESIGN.md` for Inertia React dashboard layouts.
- **Security:** `SECURITY.md` covering NoSQL injection defense and operator whitelisting.
### laravel-mongodb Agent Build Steps
# Agent Build Steps — Laravel 12 + MongoDB (NoSQL)
### Step 1: Environment Setup
Configure `.env` for MongoDB 7 (`DB_CONNECTION=mongodb`, `DB_HOST=mongodb`) and launch Docker containers.
*Verification:* `docker compose ps`
### Step 2: MongoDB Package Configuration
Install `mongodb/laravel-mongodb` and verify service provider registration.
*Verification:* `php artisan mongodb:test`
### Step 3: Document Models & Embedded Relations
Implement models extending `MongoDB\Laravel\Eloquent\Model` with embedded relationships.
*Verification:* `vendor/bin/pest tests/Feature/MongoDBModelTest.php`
### Step 4: Security Verification
Run Semgrep checks ensuring zero usage of `$where` or unescaped BSON queries.
*Verification:* `semgrep scan --config "p/php"`
## KIT SPECIFICATION: nextjs-approuter-supabase
# Next.js 15+ + Supabase + shadcn/ui — TechTalks Stack Kit
[](https://techtalks.itsumarfarooq.com/kits/nextjs-approuter-supabase/)
[](https://techtalks.itsumarfarooq.com/kits/nextjs-approuter-supabase/)
Official TechTalks Stack Kit for **Next.js 15 App Router + Supabase + shadcn/ui**. Full-stack TypeScript architecture with React Server Components, Zod-validated Server Actions, and database Row-Level Security.
## What is Inside
- **Starter Skeleton:** Clean Next.js 15 project with Supabase SSR client integration.
- **Rules (Transpiled):** Single-source rules for Server Actions, Supabase RLS policies, and App Router caching.
- **Skills:** `skills/supabase-rls/SKILL.md` for writing RLS SQL policies.
- **Design:** `DESIGN.md` for shadcn/ui token customization.
- **Security:** `SECURITY.md` covering service role key protection and BOLA defense.
### nextjs-approuter-supabase Agent Build Steps
# Agent Build Steps — Next.js 15+ + Supabase + shadcn/ui
### Step 1: Environment Setup
Configure `.env.local` with Supabase project credentials.
*Verification:* `npm run dev`
### Step 2: Supabase SSR Client Initialization
Set up server and client Supabase utilities using `@supabase/ssr`.
*Verification:* `npx tsx scripts/test-supabase.ts`
### Step 3: Server Action & Zod Validation
Implement mutations using Server Actions and enforce Zod payload validation.
*Verification:* `npm run test`
### Step 4: Row-Level Security Audit
Verify all tables reject unauthorized read and write operations.
*Verification:* `npx supabase test db`
===============================================================================
# COMPLETE SECURITY MASTERCLASS LESSONS (ALL 22 TRACK LESSONS)
===============================================================================
--- FILE: docs/01-foundations\laravel-security.md ---
# Laravel Security Best Practices — Laravel 13
> **Requirements:** Laravel 11 minimum, **Laravel 13 recommended**. Laravel 10 reached EOL on February 4, 2025 — do not use in production.
## Authentication & Authorization
Laravel 13 provides a robust, modern security foundation. Use the official starter kits for authentication scaffolding.
### Installing API Authentication (Laravel 13)
```bash
# Install Sanctum via artisan (Laravel 11+ replaces manual setup)
php artisan install:api
# This publishes migrations, config, and sets up Sanctum automatically
```
### Middleware Registration — `bootstrap/app.php` (Laravel 11+)
> Warning: **`app/Http/Kernel.php` was removed in Laravel 11.** All middleware must now be registered in `bootstrap/app.php`.
```php
withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (\Illuminate\Foundation\Configuration\Middleware $middleware) {
// Global middleware (runs on every request)
$middleware->append(SecurityHeaders::class);
$middleware->append(ForceHttps::class);
// Named middleware aliases
$middleware->alias([
'role' => \App\Http\Middleware\CheckRole::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
]);
// API middleware group
$middleware->api(append: [
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
]);
})
->withExceptions(function (\Illuminate\Foundation\Configuration\Exceptions $exceptions) {
$exceptions->renderable(function (\Throwable $e, $request) {
if ($request->expectsJson()) {
return response()->json(['error' => 'Server error'], 500);
}
});
})
->create();
```
### Key Features in Laravel 13
| Feature | Description |
|---|---|
| `install:api` artisan command | One-command Sanctum API setup |
| Enhanced `Rate::` facade | Named rate limiters with per-user scoping |
| `Precognition` | Real-time validation before form submission |
| `Model::preventSilentlyDiscardingAttributes()` | Throws exception on unguarded mass-assignment |
| `withoutOverlapping()` | Prevents concurrent job execution |
| Improved `Health` checks | Built-in `/up` endpoint for deployment monitoring |
## Mass Assignment Protection
Laravel protects against mass assignment vulnerabilities. Always use `$fillable` — never `$guarded = []`.
```php
first();
// [SECURE] Query Builder — parameterized
$users = DB::table('users')
->where('role', $role)
->where('active', true)
->get();
// [SECURE] Raw query with binding (when needed)
$results = DB::select('SELECT * FROM users WHERE email = ?', [$email]);
// [INSECURE] NEVER — SQL injection vulnerability
$results = DB::select("SELECT * FROM users WHERE email = '$email'");
```
## Cross-Site Scripting (XSS) Protection
- Blade `{{ }}` auto-escapes all output — use it by default
- Only use `{!! !!}` for **trusted, sanitized** HTML content
- Implement strict CSP with nonces (see [Secure Headers](SecureHeaders.md))
```blade
{{-- Safe — auto-escaped --}}
{{ $user->name }}
{{-- Warning: Only for pre-sanitized HTML (use with caution) --}}
{!! $sanitizedHtml !!}
{{-- Blade components auto-escape attributes --}}
```
## Encrypted Model Attributes (Store Secrets at Rest)
```php
'encrypted',
'api_key' => 'encrypted',
'settings' => 'encrypted:array', // Encrypted JSON
];
}
}
```
## File Storage Security
```php
validate([
'document' => [
'required',
'file',
'max:10240', // 10MB max
'mimes:pdf,docx,xlsx', // MIME allowlist
'mimetypes:application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document',
],
]);
// Cryptographically random filename — prevents enumeration
$filename = Str::random(40) . '.' . $request->file('document')->getClientOriginalExtension();
// Store in private disk (outside web root)
$path = $request->file('document')->storeAs('documents', $filename, 'private');
return response()->json(['path' => $path]);
}
public function download(string $filename)
{
// Authorization check first
$this->authorize('download', $filename);
// Serve from private storage — not publicly accessible
return Storage::disk('private')->download('documents/' . $filename);
}
}
```
## API Security with Laravel Sanctum 4.x
```php
validate([
'email' => ['required', 'email:rfc,dns'],
'password' => ['required', 'string', 'min:15'],
'device' => ['required', 'string', 'max:255'],
]);
if (!Auth::attempt($request->only('email', 'password'))) {
throw ValidationException::withMessages([
'email' => ['Invalid credentials.'],
]);
}
$user = $request->user();
// Revoke all previous tokens for this device
$user->tokens()->where('name', $request->device)->delete();
// Create scoped token
$token = $user->createToken(
name: $request->device,
abilities: ['read', 'write'],
expiresAt: now()->addDays(30),
);
return response()->json([
'token' => $token->plainTextToken,
'type' => 'Bearer',
'expires_at' => $token->accessToken->expires_at,
]);
}
public function logout(Request $request)
{
// Revoke current token
$request->user()->currentAccessToken()->delete();
return response()->json(['message' => 'Logged out successfully']);
}
}
```
## Rate Limiting (Laravel 13 `Rate::` Facade)
```php
user()
? Limit::perMinute(120)->by($request->user()->id) // Authenticated: 120/min
: Limit::perMinute(20)->by($request->ip()); // Guest: 20/min
});
RateLimiter::for('login', function (Request $request) {
return [
Limit::perMinute(5)->by($request->ip()),
Limit::perMinute(10)->by($request->input('email')),
];
});
```
## Environment Security
```php
// .env — production essentials
APP_ENV=production
APP_DEBUG=false // Warning: NEVER true in production
APP_KEY=base64:... // Must be set — used for encryption
// Laravel 13: use secrets manager for sensitive values
// AWS SSM: APP_KEY=${ssm:/myapp/prod/app_key}
// HashiCorp Vault: APP_KEY=${vault:secret/myapp/app_key}
```
## Security Middleware (Laravel 13)
```php
withMiddleware(function ($middleware) {
// Enforce HTTPS in production
if (app()->isProduction()) {
$middleware->append(\Illuminate\Http\Middleware\TrustProxies::class);
}
// Prevent clickjacking, set security headers
$middleware->append(\App\Http\Middleware\SecurityHeaders::class);
// CSRF — enabled for web, excluded for API (uses token auth)
$middleware->web(append: [
\App\Http\Middleware\VerifyCsrfToken::class,
]);
})
```
## Database Security
```php
[
'driver' => 'mysql',
'host' => env('DB_HOST'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'options' => [
// [SECURE] Encrypted DB connection
PDO::MYSQL_ATTR_SSL_CA => env('DB_SSL_CA'),
PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => true,
PDO::ATTR_EMULATE_PREPARES => false, // Disable emulated prepares
PDO::ATTR_STRINGIFY_FETCHES => false,
],
],
```
## Laravel 13 EOL Schedule (Reference)
| Version | Status | EOL Date |
|---|---|---|
| Laravel 13 | [SECURE] Current | August 2027 (security: Feb 2028) |
| Laravel 12 | [SECURE] Active LTS | February 2027 (security: Feb 2028) |
| Laravel 11 | [SECURE] Supported | September 2026 |
| Laravel 10 | [INSECURE] EOL | February 4, 2025 |
| Laravel 9 | [INSECURE] EOL | February 8, 2024 |
--- FILE: docs/01-foundations\php-security.md ---
# PHP Security Best Practices — PHP 8.4
> **Requirements:** PHP 8.2 minimum, PHP 8.4 recommended. PHP 8.1 is EOL (November 2024) — do not use in production.
## Input Validation & Sanitization
Always validate and sanitize user input to prevent injection attacks.
### Key Principles
- Never trust user input
- Use allowlists (not blocklists) for validation
- Sanitize output based on context (HTML, JSON, SQL, shell, etc.)
- Validate data types and formats strictly
### PHP 8.4 Typed Enums for Safe Type Handling
```php
$ext === $uploadedExt);
if ($match === null) {
throw new InvalidArgumentException('File type not allowed');
}
```
### PHP 8.4 — `#[\Deprecated]` Attribute for Insecure Code
```php
prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
```
## Cross-Site Scripting (XSS) Protection
- Escape output using `htmlspecialchars()` with `ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5`
- Use Content Security Policy (CSP) with nonces — **no `unsafe-inline`**
- Validate and sanitize input
- Use Laravel's Blade `{{ }}` which auto-escapes
```php
file($_FILES['upload']['tmp_name']);
$allowedMimes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
if (!in_array($mimeType, $allowedMimes, true)) {
throw new RuntimeException('Invalid file type');
}
// Cryptographically secure filename
$filename = bin2hex(random_bytes(16)) . '.jpg';
```
## Authentication & Authorization
- Use `password_hash()` with `PASSWORD_ARGON2ID` (OWASP 2024 recommendation)
- Minimum password length: **15 characters** (NIST SP 800-63B 2024)
- Implement Passkeys/WebAuthn as the preferred passwordless option
- Use HTTPS everywhere — TLS 1.3 preferred
- Implement rate limiting and account lockout
- Log all authentication events to structured logs
```php
65536, // 64MB minimum
'time_cost' => 3, // 3 iterations (OWASP 2024)
'threads' => 1, // 1 thread (recommended for web)
]);
// [SECURE] Always use password_verify() — timing-safe
if (password_verify($inputPassword, $hash)) {
// authenticated
}
// [SECURE] Rehash on login if parameters have changed
if (password_needs_rehash($hash, PASSWORD_ARGON2ID, ['memory_cost' => 65536, 'time_cost' => 3, 'threads' => 1])) {
$newHash = password_hash($password, PASSWORD_ARGON2ID, ['memory_cost' => 65536, 'time_cost' => 3, 'threads' => 1]);
// Update hash in database
}
```
## Error Handling
- Never expose stack traces, SQL errors, or file paths in production
- Use custom error pages (`APP_DEBUG=false` in production)
- Log errors to structured log files (Monolog/Sentry), never to the browser
- Handle all exceptions — use a top-level exception handler
```php
getMessage(), $e->getFile(), $e->getLine()));
// Return generic message to user
http_response_code(500);
echo json_encode(['error' => 'An internal server error occurred.']);
exit;
});
```
## Configuration Security
- Store ALL secrets in environment variables — never in code
- Use secrets managers (HashiCorp Vault, AWS SSM, Azure Key Vault) in production
- Restrict file permissions: `640` for configs, `750` for directories
- Keep all dependencies updated — run `composer audit --locked` in CI/CD
```bash
# Run daily in CI/CD
composer audit --locked
# Check for known vulnerabilities
composer outdated --direct
```
## PHP 8.4 Security-Relevant New Features
| Feature | Security Benefit |
|---|---|
| `array_find()` / `array_find_key()` | Safer array lookups without manual loops |
| `#[\Deprecated]` attribute | Mark insecure code formally |
| `new` in initializers | Cleaner DI for security services |
| Asymmetric property visibility | Better encapsulation of sensitive data |
| Typed class constants | Prevents type confusion in constants |
| DOM API (HTML5 parser) | Safer HTML parsing for XSS prevention |
| BCMath object API | Safer arbitrary precision for crypto math |
## PHP EOL Schedule (Reference)
| Version | Status | EOL Date |
|---|---|---|
| PHP 8.4 | Active | November 2027 |
| PHP 8.3 | [SECURE] Security fixes | November 2026 |
| PHP 8.2 | [SECURE] Security fixes | December 2026 |
| PHP 8.1 | [INSECURE] EOL | November 25, 2024 |
| PHP 8.0 | [INSECURE] EOL | November 26, 2023 |
--- FILE: docs/01-foundations\secure-coding-basics.md ---
# Secure Coding Basics
## What is Secure Coding?
Secure coding is the practice of writing software that protects against security vulnerabilities and threats. It involves implementing security measures throughout the development lifecycle to prevent, detect, and respond to security incidents.
### Key Principles of Secure Coding
1. **Defense in Depth** - Multiple layers of security controls
2. **Least Privilege** - Grant minimal necessary permissions
3. **Fail-Safe Defaults** - Default to secure behavior
4. **Input Validation** - Never trust user input
5. **Error Handling** - Don't expose sensitive information in errors
## Why Security Matters in Web Applications
### The Cost of Security Breaches
- **Financial Impact**: Data breaches cost companies millions annually
- **Reputation Damage**: Loss of customer trust and brand value
- **Legal Consequences**: Compliance violations and lawsuits
- **Operational Disruption**: System downtime and recovery costs
### Real-World Statistics
- **78%** of web applications have at least one serious vulnerability (OWASP)
- **300,000** new malware samples discovered daily
- **43%** of cyber attacks target small businesses
- **Average breach cost**: $4.45 million (IBM Cost of a Data Breach Report)
## How Attackers Target PHP and Laravel Applications
### Common Attack Vectors
#### 1. **Injection Attacks**
```php
// VULNERABLE - Direct string concatenation
$query = "SELECT * FROM users WHERE id = " . $_GET['id'];
// SECURE - Prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_GET['id']]);
```
#### 2. **Cross-Site Scripting (XSS)**
```php
// VULNERABLE - Direct output without escaping
echo "
" . htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8') . "
";
```
#### HTML Attribute Context
```php
// INCORRECT
echo "";
```
#### URL Context
```php
function escapeUrl($url) {
// Use urlencode for URL parameters
return urlencode($url);
}
// Better: validate and then escape
function safeUrl($url) {
$validated = filter_var($url, FILTER_VALIDATE_URL);
return $validated ? htmlspecialchars($validated, ENT_QUOTES, 'UTF-8') : '';
}
```
## Content Security Policy (CSP)
CSP is a security standard that helps prevent XSS by controlling which resources can be loaded and executed.
### Basic CSP Header
```php
// PHP header
header("Content-Security-Policy: default-src 'self'");
// HTML meta tag
```
### Comprehensive CSP
```php
header("Content-Security-Policy: "
. "default-src 'self'; "
. "script-src 'self' 'unsafe-inline' 'unsafe-eval'; "
. "style-src 'self' 'unsafe-inline'; "
. "img-src 'self' data: https:; "
. "font-src 'self' data:; "
. "connect-src 'self'; "
. "media-src 'none'; "
. "object-src 'none'; "
. "child-src 'self'; "
. "frame-ancestors 'none'; "
. "form-action 'self'; "
. "upgrade-insecure-requests"
);
```
### CSP Nonces for Inline Scripts
```php
// Generate nonce
$nonce = bin2hex(random_bytes(16));
// Set CSP header
header("Content-Security-Policy: script-src 'self' 'nonce-{$nonce}'");
// Use nonce in script
echo "";
```
## Input Validation and Sanitization
### Input Validation (Defense in Depth)
```php
// Validate input format before output
function validateAndDisplayName($name) {
// Validate format (allow-list approach)
if (!preg_match('/^[a-zA-Z\s\-\.\']{1,100}$/', $name)) {
return 'Invalid name format';
}
// Even with validation, still escape output
return htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
}
```
### Input Sanitization
```php
function sanitizeHtml($input) {
// Remove potentially dangerous tags
$allowedTags = '
';
return strip_tags($input, $allowedTags);
}
function sanitizeForDisplay($input) {
// Multi-step sanitization
$input = trim($input); // Remove whitespace
$input = htmlspecialchars($input, ENT_QUOTES); // Escape HTML
$input = filter_var($input, FILTER_SANITIZE_STRING); // Additional sanitization
return $input;
}
```
## Laravel XSS Protection
### Blade Templating Engine
Laravel's Blade engine automatically escapes output:
```blade
{{-- Automatic escaping --}}
Welcome, {{ $name }}
{{-- Explicit unescaping (use only for trusted content) --}}
Welcome, {!! $trustedHtml !!}
```
### Blade Escaping Functions
```blade
{{-- HTML escaping --}}
{{ $userInput }} {{-- Automatically escaped --}}
{{-- JavaScript escaping --}}
{{-- Attribute escaping --}}
{{-- Raw output (dangerous - only for trusted content) --}}
{!! $htmlContent !!}
```
### Laravel Form Helpers
```php
// Form input with automatic escaping
Form::text('name', $value);
// Raw form input (requires manual escaping)
Form::macro('rawText', function($name, $value) {
return '';
});
```
### Laravel Security Middleware
```php
headers->set('X-XSS-Protection', '1; mode=block');
$response->headers->set('X-Content-Type-Options', 'nosniff');
// Add CSP header
$response->headers->set('Content-Security-Policy',
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'");
return $response;
}
}
```
## Advanced XSS Prevention Techniques
### 1. Template Engines
Using dedicated template engines prevents XSS:
```php
// Twig (PHP template engine)
$loader = new Twig_Loader_Filesystem('templates/');
$twig = new Twig_Environment($loader, [
'autoescape' => 'html' // Automatic escaping
]);
echo $twig->render('page.html', ['name' => $userInput]);
```
### 2. HTML Purifier
Comprehensive HTML sanitization library:
```php
require_once 'vendor/ezyang/htmlpurifier/library/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
// Clean HTML input
$cleanHtml = $purifier->purify($userInput);
echo $cleanHtml; // Safe to display
```
### 3. Input Encoding Validation
Ensure input encoding is valid:
```php
function validateAndNormalizeInput($input) {
// Check for valid UTF-8
if (!mb_check_encoding($input, 'UTF-8')) {
throw new Exception('Invalid character encoding');
}
// Normalize Unicode (prevent homograph attacks)
$input = normalizer_normalize($input, Normalizer::FORM_C);
// Remove control characters
$input = preg_replace('/\p{Cc}/u', '', $input);
return $input;
}
```
## XSS in Different Contexts
### 1. JSON Responses
```php
// VULNERABLE: Direct JSON output
header('Content-Type: application/json');
echo json_encode(['message' => $_GET['msg']]);
// SECURE: Validate input before JSON encoding
$message = htmlspecialchars($_GET['msg'], ENT_QUOTES);
echo json_encode(['message' => $message]);
```
### 2. XML Output
```php
// VULNERABLE: Direct XML output
$message = $_POST['message'];
$xml = "{$message}";
// SECURE: Escape XML entities
$message = htmlspecialchars($message, ENT_QUOTES);
$xml = "{$message}";
```
### 3. CSS Injection
```php
// VULNERABLE: Direct CSS output
$color = $_GET['color'];
echo "";
// SECURE: Validate CSS values
$allowedColors = ['red', 'blue', 'green', 'black', 'white'];
$color = in_array($color, $allowedColors) ? $color : 'white';
echo "";
```
## XSS Testing and Detection
### Manual Testing
```html