# Complete OpenSpec Change Example

This example shows a complete OpenSpec change from start to finish.

## Scenario

Adding two-factor authentication (2FA) to an existing authentication system.

## Directory Structure

```
openspec/
├── specs/
│   └── auth/
│       └── spec.md                    # Existing auth spec
└── changes/
    └── add-2fa/
        ├── proposal.md                # Why we need 2FA
        ├── tasks.md                   # Implementation steps
        └── specs/
            └── auth/
                └── spec.md            # Changes to auth spec
```

## File: proposal.md

```markdown
---
id: add-2fa
relatedTasks: []
relatedRules: [security-guidelines.md]
status: draft
---

# Add Two-Factor Authentication

## Motivation

Users have requested stronger account security. Password-only authentication
is insufficient for protecting sensitive user data. Industry best practices
recommend 2FA for all accounts.

## Changes

1. Add OTP (One-Time Password) generation and verification
2. Modify login flow to require 2FA after password verification
3. Add user settings for 2FA enrollment and recovery codes
4. Add audit logging for 2FA events

## Impact

### Breaking Changes
- All users will be required to enroll in 2FA on next login
- Login API response changes to include 2FA challenge

### Database Changes
- Add `otp_secret` column to users table
- Create `otp_verification_logs` table
- Add `recovery_codes` table

### Frontend Changes
- New OTP input component
- Updated login flow with 2FA step
- New 2FA settings page

## Timeline

- Database migration: 1 day
- Backend implementation: 2-3 days
- Frontend implementation: 2-3 days
- Testing and rollout: 1 week

## Dependencies

- TOTP library (e.g., pyotp, speakeasy)
- QR code generation library
```

## File: tasks.md

```markdown
# Implementation Tasks

## 1. Database Setup
- [ ] 1.1 Add `otp_secret` column to users table (nullable initially)
- [ ] 1.2 Create `otp_verification_logs` table with columns:
  - id, user_id, success, ip_address, timestamp
- [ ] 1.3 Create `recovery_codes` table with columns:
  - id, user_id, code_hash, used, created_at
- [ ] 1.4 Write and test migration script
- [ ] 1.5 Add database indexes for performance

## 2. Backend Implementation
- [ ] 2.1 Install TOTP library dependency
- [ ] 2.2 Create OTP service with methods:
  - generate_secret()
  - generate_qr_code(secret)
  - verify_otp(secret, code)
- [ ] 2.3 Add POST /api/auth/2fa/enroll endpoint
  - Generates secret and QR code
  - Returns QR code and recovery codes
- [ ] 2.4 Add POST /api/auth/2fa/verify endpoint
  - Verifies OTP code
  - Issues JWT on success
- [ ] 2.5 Modify POST /api/auth/login endpoint
  - Return 2FA challenge instead of JWT
  - Include temporary token for 2FA verification
- [ ] 2.6 Add rate limiting to verification endpoint (3 attempts per 5 minutes)
- [ ] 2.7 Add audit logging for all 2FA events
- [ ] 2.8 Write unit tests for OTP service
- [ ] 2.9 Write integration tests for 2FA endpoints

## 3. Frontend Implementation
- [ ] 3.1 Create OTPInput component
  - 6-digit input with auto-focus
  - Paste support
  - Error state display
- [ ] 3.2 Create 2FAEnrollment component
  - Display QR code
  - Show recovery codes
  - Confirmation step
- [ ] 3.3 Update LoginForm component
  - Handle 2FA challenge response
  - Show OTP input after password verification
- [ ] 3.4 Create 2FASettings page
  - Enable/disable 2FA
  - Regenerate recovery codes
  - View 2FA status
- [ ] 3.5 Add 2FA status indicator to user profile
- [ ] 3.6 Write component tests

## 4. Documentation
- [ ] 4.1 Update API documentation
- [ ] 4.2 Create user guide for 2FA enrollment
- [ ] 4.3 Create admin guide for 2FA management
- [ ] 4.4 Update security documentation

## 5. Testing & Rollout
- [ ] 5.1 End-to-end testing
- [ ] 5.2 Security review
- [ ] 5.3 Performance testing
- [ ] 5.4 Staged rollout plan
- [ ] 5.5 Monitor error rates and user feedback
```

## File: specs/auth/spec.md (Delta)

```markdown
---
id: auth/authentication
relatedTasks: [bd-2fa1, bd-2fa2, bd-2fa3]
relatedRules: [security-guidelines.md, module-development.md]
status: active
---

# Delta for Auth Specification

## ADDED Requirements

### Requirement: Two-Factor Authentication
The system MUST require a second factor (OTP) during login for all users.

#### Scenario: 2FA enrollment
- GIVEN a user without 2FA enabled
- WHEN the user accesses the 2FA settings page
- THEN a QR code is generated
- AND recovery codes are displayed
- AND the user must verify an OTP to complete enrollment

#### Scenario: Login with 2FA
- GIVEN a user with 2FA enabled
- WHEN the user submits valid credentials
- THEN a 2FA challenge is returned
- AND a temporary token is issued (valid for 5 minutes)
- AND no JWT is issued until OTP verification

#### Scenario: Valid OTP
- GIVEN a user has received a 2FA challenge
- WHEN the user submits a valid OTP within 5 minutes
- THEN a JWT is issued
- AND the user is logged in
- AND the verification is logged

#### Scenario: Invalid OTP
- GIVEN a user has received a 2FA challenge
- WHEN the user submits an invalid OTP
- THEN an error message is displayed
- AND the user can retry up to 3 times
- AND after 3 failures, the temporary token is invalidated

#### Scenario: Expired 2FA challenge
- GIVEN a user has received a 2FA challenge
- WHEN more than 5 minutes have passed
- THEN the temporary token is invalid
- AND the user must restart the login process

### Requirement: Recovery Codes
The system MUST provide recovery codes for account recovery.

#### Scenario: Generate recovery codes
- WHEN a user enrolls in 2FA
- THEN 10 recovery codes are generated
- AND codes are displayed once
- AND codes are hashed before storage

#### Scenario: Use recovery code
- GIVEN a user cannot access their OTP device
- WHEN the user submits a valid recovery code
- THEN the code is marked as used
- AND a JWT is issued
- AND the user is logged in

## MODIFIED Requirements

### Requirement: User Authentication
The system SHALL issue a JWT on successful login after password and 2FA verification.

#### Scenario: Valid credentials (MODIFIED)
- WHEN a user submits valid credentials
- THEN if 2FA is enabled, a 2FA challenge is returned (CHANGED)
- AND if 2FA is disabled, a JWT is returned (CHANGED)
- AND the login attempt is logged

## REMOVED Requirements

(None for this change)
```

## After Implementation

Once all tasks are complete, archive the change:

### With CLI
```bash
openspec archive add-2fa --yes
```

### Without CLI
1. Copy the delta from `openspec/changes/add-2fa/specs/auth/spec.md`
2. Apply ADDED/MODIFIED sections to `openspec/specs/auth/spec.md`
3. Move `openspec/changes/add-2fa/` to `openspec/archive/add-2fa/`

The source spec now includes all 2FA requirements as the new source of truth.

