# MediaVerse — Downloader Module Specification

## 1. Module Overview

The Downloader Module is the foundational component of MediaVerse, responsible for acquiring media content from supported platforms in a legally compliant manner. It provides a robust, resumable, and efficient download system with extensive format support and metadata handling.

### Key Capabilities
- Multi-source URL parsing and validation
- Adaptive quality selection
- Concurrent download management
- Format conversion pipeline
- Metadata extraction and embedding
- Subtitle acquisition
- Resume/retry mechanisms

---

## 2. Input Methods

### 2.1 URL Input Interface

```
┌─────────────────────────────────────────────────────────────┐
│  URL Input Component                                         │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────────────────────────────────────────────┐   │
│  │  🔗 Paste URL here...                              │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                              │
│  [Analyze URL]  [Add to Queue]  [Download Now]             │
│                                                              │
│  Recent:                                                     │
│  • youtube.com/watch?v=... (2 hours ago)                    │
│  • vimeo.com/... (Yesterday)                               │
└─────────────────────────────────────────────────────────────┘
```

**Input Validation Pipeline:**
1. **Sanitization**: Trim whitespace, normalize protocol
2. **Parsing**: Extract domain, path, query parameters
3. **Platform Detection**: Match against supported sites database
4. **Reachability Check**: HEAD request to validate accessibility
5. **Content Analysis**: Determine available formats, qualities

### 2.2 Drag & Drop Interface

**Supported Drop Targets:**
- Main window drop zone
- System tray icon
- Browser extension (future)
- Mobile share sheet (iOS/Android)

**Drop Handling:**
```typescript
interface DropEvent {
  type: 'url' | 'file' | 'text';
  data: string | File[];
  source: 'browser' | 'explorer' | 'clipboard';
  timestamp: number;
}
```

### 2.3 Clipboard Detection

**Smart Clipboard Monitoring:**
- Background monitoring (with user permission)
- URL pattern matching using regex
- Automatic popup when valid URL detected
- Configurable auto-add to queue

```typescript
const URL_PATTERNS = {
  YOUTUBE: /^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtu\\.be)\\/.+/,
  VIMEO: /^(https?:\\/\\/)?(www\\.)?vimeo\\.com\\/.+/,
  // ... 50+ patterns
};
```

### 2.4 Batch Processing

**Batch Input Methods:**
- Multi-line text input (one URL per line)
- CSV/JSON file import
- Browser bookmark import
- Playlist/channel URLs (auto-expand)

**Batch Configuration:**
```typescript
interface BatchConfig {
  urls: string[];
  defaultQuality: 'best' | 'worst' | 'custom';
  defaultFormat: string;
  outputTemplate: string;
  autoStart: boolean;
  maxConcurrent: number;
}
```

---

## 3. Download Capabilities

### 3.1 Quality Selection

**Video Quality Tiers:**
| Tier | Resolution | Bitrate | Use Case |
|------|------------|---------|----------|
| 8K | 7680×4320 | 80+ Mbps | Archival |
| 4K | 3840×2160 | 25-40 Mbps | Premium |
| 1440p | 2560×1440 | 10-20 Mbps | High Quality |
| 1080p | 1920×1080 | 5-10 Mbps | Standard |
| 720p | 1280×720 | 2.5-5 Mbps | Mobile |
| 480p | 854×480 | 1-2.5 Mbps | Low Bandwidth |
| 360p | 640×360 | 0.5-1 Mbps | Preview |

**Audio Quality Tiers:**
| Format | Bitrate | Sample Rate | Channels |
|--------|---------|-------------|----------|
| FLAC | Lossless | 96kHz | 2.0/5.1/7.1 |
| AAC 320 | 320 kbps | 48kHz | 2.0 |
| AAC 256 | 256 kbps | 48kHz | 2.0 |
| MP3 320 | 320 kbps | 44.1kHz | 2.0 |
| MP3 192 | 192 kbps | 44.1kHz | 2.0 |
| Opus | 128 kbps | 48kHz | 2.0 |

### 3.2 Format Support

**Container Formats:**
- **MP4**: H.264/H.265/AV1 video + AAC/Opus audio
- **MKV**: All codecs, subtitle tracks, chapters
- **WebM**: VP8/VP9/AV1 + Vorbis/Opus
- **MOV**: ProRes, DNxHD (professional)
- **AVI**: Legacy support
- **FLV**: Archive compatibility

