Metadata-Version: 2.4
Name: mediarelay
Version: 1.0.39
Summary: A video streaming server that allows you to securely share your personal video library over the internet
Author: tboy1337
License: # Commercial Restricted License (CRL)
        
        **Version 1.1**
        
        **Copyright (c) 2025 tboy1337**
        
        ## Grant of Rights
        
        Subject to the terms and conditions of this license, the copyright holder grants you a worldwide, royalty-free, non-exclusive license to use, copy, modify, and distribute this software and associated documentation files (the "Software") for **Non-Commercial Use** only.
        
        ## Definitions
        
        **"Non-Commercial Use"** means use of the Software that is not primarily intended for or directed toward commercial advantage or monetary compensation. Non-Commercial Use includes:
        
        - Personal use, learning, and experimentation
        - Academic research and education
        - Open source projects that are not monetized
        - Internal evaluation within a commercial organization (limited to 30 days)
        - Use by registered non-profit organizations for their non-profit activities
        
        **"Commercial Use"** means any use of the Software that is primarily intended for or directed toward commercial advantage or monetary compensation, including but not limited to:
        
        - Use in any product or service that generates revenue
        - Use by for-profit organizations in their business operations
        - Integration into commercial software or services
        - Use in providing paid consulting, support, or services
        - Use in any business process that contributes to revenue generation
        - Use by organizations with annual revenue exceeding $100,000 USD
        
        **Note:** Any Commercial Use of the Software requires a separate commercial license from the copyright holder.
        
        ## Conditions
        
        For Non-Commercial Use, you may:
        
        - Use, copy, and modify the Software
        - Distribute copies of the Software
        - Distribute your modifications under this same license
        
        You must:
        
        - Include this license notice in all copies or substantial portions of the Software
        - Not remove or alter any copyright notices
        
        ## Restrictions
        
        You may not:
        
        - Use the Software for Commercial Use without a commercial license
        - Sublicense the Software under different terms
        - Use the Software in any way that violates applicable laws
        - Remove, obscure, or modify any licensing, copyright, or other legal notices
        
        ## No Warranty
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
        ## Termination
        
        This license terminates automatically if you violate any of its terms. Upon termination, you must cease all use and distribution of the Software and destroy all copies in your possession.
        
        ## Governing Law
        
        This license shall be governed by and construed in accordance with the laws of the United Kingdom, without regard to its conflict of law provisions.
        
Project-URL: Homepage, https://github.com/tboy1337/MediaRelay
Project-URL: Documentation, https://github.com/tboy1337/MediaRelay/tree/main/docs
Project-URL: Repository, https://github.com/tboy1337/MediaRelay
Project-URL: Issues, https://github.com/tboy1337/MediaRelay/issues
Keywords: video,streaming,server,media,flask,security,authentication
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: End Users/Desktop
Classifier: Topic :: Multimedia :: Video
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Operating System :: OS Independent
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Environment :: Web Environment
Classifier: Framework :: Flask
Classifier: Typing :: Typed
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: Flask
Requires-Dist: jinja2
Requires-Dist: Werkzeug
Requires-Dist: waitress
Requires-Dist: flask-limiter
Requires-Dist: python-dotenv
Requires-Dist: click
Requires-Dist: colorlog
Requires-Dist: psutil
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-timeout; extra == "dev"
Requires-Dist: pytest-xdist; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: pytest-html; extra == "dev"
Requires-Dist: pytest-json-report; extra == "dev"
Requires-Dist: pytest-mock; extra == "dev"
Requires-Dist: pylint; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: isort; extra == "dev"
Requires-Dist: bandit; extra == "dev"
Requires-Dist: types-psutil; extra == "dev"
Requires-Dist: types-waitress; extra == "dev"
Requires-Dist: types-Flask; extra == "dev"
Requires-Dist: types-click; extra == "dev"
Requires-Dist: types-Werkzeug; extra == "dev"
Requires-Dist: autopep8; extra == "dev"
Requires-Dist: pip-audit; extra == "dev"
Dynamic: license-file

# MediaRelay

A video streaming server that allows you to securely share your personal video library over the internet. Built with robust security, monitoring, and performance features.

## ✨ Features

### 🔒 Security
- **Multi-layer Authentication**: HTTP Basic Auth + Session Management
- **Path Traversal Protection**: Prevents unauthorized file access
- **Security Headers**: XSS, SameSite cookie protection, clickjacking protection
- **Rate Limiting**: Configurable request throttling
- **Security Audit Logging**: Comprehensive security event tracking
- **Session Management**: Secure sessions with configurable timeouts

### 🎥 Media Streaming  
- **Universal Format Support**: MP4, MKV, AVI, MOV, WebM, M4V, FLV
- **Subtitle Support**: SRT and WebVTT (`.srt`, `.vtt`) subtitle files
- **Audio Support**: MP3, AAC, OGG, WAV
- **Range Requests**: Efficient streaming with seek support
- **Mobile Optimized**: Responsive design for all devices

