# @averox/cryptosphare

A powerful end-to-end encrypted messaging and media streaming SDK with built-in security monitoring.

## Features

- 🔒 **End-to-End Encryption (E2EE)**

  - No API key required
  - Forward secrecy support
  - Quantum-resistant encryption options
  - Automatic key rotation
  - Multiple encryption algorithms (AES-256-GCM, ChaCha20-Poly1305)

- 🎥 **Secure Media Streaming**

  - Encrypted audio streaming
  - Encrypted video streaming
  - Configurable quality settings

- 📊 **Real-time Monitoring**
  - Encryption/decryption logs
  - Key management events
  - Performance metrics
  - UI integration events

## Security Architecture

### End-to-End Encryption (E2EE)

- ✅ All data is encrypted on the sender's device
- ✅ Data remains encrypted in transit
- ✅ Only decrypted on the recipient's device
- ✅ No intermediary can access unencrypted data
- ✅ No central key storage or management

### Encryption Algorithms

- **AES-256-GCM**

  - 256-bit key length
  - Galois/Counter Mode for authenticated encryption
  - Perfect for high-security requirements

- **ChaCha20-Poly1305**
  - Excellent performance on mobile devices
  - Built-in authentication
  - Strong security guarantees

### Key Management

- 🔄 Automatic key rotation (configurable intervals)
- 🔐 Secure key generation using cryptographic random numbers
- ⚠️ Automatic key compromise detection
- 📝 Complete key lifecycle management

### Forward Secrecy

- New encryption keys for each session
- Previous messages remain secure even if current keys are compromised
- Automatic session key generation

### Quantum Resistance

- Optional quantum-resistant algorithms
- Future-proof security
- Protection against quantum computing attacks

### Security Monitoring

- Real-time security event monitoring
- Automatic detection of:
  - Key compromises
  - Failed encryption operations
  - Unusual patterns
  - Performance degradation
- Customizable security alerts

## Installation

```bash
npm install @averox/cryptosphare
# or
yarn add @averox/cryptosphare
```

## Quick Start

```typescript
import { Config } from '@averox/cryptosphare';

// Initialize the SDK
const sdk = new Config({
  encryption: {
    forwardSecrecy: true,
    algorithm: 'AES-256-GCM',
  },
});

// Initialize secure features
sdk.initialize();
```

## Configuration Options

### Basic Configuration

```typescript
const sdk = new Config({
  // Encryption settings
  encryption: {
    forwardSecrecy: true, // Enable perfect forward secrecy
    quantumResistant: false, // Enable quantum-resistant algorithms
    algorithm: 'AES-256-GCM', // 'AES-256-GCM' or 'ChaCha20-Poly1305'
    keyRotationInterval: 24, // Key rotation interval in hours
  },

  // Media streaming settings
  streaming: {
    audio: true, // Enable audio streaming
    video: true, // Enable video streaming
    videoQuality: '720p', // '480p', '720p', or '1080p'
    audioQuality: 'high', // 'low', 'medium', or 'high'
  },

  // Monitoring settings
  monitoring: {
    encryptionLogs: true, // Enable encryption operation logs
    keyMonitoring: true, // Enable key management monitoring
    performanceMetrics: true, // Enable performance metrics
  },
});
```

### Event Monitoring

Monitor encryption operations and key management events:

```typescript
// Listen for encryption events
sdk.on('encryptionOperation', (stats) => {
  console.log('Encryption operation:', stats);
  // stats: {
  //   operationId: string;
  //   type: 'encrypt' | 'decrypt';
  //   success: boolean;
  //   latency: number;
  //   timestamp: Date;
  // }
});

// Listen for key rotation events
sdk.on('keyRotated', (event) => {
  console.log('Key rotation:', event);
  // event: {
  //   type: 'rotated';
  //   status: 'active';
  //   timestamp: Date;
  //   metadata: { oldKey: string; newKey: string; }
  // }
});

// Listen for metrics updates
sdk.on('metricsUpdate', (metrics) => {
  console.log('Metrics update:', metrics);
  // metrics: {
  //   totalOperations: number;
  //   successRate: number;
  //   averageLatency: number;
  //   lastUpdated: Date;
  // }
});
```

### Custom Event Handlers

Define custom handlers for specific events:

```typescript
const sdk = new Config({
  monitoring: {
    eventHandlers: {
      // Handle key rotation events
      onKeyRotation: (event) => {
        updateKeyRotationUI(event);
      },

      // Handle encryption operations
      onEncryption: (stats) => {
        updateEncryptionStatsUI(stats);
      },

      // Handle metrics updates
      onMetricsUpdate: (metrics) => {
        updateDashboardUI(metrics);
      },
    },
  },
});
```

## UI Integration Examples

### Real-time Encryption Monitoring

```typescript
// React component example
function EncryptionMonitor() {
  const [stats, setStats] = useState([]);

  useEffect(() => {
    const sdk = new Config({
      monitoring: {
        encryptionLogs: true,
        eventHandlers: {
          onEncryption: (newStats) => {
            setStats(prev => [...prev, newStats]);
          }
        }
      }
    });

    sdk.initialize();
  }, []);

  return (
    <div>
      <h2>Encryption Operations</h2>
      {stats.map(stat => (
        <div key={stat.operationId}>
          <p>Type: {stat.type}</p>
          <p>Success: {stat.success ? '✅' : '❌'}</p>
          <p>Latency: {stat.latency}ms</p>
        </div>
      ))}
    </div>
  );
}
```

### Security Dashboard

```typescript
// React component example
function SecurityDashboard() {
  const [metrics, setMetrics] = useState(null);

  useEffect(() => {
    const sdk = new Config({
      monitoring: {
        performanceMetrics: true,
        eventHandlers: {
          onMetricsUpdate: (newMetrics) => {
            setMetrics(newMetrics);
          }
        }
      }
    });

    sdk.initialize();
  }, []);

  return (
    <div>
      <h2>Security Metrics</h2>
      {metrics && (
        <>
          <p>Total Operations: {metrics.totalOperations}</p>
          <p>Success Rate: {(metrics.successRate * 100).toFixed(2)}%</p>
          <p>Average Latency: {metrics.averageLatency.toFixed(2)}ms</p>
          <p>Last Updated: {metrics.lastUpdated.toLocaleString()}</p>
        </>
      )}
    </div>
  );
}
```

## Best Practices

1. **Key Rotation**

   - Enable automatic key rotation for enhanced security
   - Use shorter rotation intervals for sensitive data

2. **Monitoring**

   - Enable encryption logs in development for debugging
   - Use performance metrics to monitor system health
   - Implement UI feedback for security events

3. **Error Handling**
   - Always handle encryption operation errors
   - Monitor key compromise events
   - Implement proper error recovery strategies

## Security Considerations

1. **Forward Secrecy**

   - Enable `forwardSecrecy` for sensitive communications
   - Regularly rotate encryption keys

2. **Quantum Resistance**

   - Enable `quantumResistant` for future-proof security
   - Consider performance impact when enabled

3. **Media Streaming**
   - Use appropriate quality settings for your use case
   - Consider bandwidth and latency requirements

## License

MIT License - see the [LICENSE](LICENSE) file for details

## Support

For issues and feature requests, please [open an issue](https://github.com/av-waseem/cryptosphare/issues) on GitHub.

## Contributing

Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details on our code of conduct and the process for submitting pull requests.
