# b0esche.cloud Authentication System

This document describes the complete passkey-first authentication and authorization system for b0esche.cloud.

## Overview

b0esche.cloud implements a modern, secure, username-only, passkey-first authentication system with comprehensive admin functionality and recovery options.

## Authentication Flow

### Primary Authentication: Passkeys (WebAuthn)

- **Username + Passkey Registration**: Users create an account with just a username and register a passkey
- **Passkey-First Login**: Primary authentication method using WebAuthn/FIDO2 standards
- **Device Support**: Works with Touch ID, Windows Hello, YubiKey, and other FIDO2 authenticators
- **Multiple Passkeys**: Users can register multiple devices for redundancy

### Fallback Options

- **Optional Password**: Users can add a password as a fallback authentication method
- **Recovery Codes**: 10 single-use recovery codes generated per user
- **Admin Recovery**: Admins can assist with account recovery if needed

## User Roles and Permissions

### Role Hierarchy

1. **superadmin** (Level 3): Full system access
   - User management and role assignments
   - Admin invitation system
   - System configuration access
   - All organization management

2. **admin** (Level 2): Administrative access
   - Organization management
   - User role promotion (within their orgs)
   - Activity monitoring
   - File management across organizations

3. **user** (Level 1): Standard user access
   - Personal file management
   - Organization membership
   - Basic account settings

## Bootstrap Process

### Creating the First Administrator

The system includes a bootstrap utility to create the first superadmin user securely:

```bash
# Interactive mode (recommended for production)
./bin/bootstrap

# Environment variable mode (recommended for automation)
export BOOTSTRAP_ADMIN_USERNAME=admin
export BOOTSTRAP_ADMIN_PASSWORD=secure_password_123
./bin/bootstrap
```

#### Bootstrap Process

1. **Check Existing Admin**: Verifies no superadmin user already exists
2. **Secure Input**: Prompts for username and password (or reads from environment)
3. **Password Security**: Enforces minimum 8-character passwords
4. **Role Assignment**: Automatically assigns superadmin role
5. **Secure Storage**: Passwords are bcrypt-hashed before storage

#### Security Guidelines

- **Immediate Action**: Log in immediately after bootstrap to register a passkey
- **Passkey Priority**: Set up passkeys and consider removing the password
- **Recovery Setup**: Generate recovery codes during first login
- **Credential Rotation**: Never leave default credentials in production

## API Endpoints

### Authentication Endpoints

```
POST /auth/passkey/register/start
POST /auth/passkey/register/verify
POST /auth/passkey/login/start  
POST /auth/passkey/login/verify
```

### Device Management

```
GET  /auth/passkey/devices          # List user's passkeys
POST /auth/passkey/devices/add      # Add new passkey
DELETE /auth/passkey/devices/{id}   # Remove passkey
```

### Recovery System

```
POST /auth/recovery/codes/generate  # Generate recovery codes
POST /auth/recovery/codes/use       # Use recovery code
DELETE /auth/recovery/codes/revoke   # Revoke all codes
```

### Admin Operations

```
GET    /auth/admin/invitations       # List invitations
POST   /auth/admin/invitations       # Create invitation
POST   /auth/admin/invitations/accept # Accept invitation
DELETE /auth/admin/invitations/{id}  # Revoke invitation
```

### Password Fallback

```
POST /auth/password/add     # Add password to account
DELETE /auth/password/remove # Remove password from account
```

## Environment Configuration

```bash
# Server Configuration
SERVER_ADDR=:8080
DATABASE_URL=postgresql://user:pass@localhost/db

# WebAuthn Configuration
WEBAUTHN_RP_ID=www.b0esche.cloud
WEBAUTHN_RP_NAME=b0esche.cloud
WEBAUTHN_RP_ORIGIN=https://www.b0esche.cloud

# Security Configuration
JWT_SECRET=your_jwt_secret_key
PASSKEY_TIMEOUT=300000
RECOVERY_CODE_EXPIRY=86400
MAX_RECOVERY_CODES=10
```

## Security Features

### WebAuthn Security