### 📊 Monitoring & Performance
- **Health Check Endpoint**: Real-time server status
- **Performance Metrics**: Request timing and throughput monitoring  
- **Comprehensive Logging**: Application, security, error, and performance logs
- **Multi-threaded**: Configurable concurrency for high performance
- **Resource Monitoring**: CPU, memory, and disk snapshot logged at server startup (`log_system_info`)

### 🛠️ Advanced Features
- **Environment Configuration**: Full environment variable support
- **90%+ Test Coverage**: Comprehensive test suite with branch coverage and security tests
- **Service Management**: System service configurations — see [Deployment Guide](docs/deployment_guide.md)
- **Log Rotation**: Automatic log rotation and archival
- **API Support**: RESTful JSON API for integration

## 📋 Requirements

- **Python**: 3.12 or higher
- **Operating System**: Windows 10+, macOS 10.15+, or Linux (Ubuntu 20.04+ recommended)
- **Memory**: Minimum 2GB RAM, 4GB+ recommended for optimal performance
- **Storage**: 1GB for application, additional space for video content
- **Network**: Stable internet connection for remote access

## 🚀 Quick Start

### 1. Installation

**Recommended — install from PyPI:**

```bash
# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate  # Linux/macOS
venv\Scripts\activate     # Windows

pip install mediarelay
```

That installs the `mediarelay`, `mediarelay-config`, `mediarelay-genpass`, and `mediarelay-validate` commands. No need to clone the repository.

