npm package: @personql/core
Description: PersonQL Core - Unified authentication, session management, and security utilities
Author: PersonQL Team
Latest version: 1.0.6

# @personql/core

PersonQL Core - Unified authentication, session management, and security utilities for the PersonQL monorepo.

## Overview

This package provides consolidated authentication, session management, and security utilities from both PersonAI/PersonQL and PersonQL codebases. It offers a comprehensive solution for managing user sessions, authentication, and security features with AI-powered insights.

## Features

### 🔐 Authentication & Security
- **Unified Crypto Utilities**: Consolidated cryptographic functions with fallbacks
- **Password Hashing**: PBKDF2 with fallback support
- **Token Management**: Secure token generation and validation
- **HMAC Generation**: Cryptographically secure HMAC signatures
- **AES-GCM Encryption**: Modern encryption with fallback support

### 👤 Session Management
- **Anonymous Sessions**: Track anonymous users with device fingerprinting
- **Authenticated Sessions**: Full session management for logged-in users
- **AI-Powered Analysis**: Behavioral analysis and risk scoring
- **Memory Management**: LRU eviction and cleanup strategies
- **Multi-Device Support**: Handle multiple sessions per user

### 🔍 Security Features
- **Device Fingerprinting**: Advanced browser and device detection
- **Risk Assessment**: Real-time risk scoring and analysis
- **Suspicious Activity Detection**: Bot detection and anomaly identification
- **Rate Limiting**: Built-in rate limiting and abuse prevention
- **Audit Logging**: Comprehensive security event logging

### 🎯 AI Analysis
- **Engagement Scoring**: User engagement analysis
- **Behavior Consistency**: Pattern recognition and anomaly detection
- **Upgrade Recommendations**: Smart suggestions for user conversion
- **Performance Monitoring**: Session performance tracking

## Installation

```bash
pnpm add @personql/core
```

## Usage

### Basic Session Management

```typescript
import { SessionManager } from '@personql/core';

const sessionManager = new SessionManager();

// Create anonymous session
const anonymousSession = await sessionManager.createAnonymousSession(
  'user123',
  'device-fingerprint-here'
);

// Create authenticated session
const { session, tokens } = await sessionManager.createAuthenticatedSession(
  'user123',
  'device-fingerprint-here',
  'password'
);

// Add events to session
await sessionManager.addEventToSession(session.id, {
  id: 'event123',
  type: 'page_view',
  timestamp: new Date(),
  sessionId: session.id,
  individualId: 'user123'
});
```

### Crypto Utilities

```typescript
import {
  generateSecureToken,
  hashPassword,
  encryptData,
  decryptData
} from '@personql/core';

// Generate secure tokens
const token = generateSecureToken(64);

// Hash passwords
const { hash, salt } = await hashPassword('user-password');

// Encrypt sensitive data
const { encrypted, iv } = await encryptData('sensitive-data', 'encryption-key');

// Decrypt data
const decrypted = await decryptData(encrypted, iv, 'encryption-key');
```

### Device Fingerprinting

```typescript
import { generateFingerprint } from '@personql/core';

const fingerprintData = {
  userAgent: navigator.userAgent,
  language: navigator.language,
  platform: navigator.platform,
  // ... other fingerprint data
};

const fingerprint = await generateFingerprint(fingerprintData);
```

## Architecture

### Directory Structure

```
packages/personql-core/
├── src/
│   ├── auth/
│   │   ├── utils/
│   │   │   └── crypto.ts          # Consolidated crypto utilities
│   │   ├── services/
│   │   │   └── session-manager.ts # Session management service
│   │   ├── types/
│   │   │   └── index.ts           # Type definitions
│   │   └── constants/
│   │       └── index.ts           # Configuration constants
│   ├── utils/
│   │   └── index.ts               # Utility functions
│   ├── client/
│   │   └── index.ts               # Client utilities
│   ├── components/
│   │   └── index.ts               # React components
│   └── index.ts                   # Main exports
├── package.json
├── tsconfig.json
└── README.md
```

### Key Components

1. **SessionManager**: Core service for managing both anonymous and authenticated sessions
2. **Crypto Utils**: Comprehensive cryptographic utilities with fallbacks
3. **Type System**: Unified type definitions for all authentication and session features
4. **Constants**: Configuration constants for security and session management

## Configuration

The package uses sensible defaults but can be configured through the constants:

```typescript
import { AUTH_CONFIG, ID_GENERATORS } from '@personql/core';

// Customize session timeouts
AUTH_CONFIG.ANONYMOUS_SESSION_TIMEOUT = 60; // 60 minutes
AUTH_CONFIG.AUTHENTICATED_SESSION_TIMEOUT = 240; // 4 hours

// Customize token lengths
ID_GENERATORS.SESSION_LENGTH = 48;
ID_GENERATORS.TOKEN_LENGTH = 128;
```

## Security Features

### Multi-layered Security
- **Cryptographic Security**: Modern encryption with fallbacks
- **Session Security**: Secure session management with expiration
- **Device Trust**: Device fingerprinting and trust scoring
- **Risk Analysis**: Real-time risk assessment and anomaly detection

### Compliance Ready
- **Audit Logging**: Comprehensive logging of security events
- **Rate Limiting**: Built-in protection against abuse
- **Data Protection**: Secure handling of sensitive information

## Performance

### Memory Management
- **LRU Eviction**: Least recently used session cleanup
- **Memory Pressure Detection**: Automatic cleanup under memory pressure
- **Optimized Algorithms**: Efficient analysis and scoring algorithms

### Scalability
- **Configurable Limits**: Session limits per user and globally
- **Cleanup Intervals**: Configurable cleanup schedules
- **Performance Monitoring**: Built-in performance tracking

## Migration Guide

### From PersonAI/PersonQL
The package consolidates and enhances the existing authentication and session management features:

1. **Crypto utilities** are now unified with enhanced security
2. **Session management** includes AI-powered analysis
3. **Type definitions** are comprehensive and backward compatible

### From PersonQL
The session manager has been enhanced with:
1. **Better memory management** with LRU eviction
2. **Enhanced security** features and risk analysis
3. **Improved performance** monitoring and optimization

## Development

### Building
```bash
pnpm build --filter @personql/core
```

### Testing
```bash
pnpm test --filter @personql/core
```

### Development Mode
```bash
pnpm dev --filter @personql/core
```

## Contributing

When contributing to this package:

1. **Maintain backward compatibility** for existing APIs
2. **Add comprehensive tests** for new features
3. **Update documentation** for any API changes
4. **Follow security best practices** for all crypto operations

## License

MIT License - see the main repository license file.

## Support

For issues and questions:
- Create an issue in the main PersonQL repository
- Check the documentation for usage examples
- Review the type definitions for API details