# TrackPro — Link Intelligence & Security Analysis Platform

## Overview

TrackPro is a self-hosted tracking link platform for security analysis, fraud detection, and abuse prevention. Generate unique tracking links, send them to subjects, and collect comprehensive technical metadata when accessed.

**Stack:** PHP 7.4+ / MySQL 5.7+ / Vanilla JS / Chart.js / cPanel-ready

---

## Quick Start (cPanel Deployment)

### 1. Upload Files
Upload the entire `trackpro/` folder to `public_html/trackpro/` or a subdomain root.

### 2. Create MySQL Database
- cPanel → MySQL Databases → Create database: `trackpro_db`
- Create user and assign ALL PRIVILEGES to that database

### 3. Run Installer
Visit: `https://yourdomain.com/trackpro/install.php`
- Enter database credentials, admin username, email, password
- Click Install
- **DELETE install.php immediately after**

### 4. Login
Visit: `https://yourdomain.com/trackpro/admin/`

### 5. Tracking Links Format
```
https://yourdomain.com/trackpro/t/XXXXXXXX
```

---

## Architecture

```
trackpro/
├── install.php              # One-time DB setup (DELETE after)
├── .htaccess                # URL rewriting + security headers
├── admin/
│   ├── index.php            # Dashboard SPA
│   ├── login.php            # Authentication page
│   └── logout.php           # Session destroy
├── api/
│   └── router.php           # REST API endpoints
├── tracking/
│   └── capture.php          # Link handler + JS data collector
├── includes/
│   ├── config.php           # Auto-generated DB credentials
│   ├── db.php               # PDO connection + helpers
│   ├── auth.php             # Session auth + RBAC
│   └── intelligence.php     # IP lookup + UA parser + risk engine
└── assets/
    └── css/
        └── admin.css        # Dashboard styles
```

---

## Role-Based Access Control

| Role        | Dashboard | Create Links | View Sessions | Export | Manage Users | Settings |
|-------------|-----------|--------------|---------------|--------|--------------|----------|
| superadmin  | ✅        | ✅           | ✅            | ✅     | ✅           | ✅       |
| admin       | ✅        | ✅           | ✅            | ✅     | ❌           | ❌       |
| analyst     | ✅        | ❌           | ✅            | ✅     | ❌           | ❌       |
| viewer      | ✅        | ❌           | ✅            | ❌     | ❌           | ❌       |

---

## Data Collection Categories

### Collected Server-Side (on link access)
- IP address (v4/v6), ISP, ASN, organization, network type
- Proxy/VPN/Tor detection
- Country, region, city, postal code, timezone
- User-Agent string, browser, OS, device type
- Referrer, UTM parameters, campaign IDs
- Accept headers, DNT flag

### Collected Client-Side (JavaScript)
- Screen resolution, viewport, pixel ratio, color depth
- Touch support, max touch points
- Battery level & charging status
- GPU vendor & renderer (WebGL)
- CPU architecture (User-Agent Client Hints)
- Canvas fingerprint hash
- WebGL fingerprint hash
- Audio fingerprint hash
- Font detection (20 common fonts)
- Plugin list
- Hardware concurrency, device memory
- Cookies enabled flag
- Behavioral: click count, scroll depth, session duration, keystroke count, mouse movement samples

### Risk Scoring (calculated automatically)
- Device trust score (0-100)
- Fraud score (0-100)
- Risk score (0-100)
- Bot likelihood (0-100)
- Emulator detection
- Risk factors: tor_detected, vpn_detected, proxy_detected, datacenter_ip, bot_ua_detected, no_fingerprint, unusual_hardware, possible_emulator

### NOT Implemented (App-Only / Restricted — documented only)
- Wi-Fi SSIDs
- Bluetooth beacons
- GPS coordinates (requires user permission)
- Cell tower data
- IMSI / IMEI
- Telecom subscriber records

---

## API Endpoints

All API calls go through `api/router.php?route=ROUTE`

### Public
| Route     | Method | Description                    |
|-----------|--------|--------------------------------|
| `collect` | POST   | Receive client-side JS data    |