- **FIDO2/WebAuthn Compliant**: Full compliance with WebAuthn Level 2
- **Origin Binding**: Credentials bound to specific domain
- **Challenge-Response**: Cryptographic challenge verification
- **Device Attestation**: Optional device verification
- **Public Key Crypto**: Asymmetric cryptography with private keys never leaving devices

### Account Security

- **Rate Limiting**: Built-in protection against brute force attacks
- **Session Management**: Secure HTTP-only sessions with configurable expiration
- **Audit Logging**: Comprehensive logging of all authentication and admin actions
- **Role-Based Access Control**: Hierarchical permission system

### Data Protection

- **Password Hashing**: bcrypt with automatic salt generation
- **Recovery Code Hashing**: Secure one-way hashing of recovery codes
- **No Plaintext Storage**: No sensitive data stored in plaintext
- **Input Validation**: Comprehensive input sanitization and validation

## Database Schema

The authentication system uses the following key tables:

- **users**: User accounts with role-based access control
- **roles**: Hierarchical role definitions
- **passkeys**: WebAuthn credential storage
- **recovery_codes**: One-time recovery codes
- **admin_invitations**: Secure admin invitation system
- **sessions**: Secure session management

## Development and Testing

### Running Locally

1. **Setup Database**: Ensure PostgreSQL is running with migrations applied
2. **Bootstrap Admin**: Run the bootstrap command to create first admin
3. **Start Server**: Run the API server with appropriate environment
4. **Test Authentication**: Use the Flutter app or API tests

### Testing WebAuthn

WebAuthn requires HTTPS in production browsers. For local testing:

```bash
# Use mkcert for local HTTPS
mkcert -install
mkcert localhost 127.0.0.1 ::1

# Set environment for local development
export WEBAUTHN_RP_ID=localhost
export WEBAUTHN_RP_ORIGIN=https://localhost:8080
```

## User Experience

### Signup Flow

1. **Username Selection**: User chooses a unique username
2. **Real-time Validation**: Immediate feedback on username availability
3. **Passkey Creation**: Browser prompts for passkey registration
4. **Account Creation**: Automatic account creation with passkey

### Login Flow

1. **Passkey Detection**: System shows available passkeys
2. **Biometric Prompt**: Browser authenticates with passkey
3. **Session Creation**: Secure session established
4. **Redirect**: User directed to dashboard

### Security Settings

Users can manage their security through the Settings > Security page:

- **Device Management**: View, add, remove, and label passkeys
- **Recovery Codes**: Generate new recovery codes
- **Password Options**: Add or remove password fallback
- **Account Recovery**: Secure account recovery options

## Troubleshooting

### Common Issues

1. **WebAuthn Not Supported**: Use a modern browser (Chrome, Firefox, Safari, Edge)
2. **HTTPS Required**: WebAuthn requires HTTPS in production environments
3. **Device Compatibility**: Ensure devices support FIDO2/WebAuthn
4. **Database Connection**: Verify database connection and migrations

### Bootstrap Issues

1. **Permission Denied**: Ensure proper file permissions on bootstrap binary
2. **Database Connection**: Check DATABASE_URL configuration
3. **Port Conflicts**: Ensure database port is accessible

### Recovery Process

If a user loses access to all passkeys:

1. **Use Recovery Code**: Enter one of the 10 recovery codes
2. **Contact Admin**: Admins can assist with account recovery
3. **Re-register Passkey**: Set up new passkeys after recovery
4. **Generate New Recovery Codes**: Replace used recovery codes

## Monitoring and Maintenance

### Key Metrics

Monitor these metrics for system health:

- Authentication success/failure rates
- Passkey registration and usage patterns
- Recovery code usage frequency
- Admin action audit logs
- Session expiration and renewal rates

### Maintenance Tasks

Regular maintenance includes:

- Clean up expired sessions and recovery codes
- Review audit logs for suspicious activity
- Update role assignments as needed
- Monitor WebAuthn compatibility with browser updates

## Support and Documentation

For additional support:

- **Technical Issues**: Check application logs and database status
- **Security Concerns**: Review audit logs and user activity
- **Feature Requests**: Follow the contribution guidelines
- **Documentation Updates**: Keep this document current with system changes

---

**Last Updated**: January 2026  
**Version**: 1.0  
**Compatibility**: WebAuthn Level 2, FIDO2