SECURITY SYSTEM - nself-org/cli GitHub Wiki
Sprint 17: Advanced Security (25pts)
Complete security infrastructure for self-hosted nself backends.
- Hardware security keys (YubiKey, Titan, etc.)
- Platform authenticators (Touch ID, Face ID, Windows Hello)
- FIDO2 compliant implementation
- Anti-replay protection with signature counters
- Multiple keys per user
- Track all user devices
- Device fingerprinting
- Trust/untrust devices
- Risk scoring per device
- Session correlation
- Comprehensive audit trail
- Real-time event capture
- Suspicious activity detection
- Risk scoring
- Event categorization (authentication, authorization, device, suspicious)
- Automated incident creation
- Incident tracking and management
- Priority and severity levels
- Assignment and resolution workflow
- Forensics and evidence collection
- Weak password detection
- Missing MFA warnings
- Expired session cleanup
- Suspicious activity patterns
- Brute force detection
- Credential stuffing detection
- Password history tracking
- Reuse prevention
- Age tracking
- Strength validation
- Common password detection
- auth.webauthn_credentials - WebAuthn/FIDO2 keys
- auth.user_devices - Device tracking
- auth.security_events - Security audit log
- auth.security_incidents - Incident management
- auth.security_metrics - Security analytics
- auth.password_history - Password change tracking
-
auth.log_security_event()- Log security events -
auth.calculate_device_risk_score()- Device risk assessment -
auth.detect_suspicious_activity()- Pattern detection -
auth.get_weak_passwords()- Vulnerability scanning
# Run full security scan
nself security scan
# Scan for weak passwords
nself security scan passwords
# Scan for missing MFA
nself security scan mfa
# Scan for expired sessions
nself security scan sessions
# Scan for suspicious activity
nself security scan suspicious# List devices for a user
nself security devices list <user_id>
# Trust a device
nself security devices trust <device_id>
# Untrust a device
nself security devices untrust <device_id>
# Remove a device
nself security devices remove <device_id># List open incidents
nself security incidents list
# List resolved incidents
nself security incidents list resolved
# Show incident details
nself security incidents show <incident_id>
# Create manual incident
nself security incidents create "Incident Title" high "Description"
# Resolve incident
nself security incidents resolve <incident_id> "Resolution notes"# View recent security events
nself security events
# View events for specific user
nself security events <user_id> [limit]# List WebAuthn keys for user
nself security webauthn list <user_id>
# Remove WebAuthn key
nself security webauthn remove <key_id>
# Note: Adding keys must be done through web UI# Delegate to MFA CLI
nself security mfa enable --method=totp --user=<user_id>- Password strength checking
- Session anomaly detection
- Device fingerprinting
- User agent parsing
- Brute force detection
- Credential stuffing detection
- Account takeover detection
- Risk scoring
- Vulnerability scanning (SQL injection, XSS)
- Challenge generation
- Registration options
- Authentication options
- Credential storage
- Signature verification
- Counter management
- Attestation processing
- Transport detection
- Authenticator type identification
- Security level assessment
- Incident detection automation
- Automated response playbooks
- Account locking
- IP blocking
- Session revocation
- Password reset enforcement
- MFA requirement
- Escalation workflows
- Forensics collection
- Incident analysis
- Resolution tracking
- Metrics (MTTD, MTTR)
-
Run the migration:
nself migrate run 014_create_security_system.sql
-
Scan for vulnerabilities:
nself security scan
-
Enable MFA for users:
nself security mfa enable --method=totp --user=<user_id>
-
Monitor security events:
nself security events
-
Detect incident:
nself security scan suspicious
-
Review incident:
nself security incidents list nself security incidents show <incident_id>
-
Take action:
# Lock compromised account # (would be done through API) # Block malicious IP # (would be done through API) # Revoke sessions # (would be done through API)
-
Resolve incident:
nself security incidents resolve <incident_id> "Incident resolved, user notified"
# List devices for user
nself security devices list <user_id>
# Trust known devices
nself security devices trust <device_id>
# Remove suspicious devices
nself security devices remove <device_id>-
Enable MFA for all admin accounts
- Use TOTP (Google Authenticator, Authy)
- Add hardware keys (YubiKey) for critical accounts
- Generate backup codes
-
Monitor security events regularly
- Check for suspicious activity daily
- Review open incidents weekly
- Investigate high-risk events immediately
-
Implement password policies
- Enforce strong passwords
- Require password changes every 90 days
- Prevent password reuse (last 5 passwords)
-
Trust user devices
- Review devices monthly
- Remove inactive devices
- Trust only known devices
-
Enable automated responses
- Configure incident response playbooks
- Set up alerting (email, Slack, PagerDuty)
- Automate account locking for brute force
-
Hardware Security Keys
- Require hardware keys for admin access
- Support multiple keys per user (backup)
- Use FIPS-certified keys for compliance
-
Security Monitoring
- Set up Prometheus alerts for security events
- Use Grafana dashboards for visualization
- Export security events to SIEM
-
Incident Response
- Define incident severity levels
- Create escalation procedures
- Conduct post-incident reviews
- Document lessons learned
-
Compliance
- Regular security audits
- Penetration testing
- Vulnerability scanning
- Access reviews
Security features are exposed through Hasura GraphQL:
# Query security events
query GetSecurityEvents($userId: uuid!) {
auth_security_events(
where: { user_id: { _eq: $userId } }
order_by: { created_at: desc }
limit: 50
) {
id
event_type
severity
description
is_suspicious
risk_score
created_at
}
}
# Query user devices
query GetUserDevices($userId: uuid!) {
auth_user_devices(
where: { user_id: { _eq: $userId } }
order_by: { last_seen_at: desc }
) {
id
device_name
device_type
is_trusted
risk_score
last_seen_at
}
}
# Query WebAuthn credentials
query GetWebAuthnKeys($userId: uuid!) {
auth_webauthn_credentials(
where: { user_id: { _eq: $userId } }
order_by: { created_at: desc }
) {
id
name
credential_type
authenticator_attachment
created_at
last_used_at
}
}User Action โ Application โ Security Event Logger
โ
Security Event Table
โ
Suspicious Activity Detector
โ
Incident Creator
โ
Automated Response Playbook
โ
Resolution & Metrics
User Login โ Device Fingerprint โ Device Lookup
โ
New Device?
โ โ
Yes No
โ โ
Create Device Update Last Seen
โ โ
Calculate Risk Score
โ
Log Security Event
โ
Check If Suspicious
โ
Create Incident If Needed
Registration:
User โ Generate Challenge โ Frontend Creates Credential
โ
Store Public Key & Counter
โ
Mark As Enrolled
Authentication:
User โ Generate Challenge โ Frontend Signs Challenge
โ
Verify Signature
โ
Check Counter (anti-replay)
โ
Update Counter
โ
Log Security Event
- All foreign keys are indexed
- Time-series queries optimized (created_at DESC)
- Risk score queries indexed
- Suspicious activity filtered with partial index
- Security events can be partitioned by month
- Metrics table can be partitioned by day
- Improves query performance for large datasets
- Consider archiving old security events (>1 year)
- Keep incident records indefinitely (compliance)
- Rotate security metrics based on policy
# Create test user
nself auth signup [email protected] --password=test123
# Enable MFA
nself security mfa enable --method=totp --user=<user_id>
# Simulate brute force (would trigger incident)
# Multiple failed logins
# View security events
nself security events <user_id>
# Check incidents
nself security incidents listSecurity features integrate with:
- Authentication system (auth.sh, mfa.sh)
- Rate limiting (rate-limit.sh)
- Session management
- Hasura GraphQL
- PostgreSQL RLS
- Check PostgreSQL connection
- Verify auth schema exists
- Check RLS policies
- Verify user permissions
- Ensure HTTPS (required for WebAuthn)
- Check browser compatibility
- Verify RP ID matches domain
- Check credential storage
- Check suspicious activity detection
- Verify incident table exists
- Check detection thresholds
- Review security event logs
- IP geolocation integration
- Behavioral biometrics
- Threat intelligence feeds
- SIEM integration
- Automated penetration testing
- Security compliance reports (SOC 2, HIPAA)
- Advanced ML-based anomaly detection
- Real-time security dashboards
For issues and questions:
- Documentation: https://docs.nself.org/security
- GitHub Issues: https://github.com/nself-org/cli/issues
- Discord: https://discord.gg/nself
Part of nself - MIT License