### Authenticated (session cookie required)
| Route              | Method | Description                 |
|--------------------|--------|-----------------------------|
| `dashboard/stats`  | GET    | Dashboard statistics        |
| `links`            | GET    | List tracking links         |
| `links`            | POST   | Create new link             |
| `links/{id}`       | PUT    | Update link                 |
| `links/{id}`       | DELETE | Revoke (deactivate) link    |
| `sessions`         | GET    | List sessions with filters  |
| `sessions/{id}`    | GET    | Full session detail         |
| `export`           | POST   | Export data (CSV/JSON)      |
| `users`            | GET    | List users (superadmin)     |
| `users`            | POST   | Create user (superadmin)    |
| `settings`         | GET    | View settings (superadmin)  |
| `settings`         | POST   | Update settings (superadmin)|

---

## Link Landing Modes

1. **Neutral** — Shows a simple "Page Loaded" message while collecting data
2. **Redirect** — Collects data, then redirects to a destination URL after 2.5 seconds
3. **Custom HTML** — Renders your custom HTML content on the landing page

---

## IP Intelligence

By default uses the free `ip-api.com` service (no API key, 45 requests/minute limit).

For production, swap the provider in `includes/intelligence.php`:
- **ipinfo.io** — Free tier: 50k/month
- **IPQualityScore** — Advanced fraud/proxy detection
- **MaxMind GeoIP2** — Local database, no rate limits

Set the API key in Settings → `ip_lookup_api_key`.

---

## Export Formats

- **CSV** — Direct download, all session data flattened into columns
- **JSON** — Structured data with nested objects
- **PDF** — Not built-in; use browser print or a reporting tool on the CSV/JSON

Filters: by link, date range. Max 50,000 rows per export.

---

## Security Features

- Bcrypt password hashing (cost 12)
- Session regeneration on login
- HTTP-only, secure, SameSite=Strict cookies
- 2-hour session timeout
- CSRF token support
- X-Content-Type-Options, X-Frame-Options, X-XSS-Protection headers
- Prepared statements (PDO) — no SQL injection
- Input sanitization throughout
- Audit log for all admin actions
- Consent logging table for GDPR compliance

---

## GDPR / CCPA Compliance Notes

1. The landing page displays a privacy notice by default
2. Enable `require_consent` in Settings to show a consent banner
3. All data collection is logged with timestamps
4. The `consent_log` table records consent decisions per session
5. Set `data_retention_days` to auto-purge old data (implement via cron)
6. Export functionality supports data subject access requests (DSAR)
7. Users can be deleted, which cascades through all session data

**Recommended:** Add a proper privacy policy page linked from the landing page.

---

## Cron Jobs (Optional)

Add to cPanel → Cron Jobs for automated maintenance:

```bash
# Purge expired data daily at 3 AM
0 3 * * * php /home/youraccount/public_html/trackpro/cron/purge.php

# Keep sessions alive (if using long-running processes)
*/5 * * * * curl -s https://yourdomain.com/trackpro/api/router.php?route=ping > /dev/null
```

---

## Database Tables

| Table              | Purpose                                    |
|--------------------|--------------------------------------------|
| `users`            | Admin accounts with roles                  |
| `tracking_links`   | Generated tracking links                   |
| `sessions`         | One row per link access                    |
| `network_data`     | IP, ISP, ASN, proxy/VPN/Tor flags          |
| `location_data`    | Geo: country, city, timezone               |
| `device_data`      | Device type, OS, screen, GPU, battery      |
| `browser_data`     | Browser, engine, UA, DNT, cookies          |
| `fingerprint_data` | Canvas, WebGL, audio, font, plugin hashes  |
| `behavioral_data`  | Clicks, scroll, mouse, keystroke events    |
| `attribution_data` | Referrer, UTM params, campaign IDs         |
| `risk_data`        | Trust/fraud/risk/bot scores                |
| `consent_log`      | GDPR consent records                       |
| `audit_log`        | Admin action history                       |
| `settings`         | Key-value app configuration                |

---

## Troubleshooting

**Links return 404:** Ensure `mod_rewrite` is enabled and `.htaccess` is being read. In cPanel, check Apache handlers.

**IP lookup returns null:** The free ip-api.com only works over HTTP (not HTTPS) and has rate limits. For production use, switch to a paid provider.

**Charts not loading:** Chart.js is loaded from CDN (cdnjs.cloudflare.com). Ensure outbound network access is allowed.

**Session timeout too short:** Change `session_timeout_minutes` in Settings, and update the PHP check in `auth.php` (default 7200 seconds = 2 hours).
