# Security & Access Control

> **Last verified:** 2026-10-31 against the working tree — decoupled panel gates (`User::canAccessPanel`), first-time vendor onboarding enforcement (`EnsureVendorOnboardingCompleted`), token gates (`ProductController::reveal`), Free vs. Paid Interactive Prompt Engine isolation (`products/show.blade.php`), scoped queries, 30-day trusted device 2FA cookies (`trusted_device_{user_id}`), withdrawal concurrency locks (`WDR-XXXXXX`), coupon validation, and webhook handling were verified.

## 1. Multi-Panel Role Authorization
In a multi-vendor digital marketplace, securing access to administrative control vs seller functionality is essential.

### A. Strict Panel Authorization (`User::canAccessPanel` & `AuthController`)
- **Panel Authorization & Guard Checks**:
  - `User::canAccessPanel(Panel $panel)` strictly verifies roles and account restrictions:
    - Rejects any user where `$this->isBanned()` or `$this->is_suspended` is `true`.
    - `/admin`: Restricted strictly to `role === 'admin'`.
    - `/vendor/dashboard` (and `/vendor/*` routes): Accessible immediately to any non-suspended, non-banned user with `role === 'vendor'` — **decoupled from Admin KYC approval** so new sellers have instant access after registration and onboarding.
  - `UserResource`, `VendorResource`, and `PayoutResource` strictly enforce `canViewAny()` ensuring non-admins cannot access admin resources.
  - Vendor resources (`ProductResource`, `VendorSalesResource`, `CouponResource`, `VendorReviewResource`, `TicketResource`) enforce `getEloquentQuery()` query scoping (`where('user_id', auth()->id())`).