**Audio-Only Formats:**
- **MP3**: Universal compatibility
- **AAC**: Apple ecosystem
- **FLAC**: Lossless archival
- **Opus**: Best compression
- **WAV**: Uncompressed
- **M4A**: iTunes compatible

### 3.3 Audio Extraction

**Extraction Pipeline:**
1. Download source video (or use existing)
2. Demux audio stream without re-encoding (when possible)
3. Convert to target format if necessary
4. Embed metadata and artwork
5. Write to output location

**Extraction Options:**
```typescript
interface AudioExtractionOptions {
  source: 'video_url' | 'local_file';
  outputFormat: 'mp3' | 'aac' | 'flac' | 'opus' | 'wav';
  bitrate: number | 'source';
  sampleRate: number | 'source';
  channels: 1 | 2 | 'source';
  metadata: boolean;
  artwork: boolean;
}
```

### 3.4 Subtitle Handling

**Subtitle Sources:**
- Embedded in video container
- Separate file download (SRT, VTT, ASS)
- Auto-generated (if available)
- Community translations

**Subtitle Options:**
```typescript
interface SubtitleOptions {
  languages: string[]; // ISO 639-1 codes
  formats: ('srt' | 'vtt' | 'ass' | 'embedded')[];
  autoTranslate: boolean;
  burnIn: boolean; // Hardcode into video
  defaultLanguage: string;
}
```

---

## 4. System Flow

### 4.1 Download Lifecycle State Machine

```
┌─────────┐    ┌──────────┐    ┌─────────┐    ┌──────────┐
│ PENDING │───▶│ ANALYZING│───▶│ QUEUED  │───▶│ DOWNLOAD │
└─────────┘    └──────────┘    └─────────┘    └────┬─────┘
                                                   │
    ┌───────────────────────────────────────────────┘
    │
    ▼
┌─────────┐    ┌─────────┐    ┌─────────┐    ┌─────────┐
│ PAUSED  │◀──▶│ ACTIVE  │───▶│MERGING  │───▶│COMPLETE │
└────┬────┘    └────┬────┘    └─────────┘    └────┬────┘
     │              │                              │
     │         ┌────┴────┐                        │
     └────────▶│ FAILED  │◀───────────────────────┘
               └────┬────┘
                    │
               ┌────┴────┐
               │ RETRY   │
               └─────────┘
```

**State Definitions:**

| State | Description | Transitions |
|-------|-------------|-------------|
| PENDING | Initial state, awaiting analysis | → ANALYZING |
| ANALYZING | Fetching metadata, available formats | → QUEUED, FAILED |
| QUEUED | Waiting for download slot | → DOWNLOAD, CANCELLED |
| DOWNLOAD | Actively downloading segments | → PAUSED, FAILED, MERGING |
| PAUSED | User or system paused | → DOWNLOAD, CANCELLED |
| MERGING | Combining segments, converting | → COMPLETE, FAILED |
| COMPLETE | Finished successfully | → (terminal) |
| FAILED | Error occurred | → RETRY, CANCELLED |
| CANCELLED | User cancelled | → (terminal) |
| RETRY | Scheduled for retry | → DOWNLOAD |

### 4.2 Download Process Flow

```
┌─────────────────────────────────────────────────────────────┐
│  1. URL RECEIVED                                             │
│     • Validate format                                         │
│     • Check against blocklist                                 │
│     • Parse platform and content ID                           │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────────────────┐
│  2. CONTENT ANALYSIS                                         │
│     • Fetch available formats (yt-dlp/yt-dlp)                │
│     • Extract metadata (title, duration, uploader)           │
│     • Determine best quality match                           │
│     • Check for subtitles                                    │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────────────────┐
│  3. USER CONFIGURATION                                         │
│     • Present quality options                                 │
│     • Show format selection                                   │
│     • Configure output location                             │
│     • Set post-processing options                           │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────────────────┐
│  4. QUEUE PLACEMENT                                            │
│     • Check concurrent download limits                      │
│     • Assign priority                                         │
│     • Reserve disk space                                      │
│     • Create download record                                  │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────────────────┐
│  5. DOWNLOAD EXECUTION                                         │
│     • Initialize HTTP client with resume support            │
│     • Download segments/chunks                                │
│     • Verify checksums                                        │
│     • Update progress                                         │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────────────────┐
│  6. POST-PROCESSING                                            │
│     • Merge segments (if applicable)                        │
│     • Convert format (if needed)                            │
│     • Embed metadata                                          │
│     • Download/embed subtitles                              │
│     • Generate thumbnail                                    │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────────────────┐
│  7. COMPLETION                                                 │
│     • Move to final location                                  │
│     • Add to media library                                    │
│     • Trigger automation rules                              │
│     • Send notification                                     │
└─────────────────────────────────────────────────────────────┘
```

