# Supervisor Platform - SRS

**Platform Architecture:** Dual-Stack Enterprise Facility Compliance & Attendance Monitoring System  
**Backend:** LAMP Stack (Linux, Apache, MySQL/MariaDB, PHP 8.x PDO) + Web Admin Portal  
**Mobile:** React Native (Expo SDK 57, New Architecture, Expo Router, React Native 0.86.2, React 19.2.3, SQLite 3)  
**Evaluation Date:** August 15, 2026  

---

## Executive Summary & Launch Readiness Verdict

### **Verdict: GO WITH CONDITIONS**

The Supervisor codebase demonstrates exceptional engineering quality, strict cryptographic authentication patterns, defensive offline-first data replication, and comprehensive protection against common web vulnerabilities (zero SQL injection vulnerabilities found, prepared statements enforced across all endpoints, strict CSRF validation, and session fixation guards).

Before greenlighting public production traffic, four operational and infrastructure conditions must be resolved:

1. **Delete or protect `setup.php`** on the production web server to prevent unauthorized administrator password resets.
2. **Enforce HTTPS (TLS)** on the mobile API base URL (current `.env` points to plaintext HTTP `http://129.225.110.110/admin-portal`).
3. **Configure the host OS Cron daemon** to invoke the background missed-heartbeat detection script (`api/v1/heartbeat-check.php`) every 5 minutes.
4. **Provision production environment variables** for MySQL (`DB_HOST`, `DB_USER`, `DB_PASS`, `DB_NAME`).

---

## 1. Backend (PHP/MySQL) Architecture Map

```
admin-portal/
├── api/v1/                      # REST API Endpoints (JSON)
│   ├── areas.php                # CRUD for facility cleaning zones
│   ├── assignments.php          # CRUD for employee zone assignments
│   ├── device-binding.php       # Hardware registration & token minting
│   ├── employees.php            # CRUD for employee profiles
│   ├── events.php               # Compliance telemetry & shift event ingestion
│   ├── flags.php                # Incident & compliance flag management
│   ├── heartbeat-check.php      # Periodic missed heartbeat detector
│   ├── pull-request.php         # Real-time telemetry query endpoint
│   └── shifts.php               # Shift records & manual status overrides
├── config/
│   ├── constants.php            # App name, facility, and timezone definitions
│   └── database.php             # PDO singleton, MySQL/SQLite driver & auto-migrations
├── includes/
│   ├── auth.php                 # Web session auth guard & login rate-limiting
│   ├── csrf.php                 # Cryptographic CSRF token generation & validation
│   ├── functions.php            # Dual-auth validator, JSON responder, sanitize helpers
│   ├── header.php / footer.php  # HTML UI shell & Lucide icon bootstrap
│   └── sidebar.php              # Navigation drawer
├── migrations/
│   └── 001_initial_schema.sql   # Relational schema (MySQL 8.0+ / SQLite compatible)
├── pages/                       # Admin Portal Server-Rendered Views
│   ├── activity.php             # Telemetry audit & accelerometer variance graphs
│   ├── areas.php                # Cleaning zone & staff assignment management
│   ├── dashboard.php            # Operational KPIs & active shift monitoring
│   ├── employees.php            # Employee roster & hardware device binding
│   ├── login.php / logout.php   # Admin session authentication
│   └── monthly-report.php       # Compliance ledger & CSV export
├── index.php                    # Redirects to pages/dashboard.php
└── setup.php                    # Initial admin provisioning utility
```