- **Vendor Profile Singleton Scoping (`/vendor/profile`)**:
  - The profile page is a singleton custom page (`App\Filament\Vendor\Pages\Profile`, slug `profile`) that accepts **no route parameters** and always binds its form to `auth()->user()`, so there is no ID parameter left to tamper with.
  - `GET /vendor/vendor-profile` 302-redirects to `/vendor/profile`; the former parameterized `/vendor/vendor-profile/{id}` route no longer exists (verified `404`).
  - Cross-vendor isolation therefore relies on the query scoping listed below (`where('user_id', auth()->id())`) on every vendor resource.
  - NID/Passport numbers are validated as unique across `vendor_settings` (a vendor cannot reuse another account's identity number).
- **First-Time Vendor Onboarding & Decoupled KYC Middleware (`VendorPanelProvider::authMiddleware()`)**:
  - `App\Http\Middleware\EnsureVendorOnboardingCompleted`: Intercepts any authenticated vendor with `onboarding_completed_at === null` and redirects them to `/vendor/onboarding` (allowing Livewire & logout requests). Once `onboarding_completed_at` is stamped, visiting `/vendor/onboarding` redirects back to `/vendor/dashboard`.
  - `App\Http\Middleware\EnsureVendorIsVerified`: Enforces suspension/ban blocks (`abort(403)`) while granting unverified vendors (`is_verified = false` / `verification_status != 'approved'`) **full operational freedom** across all 10 Vendor Panel pages (upload prompts, manage prompts, create coupons, reply to reviews, open tickets, add payment methods). Admin KYC approval specifically controls the **Verified Seller Badge (`✓`)** (`$user->isVerified()`) and surfaces a helpful KYC notice inside the Request Withdrawal modal on `/vendor/payouts`.
- **Private KYC Document Delivery**:
  - Vendor-side KYC uploads use the **private `local` disk** (`kyc-documents/`, `visibility('private')`, path from `config('marketplace.kyc_disk')`) — never a public URL.
  - `KycPreviewController` (`GET /vendor/kyc/preview/{file}`, base64-encoded path) serves the file only to its owner (`id_document` / `id_document_back` / `id_document_selfie` match) or an admin; everyone else gets `403`, and traversal attempts (`..`), malformed paths and missing files get `404`.
- **Account Restriction (Ban & Suspension) Enforcement**:
  - `User::isBanned()` and `is_suspended` are checked in `AuthController` login flows and `RevalidateAdminSession`; banned or suspended users are rejected immediately, and `Product::scopePublished()` hides prompts belonging to banned/suspended vendors.
  - Admins manage bans in `UserResource` (`is_banned` toggle + `ban_reason` textarea) and vendor suspensions/payout freezes in `VendorResource` (`is_suspended` + `is_payout_frozen`).

- **Withdrawal & Payout Security Controls (`/vendor/payouts` & `/admin/payouts`)**:
  - Payout balance calculations (`getAvailableBalanceAttribute`, `getPendingWithdrawalBalanceAttribute`, `getWithdrawnTotalAttribute`) enforce `total_earnings - (pending + processing + completed payouts)` so funds in flight are immediately locked and cannot be double-withdrawn.
  - Withdrawal initiation (`VendorBilling::submitWithdrawalRequest()`) uses `DB::transaction()` with `User::lockForUpdate()`, checks `is_payout_frozen`, validates against the configured minimum threshold (`MARKETPLACE_MIN_WITHDRAWAL` env, default `$20.00` via `config/marketplace.php`), generates a unique `WDR-XXXXXX` `reference_id`, and stores an immutable JSON snapshot of the selected `PayoutMethod` in `payout_details`.
  - Payout status transitions (`Mark as Processing`, `Complete & Mark Paid`, and `Reject & Refund Balance` which restores `available_balance` and notifies the vendor) are restricted to admins via `PayoutResource` and `VendorResource\RelationManagers\PayoutsRelationManager`.
- In `App\Filament\Vendor\Resources\VendorSalesResource::getEloquentQuery()`, sales transactions are strictly scoped using `whereHas('product', fn($q) => $q->where('user_id', auth()->id()))`.
- In `App\Filament\Vendor\Resources\VendorReviewResource::getEloquentQuery()`, customer reviews are strictly scoped to the vendor's own profile and prompt listings (`where('vendor_id', auth()->id())->orWhereHas('product', fn ($q) => $q->where('user_id', auth()->id()))`).
- In `App\Filament\Vendor\Resources\CouponResource::getEloquentQuery()`, coupons are scoped with `where('user_id', auth()->id())`; at checkout `ProductController@checkout` only accepts a coupon whose `user_id` equals the product's creator, and `Coupon::isValid()` enforces `is_active`, expiry, `usage_limit` and `min_order_amount` before any discount is applied (amounts are computed server-side, never trusted from input).
- **Support Ticket Scoping & Isolation**:
  - In `App\Filament\Vendor\Resources\TicketResource::getEloquentQuery()`, support tickets are strictly scoped to `where('user_id', auth()->id())` so sellers can never access other users' support threads.
  - Ticket attachments are stored under `tickets/attachments` — on the `r2` disk when `FILESYSTEM_DISK=r2`, otherwise on the `public` disk — with 10MB size limits and MIME-type restrictions (`image/*`, `application/pdf`, `text/plain`).
  - Admins access `/admin/tickets` to answer inquiries and update statuses with authorized database notification dispatching.

---

## 2. Digital Product & Customer Portal Protection
In a prompt marketplace, the `prompt_text` is the core digital asset. Preventing unauthorized exposure is critical.

### A. Access Token, Library & Free vs. Paid Prompt Payload Isolation
- **Unpurchased Paid Prompts (`price > 0`)**: The `prompt_text` field is NEVER exposed in the public marketplace API, index cards, or unpurchased product detail DOM. Instead, `products/show.blade.php` renders an encrypted/locked preview notice requiring Stripe Checkout purchase.
- **Free Community Prompts (`price == 0`) & Purchased Prompts (`$isUnlocked`)**:
  - `products/show.blade.php` computes `$isUnlocked = $product->isFree() || $hasPurchased` (where `$hasPurchased` verifies a `paid` order for `auth()->id()` or `auth()->user()->email`).
  - Only when `$isUnlocked === true` does Blade include `resources/views/products/partials/interactive-prompt-engine.blade.php` to unlock the Interactive Prompt Playground (`${variable:default}` live inputs, 1-click Copy, and ChatGPT/Claude/Perplexity launch buttons).
- **Post-Purchase Reveal Endpoint (`/prompt/reveal/{token}`)**:
  - Access to `products/reveal.blade.php` is restricted to valid orders with a status of `paid`.
  - Each purchase generates an unguessable 32-character `access_token` (`Str::random(32)`).
  - The `reveal($token)` endpoint queries `Order::where('access_token', $token)->where('status', 'paid')->firstOrFail()`. If the token is invalid or unpaid, a 404 Exception is thrown.
- **Customer Library Scoping**: In `CustomerController::library`, customer library access queries orders matching `where('user_id', auth()->id())->orWhere('email', auth()->user()->email)->where('status', 'paid')`, preventing buyers from accessing other users' purchased prompts.
- **Admin 1-Click Prompts.chat Importer Security**:
  - The `importPromptsChat` header action in `App\Filament\Resources\ProductResource\Pages\ListProducts` is restricted to the `admin` panel (`Filament::getCurrentPanel()?->getId() === 'admin'`) and checks `auth()->user()?->hasPermission('products.create')`.
  - Every admin-triggered import logs an immutable entry via `AuditLog::record('product.imported_prompts_chat', null, ['limit' => ..., 'pricing' => ..., 'download_images' => ...])`.

---

## 3. Community Engagement & Review Security
- **Authentication Requirement**: Toggling follow state (`/creator/follow/{user}`), wishlist favorites (`/product/favorite/{product}`), and review submissions (`/reviews/submit`) require authenticated customer sessions (`auth` middleware).
- **Anti-Duplication**:
  - `follows` table enforces `UNIQUE(['user_id', 'vendor_id'])` at the database level.
  - `favorites` table enforces `UNIQUE(['user_id', 'product_id'])` at the database level.
- **Review Moderation**: Reviews support status-based visibility (`approved`, `pending`, `rejected`), ensuring admin moderation via `ReviewResource` can swiftly hide abusive or spam content.

---

## 4. Payment & Webhook Security

### A. CSRF Exemption for Webhooks
- The `/api/stripe/webhook` route is exempted from CSRF verification (`->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class])`) because requests originate from Stripe's IP addresses.

### B. Webhook Signature Verification
- In `StripeWebhookController`, incoming requests are verified against `config('services.stripe.webhook_secret')` using `Stripe\Webhook::constructEvent($payload, $sigHeader, $secret)`.
- If the signature does not match, a `400 Bad Request` error is returned to prevent spoofed status updates.

---

## 5. Environment Variable & Database Credentials Security
- API keys (`STRIPE_SECRET`, `STRIPE_KEY`, `CLOUDFLARE_R2_SECRET_ACCESS_KEY`, `DB_PASSWORD`) and database ports (`DB_PORT=3306`) are maintained strictly inside `.env`.
- `.env` is listed in `.gitignore` to prevent database credential or API secret exposure in version control.
- Sample keys and port defaults are maintained safely in `.env.example`.

---

## 6. General Input Sanitization & Validation
- Form submissions require email validation (`'email' => 'required|email'`).
- Parameterized queries via Eloquent ORM protect against SQL Injection.
- Blade's `{{ }}` syntax escapes output to prevent Cross-Site Scripting (XSS).

---

## 7. Notification & Tracking Data Isolation
- **User Scoping on Database Notifications**: All notifications generated by Model Observers (`FollowObserver`, `OrderObserver`, `ReviewObserver`, `ProductObserver`, `TicketMessageObserver`) are strictly scoped and dispatched only to the authorized user's primary key (`sendToDatabase($user)`).
- **View-to-Clear Validation**: Navigation badge clearing logic strictly operates on `auth()->user()`, guaranteeing sellers cannot view or manipulate other users' unread timestamps.

---

## 8. Cloudflare R2 Object Storage & File Upload Security
- **Local Temporary Staging**: Temporary file uploads are handled locally via `'disk' => 'local'` (`config/livewire.php`) to prevent client-side credential or pre-signed URL exposure.
- **Strict MIME-Type & Size Validation**:
  - Cover images: Restricted to image formats with editor validation.
  - Video previews: Restricted to `['video/mp4', 'video/webm', 'video/quicktime']` with max size limit of 50MB.
  - KYC Identity Documents: Restricted to `['image/*', 'application/pdf']` with 10MB limits.
  - **Private KYC Disk**: vendor-side documents live on the non-public `local` disk (`kyc-documents/`) behind the owner-or-admin preview route; only legacy/admin-side copies may sit on `users/documents/` of the `r2`/`public` disk.
- **Directory-Based Object Segregation**: Cloud storage objects are isolated into distinct subdirectories (`prompts/covers/`, `prompts/videos/`, `users/avatars/`, `users/documents/`, `tickets/attachments/`).
- **CDN Public Isolation**: Zero-egress fee public asset delivery through Cloudflare Edge CDN using verified public bucket access points.

## Admin Panel Audit — 2026-10-04
Open findings (see `admin-panel-blueprint.md` §7): no 2FA/TOTP; password policy `min:8` (target 12+); Stripe webhook accepts unsigned payload when secret empty (`StripeWebhookController.php`); `APP_DEBUG=true`; missing security headers (X-Frame-Options/frame-ancestors, X-Content-Type-Options, Referrer-Policy, HSTS, CSP) and `X-Powered-By` exposed; `SESSION_SECURE_COOKIE` unset; `QUEUE_CONNECTION=sync`.

### Remediation 2026-10-04
Implemented: TOTP 2FA (mandatory for admins, recovery codes, `admin:reset-2fa`), 12+ char password policy, webhook signature enforced outside local/testing, `SecurityHeaders` middleware, admin idle timeout + optional IP allowlist, secure-by-default session cookie, `php artisan go-live:check`, `.env.production.example`.

---

## 9. Role-Based Hybrid Two-Factor Authentication (2FA) Architecture

A centralized, multi-tier hybrid 2FA system supporting both RFC 6238 TOTP Authenticator Apps (Google/Microsoft Authenticator) and Email One-Time Passwords (OTP).

### A. Role-Based Enforcement Rules
1. **Admin Panel (`/admin`)**:
   - **Method**: Authenticator App (TOTP) **ONLY**.
   - **Enforcement**: Strictly **Mandatory**. Unconfigured administrators are automatically redirected to QR-code onboarding (`/admin-security/2fa/setup`).
   - Every administrative login strictly requires the 6-digit TOTP verification code (or single-use recovery code).
   - Session State: Guarded by `AdminSecurityGate` checking session `admin_2fa_passed`.

2. **Vendor Panel (`/vendor`)**:
   - **One-Time Account Email Verification & Session Persistence**: Upon verifying the 6-digit Email OTP (10-minute validity via `SendEmailOtpNotification`) or TOTP once, `email_verified_at` is stamped (`now()`) and `session(['2fa_verified' => true, 'vendor_2fa_passed' => true])` is persisted for the active session so `TwoFactorMiddleware` allows seamless navigation across all `/vendor/*` routes without re-prompting.
   - **30-Day Trusted Device Cookie (`trusted_device_{user_id}`)**: Checking *"Trust this device for 30 days"* on `/2fa/challenge` queues an encrypted HTTP-only cookie (`trusted_device_{user_id}`, 43,200 minutes) and records the hashed token in `users.trusted_devices`. Subsequent logins from the same browser/device bypass the Email OTP challenge completely and go straight to `/vendor/dashboard` (or `/vendor/onboarding` if first-time) unless explicit TOTP 2FA (`preferred_2fa_method === 'totp'`) is enabled.
   - **Authenticator App (TOTP)**: **Optional**. Vendors can configure and activate TOTP in `/vendor/profile`.
   - **Method Switcher**: Vendors with TOTP configured can seamlessly toggle between Authenticator App and Email OTP on the challenge screen (`/2fa/challenge`).
   - **Resend Cooldown**: 60-second rate-limited countdown timer (Alpine.js live counter + server timestamp verification).
   - Session State: Guarded by `TwoFactorMiddleware` registered in `VendorPanelProvider::authMiddleware()` checking `session('2fa_verified')` / `session('vendor_2fa_passed')` or a valid `trusted_device_{user_id}` cookie.

3. **Customer / Frontend (`/customer/profile`)**:
   - **Methods**: Both Authenticator App (TOTP) and Email OTP are **Optional**.
   - Customers can independently toggle Email OTP and/or configure Authenticator App in `/customer/profile`.
   - When enabled, customer protected routes (`/customer/profile`, `/my-library`, `/my-favorites`, `/following`) intercept unverified sessions and require the 2FA challenge.
   - Session State: Guarded by `TwoFactorMiddleware` checking session `customer_2fa_passed`.

### B. Core Security Safeguards
- **In-House RFC 6238 TOTP Engine**: Zero unneeded heavy packages; pure PHP `App\Support\Security\Totp` with base32 decoding, SHA-1 HMAC, window tolerance `window = 2` (+/- 60s clock drift tolerance).
- **Hashed & Expiring Email OTP**: `email_otp_code` stored hashed via `Hash::make()` with explicit `email_otp_expires_at` timestamp.
- **Encrypted Secrets & Recovery Codes**: `two_factor_secret` and `two_factor_recovery_codes` encrypted via Laravel `Crypt::encryptString()`. Single-use recovery codes are stored as hashed strings and deleted immediately upon successful use.
- **Sensitive Audit Logging**: All 2FA events (`auth.2fa_enabled`, `auth.2fa_email_passed`, `auth.2fa_email_failed`, `auth.2fa_totp_passed`, `auth.2fa_totp_failed`, `auth.2fa_recovery_used`) are recorded to `audit_logs` marked as sensitive.

---

## 10. Single Centralized Login & Access Control Hardening

### A. Centralized Entry Point (`/login`)
- **Single Authentication Surface**: All user roles (Admins, Vendors, Customers) authenticate through the unified, hardened endpoint at `GET/POST /login`.
- **Brute-Force Protection**: Standardized rate limiter (`5,1` per email+IP throttle) prevents credential stuffing attacks across all roles.
- **Session Regeneration**: Upon successful `Auth::attempt()`, `$request->session()->regenerate()` is executed to prevent session fixation attacks.

### B. Decommissioned Panel Login Endpoints
- Redundant `/admin/login` and `/vendor/login` login forms are safely decommissioned.
- Visiting `/admin/login` or `/vendor/login` immediately issues a 302 redirect to `/login` (or directly to `/admin` or `/vendor` if the user is already authenticated).
- Route names `filament.admin.auth.login` and `filament.vendor.auth.login` are retained as safe redirect aliases to guarantee zero runtime routing exceptions.

### C. Panel Unauthenticated Access Interception
- `App\Providers\Filament\AdminPanelProvider` and `App\Providers\Filament\VendorPanelProvider` share the `web` authentication guard (`->authGuard('web')`).
- `App\Http\Middleware\RedirectToCentralLogin` (extending Filament's `Authenticate`) intercepts unauthenticated visits to `/admin` or `/vendor/*` and redirects directly to `route('login')`.

### D. 2FA Interception Preservation
- Admin users are redirected to `/admin` with `admin_2fa_passed` cleared, ensuring `RevalidateAdminSession` and `AdminSecurityGate` enforce mandatory TOTP verification.
- Vendor users are checked for trusted 30-day device cookies and email verification; unverified or unrecognized logins redirect to `2fa.challenge`.
- Customer users with optional 2FA enabled redirect to `2fa.challenge`; otherwise to intended destination.

### E. Unified Logout Session Purge
- `CustomLogoutResponse` (bound to `\Filament\Http\Responses\Auth\Contracts\LogoutResponse`) and `AuthController::logout` explicitly purge all 2FA session state keys (`2fa_verified`, `vendor_2fa_passed`, `admin_2fa_passed`, `customer_2fa_passed`, `admin_last_activity`, `2fa_current_method`, `2fa_otp_sent_at`), invalidate the session, and regenerate the CSRF token on logout.