---

## 5. Component Architecture

### 5.1 Module Structure

```
src/
├── downloader/
│   ├── core/
│   │   ├── DownloadManager.ts          # Central coordinator
│   │   ├── DownloadQueue.ts            # Priority queue management
│   │   ├── DownloadWorker.ts           # Individual download handler
│   │   └── StateMachine.ts             # Download state management
│   ├── input/
│   │   ├── URLParser.ts                # URL validation & parsing
│   │   ├── ClipboardMonitor.ts         # Background clipboard watcher
│   │   ├── DragDropHandler.ts          # Drag & drop processing
│   │   └── BatchProcessor.ts           # Batch URL handling
│   ├── analysis/
│   │   ├── ContentAnalyzer.ts          # Metadata extraction
│   │   ├── FormatSelector.ts           # Quality/format selection
│   │   ├── PlatformAdapter.ts          # Platform-specific logic
│   │   └── SubtitleFetcher.ts          # Subtitle discovery
│   ├── engine/
│   │   ├── HTTPDownloader.ts           # HTTP/HTTPS download
│   │   ├── SegmentDownloader.ts        # DASH/HLS segment handling
│   │   ├── ResumeManager.ts            # Partial download management
│   │   ├── SpeedLimiter.ts             # Bandwidth throttling
│   │   └── ConnectionPool.ts           # HTTP connection management
│   ├── processing/
│   │   ├── FFmpegProcessor.ts          # Video/audio processing
│   │   ├── MetadataEmbedder.ts         # Metadata injection
│   │   ├── ThumbnailGenerator.ts       # Thumbnail extraction
│   │   └── SubtitleProcessor.ts        # Subtitle conversion
│   ├── storage/
│   │   ├── DownloadRepository.ts       # Download persistence
│   │   ├── TempFileManager.ts          # Temporary file handling
│   │   └── OutputOrganizer.ts          # File organization
│   └── types/
│       ├── Download.ts                 # Core types
│       ├── Queue.ts                    # Queue types
│       └── Events.ts                   # Event definitions
```

### 5.2 Core Components

#### DownloadManager (Singleton)
```typescript
class DownloadManager extends EventEmitter {
  private queue: DownloadQueue;
  private workers: Map<string, DownloadWorker>;
  private config: DownloadConfig;
  
  async addDownload(url: string, options: DownloadOptions): Promise<Download>;
  async pauseDownload(id: string): Promise<void>;
  async resumeDownload(id: string): Promise<void>;
  async cancelDownload(id: string): Promise<void>;
  async retryDownload(id: string): Promise<void>;
  
  getActiveDownloads(): Download[];
  getQueueStatus(): QueueStatus;
  
  on(event: 'progress', callback: (update: ProgressUpdate) => void): void;
  on(event: 'complete', callback: (download: Download) => void): void;
  on(event: 'error', callback: (error: DownloadError) => void): void;
}
```

#### DownloadWorker
```typescript
class DownloadWorker extends EventEmitter {
  private download: Download;
  private state: DownloadState;
  private httpClient: HTTPDownloader;
  private processor: FFmpegProcessor;
  
  async start(): Promise<void>;
  async pause(): Promise<void>;
  async resume(): Promise<void>;
  async cancel(): Promise<void>;
  
  private async analyze(): Promise<AnalysisResult>;
  private async download(): Promise<void>;
  private async process(): Promise<void>;
  private async finalize(): Promise<void>;
  
  getProgress(): ProgressInfo;
  getState(): DownloadState;
}
```

