# Security

## Authorisation

- Roles: `customer`, `creator`, `staff`, `admin` (`users.role`, never mass-assignable; sign-ups are always customers).
- `/admin/*` requires `auth` + `admin` middleware; non-staff receive **404**.
- Gates (`AppServiceProvider::defineGates`):
  - staff + admin: `manage-catalog`, `manage-inventory`, `manage-orders`, `moderate-ugc`, `manage-challenges`, `view-customers`
  - admin only: `manage-pricing`, `manage-settings`, `manage-rewards`, `manage-creators`, `manage-ai`, `manage-campaigns`, `view-analytics`, `view-audit-log`, `issue-refunds`, `manage-staff`, `adjust-points`
- Routes declare `can:` middleware **and** Livewire actions call `$this->authorize()` again (Livewire requests bypass route middleware after mount).
- Suspended accounts are signed out on their next request.
- Customers can only read/modify their own records (queries are scoped through `auth()->user()->…`).

## Data integrity

- Prices: `price`/`sale_price` are not fillable; changed only via `PriceManager` (history + audit).
- Stock: changed only via `InventoryService` inside transactions with row locks; reasons required for manual changes.
- Audit log records admin changes with old/new values and IP.

## Web protections

- CSRF on all web forms (Laravel default); webhooks are excluded and verify signatures instead (Phase 2+).
- Blade escapes output; Markdown content renders with raw HTML **escaped** and unsafe links disabled.
- JSON-LD is encoded with `JSON_HEX_TAG`.
- Security headers: `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`, HSTS on HTTPS.
- Login throttled (5/min per email+IP); API, checkout and webhook rate limiters defined.
- Uploads: MIME + real image sniffing (`getimagesize`), size and dimension limits, random filenames, re-encoded to WebP (strips EXIF). Customer uploads go to the non-public `private` disk.
- `robots.txt` blocks admin/account/cart/checkout and the whole site outside production.

## Payments (Paystack)

- The browser redirect is never trusted: `/checkout/callback` calls Paystack's verify API server-side.
- Webhooks: HMAC-SHA512 of the raw body with the secret key (`x-paystack-signature`), constant-time compare, 401 otherwise. Each call is stored in `webhook_calls` with a unique idempotency key; retries are acknowledged without reprocessing. `charge.success` is re-verified with the API before use.
- `PaymentConfirmation` checks reference, amount (kobo) and currency against the order; any mismatch holds the order for review instead of marking it paid. Row locks make callback + webhook races safe.
- Prices, discounts and shipping are recalculated server-side in `PlaceOrder`; the browser only sends address/contact/delivery choice.
- Refunds are admin-only (`issue-refunds`) and audited; nothing is written if Paystack rejects the refund.
- Order pages: owner only, or a signed URL (60-day expiry) from the confirmation email.

## Loyalty & referrals