### 1.1 Entry Points and Routing
* **Routing Paradigm:** Direct script-based execution (raw PHP endpoints). No framework router, front controller, or Apache `.htaccess` rewrite rules are required.
* **Portal Entry Point:** [`admin-portal/index.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/index.php#L1-L4) redirects incoming HTTP GET requests directly to [`pages/dashboard.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/pages/dashboard.php).
* **Setup Utility:** [`admin-portal/setup.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/setup.php#L1-L44) provides interactive web and CLI administration setup to seed or update the `admin` user password with bcrypt.

### 1.2 Distinct API Endpoints Consumed by Clients

| HTTP Method | Route Path | File Location | Description & Payload |
|---|---|---|---|
| `POST` | `/api/v1/device-binding.php` | [`api/v1/device-binding.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/device-binding.php#L4-L135) | Binds physical hardware to employee profile, prunes prior tokens, and mints a 90-day Bearer token. |
| `POST` | `/api/v1/events.php` | [`api/v1/events.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/events.php#L4-L260) | Ingests `checkin`, `checkout`, `sensor_sample`, `heartbeat`, `location_rejection`, `app_backgrounded`. |
| `GET` | `/api/v1/employees.php` | [`api/v1/employees.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/employees.php#L18-L42) | Returns employee profile details by ID or complete active employee list. |
| `POST/PUT/DELETE` | `/api/v1/employees.php` | [`api/v1/employees.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/employees.php#L45-L115) | Full CRUD and device unbinding actions. |
| `GET` | `/api/v1/areas.php` | [`api/v1/areas.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/areas.php#L18-L33) | Returns facility zones, BSL levels, duration, and shift groups. |
| `POST/PUT/DELETE` | `/api/v1/areas.php` | [`api/v1/areas.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/areas.php#L36-L96) | Admin CRUD for facility cleaning zones. |
| `GET` | `/api/v1/shifts.php` | [`api/v1/shifts.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/shifts.php#L18-L60) | Queries recorded shift history filtered by employee ID or shift status. |
| `PUT/DELETE` | `/api/v1/shifts.php` | [`api/v1/shifts.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/shifts.php#L63-L95) | Admin status overrides and shift removal. |
| `GET` | `/api/v1/assignments.php` | [`api/v1/assignments.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/assignments.php#L18-L55) | Returns active zone-to-employee assignments. |
| `POST/DELETE` | `/api/v1/assignments.php` | [`api/v1/assignments.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/assignments.php#L58-L89) | Assigns/unassigns staff to facility zones. |
| `GET/POST/PUT/DELETE` | `/api/v1/flags.php` | [`api/v1/flags.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/flags.php#L18-L105) | Incident flag audit, manual flagging, and supervisor resolution. |
| `GET` | `/api/v1/heartbeat-check.php` | [`api/v1/heartbeat-check.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/heartbeat-check.php#L1-L56) | Background cron endpoint detecting shifts missing telemetry > 6 mins. |
| `POST` | `/api/v1/pull-request.php` | [`api/v1/pull-request.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/pull-request.php#L1-L51) | Returns live status snapshot of an active employee's shift. |

### 1.3 Authentication & Session Mechanisms
1. **Mobile Client Token Authentication:**
   - Minted in [`api/v1/device-binding.php:L74-84`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/device-binding.php#L74-L84) using 32 cryptographically secure random bytes (`bin2hex(random_bytes(32))`).
   - Stored in the `api_tokens` table with an expiration timestamp set to 90 days (`time() + 90 * 86400`).
   - Injected in HTTP requests via `Authorization: Bearer <token>`.
   - Verified by [`includes/functions.php:validateApiAuth()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/includes/functions.php#L71-L107) with fallback check for non-expired tokens.
2. **Admin Web Session Authentication:**
   - Standard PHP cookie-based sessions (`$_SESSION['admin_user']`).
   - Authenticated via [`includes/auth.php:attemptLogin()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/includes/auth.php#L24-L52) using `password_verify($password, $user['password_hash'])`.
   - Includes **session fixation protection** (`session_regenerate_id(true)`).
   - Includes **login rate limiting & progressive sleep delay** (`sleep(min(5, (int)($attempts - 3)))` after 5 failed attempts).
3. **Cross-Site Request Forgery (CSRF):**
   - Cryptographic tokens generated via `bin2hex(random_bytes(32))` in [`includes/csrf.php:getCsrfToken()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/includes/csrf.php#L10-L18).
   - Validated on all state-modifying admin POST requests via `hash_equals()` in [`includes/csrf.php:checkCsrf()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/includes/csrf.php#L30-L36).

### 1.4 Database Access Pattern
* **Database Driver:** PHP Data Objects (PDO) via singleton pattern [`config/database.php:getPDO()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/config/database.php#L13-L58).
* **Prepared Statements:** **100% prepared statements with parameter binding** (`$pdo->prepare(...)` and `$stmt->execute([...])`). No raw user input string concatenation exists in any SQL statement.
* **Dual-Engine Architecture:** Primary connection targets MySQL/MariaDB (`utf8mb4`). If MySQL is offline or `DB_DRIVER=sqlite`, automatically falls back to local SQLite PDO (`database.db`).
* **Auto-Migrations:** [`config/database.php:ensureSchema()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/config/database.php#L60-L111) automatically executes [`migrations/001_initial_schema.sql`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/migrations/001_initial_schema.sql) if tables are missing.

### 1.5 Secrets & Environment Configuration
* **Config Files:**
  - [`config/database.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/config/database.php#L7-L11): Reads `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASS`, `DB_DRIVER` from `getenv()` with local fallbacks.
  - [`config/constants.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/config/constants.php#L6-L11): Defines `APP_NAME`, `APP_VERSION`, `FACILITY_NAME`, `TIMEZONE` (`Australia/Melbourne`).
* **Environment Handling:** Backend does not load a local `.env` parser; it expects native Linux environment variables, Apache `SetEnv`, or PHP-FPM environment pool configs.

### 1.6 Background Tasks & Scheduled Jobs
* **Missed Heartbeat Cron:** [`api/v1/heartbeat-check.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/heartbeat-check.php#L1-L56) is designed to run every 5 minutes via host crontab:
  ```bash
  */5 * * * * curl -s http://localhost/admin-portal/api/v1/heartbeat-check.php > /dev/null 2>&1
  ```
  Identifies active shifts with no sensor samples within the last 6 minutes using a robust `NOT EXISTS` query and raises high-severity `missed_heartbeats` flags with deduplication.

### 1.7 Third-Party Integrations
* **Google Fonts CDN:** [`DM Sans`, `DM Mono`, `Syne`] loaded in [`includes/header.php:L16`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/includes/header.php#L16).
* **Lucide Icons CDN:** `unpkg.com/lucide@latest` loaded in [`includes/header.php:L18`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/includes/header.php#L18).
* No external third-party payment, SMS, or email SDKs are connected (all records, audit trails, and flags reside entirely in the local database).

---

## 2. Mobile App (Expo SDK 57) Architecture Map

```
supervisor/
├── assets/images/               # App icons, splash screens, favicon
├── src/
│   ├── api/
│   │   └── client.ts            # HttpApiClient with timeout & bearer token injection
│   ├── app/                     # Expo Router file-based screens
│   │   ├── (tabs)/
│   │   │   ├── _layout.tsx      # Bottom navigation tabs (Agenda, Schedule, Profile)
│   │   │   ├── index.tsx        # Today's shift agenda & check-in triggers
│   │   │   ├── profile.tsx      # Diagnostics, manual sync flush & server config
│   │   │   └── schedule.tsx     # Weekly roster schedule
│   │   ├── onboarding/
│   │   │   ├── device-check.tsx # Hardware diagnostic suite & employee ID binding
│   │   │   └── pin-setup.tsx    # 4-digit backup PIN creation & confirmation
│   │   ├── _layout.tsx          # Root initialization, font loading, sync & mid-shift rehydration
│   │   ├── active-shift.tsx     # Live active shift dashboard & 190x190 elapsed timer
│   │   ├── index.tsx            # Entry redirect gatekeeper (checks PIN setup)
│   │   └── unlock.tsx           # Biometric / PIN unlock screen
│   ├── auth/
│   │   ├── biometric.ts         # Expo LocalAuthentication (disableDeviceFallback: true)
│   │   └── pin.ts               # SHA-256 PIN hashing & lockout logic
│   ├── components/
│   │   ├── AuthSheet.tsx        # Modal authentication sheet (Biometric -> PIN fallback)
│   │   ├── CapabilityRow.tsx    # Sensor status row item
│   │   ├── JobCard.tsx          # Shift cards with status badges & check-in buttons
│   │   ├── PinPad.tsx           # Custom accessible numeric keypad
│   │   └── StatusBadge.tsx      # Sync status & connection pills
│   ├── constants/
│   │   ├── config.ts            # Dynamic base URL resolution & SecureStore persistence
│   │   ├── mockData.ts          # Type definitions (Employee, FacilityZone, ScheduledShift)
│   │   └── theme.ts             # Theme tokens (colors, typography, spacing, radius)
│   ├── db/
│   │   ├── client.ts            # expo-sqlite database instance & schema initialization
│   │   ├── eventQueue.ts        # Outbound event queue with dead-letter retry tracking
│   │   ├── schema.ts            # DDL for shifts, sensor_samples, event_queue, capabilities
│   │   ├── sensorSamples.ts     # SQLite persistence for 30s motion window samples
│   │   └── shifts.ts            # SQLite shift records & check-in/out updates
│   ├── sensors/
│   │   ├── capabilities.ts      # Hardware sensor detection (Biometric, Accel, Pedometer, GPS)
│   │   ├── location.ts          # High-accuracy GPS verification & mock detection
│   │   └── motion.ts            # 10Hz accelerometer vector calculation & 30s window flush
│   ├── store/
│   │   └── appStore.ts          # Zustand state store with live API synchronization
│   └── sync/
│       └── syncEngine.ts        # 30-minute background sync & event queue flush engine
├── app.json                     # Native permissions, plugins, iOS InfoPlist & EAS config
├── eas.json                     # EAS build profiles (development, preview, production)
├── metro.config.js              # Metro bundler with SQLite wasm support
└── package.json                 # Expo 57, React Native 0.86.2, React 19.2.3 dependencies
```

### 2.1 Routing Structure
* **Framework:** Expo Router v57 (typed routes enabled in [`app.json:L73`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/app.json#L73)).
* **Navigation Flow:**
  1. [`app/index.tsx`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/app/index.tsx#L1-L35): Directs new installations to `/onboarding/device-check` and enrolled devices to `/unlock`.
  2. [`app/onboarding/device-check.tsx`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/app/onboarding/device-check.tsx#L1-L240): Hardware diagnostic suite and employee ID binding.
  3. [`app/onboarding/pin-setup.tsx`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/app/onboarding/pin-setup.tsx#L1-L109): 4-digit backup PIN creation and confirmation.
  4. [`app/unlock.tsx`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/app/unlock.tsx#L1-L145): Face ID / Biometric verification with fallback to PIN.
  5. [`app/(tabs)/_layout.tsx`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/app/(tabs)/_layout.tsx#L1-L51): 3-tab layout (`index` / Today's Agenda, `schedule` / Schedule, `profile` / Profile).
  6. [`app/active-shift.tsx`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/app/active-shift.tsx#L1-L255): Live active shift screen with continuous sensor sampling and 190x190 timer ring.

### 2.2 API & Networking Layer
* **HTTP Client:** [`src/api/client.ts:HttpApiClient`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/api/client.ts#L62-L255) uses standard `fetch` API with `AbortController` (8,000 ms timeout).
* **Endpoint Discovery:** [`src/constants/config.ts:getApiBaseUrl()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/constants/config.ts#L6-L13) dynamically resolves the server URL from `SecureStore` key `supervisor_api_base_url`, falling back to `EXPO_PUBLIC_API_URL`.
* **Authorization Injection:** [`src/api/client.ts:getAuthHeaders()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/api/client.ts#L63-L72) injects `Authorization: Bearer <token>` retrieved from `SecureStore` key `supervisor_api_bearer_token`.

### 2.3 Environment Variable Handling
* **Public Variables:** `EXPO_PUBLIC_API_URL` is configured in [`supervisor/.env`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/.env#L1).
* **Security Notice:** `EXPO_PUBLIC_` variables are inlined into the client JavaScript bundle and are **NOT** secret. In this codebase, it is correctly used solely for the non-sensitive public API server URL.

### 2.4 State Management & Persistence
* **State Store:** Zustand 5.0.14 [`src/store/appStore.ts:useAppStore`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/store/appStore.ts#L41-L127).
* **Cold Restart Mid-Shift Rehydration:** [`src/app/_layout.tsx:L59-64`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/app/_layout.tsx#L59-L64) queries SQLite `shifts` table on app startup via `getActiveShift()`. If an `in_progress` shift exists, it seamlessly rehydrates state without data loss or timer drift.
* **Offline Event Queue:** [`src/db/eventQueue.ts:enqueueEvent()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/db/eventQueue.ts#L15-L35) records every action to local SQLite. A maximum retry limit of 10 (`MAX_RETRY_COUNT = 10`) prevents infinite retry loops for malformed events.

### 2.5 Native Configurations & Device Permissions
* **Android Permissions declared in [`app.json:L29-39`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/app.json#L29-L39):**
  - `ACCESS_FINE_LOCATION`, `ACCESS_COARSE_LOCATION`
  - `ACTIVITY_RECOGNITION`
  - `USE_BIOMETRIC`, `USE_FINGERPRINT`
* **iOS InfoPlist Usage Strings declared in [`app.json:L18-22`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/app.json#L18-L22):**
  - `NSLocationWhenInUseUsageDescription`
  - `NSMotionUsageDescription`
  - `NSFaceIDUsageDescription`
* **Config Plugins:** `expo-router`, `expo-splash-screen`, `expo-secure-store`, `expo-sqlite`, `expo-local-authentication`, `expo-location`, `expo-image`.

### 2.6 Client Auth Storage & Biometrics
* **Hardware Token:** Stored in hardware Keystore via `expo-secure-store` (`supervisor_api_bearer_token`).
* **Enrolled Employee & Device ID:** Persisted in `expo-secure-store` (`supervisor_enrolled_employee_id`, `supervisor_hardware_device_id`).
* **PIN Storage:** SHA-256 hashed using `expo-crypto` and hash stored in `expo-secure-store` (`supervisor_pin_hash`).
* **Biometric Guard:** [`src/auth/biometric.ts:authenticateWithBiometric()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/auth/biometric.ts#L16-L64) sets `disableDeviceFallback: true`, preventing OS device passcode bypass per SRS requirement FA-20.

---

## 3. Cross-Stack Surface & Contract Integrity

### 3.1 Mobile-to-Backend Integration Matrix

| Mobile Client Call | HTTP Method | Target Backend Endpoint | Contract Parameters | Status |
|---|---|---|---|---|
| `apiClient.checkDeviceBinding()` | `POST` | `/api/v1/device-binding.php` | `{ employee_id, device_id }` | **MATCH** |
| `apiClient.postEvent('checkin')` | `POST` | `/api/v1/events.php` | `{ id, type: 'checkin', payload: { shiftId, area_id, zoneId, zoneCode, zoneName, lat, lng, accuracy, mocked, authMethod, timestamp } }` | **MATCH** |
| `apiClient.postEvent('checkout')` | `POST` | `/api/v1/events.php` | `{ id, type: 'checkout', payload: { shiftId, lat, lng, accuracy, mocked, authMethod, timestamp } }` | **MATCH** |
| `apiClient.postEvent('sensor_sample')` | `POST` | `/api/v1/events.php` | `{ id, type: 'sensor_sample', payload: { shiftId, windowStart, windowEnd, motionVariance, stepCount, batteryLevel, appState } }` | **MATCH** |
| `apiClient.postEvent('location_rejection')`| `POST` | `/api/v1/events.php` | `{ id, type: 'location_rejection', payload: { context, shiftId, reason, coords, accuracy, timestamp } }` | **MATCH** |
| `apiClient.postEvent('app_backgrounded')` | `POST` | `/api/v1/events.php` | `{ id, type: 'app_backgrounded', payload: { shiftId, timestamp } }` | **MATCH** |
| `apiClient.fetchEmployee()` | `GET` | `/api/v1/employees.php?id={id}` | Query: `?id={employeeId}` with `Authorization: Bearer <token>` | **MATCH** |
| `apiClient.fetchAreas()` | `GET` | `/api/v1/areas.php` | Header: `Authorization: Bearer <token>` | **MATCH** |
| `apiClient.fetchShifts()` | `GET` | `/api/v1/shifts.php?employee_id={id}` | Query: `?employee_id={employeeId}` with `Authorization: Bearer <token>` | **MATCH** |
| `apiClient.fetchAssignments()` | `GET` | `/api/v1/assignments.php?employee_id={id}`| Query: `?employee_id={employeeId}` with `Authorization: Bearer <token>` | **UNUSED** (Defined in client, not invoked in UI) |
| Cron Heartbeat Check | `GET` | `/api/v1/heartbeat-check.php` | Server-side CLI/Cron invocation | **MATCH** (Backend internal) |
| Admin Live Data Pull | `POST` | `/api/v1/pull-request.php` | `{ employee_id }` triggered from [`dashboard.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/pages/dashboard.php#L183-L197) | **MATCH** (Web UI internal) |
| Admin Flags Management | `GET/PUT/DELETE` | `/api/v1/flags.php` | Full CRUD operations from Admin Portal | **MATCH** (Web UI internal) |

### 3.2 Identified Contract Nuances & Resolutions
1. **`area_id` Forwarding:** The mobile check-in payload now passes both `area_id` and `zoneId` to ensure the relational column in `shifts.area_id` is populated on the backend.
2. **Checkout 404 Guard:** The backend validates `rowCount() === 0` on shift checkout updates, ensuring missing shift records return HTTP 404 rather than false-positive 200s.
3. **Location Rejection Reason Normalization:** The backend includes a dedicated allowlist (`services_disabled`, `permission_denied`, `poor_accuracy`, `exception`, `mocked_gps`, `location_rejection`) with description length capping (255 characters).

---

## 4. Open Questions & Codebase Observations

1. **`setup.php` Production Lifecycle:**
   - [`admin-portal/setup.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/setup.php) has an on-screen warning recommending deletion after setup, but remains physically present in the web root. In production, this file must be removed or guarded with an IP allowlist / file removal rule.
2. **`fetchAssignments()` Consumption:**
   - [`supervisor/src/api/client.ts:fetchAssignments()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/api/client.ts#L201-L220) exists and functions, but [`appStore.ts:syncLiveData()`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/store/appStore.ts#L85-L116) calls `fetchAreas()` and `fetchShifts()` directly. The zone assignments list is currently managed via `assignedAreas`.
3. **Database Environment Fallback:**
   - [`config/database.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/config/database.php#L20) defaults `$driver` to `'auto'`, falling back to SQLite if MySQL is not reachable. While ideal for offline dev, production environments should set `DB_DRIVER=mysql` to fail-fast if MySQL drops.

---

## 5. Discovered Issues & Severity Ratings

```
┌─────────────┬─────────────────────────────────────────────────────────────┬──────────┐
│ Severity    │ Issue Description                                           │ Category │
├─────────────┼─────────────────────────────────────────────────────────────┼──────────┤
│ CRITICAL    │ setup.php accessible in web root without authentication     │ Security │
│ HIGH        │ Plaintext HTTP API URL configured in mobile .env            │ Security │
│ HIGH        │ MySQL credentials rely on environment variables             │ Config   │
│ MEDIUM      │ Host OS cron job required for missed heartbeat detection    │ DevOps   │
│ MEDIUM      │ Access-Control-Allow-Origin: * on backend APIs              │ Security │
│ LOW         │ fetchAssignments() defined in mobile client but unused      │ Polish   │
└─────────────┴─────────────────────────────────────────────────────────────┴──────────┘
```

### Critical Severity
* **ISSUE-01: `setup.php` Publicly Accessible**
  - **Location:** [`admin-portal/setup.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/setup.php#L1-L107)
  - **Risk:** Anyone navigating to `/admin-portal/setup.php` can reset the `admin` user password.
  - **Remediation:** Remove the file after initial provisioning or configure web server rules to deny access.

### High Severity
* **ISSUE-02: Plaintext HTTP API Endpoint**
  - **Location:** [`supervisor/.env:L1`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/.env#L1) (`http://129.225.110.110/admin-portal`)
  - **Risk:** Mobile network requests carry Bearer tokens and location telemetry in plaintext over public networks.
  - **Remediation:** Update `EXPO_PUBLIC_API_URL` to an HTTPS endpoint backed by a valid TLS certificate before production release.

* **ISSUE-03: Production MySQL Environment Provisioning**
  - **Location:** [`admin-portal/config/database.php:L7-11`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/config/database.php#L7-L11)
  - **Risk:** If `DB_PASS` is empty and `DB_DRIVER=mysql`, the backend throws a connection exception.
  - **Remediation:** Ensure `DB_HOST`, `DB_USER`, `DB_PASS`, `DB_NAME`, and `DB_DRIVER=mysql` are defined in production web server environment.

### Medium Severity
* **ISSUE-04: Cron Job Scheduling for Heartbeat Monitor**
  - **Location:** [`admin-portal/api/v1/heartbeat-check.php`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/api/v1/heartbeat-check.php#L1-L56)
  - **Risk:** Automated missed-heartbeat compliance flags will not trigger if the endpoint is not polled periodically by the server OS.
  - **Remediation:** Add `*/5 * * * * curl -s http://localhost/admin-portal/api/v1/heartbeat-check.php` to host system crontab.

* **ISSUE-05: Backend CORS Allow-All Header**
  - **Location:** [`admin-portal/includes/functions.php:L12`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/admin-portal/includes/functions.php#L12) (`Access-Control-Allow-Origin: *`)
  - **Risk:** Allows cross-origin browser requests from any origin.
  - **Remediation:** Restrict to specific facility origin domains for web requests.

### Low Severity
* **ISSUE-06: Unused `fetchAssignments()` Client Method**
  - **Location:** [`supervisor/src/api/client.ts:L201`](file:///c:/Users/Admin/Desktop/mobileApps/v.0.1/supervisor/src/api/client.ts#L201)
  - **Risk:** Minor dead code on mobile client; does not affect functionality.

---

## 6. Pre-Launch Punch List

The following tasks represent the exact punch list required before launch, ordered strictly by severity:

### Priority 1: Critical (Launch Blockers)
- [ ] **Remove or Secure `setup.php`**: Delete `admin-portal/setup.php` or move it outside of the public document root once the initial admin account is created.

### Priority 2: High (Pre-Production Deployment)
- [ ] **Deploy TLS / HTTPS**: Provision a valid SSL/TLS certificate on the web host and update `supervisor/.env` to `https://<domain>/admin-portal`.
- [ ] **Configure Production Database Secrets**: Set `DB_DRIVER=mysql`, `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, and `DB_PASS` in the web server environment (e.g., Apache virtual host config or `/etc/environment`).

### Priority 3: Medium (Operational Readiness)
- [ ] **Enable System Crontab**: Register the 5-minute cron job for `admin-portal/api/v1/heartbeat-check.php`.
- [ ] **Restrict CORS Headers**: Scope `Access-Control-Allow-Origin` in `functions.php` to authorized facility domains.

### Priority 4: Low (Maintenance & Cleanup)
- [ ] **Clean Up Client Assignments Pull**: Wire `fetchAssignments()` into `appStore.ts:syncLiveData()` or prune the helper from `client.ts`.

Viewed Supervisor_SRS_v.0.1.md:103-127