#### DownloadQueue
```typescript
class DownloadQueue {
  private items: PriorityQueue<QueueItem>;
  private maxConcurrent: number;
  private activeCount: number;
  
  enqueue(item: QueueItem, priority?: number): void;
  dequeue(): QueueItem | null;
  peek(): QueueItem | null;
  remove(id: string): boolean;
  reorder(id: string, newIndex: number): void;
  
  getPending(): QueueItem[];
  getPosition(id: string): number;
}
```

---

## 6. APIs and Services

### 6.1 Internal API

```typescript
// Download Service Interface
interface IDownloadService {
  // Core operations
  createDownload(request: CreateDownloadRequest): Promise<Download>;
  getDownload(id: string): Promise<Download>;
  listDownloads(filter?: DownloadFilter): Promise<Download[]>;
  updateDownload(id: string, updates: Partial<Download>): Promise<Download>;
  deleteDownload(id: string): Promise<void>;
  
  // Control operations
  startDownload(id: string): Promise<void>;
  pauseDownload(id: string): Promise<void>;
  resumeDownload(id: string): Promise<void>;
  cancelDownload(id: string): Promise<void>;
  retryDownload(id: string): Promise<void>;
  
  // Batch operations
  createBatch(request: BatchRequest): Promise<BatchJob>;
  getBatchStatus(id: string): Promise<BatchStatus>;
  
  // Configuration
  getConfig(): Promise<DownloadConfig>;
  updateConfig(config: Partial<DownloadConfig>): Promise<void>;
}

// Events
interface DownloadEvents {
  'download:created': (download: Download) => void;
  'download:started': (id: string) => void;
  'download:progress': (update: ProgressUpdate) => void;
  'download:paused': (id: string) => void;
  'download:resumed': (id: string) => void;
  'download:completed': (download: Download) => void;
  'download:failed': (error: DownloadError) => void;
  'download:cancelled': (id: string) => void;
}
```

### 6.2 Platform Adapters

```typescript
abstract class PlatformAdapter {
  abstract readonly name: string;
  abstract readonly domains: string[];
  
  abstract canHandle(url: string): boolean;
  abstract analyze(url: string): Promise<AnalysisResult>;
  abstract getFormats(analysis: AnalysisResult): Promise<Format[]>;
  abstract createDownloadTask(format: Format): DownloadTask;
  
  // Optional hooks
  beforeDownload?(task: DownloadTask): Promise<void>;
  afterDownload?(task: DownloadTask): Promise<void>;
}

// Example: YouTube Adapter
class YouTubeAdapter extends PlatformAdapter {
  readonly name = 'YouTube';
  readonly domains = ['youtube.com', 'youtu.be'];
  
  private ytdlp: YTDLPWrapper;
  
  async analyze(url: string): Promise<AnalysisResult> {
    const info = await this.ytdlp.getInfo(url);
    return {
      title: info.title,
      duration: info.duration,
      uploader: info.uploader,
      thumbnails: info.thumbnails,
      formats: this.parseFormats(info.formats),
      subtitles: info.subtitles,
    };
  }
}
```

---

## 7. Error Handling

### 7.1 Error Categories

| Category | Examples | Handling Strategy |
|----------|----------|-------------------|
| Network | Timeout, DNS failure, SSL error | Exponential backoff retry |
| HTTP | 403 Forbidden, 404 Not Found, 429 Rate Limited | Platform-specific handling |
| Content | Video unavailable, age-restricted, region-blocked | User notification with details |
| Storage | Disk full, permission denied, path too long | Pause and prompt user |
| Processing | FFmpeg failure, corrupt file, codec error | Cleanup and retry with fallback |
| Unknown | Unexpected errors | Log and report, graceful degradation |

### 7.2 Retry Strategy

```typescript
interface RetryConfig {
  maxAttempts: number;        // Default: 3
  baseDelay: number;        // Default: 1000ms
  maxDelay: number;         // Default: 30000ms
  backoffMultiplier: number; // Default: 2
  retryableErrors: string[];  // Error codes that trigger retry
}

class RetryManager {
  async execute<T>(
    operation: () => Promise<T>,
    config: RetryConfig
  ): Promise<T> {
    let attempt = 0;
    let delay = config.baseDelay;
    
    while (attempt < config.maxAttempts) {
      try {
        return await operation();
      } catch (error) {
        attempt++;
        if (attempt >= config.maxAttempts) throw error;
        if (!this.isRetryable(error)) throw error;
        
        await this.sleep(delay);
        delay = Math.min(delay * config.backoffMultiplier, config.maxDelay);
      }
    }
  }
}
```

