/** * Type definitions for session management */ /** * Session data stored for each session */ interface SessionData { /** User ID associated with the session */ userId: string; /** Custom session data */ data: Record; /** Timestamp when session was created (milliseconds) */ createdAt: number; /** Timestamp when session was last accessed (milliseconds) */ lastAccessedAt: number; /** Timestamp when session expires (milliseconds) */ expiresAt: number; /** IP address of the session (optional) */ ipAddress?: string; /** User agent string (optional) */ userAgent?: string; /** Session metadata */ metadata?: Record; } /** * Session object returned to consumers */ interface Session { /** Unique session identifier */ sessionId: string; /** User ID associated with the session */ userId: string; /** Custom session data */ data: Record; /** Timestamp when session was created (milliseconds) */ createdAt: number; /** Timestamp when session was last accessed (milliseconds) */ lastAccessedAt: number; /** Timestamp when session expires (milliseconds) */ expiresAt: number; /** Whether the session is expired */ isExpired: boolean; /** IP address of the session (optional) */ ipAddress?: string; /** User agent string (optional) */ userAgent?: string; /** Session metadata */ metadata?: Record; } /** * Expiration strategy for sessions */ declare enum ExpirationStrategy { /** Session expires after a fixed time from creation */ FIXED = "fixed", /** Session expiration extends on each access (sliding window) */ SLIDING = "sliding", /** Session uses both fixed and sliding expiration */ HYBRID = "hybrid" } /** * Storage backend type for sessions */ declare enum StorageBackend { /** In-memory storage (not persistent) */ MEMORY = "memory", /** Redis storage (persistent, distributed) */ REDIS = "redis", /** ZeroDB storage (persistent, encrypted) */ ZERODB = "zerodb" } /** * Base configuration for session manager */ interface BaseSessionConfig { /** Default TTL in seconds (default: 3600 = 1 hour) */ ttl?: number; /** Expiration strategy (default: sliding) */ expirationStrategy?: ExpirationStrategy; /** Namespace/prefix for session keys */ namespace?: string; /** Enable session data encryption */ encryptData?: boolean; /** Encryption key (required if encryptData is true) */ encryptionKey?: string; /** Maximum concurrent sessions per user (0 = unlimited) */ maxSessionsPerUser?: number; /** Enable session locking for concurrent access */ enableLocking?: boolean; /** Lock timeout in milliseconds (default: 5000) */ lockTimeout?: number; /** Cleanup interval in milliseconds (default: 300000 = 5 minutes) */ cleanupInterval?: number; /** Enable automatic cleanup of expired sessions */ autoCleanup?: boolean; } /** * Configuration for in-memory session store */ interface InMemorySessionConfig extends BaseSessionConfig { type: 'memory'; /** Maximum number of sessions to store (LRU eviction) */ maxSessions?: number; } /** * Configuration for Redis session store */ interface RedisSessionConfig extends BaseSessionConfig { type: 'redis'; /** Redis connection URL */ url?: string; /** Redis host */ host?: string; /** Redis port */ port?: number; /** Redis password */ password?: string; /** Redis database number */ db?: number; /** Key prefix for Redis keys */ keyPrefix?: string; } /** * Configuration for ZeroDB session store */ interface ZeroDBSessionConfig extends BaseSessionConfig { type: 'zerodb'; /** ZeroDB project ID */ projectId: string; /** ZeroDB API key */ apiKey: string; /** Table name for sessions */ tableName?: string; } /** * Union type for all session configurations */ type SessionConfig = InMemorySessionConfig | RedisSessionConfig | ZeroDBSessionConfig; /** * Options for creating a new session */ interface CreateSessionOptions { /** Custom TTL in seconds (overrides default) */ ttl?: number; /** IP address of the client */ ipAddress?: string; /** User agent string */ userAgent?: string; /** Custom metadata */ metadata?: Record; } /** * Options for updating a session */ interface UpdateSessionOptions { /** Whether to update the lastAccessedAt timestamp */ updateLastAccessed?: boolean; /** Merge data instead of replacing */ merge?: boolean; } /** * Options for refreshing a session */ interface RefreshSessionOptions { /** Custom TTL in seconds (overrides default) */ ttl?: number; } /** * Options for listing sessions */ interface ListSessionsOptions { /** Include expired sessions */ includeExpired?: boolean; /** Limit number of results */ limit?: number; /** Offset for pagination */ offset?: number; } /** * Session statistics */ interface SessionStats { /** Total number of sessions */ totalSessions: number; /** Number of active (non-expired) sessions */ activeSessions: number; /** Number of expired sessions */ expiredSessions: number; /** Sessions grouped by user ID */ sessionsByUser?: Record; /** Average session duration in milliseconds */ averageDuration?: number; } /** * Session store interface that all storage backends must implement */ interface SessionStore { /** * Get a session by ID */ get(sessionId: string): Promise; /** * Set/update a session */ set(sessionId: string, data: SessionData): Promise; /** * Delete a session */ delete(sessionId: string): Promise; /** * Check if a session exists */ exists(sessionId: string): Promise; /** * Get all sessions for a user */ getByUserId(userId: string): Promise>; /** * Delete all sessions for a user */ deleteByUserId(userId: string): Promise; /** * Get all session IDs */ getAllSessionIds(): Promise; /** * Remove expired sessions */ cleanup(): Promise; /** * Get session statistics */ getStats(): Promise; /** * Acquire a lock for a session */ acquireLock?(sessionId: string, timeout: number): Promise; /** * Release a lock for a session */ releaseLock?(sessionId: string): Promise; /** * Close the store connection */ close?(): Promise; } /** * Session event types */ declare enum SessionEvent { CREATED = "session:created", UPDATED = "session:updated", REFRESHED = "session:refreshed", DELETED = "session:deleted", EXPIRED = "session:expired", LOCKED = "session:locked", UNLOCKED = "session:unlocked" } /** * Session event payload */ interface SessionEventPayload { /** Session ID */ sessionId: string; /** User ID */ userId: string; /** Event type */ event: SessionEvent; /** Timestamp */ timestamp: number; /** Additional data */ data?: Record; } /** * Session Manager - Comprehensive session management for AI applications * Supports multiple storage backends, expiration strategies, and security features */ /** * Event listener for session events */ type SessionEventListener = (payload: SessionEventPayload) => void; /** * SessionManager - Main class for managing user sessions */ declare class SessionManager { private store; private defaultTTL; private expirationStrategy; private encryptData; private encryptionKey?; private maxSessionsPerUser; private enableLocking; private lockTimeout; private cleanupInterval?; private eventListeners; constructor(config: SessionConfig); /** * Create the appropriate store based on configuration */ private createStore; /** * Create a new session */ create(userId: string, data?: Record, options?: CreateSessionOptions): Promise; /** * Get a session by ID */ get(sessionId: string): Promise; /** * Update a session's data */ update(sessionId: string, data: Record, options?: UpdateSessionOptions): Promise; /** * Delete a session */ delete(sessionId: string): Promise; /** * Refresh/extend a session's expiration */ refresh(sessionId: string, options?: RefreshSessionOptions): Promise; /** * Get all sessions for a user */ getUserSessions(userId: string): Promise; /** * Delete all sessions for a user */ deleteUserSessions(userId: string): Promise; /** * List sessions with optional filters */ list(options?: ListSessionsOptions): Promise; /** * Validate if a session is active */ validate(sessionId: string): Promise; /** * Clean up expired sessions */ cleanup(): Promise; /** * Get session statistics */ getStats(): Promise; /** * Acquire a lock for a session */ private acquireLock; /** * Release a lock for a session */ private releaseLock; /** * Convert SessionData to Session object */ private toSession; /** * Encrypt session data */ private encrypt; /** * Decrypt session data */ private decrypt; /** * Register an event listener */ on(event: SessionEvent, listener: SessionEventListener): void; /** * Remove an event listener */ off(event: SessionEvent, listener: SessionEventListener): void; /** * Emit a session event */ private emit; /** * Close the session manager and cleanup resources */ close(): Promise; } /** * In-memory session store implementation * Provides fast session storage using Maps with LRU eviction */ /** * In-memory session store with LRU eviction */ declare class InMemorySessionStore implements SessionStore { private sessions; private userSessions; private locks; private accessOrder; private maxSessions; constructor(maxSessions?: number); /** * Get a session by ID */ get(sessionId: string): Promise; /** * Set/update a session */ set(sessionId: string, data: SessionData): Promise; /** * Delete a session */ delete(sessionId: string): Promise; /** * Check if a session exists */ exists(sessionId: string): Promise; /** * Get all sessions for a user */ getByUserId(userId: string): Promise>; /** * Delete all sessions for a user */ deleteByUserId(userId: string): Promise; /** * Get all session IDs */ getAllSessionIds(): Promise; /** * Remove expired sessions */ cleanup(): Promise; /** * Get session statistics */ getStats(): Promise; /** * Acquire a lock for a session */ acquireLock(sessionId: string, timeout: number): Promise; /** * Release a lock for a session */ releaseLock(sessionId: string): Promise; /** * Update access order for LRU tracking */ private updateAccessOrder; /** * Evict the oldest (least recently used) session */ private evictOldest; /** * Get the number of sessions in the store */ get size(): number; /** * Clear all sessions (for testing) */ clear(): Promise; } /** * ZeroDB session store implementation * Provides persistent, encrypted session storage using ZeroDB */ /** * ZeroDB session store with encryption support */ declare class ZeroDBSessionStore implements SessionStore { private projectId; private apiKey; private tableName; private baseUrl; constructor(config: Omit); /** * Make an authenticated request to ZeroDB */ private request; /** * Initialize the sessions table if it doesn't exist */ initialize(): Promise; /** * Get a session by ID */ get(sessionId: string): Promise; /** * Set/update a session */ set(sessionId: string, data: SessionData): Promise; /** * Delete a session */ delete(sessionId: string): Promise; /** * Check if a session exists */ exists(sessionId: string): Promise; /** * Get all sessions for a user */ getByUserId(userId: string): Promise>; /** * Delete all sessions for a user */ deleteByUserId(userId: string): Promise; /** * Get all session IDs */ getAllSessionIds(): Promise; /** * Remove expired sessions */ cleanup(): Promise; /** * Get session statistics */ getStats(): Promise; /** * Acquire a lock for a session * Note: ZeroDB doesn't natively support locks, so we use a separate locks table */ acquireLock(sessionId: string, timeout: number): Promise; /** * Release a lock for a session */ releaseLock(sessionId: string): Promise; /** * Close the store connection */ close(): Promise; } export { type BaseSessionConfig as B, type CreateSessionOptions as C, ExpirationStrategy as E, InMemorySessionStore as I, type ListSessionsOptions as L, type RedisSessionConfig as R, SessionManager as S, type UpdateSessionOptions as U, ZeroDBSessionStore as Z, type Session as a, type SessionData as b, type SessionConfig as c, type InMemorySessionConfig as d, type ZeroDBSessionConfig as e, SessionEvent as f, StorageBackend as g, type SessionStore as h, type SessionStats as i, type RefreshSessionOptions as j, type SessionEventPayload as k };