secure-session-tracker
v0.0.2
Published
A custom Node.js library for monitoring and reacting to user authentication sessions and events in real-time.
Maintainers
Readme
🔐 Secure Session Tracker
A powerful, event-driven Node.js library for real-time authentication session monitoring and management.
📋 Table of Contents
✨ Features
🎯 Core Capabilities
- Event-Driven Architecture: React to auth events in real-time
- TypeScript First: Full type safety and IntelliSense support
- Zero Dependencies: Lightweight and fast
- Provider Agnostic: Works with any auth system
- Extensible: Add custom event types and handlers
🔧 Advanced Features
- Session Context Helpers: Built-in utilities for session management
- Error Resilience: Graceful error handling in event handlers
- Metadata Support: Attach custom data to events
- Async/Await Ready: Full promise support
- Logging Integration: Built-in activity logging
🚀 Installation
npm install secure-session-trackeryarn add secure-session-trackerpnpm add secure-session-tracker🎯 Quick Start
Basic Setup
import { AuthEventManager } from 'secure-session-tracker';
// Create an instance
const authTracker = new AuthEventManager();
// Subscribe to login events
authTracker.subscribe('login', (event, context) => {
console.log(`User ${event.userId} logged in from ${event.ip}`);
context.logActivity(`Login detected for ${event.userId}`);
});
// Trigger an event
await authTracker.trigger('login', {
userId: 'user123',
sessionId: 'sess456',
ip: '192.168.1.1',
userAgent: 'Chrome/91.0',
metadata: { source: 'web_app' }
});Advanced Example with Multiple Events
import { AuthEventManager, AuthActionType } from 'secure-session-tracker';
const tracker = new AuthEventManager();
// Handle multiple event types
const eventHandler = (event: any, context: any) => {
switch (event.type) {
case 'login':
context.logActivity(`User login: ${event.userId}`);
break;
case 'password_changed':
context.revokeSession(event.sessionId);
break;
case 'account_locked':
// Send notification
break;
}
};
// Subscribe to all events
(['login', 'logout', 'password_changed', 'role_changed', 'session_expired', 'account_locked'] as AuthActionType[]).forEach(type => {
tracker.subscribe(type, eventHandler);
});📚 API Reference
AuthEventManager
subscribe(type: AuthActionType, callback: AuthEventCallback)
Registers an event handler for a specific authentication action.
Parameters:
type: The event type to listen forcallback: Function to execute when event occurs
trigger(type: AuthActionType, payload: EventPayload)
Triggers an authentication event with associated data.
Parameters:
type: The type of authentication actionpayload: Event data (userId, sessionId, etc.)
Returns: Promise
Event Types
type AuthActionType =
| "login" // User successfully logs in
| "logout" // User logs out
| "password_changed" // Password modification
| "role_changed" // User role/permission update
| "session_expired" // Session timeout
| "account_locked"; // Account security lockEvent Structure
interface AuthActivity {
type: AuthActionType;
userId: string;
sessionId?: string;
ip?: string;
userAgent?: string;
timestamp: Date;
metadata?: Record<string, any>;
}Context Helpers
interface EventContext {
revokeSession(sessionId: string): void;
logActivity(message: string): void;
}🔄 Event Flow
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Auth Action │ -> │ Event Triggered │ -> │ Handlers Run │
│ (Login, etc.) │ │ │ │ │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ Context │
│ Helpers │
│ Execute │
└─────────────────┘Flow Explanation:
- Authentication action occurs in your app
- Call
authTracker.trigger()with event data - Registered handlers execute with event and context
- Context helpers perform additional actions (logging, session management)
💡 Use Cases
🔒 Security Monitoring
tracker.subscribe('login', (event, context) => {
if (isSuspiciousIP(event.ip)) {
context.logActivity(`Suspicious login from ${event.ip}`);
// Trigger security alert
}
});📊 Analytics & Tracking
tracker.subscribe('login', (event) => {
analytics.track('user_login', {
userId: event.userId,
timestamp: event.timestamp,
source: event.metadata?.source
});
});🔄 Session Management
tracker.subscribe('password_changed', (event, context) => {
// Invalidate all user sessions
context.revokeSession(event.sessionId);
// Force re-authentication
});📧 Notifications
tracker.subscribe('account_locked', (event) => {
emailService.send({
to: getUserEmail(event.userId),
subject: 'Account Security Alert',
body: 'Your account has been locked due to suspicious activity.'
});
});🤝 Contributing
We love contributions! Here's how you can help:
Development Setup
git clone https://github.com/codewithevilxd/secure-session-tracker.git
cd secure-session-tracker
npm install
npm run devRunning Tests
npm testBuilding
npm run buildGuidelines
- Follow TypeScript best practices
- Add tests for new features
- Update documentation
- Use conventional commits
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
Built with ❤️ by Nishant Gaurav
Made with passion for secure, event-driven authentication workflows.