### 7.3 Error Recovery

**Automatic Recovery:**
- Resume partial downloads on app restart
- Retry failed segments individually
- Fallback to alternative formats
- Degrade quality if bandwidth insufficient

**Manual Recovery:**
- Retry with different settings
- Skip and continue queue
- Export error log for support

---

## 8. Storage Design

### 8.1 Download Record Schema

```typescript
interface Download {
  // Identity
  id: string;                    // UUID v4
  createdAt: Date;
  updatedAt: Date;
  
  // Source
  url: string;
  platform: string;
  contentId: string;
  
  // Content metadata
  title: string;
  description?: string;
  duration?: number;              // seconds
  uploader?: string;
  uploadDate?: Date;
  thumbnailUrl?: string;
  
  // Configuration
  selectedFormat: Format;
  outputPath: string;
  outputFormat: string;
  options: DownloadOptions;
  
  // Status
  state: DownloadState;
  progress: {
    bytesDownloaded: number;
    bytesTotal: number;
    bytesPerSecond: number;
    etaSeconds: number;
    percentComplete: number;
  };
  
  // History
  attempts: Attempt[];
  startedAt?: Date;
  completedAt?: Date;
  error?: ErrorInfo;
  
  // Relations
  batchId?: string;
  parentId?: string;            // For playlists
  children?: string[];          // Playlist items
}

interface Attempt {
  startedAt: Date;
  endedAt: Date;
  success: boolean;
  error?: ErrorInfo;
  bytesDownloaded: number;
}
```

### 8.2 File Organization

**Default Structure:**
```
~/MediaVerse/
├── downloads/
│   ├── {platform}/
│   │   ├── {uploader}/
│   │   │   ├── {title}_{id}.{ext}
│   │   │   └── {title}_{id}.{ext}.thumb.jpg
│   │   └── ...
│   └── ...
├── temp/
│   └── {download-id}/
│       ├── segments/
│       ├── metadata.json
│       └── partial.dat
└── subtitles/
    └── {language}/
        └── {download-id}.srt
```

**Customizable Templates:**
```typescript
type PathTemplate = 
  | '{platform}/{uploader}/{title}_{id}.{ext}'
  | '{date:YYYY}/{date:MM}/{title}.{ext}'
  | '{type}/{quality}/{title}.{ext}'
  | string; // Custom
```

### 8.3 Resume Data

```typescript
interface ResumeData {
  downloadId: string;
  url: string;
  segments: SegmentResume[];
  headers: Record<string, string>;
  cookies?: string;
  lastModified?: string;
  etag?: string;
}

interface SegmentResume {
  index: number;
  startByte: number;
  endByte: number;
  downloadedBytes: number;
  checksum?: string;
}
```

---

## 9. Sequence Diagrams

### 9.1 Single Download Flow

```
┌─────────┐     ┌─────────────┐     ┌──────────────┐     ┌──────────┐
│   UI    │     │ DownloadMgr │     │ DownloadWorker│    │ Platform │
└────┬────┘     └──────┬──────┘     └───────┬──────┘     └────┬─────┘
     │                 │                    │                 │
     │  addDownload()  │                    │                 │
     │────────────────▶│                    │                 │
     │                 │                    │                 │
     │                 │  createWorker()    │                 │
     │                 │───────────────────▶│                 │
     │                 │                    │                 │
     │                 │                    │  analyze()      │
     │                 │                    │────────────────▶│
     │                 │                    │                 │
     │                 │                    │◀────────────────│
     │                 │                    │  AnalysisResult │
     │                 │                    │                 │
     │  download:created│                    │                 │
     │◀────────────────│                    │                 │
     │                 │                    │                 │
     │                 │  start()           │                 │
     │                 │───────────────────▶│                 │
     │                 │                    │                 │
     │  download:started│                    │                 │
     │◀────────────────│                    │                 │
     │                 │                    │                 │
     │                 │  download:progress │                 │
     │◀─────────────────────────────────────│                 │
     │                 │                    │                 │
     │                 │                    │  download()     │
     │                 │                    │────────────────▶│
     │                 │                    │                 │
     │                 │                    │◀────────────────│
     │                 │                    │  segments       │
     │                 │                    │                 │
     │                 │                    │  process()      │
     │                 │                    │────────┐        │
     │                 │                    │        │        │
     │                 │                    │◀───────┘        │
     │                 │                    │                 │
     │                 │  download:completed  │                 │
     │◀─────────────────────────────────────│                 │
     │                 │                    │                 │
```

