This document outlines the comprehensive security measures implemented in the Digital Twin Counter application to protect against various threats and ensure data integrity.
The Digital Twin Counter implements a multi-layered security approach with both client-side and server-side protections, comprehensive logging, and real-time monitoring capabilities.
- 100ms minimum interval between requests per user
- Browser-based session management with localStorage persistence
- Client-side validation before sending requests to server
- Automatic blocking of rapid-fire requests
- 1 click per 100ms enforced at the server level
- 100 requests per 10-second window maximum
- Exponential backoff for violations:
- Base block duration: 60 seconds
- Multiplier: 2x for each violation
- Maximum block duration: 24 hours
- Volume-based request monitoring
- Automatic IP-based session blocking
- Violation threshold system (5 violations = block)
- Progressive penalty system with exponential backoff
// Unique session ID generation
session_${timestamp}_${randomPart}_${browserFingerprint}
- User agent string
- Screen resolution
- Language settings
- Timezone offset
- Canvas fingerprinting
- Last activity timestamp
- Request count per window
- Violation count
- Block status and duration
- IP address logging
- Whitelist approach: Only "global-counter" allowed
- Maximum length: 50 characters
- Character filtering: Blocks
<>"'&\
to prevent injection - Non-empty string requirement
- Range limits: -1,000,000 to +1,000,000
- Finite number validation
- Server-side boundary checking
- Non-negative integer requirement
- Optimistic concurrency control
- Version mismatch detection
- 50ms threshold: Requests faster than human capability
- Pattern analysis for automated clicking
- User agent analysis
- Behavioral anomaly detection
- Progressive penalty system
- Violation count reduction for good behavior
- Automatic session blocking for repeated violations
- All business logic executed on server
- Client-side validation for UX only
- Server-side re-validation of all inputs
- Atomic database operations
- Version-based conflict detection
- Automatic retry with exponential backoff
- Race condition prevention
- Data consistency guarantees
rate_limit
: Request frequency violationsddos_attempt
: Volume-based attack detectionautomation_detected
: Bot/automated behaviorinvalid_input
: Malformed or malicious inputblocked_access_attempt
: Access while blockedadmin_block
/admin_unblock
: Administrative actions
- Low: Normal operational events
- Medium: Minor security violations
- High: Significant security threats
- Critical: Severe attacks or system compromise
{
sessionId: string,
action: "increment" | "decrement" | "reset",
input: { name?, expectedVersion? },
result: "success" | "blocked" | "rate_limited" | "invalid_input",
timestamp: number,
processingTime: number,
ipAddress?: string
}
{
sessionId: string,
ipAddress?: string,
eventType: string,
severity: "low" | "medium" | "high" | "critical",
details: {
action?: string,
userAgent?: string,
requestInterval?: number,
violationCount?: number,
additionalData?: string
},
timestamp: number,
resolved: boolean
}
- Active sessions in last hour
- Security events in last 24 hours
- Currently blocked sessions
- Events by type and severity
- Top violators list
- View active sessions
- Block/unblock sessions manually
- Adjust violation counts
- View session history
- Filter events by type/severity
- Mark events as resolved
- Export security logs
- Generate security reports
// Clean up old records (configurable retention)
cleanupOldRecords({ olderThanDays: 30 })
- Security events cleanup
- Audit log cleanup
- Inactive session cleanup
- Configurable retention periods
- Parameterized queries through Convex
- Input sanitization and validation
- Type-safe database operations
- No raw SQL execution
- Character filtering on inputs
- HTML entity encoding
- Content Security Policy headers
- Safe DOM manipulation
- Session-based validation
- Origin verification
- State verification tokens
- Secure session management
- Timestamp validation
- Session uniqueness
- Request sequence tracking
- Nonce-based protection
- Indexed database queries
- Optimized audit logging
- Lazy cleanup operations
- Minimal security overhead
- Session-based tracking
- Distributed rate limiting ready
- Efficient memory usage
- Background cleanup processes
const RATE_LIMIT_DELAY = 100; // ms between requests
const MAX_REQUESTS = 100; // per 10-second window
const VIOLATION_THRESHOLD = 5; // violations before block
const BLOCK_DURATION_BASE = 60000; // base block duration (ms)
const MAX_BLOCK_DURATION = 24 * 60 * 60 * 1000; // 24 hours
const AUTOMATION_DETECTION_THRESHOLD = 50; // ms for bot detection
- Adjustable rate limits
- Configurable block durations
- Flexible violation thresholds
- Custom security rules
- Never trust client-side validation
- Always validate inputs server-side
- Use atomic operations for data consistency
- Implement comprehensive logging
- Monitor security events regularly
- Use HTTPS in production
- Implement proper CORS policies
- Regular security audits
- Monitor security metrics
- Keep dependencies updated
- Regular log review
- Automated alerting for critical events
- Backup security data
- Performance monitoring
- Incident response procedures
- ✅ DDoS attacks
- ✅ Rate limiting bypass
- ✅ Automated clicking/bots
- ✅ Race conditions
- ✅ Data corruption
- ✅ Input injection
- ✅ Session hijacking
- ✅ Replay attacks
- IP geolocation blocking
- Advanced ML-based bot detection
- API key authentication
- Multi-factor authentication
- Advanced threat intelligence
- Real-time blocking of violating sessions
- Exponential backoff for repeated violations
- Comprehensive event logging
- Performance impact minimization
- Admin dashboard for monitoring
- Manual session blocking/unblocking
- Security event investigation
- Custom response actions
- OWASP security guidelines
- Zero-trust architecture principles
- Defense in depth strategy
- Principle of least privilege
- Minimal data collection
- Secure data storage
- Regular data cleanup
- Privacy-conscious design
# Test rate limiting
for i in {1..20}; do curl -X POST /api/increment & done
# Test DDoS protection
ab -n 1000 -c 100 http://localhost:5173/
# Test input validation
curl -X POST -d '{"name":"<script>alert(1)</script>"}' /api/increment
- Open multiple browser tabs
- Rapidly click increment/decrement
- Monitor security events in admin dashboard
- Verify blocking behavior
- Test session recovery
This comprehensive security implementation ensures the Digital Twin Counter is protected against a wide range of threats while maintaining excellent user experience and performance.