**Windows users** can alternatively download a pre-built executable from [GitHub Releases](https://github.com/tboy1337/MediaRelay/releases). Place a `.env` file in the same directory as `MediaRelay.exe` and run the executable.

**From source (development or contributing):**

```bash
git clone https://github.com/tboy1337/MediaRelay.git
cd MediaRelay

python -m venv venv
source venv/bin/activate  # Linux/macOS
venv\Scripts\activate     # Windows

pip install -e ".[dev]"
```

Use `pip install -e .` instead of `pip install -e ".[dev]"` if you only need the application without test and lint tools.

### 2. Configuration

```bash
# Generate sample configuration
mediarelay-config

# Copy and edit configuration
copy .env.example .env   # Windows
cp .env.example .env     # Linux/macOS
# Edit .env with your settings
```

### 3. Security Setup

Generate required security credentials:

```bash
# Generate Flask secret key and password hash
mediarelay-genpass
```

The script will:
1. **Ask for your preferred username** (e.g., `admin`, `user`, etc.)
2. **Generate or create your password**:
   - Choose 'y' to generate a secure 35-character password automatically
   - Choose 'n' to enter your own password (minimum 12 characters)
3. **Generate a Flask secret key** (for session security)
4. **Create a password hash** (for secure authentication)

**Example output:**
```
============================================================
CONFIGURATION VALUES FOR .env FILE
============================================================
VIDEO_SERVER_SECRET_KEY=a1b2c3d4e5f67890abcdef1234567890abcdef1234567890abcdef1234567890
VIDEO_SERVER_USERNAME=admin
VIDEO_SERVER_PASSWORD_HASH=scrypt:32768:8:1$abc123$def456...
```

**Important Security Notes**: 
- **Save your password securely** - you'll need it to log in to the web interface
- **Copy all three generated values** to your `.env` file immediately
- **Never share your secret key or password hash** - treat them like private keys
- **Regenerate credentials** if you suspect they've been compromised
- The script uses **cryptographically secure random generation** for maximum security

### 4. Start the Server

```bash
# Start the server
mediarelay

# Or with custom configuration
mediarelay --host 0.0.0.0 --port 8080
```

Once the server is running, you can access it in your web browser at:
- **Local access**: http://localhost:5000
- **Network access**: http://YOUR_IP_ADDRESS:5000 (if configured with --host 0.0.0.0)

### 🔧 Configuration

#### Step-by-Step Configuration Process

1. **Create your configuration file** (if you do not already have `.env.example` from a source checkout, run `mediarelay-config` first):
   ```bash
   copy .env.example .env   # Windows
   cp .env.example .env     # Linux/macOS
   ```

2. **Generate security credentials**:
   ```bash
   mediarelay-genpass
   ```

3. **Update your `.env` file** with the generated values:
   - Replace `VIDEO_SERVER_SECRET_KEY=your-secret-key-here` with your generated secret key
   - Replace `VIDEO_SERVER_USERNAME=tboy1337` with your chosen username  
   - Replace `VIDEO_SERVER_PASSWORD_HASH=your-password-hash-here` with your generated hash

4. **Configure other settings** as needed (video directory, port, etc.)

5. **Validate configuration** before production deployment:
   ```bash
   mediarelay-validate
   ```

6. **Start the server** (configuration is validated on startup):
   ```bash
   mediarelay
   ```

#### Key Environment Variables

```bash
# Server Configuration
VIDEO_SERVER_HOST=0.0.0.0
VIDEO_SERVER_PORT=5000  
VIDEO_SERVER_DIRECTORY=/path/to/videos
VIDEO_SERVER_THREADS=6

# Security (Required - Generate using mediarelay-genpass)
VIDEO_SERVER_USERNAME=your_username                    # Your chosen username
VIDEO_SERVER_PASSWORD_HASH=your_secure_hash            # Generated password hash
VIDEO_SERVER_SECRET_KEY=your_secret_key                # Generated Flask secret key

# Performance
VIDEO_SERVER_RATE_LIMIT_PER_MIN=60
VIDEO_SERVER_SESSION_TIMEOUT=3600
VIDEO_SERVER_MAX_FILE_SIZE=21474836480  # 20GB default, set to 0 to disable

# Session Cookies (set Secure=true when serving over HTTPS)
VIDEO_SERVER_SESSION_COOKIE_SECURE=true
VIDEO_SERVER_SESSION_COOKIE_HTTPONLY=true
VIDEO_SERVER_SESSION_COOKIE_SAMESITE=Strict

# Reverse proxy (set true ONLY when behind a trusted reverse proxy)
VIDEO_SERVER_BEHIND_PROXY=false

# Account lockout (failed login protection)
VIDEO_SERVER_LOCKOUT_MAX_ATTEMPTS=5
VIDEO_SERVER_LOCKOUT_DURATION=900

# Logging
VIDEO_SERVER_LOG_LEVEL=INFO
VIDEO_SERVER_LOG_DIR=./logs
VIDEO_SERVER_LOG_CONSOLE=true

# Production mode (rejects placeholder credentials)
VIDEO_SERVER_PRODUCTION=true
```

## Development

Run the full quality gate locally:

```bash
python scripts/verify.py
```

This runs black, isort, mypy, bandit, pylint, pip-audit, and pytest with 90% branch coverage.

## 🔒 Security

### Authentication & Authorization

```python
# Multi-layer authentication
HTTP_BASIC_AUTH + SESSION_MANAGEMENT + SAMESITE_COOKIES
```

### Security Headers

```http
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=31536000  # When VIDEO_SERVER_HSTS=true or VIDEO_SERVER_BEHIND_PROXY=true
Content-Security-Policy: default-src 'self'; media-src 'self'; style-src 'self' 'unsafe-inline'
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()
X-Permitted-Cross-Domain-Policies: none
```

`X-XSS-Protection` is intentionally omitted (deprecated in modern browsers).

### Reverse Proxy Warning

Set `VIDEO_SERVER_BEHIND_PROXY=true` and `VIDEO_SERVER_PROXY_TRUSTED=true` only when MediaRelay runs behind a trusted reverse proxy (nginx, Caddy, etc.) and is bound to localhost. Without `PROXY_TRUSTED`, client IP and rate limits use the direct connection address, not `X-Forwarded-For`. Direct internet exposure with proxy headers enabled allows IP spoofing. See [SECURITY.md](SECURITY.md).

### Security Monitoring

All security events are logged:
- Authentication attempts (success/failure)
- Path traversal attempts
- Rate limit violations
- File access attempts
- Account lockout events

Logout requires `POST /logout` with a CSRF token via the `X-CSRF-Token` header or `csrf_token` form field (see [API documentation](docs/api_documentation.md)). `GET /logout` is rejected with `405 Method Not Allowed`.

`VIDEO_SERVER_HOST` is validated at startup (must be a valid IP address or hostname).

## 📈 Performance

### Performance Features

- **Multi-threading**: Configurable worker threads
- **Range Requests**: Efficient video streaming
- **HTTP Caching**: Browser caching for static content
- **Connection Pooling**: Supports multiple users simultaneously
- **Memory Management**: Automatic resource cleanup

## 📊 API Usage

### Available Endpoints

```bash
# Health check (no auth required)
GET /health

# Directory listing  
GET /api/files?path=movies

# File streaming
GET /stream/path/to/video.mp4

# Web interface
GET /
GET /path/to/directory/
```

### Using the API

```python
import requests
from requests.auth import HTTPBasicAuth

auth = HTTPBasicAuth('username', 'password')

# Get file listing
response = requests.get(
    'http://localhost:5000/api/files', 
    auth=auth
)
files = response.json()

# Stream video
video_url = 'http://localhost:5000/stream/movie.mp4'
response = requests.get(video_url, auth=auth, stream=True)
```

## 🔧 Troubleshooting

### Common Issues

**Server won't start**: Check logs in `logs/error.log`
**Authentication issues**: 
  - Verify your `.env` file has all three security values from `mediarelay-genpass`
  - Ensure you're using the correct username and password you generated
  - Regenerate credentials if needed: `mediarelay-genpass`
**Performance problems**: Increase thread count (`VIDEO_SERVER_THREADS`)
**Network access**: Check firewall and port forwarding
**Missing .env file**: Copy `.env.example` to `.env` and configure

### Debug Mode

```bash
VIDEO_SERVER_DEBUG=true
VIDEO_SERVER_LOG_LEVEL=DEBUG
mediarelay
```

### Support

- **Documentation**: [docs/README.md](docs/README.md)
- **Logs**: Review application logs in `logs/`
- **Health Check**: `curl http://localhost:5000/health`
- **Security**: [SECURITY.md](SECURITY.md)
- **Issues**: Create GitHub issue with logs and configuration

## 📄 License

This project is licensed under the CRL License - see the [LICENSE.md](LICENSE.md) file for details.
