Skip to content

Commit 0b76b97

Browse files
committed
docs: add comprehensive security documentation
- Complete security architecture overview - Rate limiting and DDoS protection details - Session management and browser fingerprinting - Input validation and sanitization procedures - Automated behavior detection mechanisms - Security event logging and audit trails - Administrative controls and monitoring - Attack mitigation strategies - Performance and scalability considerations - Security best practices and compliance - Threat model and incident response procedures - Testing methodologies for security features This documentation provides complete coverage of all implemented security measures and serves as a reference for developers, security auditors, and system administrators.
1 parent 43d3793 commit 0b76b97

File tree

1 file changed

+337
-0
lines changed

1 file changed

+337
-0
lines changed

SECURITY.md

Lines changed: 337 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,337 @@
1+
# Security Documentation
2+
3+
This document outlines the comprehensive security measures implemented in the Digital Twin Counter application to protect against various threats and ensure data integrity.
4+
5+
## Overview
6+
7+
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.
8+
9+
## Security Architecture
10+
11+
### 1. Rate Limiting & DDoS Protection
12+
13+
#### Client-Side Rate Limiting
14+
- **100ms minimum interval** between requests per user
15+
- Browser-based session management with localStorage persistence
16+
- Client-side validation before sending requests to server
17+
- Automatic blocking of rapid-fire requests
18+
19+
#### Server-Side Rate Limiting
20+
- **1 click per 100ms** enforced at the server level
21+
- **100 requests per 10-second window** maximum
22+
- Exponential backoff for violations:
23+
- Base block duration: 60 seconds
24+
- Multiplier: 2x for each violation
25+
- Maximum block duration: 24 hours
26+
27+
#### DDoS Protection
28+
- Volume-based request monitoring
29+
- Automatic IP-based session blocking
30+
- Violation threshold system (5 violations = block)
31+
- Progressive penalty system with exponential backoff
32+
33+
### 2. Session Management
34+
35+
#### Session Creation
36+
```typescript
37+
// Unique session ID generation
38+
session_${timestamp}_${randomPart}_${browserFingerprint}
39+
```
40+
41+
#### Browser Fingerprinting
42+
- User agent string
43+
- Screen resolution
44+
- Language settings
45+
- Timezone offset
46+
- Canvas fingerprinting
47+
48+
#### Session Tracking
49+
- Last activity timestamp
50+
- Request count per window
51+
- Violation count
52+
- Block status and duration
53+
- IP address logging
54+
55+
### 3. Input Validation & Sanitization
56+
57+
#### Counter Name Validation
58+
- **Whitelist approach**: Only "global-counter" allowed
59+
- Maximum length: 50 characters
60+
- Character filtering: Blocks `<>"'&\` to prevent injection
61+
- Non-empty string requirement
62+
63+
#### Counter Value Validation
64+
- Range limits: -1,000,000 to +1,000,000
65+
- Finite number validation
66+
- Server-side boundary checking
67+
68+
#### Version Validation
69+
- Non-negative integer requirement
70+
- Optimistic concurrency control
71+
- Version mismatch detection
72+
73+
### 4. Automated Behavior Detection
74+
75+
#### Bot Detection
76+
- **50ms threshold**: Requests faster than human capability
77+
- Pattern analysis for automated clicking
78+
- User agent analysis
79+
- Behavioral anomaly detection
80+
81+
#### Violation Tracking
82+
- Progressive penalty system
83+
- Violation count reduction for good behavior
84+
- Automatic session blocking for repeated violations
85+
86+
### 5. Server-Authoritative Architecture
87+
88+
#### Zero Client Trust
89+
- All business logic executed on server
90+
- Client-side validation for UX only
91+
- Server-side re-validation of all inputs
92+
- Atomic database operations
93+
94+
#### Optimistic Concurrency Control
95+
- Version-based conflict detection
96+
- Automatic retry with exponential backoff
97+
- Race condition prevention
98+
- Data consistency guarantees
99+
100+
## Security Events & Logging
101+
102+
### Event Types
103+
104+
#### Security Events
105+
- `rate_limit`: Request frequency violations
106+
- `ddos_attempt`: Volume-based attack detection
107+
- `automation_detected`: Bot/automated behavior
108+
- `invalid_input`: Malformed or malicious input
109+
- `blocked_access_attempt`: Access while blocked
110+
- `admin_block`/`admin_unblock`: Administrative actions
111+
112+
#### Severity Levels
113+
- **Low**: Normal operational events
114+
- **Medium**: Minor security violations
115+
- **High**: Significant security threats
116+
- **Critical**: Severe attacks or system compromise
117+
118+
### Audit Trail
119+
120+
#### Request Auditing
121+
```typescript
122+
{
123+
sessionId: string,
124+
action: "increment" | "decrement" | "reset",
125+
input: { name?, expectedVersion? },
126+
result: "success" | "blocked" | "rate_limited" | "invalid_input",
127+
timestamp: number,
128+
processingTime: number,
129+
ipAddress?: string
130+
}
131+
```
132+
133+
#### Security Event Logging
134+
```typescript
135+
{
136+
sessionId: string,
137+
ipAddress?: string,
138+
eventType: string,
139+
severity: "low" | "medium" | "high" | "critical",
140+
details: {
141+
action?: string,
142+
userAgent?: string,
143+
requestInterval?: number,
144+
violationCount?: number,
145+
additionalData?: string
146+
},
147+
timestamp: number,
148+
resolved: boolean
149+
}
150+
```
151+
152+
## Administrative Controls
153+
154+
### Monitoring Queries
155+
156+
#### Real-time Statistics
157+
- Active sessions in last hour
158+
- Security events in last 24 hours
159+
- Currently blocked sessions
160+
- Events by type and severity
161+
- Top violators list
162+
163+
#### Session Management
164+
- View active sessions
165+
- Block/unblock sessions manually
166+
- Adjust violation counts
167+
- View session history
168+
169+
#### Event Management
170+
- Filter events by type/severity
171+
- Mark events as resolved
172+
- Export security logs
173+
- Generate security reports
174+
175+
### Cleanup & Maintenance
176+
177+
#### Automated Cleanup
178+
```typescript
179+
// Clean up old records (configurable retention)
180+
cleanupOldRecords({ olderThanDays: 30 })
181+
```
182+
183+
- Security events cleanup
184+
- Audit log cleanup
185+
- Inactive session cleanup
186+
- Configurable retention periods
187+
188+
## Attack Mitigation
189+
190+
### SQL Injection Prevention
191+
- Parameterized queries through Convex
192+
- Input sanitization and validation
193+
- Type-safe database operations
194+
- No raw SQL execution
195+
196+
### XSS Protection
197+
- Character filtering on inputs
198+
- HTML entity encoding
199+
- Content Security Policy headers
200+
- Safe DOM manipulation
201+
202+
### CSRF Protection
203+
- Session-based validation
204+
- Origin verification
205+
- State verification tokens
206+
- Secure session management
207+
208+
### Replay Attack Prevention
209+
- Timestamp validation
210+
- Session uniqueness
211+
- Request sequence tracking
212+
- Nonce-based protection
213+
214+
## Performance Considerations
215+
216+
### Efficient Operations
217+
- Indexed database queries
218+
- Optimized audit logging
219+
- Lazy cleanup operations
220+
- Minimal security overhead
221+
222+
### Scalability
223+
- Session-based tracking
224+
- Distributed rate limiting ready
225+
- Efficient memory usage
226+
- Background cleanup processes
227+
228+
## Configuration
229+
230+
### Security Constants
231+
```typescript
232+
const RATE_LIMIT_DELAY = 100; // ms between requests
233+
const MAX_REQUESTS = 100; // per 10-second window
234+
const VIOLATION_THRESHOLD = 5; // violations before block
235+
const BLOCK_DURATION_BASE = 60000; // base block duration (ms)
236+
const MAX_BLOCK_DURATION = 24 * 60 * 60 * 1000; // 24 hours
237+
const AUTOMATION_DETECTION_THRESHOLD = 50; // ms for bot detection
238+
```
239+
240+
### Customization
241+
- Adjustable rate limits
242+
- Configurable block durations
243+
- Flexible violation thresholds
244+
- Custom security rules
245+
246+
## Security Best Practices
247+
248+
### Development
249+
1. Never trust client-side validation
250+
2. Always validate inputs server-side
251+
3. Use atomic operations for data consistency
252+
4. Implement comprehensive logging
253+
5. Monitor security events regularly
254+
255+
### Deployment
256+
1. Use HTTPS in production
257+
2. Implement proper CORS policies
258+
3. Regular security audits
259+
4. Monitor security metrics
260+
5. Keep dependencies updated
261+
262+
### Operations
263+
1. Regular log review
264+
2. Automated alerting for critical events
265+
3. Backup security data
266+
4. Performance monitoring
267+
5. Incident response procedures
268+
269+
## Threat Model
270+
271+
### Addressed Threats
272+
- ✅ DDoS attacks
273+
- ✅ Rate limiting bypass
274+
- ✅ Automated clicking/bots
275+
- ✅ Race conditions
276+
- ✅ Data corruption
277+
- ✅ Input injection
278+
- ✅ Session hijacking
279+
- ✅ Replay attacks
280+
281+
### Future Enhancements
282+
- IP geolocation blocking
283+
- Advanced ML-based bot detection
284+
- API key authentication
285+
- Multi-factor authentication
286+
- Advanced threat intelligence
287+
288+
## Incident Response
289+
290+
### Automatic Response
291+
1. Real-time blocking of violating sessions
292+
2. Exponential backoff for repeated violations
293+
3. Comprehensive event logging
294+
4. Performance impact minimization
295+
296+
### Manual Response
297+
1. Admin dashboard for monitoring
298+
2. Manual session blocking/unblocking
299+
3. Security event investigation
300+
4. Custom response actions
301+
302+
## Compliance & Standards
303+
304+
### Security Standards
305+
- OWASP security guidelines
306+
- Zero-trust architecture principles
307+
- Defense in depth strategy
308+
- Principle of least privilege
309+
310+
### Data Protection
311+
- Minimal data collection
312+
- Secure data storage
313+
- Regular data cleanup
314+
- Privacy-conscious design
315+
316+
## Testing Security
317+
318+
### Automated Testing
319+
```bash
320+
# Test rate limiting
321+
for i in {1..20}; do curl -X POST /api/increment & done
322+
323+
# Test DDoS protection
324+
ab -n 1000 -c 100 http://localhost:5173/
325+
326+
# Test input validation
327+
curl -X POST -d '{"name":"<script>alert(1)</script>"}' /api/increment
328+
```
329+
330+
### Manual Testing
331+
1. Open multiple browser tabs
332+
2. Rapidly click increment/decrement
333+
3. Monitor security events in admin dashboard
334+
4. Verify blocking behavior
335+
5. Test session recovery
336+
337+
This comprehensive security implementation ensures the Digital Twin Counter is protected against a wide range of threats while maintaining excellent user experience and performance.

0 commit comments

Comments
 (0)