# GDConnect Technical Architecture & Protocol Specification
**Document Version:** 1.0.0  
**Product:** GDConnect Enterprise Remote Desktop & Remote Support Platform  
**Target OS (Server):** Windows Server 2019 / 2022 / 2025, Windows 10/11 (Dev/Test)  
**Target OS (Client):** Windows 10, Windows 11, Windows Server (Desktop Experience)  

---

## 1. System Overview & Monorepo Layout

GDConnect is engineered as an enterprise-grade, self-hosted, hybrid remote desktop and remote support platform.
The monorepo structure is designed for modular development, cross-package code sharing, and clean service isolation:

```
GDConnect/
├── apps/
│   ├── desktop/                      # Tauri 2 + React 18 + TypeScript + Tailwind desktop client
│   │   ├── src/                      # Client UI (Home, RemoteViewer, Settings, AddressBook, Chat, FileTransfer)
│   │   ├── src-tauri/                # Rust backend: DXGI/WGC screen capture, input injection, WebRTC P2P
│   │   └── package.json
│   └── admin/                        # Next.js / Vite React Admin Dashboard
│       ├── src/                      # Overview, Devices, Sessions, Users, Monitoring, Audit logs
│       └── package.json
├── services/
│   ├── api/                          # Fastify REST API (auth, devices, sessions, health, audit)
│   ├── signaling/                    # WebSocket Signaling Server (device presence, SDP/ICE negotiation)
│   ├── device-registry/              # Device state machine and persistence layer
│   └── session-manager/              # Active remote session coordinator and auth token dispenser
├── packages/
│   ├── shared-types/                 # Shared TypeScript models, DTOs, Enums, API contracts
│   ├── protocol/                     # Signaling and WebRTC control protocol serialization
│   ├── ui/                           # Reusable UI component library (Tailwind + Radix primitives)
│   └── configuration/                # Central config parser with env validation (.env and JSON schemas)
├── infrastructure/
│   ├── windows-server/               # WinSW service definitions, XML templates, Caddy/IIS configs
│   ├── turn/                         # STUN/TURN configurations and verification tests
│   └── scripts/                      # PowerShell deployment, lifecycle, and firewall management scripts
├── database/
│   ├── schema/                       # PostgreSQL Prisma schemas and SQL migrations
│   └── migrations/                   # Sequential migration scripts
├── docs/                             # Architecture specs, security model, deployment runbooks
├── tests/                            # E2E integration and unit test suite
├── package.json                      # NPM Workspace root
└── tsconfig.base.json                # Shared TypeScript compiler options
```

---

## 2. Windows Server Lifecycle & Service Architecture

To guarantee that GDConnect backend services remain active when the RDP administrator closes the connection, logs out, or the server reboots:

1. **Persistent Windows Services via WinSW (Windows Service Wrapper):**
   - `GDConnect-API` (Runs `node dist/index.js` for API service, port 5000)
   - `GDConnect-Signaling` (Runs `node dist/index.js` for Signaling service, port 5001)
   - `GDConnect-Admin` (Hosts Admin Web App or reverses through Caddy/IIS, port 5002)
   - `PostgreSQL` runs as a native Windows service (`postgresql-x64-XX`).

2. **PowerShell Service Management Suite (`infrastructure/scripts`):**
   - `install.ps1`: Automated dependency verification, directory hierarchy creation (`C:\GDConnect`), service registration.
   - `start.ps1`, `stop.ps1`, `restart.ps1`: Service control with status polling.
   - `status.ps1`: Comprehensive health report of all 3 services + database + listening ports.
   - `firewall.ps1`: Automatic Windows Defender Firewall rule configuration for TCP 5000 (API), TCP 5001 (Signaling), TCP/UDP 3478 (STUN/TURN), UDP 49152-65535 (WebRTC Media Range).
   - `health-check.ps1`: Periodic probe validating HTTP API, WebSocket handshake, and DB latency.

---

## 3. Device Identity & Security Architecture

1. **Device ID Format:**
   - Structured format: `GD-XXX-XXX-XXX` (e.g. `GD-482-193-726`)
   - Generated using cryptographically secure random numbers and checked for uniqueness.
   - Bound to hardware fingerprint (CPU UUID + Primary NIC MAC hash) stored in the Windows Credential Manager / encrypted local keystore.
   - Remains stable across app updates and restarts.

2. **Cryptographic & Auth Pipeline:**
   - Passwords hashed using **Argon2id**.
   - Session Tokens: Ed25519/HMAC-SHA256 JWTs with 15-minute access token lifespan and rotating refresh tokens.
   - Signaling Handshake: Authenticated via device identity certificate/token over TLS (WSS).
   - Remote Access Authorization:
     - **Interactive Access:** Controller sends request -> Host displays modal with requester details & permissions -> Remote user accepts -> WebRTC Offer/Answer exchanged.
     - **Unattended Access:** Device owner sets dedicated strong unattended password hashed with Argon2id; controller must provide unattended auth proof verified against server.

---

## 4. Signaling & WebRTC Protocol Architecture

1. **Signaling Message Schema (`packages/protocol`):**
   - `DEVICE_REGISTER`: Client announces Device ID, hostname, OS, IP list, public status.
   - `DEVICE_ONLINE` / `DEVICE_OFFLINE`: Presence broadcast.
   - `SESSION_REQUEST`: Controller requests connection with target Device ID + requested permissions.
   - `SESSION_RESPONSE`: Target host approves or rejects.
   - `WEBRTC_OFFER`: SDP Offer from controller or host.
   - `WEBRTC_ANSWER`: SDP Answer.
   - `ICE_CANDIDATE`: Trickle ICE candidates (Host/SRFLX/Relay).
   - `SESSION_HEARTBEAT`: Kept alive every 5s; automatic disconnect upon 15s timeout.
   - `SESSION_TERMINATE`: Graceful teardown.

2. **Connection Priority Engine:**
   1. **Direct LAN:** Detect matching subnet / private IP candidates -> direct P2P.
   2. **WebRTC P2P (STUN):** NAT traversal via STUN server (`stun:stun.l.Anthropic.com:19302` or self-hosted).
   3. **TURN Relay:** Fallback to TURN relay over UDP/TCP 3478 when symmetric NAT blocks direct P2P.

---

## 5. Database Schema Specification (PostgreSQL / Prisma)

The primary relational data model includes:
- `users`: Administrative and operator accounts with RBAC roles (`SUPERADMIN`, `ADMIN`, `SUPPORT_TECH`, `USER`).
- `devices`: Registered machines with `device_id`, `name`, `os_info`, `public_ip`, `local_ip`, `status`, `last_seen`.
- `device_tokens`: Authentication secrets for registered devices.
- `device_authorizations`: Authorized controller-to-host relations for unattended or pre-authorized access.
- `sessions`: Audit log of remote sessions with start time, end time, duration, controller_id, host_id, connection_type (`DIRECT_LAN`, `P2P_STUN`, `TURN_RELAY`).
- `session_permissions`: Granular flags per session (`allow_remote_control`, `allow_file_transfer`, `allow_clipboard`, `allow_audio`).
- `connection_logs`: High-frequency network events and quality metrics.
- `file_transfers`: Auditable log of file transfers (filename, size, SHA256 hash, status, direction).
- `user_groups` & `user_group_devices`: Organizational address book grouping (e.g., Office, Branch, Support).
- `audit_logs`: Immutable security audit trail.
- `server_settings`: Dynamic server configuration parameters.