### 9.2 Batch Download Flow

```
┌─────────┐     ┌─────────────┐     ┌──────────┐     ┌─────────────┐
│   UI    │     │ BatchProcessor│    │ Queue    │     │ Workers     │
└────┬────┘     └──────┬──────┘     └────┬─────┘     └──────┬──────┘
     │                 │                 │                  │
     │ createBatch()   │                 │                  │
     │────────────────▶│                 │                  │
     │                 │                 │                  │
     │                 │ expandURLs()    │                  │
     │                 │────────────────▶│                  │
     │                 │                 │                  │
     │                 │◀────────────────│                  │
     │                 │  expanded[]     │                  │
     │                 │                 │                  │
     │                 │  enqueueAll()   │                  │
     │                 │────────────────▶│                  │
     │                 │                 │                  │
     │  batch:created  │                 │                  │
     │◀────────────────│                 │                  │
     │                 │                 │                  │
     │                 │                 │  dequeue()       │
     │                 │                 │────────────────▶│
     │                 │                 │                  │
     │                 │                 │◀─────────────────│
     │                 │                 │  worker ready    │
     │                 │                 │                  │
     │                 │                 │  (repeat for     │
     │                 │                 │   each item)     │
     │                 │                 │                  │
     │  batch:progress │                 │                  │
     │◀───────────────────────────────────│                  │
     │                 │                 │                  │
     │                 │                 │  batch:complete  │
     │◀──────────────────────────────────────────────────────│
     │                 │                 │                  │
```

---

## 10. Performance Optimizations

### 10.1 Concurrent Downloads

**Connection Management:**
- HTTP/2 multiplexing where supported
- Connection pooling (max 6 connections per host)
- Domain-based rate limiting
- Adaptive concurrency based on bandwidth

```typescript
interface ConcurrencyConfig {
  globalMax: number;           // Total concurrent downloads
  perHostMax: number;          // Per-domain limit
  perPlaylistMax: number;      // For batch operations
  adaptive: boolean;           // Adjust based on speed
}
```

### 10.2 Segment Downloading

**DASH/HLS Optimization:**
- Parallel segment downloads
- Adaptive bitrate switching
- Segment prefetching
- Buffer management

### 10.3 Disk I/O

**Optimizations:**
- Async file operations
- Buffered writes (1MB chunks)
- Sparse file support
- SSD-aware scheduling

---

## 11. Monitoring & Telemetry

### 11.1 Metrics

| Metric | Type | Description |
|--------|------|-------------|
| download_started | counter | Total downloads initiated |
| download_completed | counter | Successful completions |
| download_failed | counter | Failures by category |
| download_duration | histogram | Time from start to complete |
| download_speed | gauge | Bytes per second |
| queue_size | gauge | Current queue length |
| active_downloads | gauge | Currently downloading |

### 11.2 Events

```typescript
interface DownloadEvent {
  name: 'download.started' | 'download.progress' | 'download.completed' | 
        'download.failed' | 'download.cancelled';
  timestamp: number;
  downloadId: string;
  properties: Record<string, any>;
  userId?: string;
}
```

---

## 12. Security Considerations

### 12.1 Input Validation
- URL whitelist/blacklist
- Path traversal prevention
- Content-type verification
- Size limits

### 12.2 Network Security
- TLS 1.3 enforcement
- Certificate pinning for APIs
- DNS-over-HTTPS support
- Proxy configuration

### 12.3 File Security
- Download sandboxing
- Virus scanning integration (optional)
- Quarantine for suspicious files
- Safe file naming

---

*Document Version: 1.0*
*Last Updated: 2026-05-27*
*Owner: Engineering Team*