- Points, rewards and referral payouts are computed server-side from paid orders; nothing is accepted from the client.
- Reward codes are personal (`coupons.user_id`), single-use, time-limited. Redemption locks the reward row (stock/limits can't be oversubscribed).
- Coupon usage limits are enforced atomically when payment is confirmed (coupon row locked, conditional increment), so parallel checkouts can't exceed them; a losing race flags the order for staff review instead of over-redeeming.
- Manual point changes are admin-only (`adjust-points`), need a reason, and are audited.
- Referrals block self-referral (same email or phone), only count a friend's first paid order, enforce a minimum and a window, and reverse on refund.
- API tokens: Laravel Sanctum bearer tokens, issuance throttled; customer endpoints are scoped to the token owner.

## AI try-on

- Explicit consent required and stored. Photos/results only on the private disk; served via signed expiring URLs plus an ownership check; `no-store` caching.
- Uploads validated (type, size, dimensions) and re-encoded, which strips EXIF/GPS before a provider sees them.
- Originals auto-deleted (default 60 min), unsaved results (default 24 h). Admins see results only, never originals, and only on request.
- An account's previews are visible to that account only; guest previews to their session.
- Replicate webhooks verified (Standard Webhooks HMAC-SHA256, 5-minute tolerance); only metadata is logged.
- Daily, per-IP and monthly-budget limits stop abuse and runaway cost. The development provider can't run in production.

## Wall & challenges

- Posting needs an account, explicit consent (own photo, 16+, may be shown with credit) and is rate-limited (pending and daily caps, plus API throttle).
- Photos are re-encoded server-side (strips EXIF/GPS, rejects non-images) and stored privately; only approved posts are served publicly. Captions are stripped of HTML and always escaped.
- Every moderation action re-checks `moderate-ugc` and is audited; challenge management needs `manage-challenges`. Draft challenges are visible to staff only.
- Votes: signed-in customers, one per entry (database unique key), not on their own entry, only while voting is open and only for approved entries.
- Points for posts are paid once (ledger keys) and reversed when a moderator removes an approved post. A winning entry can't be deleted or rejected.

## Creator programme

- `manage-creators` (admins only) for approvals, rates, suspension, campaigns and payouts; every one is audited, including viewing a full bank account number.
- Attribution is decided server-side from paid orders: unique conversion per order, commission only on merchandise after discounts, reversed on refund/cancel, clawed back if already paid.
- Self-referral blocked by account, email and phone; creators can't apply their own code and their own clicks aren't recorded.
- `/go/{token}` only redirects to paths on this store (no open redirect). Click IPs are stored as an HMAC, not raw.
- Payout account numbers are encrypted at rest (`APP_KEY`) and masked in every view; creators see no customer personal data.

## Campaigns, CRM & email

- Campaigns are admin-only (`manage-campaigns`) and audited. Each runs at most once per event per customer (database-unique run key); actions run without re-triggering campaigns (no loops). Coupons they create are personal and single-use; creator commission changes are audited and can be limited to increases.
- On-site message links must be internal paths; webhook actions must be HTTPS. Outbound webhooks and CRM webhooks are HMAC-signed (`X-BeAuthentic-Signature: t=…,v1=…`) with an idempotency key.
- Inbound `/webhooks/crm` verifies HMAC with a 5-minute window, is idempotent, stores only a hash of the email, and can only change marketing consent and tags.
- Marketing emails go only to opted-in customers and include a signed one-click unsubscribe (GET shows a button; only POST changes state). Service emails ignore marketing consent by design.
- CRM payloads contain contact basics and order facts — never passwords, tokens, addresses' full detail beyond state, or payment data. CRM credentials live only in `.env`.
- Analytics CSV exports neutralise spreadsheet formulas.

## Phase 8 security audit (2026-10-12)

| Area | Result |
|---|---|
| Dependencies | `composer audit` and `npm audit --omit=dev`: no known vulnerabilities |
| SQL injection | Every raw expression reviewed: static SQL or bound parameters only |
| XSS | Every unescaped Blade output reviewed: Markdown rendered with `html_input: escape` and unsafe links off; JSON-LD encoded with `JSON_HEX_TAG`; user text always escaped |
| Authorisation | Automated sweep (`RouteSweepTest`): customers get 404 on every admin page; staff get exactly what the gate matrix allows. Admin Livewire actions reviewed for action-level checks — two that relied on `mount()` only (order fulfilment buttons, image reordering) now re-check |
| Error leakage | Branded, standalone error pages (404/403/419/429/500/503); `APP_DEBUG=false` never shows traces; Livewire errors become friendly toasts in production |
| Logs | `RedactSecrets` masks passwords, tokens, API keys (Paystack, OpenAI, Replicate, webhook secrets), bearer tokens and card fields before anything is written |
| Transport | HTTPS redirect + HSTS in production, secure/HttpOnly/SameSite=Lax session cookies by default, trusted proxies via config |
| Headers | `nosniff`, `SAMEORIGIN`, strict referrer, permissions policy, baseline CSP (`object-src 'none'`, `base-uri 'self'`, `frame-ancestors 'self'`, `form-action` self + Paystack) |
| Rate limits | login 5/min; sign-up/reset/verification 10/min & 30/h per IP; checkout 10/min; quiz 20/min; API 60/min; webhooks 120/min; AI per guest/user/day + per IP/hour + monthly budget; Wall posts (pending + daily caps); challenge votes 30/min; `/go` and `/ref` links |
| Uploads | Real-image checks, re-encoding (strips EXIF/GPS), private disk for customer photos, random file names; dotfiles blocked by `.htaccess` |
| Backups | Optional AES-256 archives, `.env` only inside encrypted archives, AI originals excluded, downloads admin-only, filename-validated and audited |
| Deploy-time | `env()` used only in `config/` so `config:cache` can't silently drop settings (found and fixed: trusted proxies, seeder admin); `.env.example` no longer ships `SESSION_SECURE_COOKIE=false` |

Known, accepted: the CSP doesn't restrict scripts (`script-src`), because Livewire/Alpine need inline evaluation; output escaping is the XSS defence.

## AI provider keys in admin

- Entered in Admin → AI Try-On (admins only, `manage-ai`).
- Encrypted with `APP_KEY` (`Crypt`) in the settings table, never rendered back (masked preview only), cleared from the form after saving.
- Audited without the value and redacted from logs.
- If decryption fails (APP_KEY rotated), the app falls back to `.env`.

## Secrets

Only in `.env`, with one exception: AI provider keys can be entered in admin, where they're stored encrypted (see above). No other key is stored through the settings UI. `APP_DEBUG=false` in production. Sensitive fields are excluded from flashed input.

## Planned

Two-factor authentication for staff/admin (Fortify supports it; disabled for V1).
