# 🔐 Authentication Service

> **User identity and session management** with Nostr key handling, dependency injection architecture, and secure client-side key management.

## Table of Contents

- [[#Service Overview]]
- [[#Architecture]]
- [[#Key Features]]
- [[#Usage Patterns]]
- [[#Authentication Flow]]
- [[#Security Considerations]]

## Service Overview

The `AuthService` is a core infrastructure service that manages user authentication, identity, and session state throughout the application. It provides secure Nostr key management with client-side encryption and reactive state management.

**Service Token**: `SERVICE_TOKENS.AUTH_SERVICE`  
**Location**: `src/modules/base/auth/auth-service.ts`  
**Dependencies**: `LnbitsAPI` for backend integration

## Architecture

### Dependency Injection Pattern
The authentication system uses dependency injection for clean, modular access:

```typescript
// Service registration (base module)
container.provide(SERVICE_TOKENS.AUTH_SERVICE, authService)

// Service consumption (components)
const auth = useAuth() // Via composable wrapper

// Service consumption (other services)
const authService = injectService(SERVICE_TOKENS.AUTH_SERVICE)
```

### Reactive State Management
AuthService integrates Vue's reactivity system for automatic UI updates:

```typescript
export class AuthService extends BaseService {
  public isAuthenticated = ref(false)
  public user = ref<User | null>(null)
  public isLoading = ref(false)
  public error = ref<Error | null>(null)
  
  // Computed properties for component compatibility
  public currentUser = computed(() => this.user.value)
  public userDisplay = computed(() => this.user.value?.name || 'Anonymous')
}
```

## Key Features

### 🔑 **Nostr Key Management**
- **Secure Key Generation** - Client-side key pair creation with proper entropy
- **Key Import/Export** - Support for existing Nostr keys (nsec/hex formats)
- **Encrypted Storage** - User keys encrypted with password-derived encryption
- **Key Recovery** - Secure key backup and restoration mechanisms

### 👤 **User Identity & Profiles**
- **Nostr Profile Management** - NIP-01 compatible user metadata
- **Profile Updates** - Real-time profile information synchronization
- **Display Name Handling** - Fallback from name → display_name → truncated pubkey
- **Avatar Support** - Profile picture URLs with fallback handling

### 🔒 **Session Management**
- **Persistent Sessions** - Secure localStorage-based session persistence  
- **Auto-Initialization** - Automatic session restoration on app startup
- **Secure Logout** - Complete session cleanup and key removal
- **Token Management** - LNBits API token handling and refresh

### 🌐 **Backend Integration**
- **LNBits API** - Wallet integration for Lightning functionality
- **Event Publishing** - User profile publishing to Nostr relays
- **Real-time Updates** - Reactive profile updates across relays

## Usage Patterns

### Component Usage (Recommended)
```vue
<script setup lang="ts">
import { useAuth } from '@/composables/useAuthService'

const auth = useAuth()

// Access reactive authentication state
const isAuthenticated = auth.isAuthenticated
const currentUser = auth.currentUser
const userDisplay = auth.userDisplay

// Authentication methods
const handleLogin = async (privateKey: string) => {
  try {
    await auth.login({ privateKey })
    // Success handled automatically by service
  } catch (error) {
    // Error handling
    console.error('Login failed:', error)
  }
}

const handleLogout = () => auth.logout()
</script>
```

### Service Usage (Other Services)
```typescript
import { injectService, SERVICE_TOKENS } from '@/core/di-container'

export class ChatService extends BaseService {
  private get authService(): AuthService {
    return this.dependencies.get('AuthService') as AuthService
  }
  
  async sendMessage(content: string) {
    const user = this.authService.user.value
    if (!user?.pubkey || !user?.prvkey) {
      throw new Error('Authentication required')
    }
    
    // Use authenticated user data for message signing
  }
}
```

### Store Integration
```typescript
// In Pinia stores
export const useMyStore = defineStore('myStore', () => {
  const auth = useAuth()
  
  // Reactive dependency on auth state
  const userSpecificData = computed(() => {
    if (!auth.isAuthenticated.value) return []
    return loadDataForUser(auth.currentUser.value.pubkey)
  })
  
  return { userSpecificData }
})
```

## Authentication Flow

### 1. App Initialization
```typescript
// App startup sequence
const authService = injectService(SERVICE_TOKENS.AUTH_SERVICE)
await authService.initialize()

if (authService.isAuthenticated.value) {
  // User has valid session - proceed to app
} else {
  // Redirect to login/onboarding
}
```

### 2. User Login Process
1. **Key Input** - User provides private key (nsec, hex, or generates new)
2. **Key Validation** - Validate key format and derive public key
3. **Profile Loading** - Fetch existing Nostr profile if available  
4. **Session Creation** - Encrypt and store keys securely
5. **Service Initialization** - Initialize user-scoped services
6. **UI Updates** - Reactive state triggers navigation/UI changes

### 3. Authentication Guards
```typescript
// Router guards use auth service
router.beforeEach((to, from, next) => {
  const authService = injectService(SERVICE_TOKENS.AUTH_SERVICE)
  
  if (to.meta.requiresAuth && !authService.isAuthenticated.value) {
    next('/login')
  } else {
    next()
  }
})
```

### 4. Logout Process
1. **Session Cleanup** - Clear encrypted keys from storage
2. **Service Reset** - Reset all user-scoped service state
3. **Relay Cleanup** - Close user-specific Nostr subscriptions
4. **UI Reset** - Clear user data from stores and components
5. **Navigation** - Redirect to login/public areas

## Security Considerations

### 🔐 **Client-Side Security**
- **No Server Keys** - Private keys never leave the client
- **Encrypted Storage** - Keys encrypted with user-provided password
- **Memory Management** - Secure key handling in memory
- **Input Validation** - Strict validation of key formats and data

### 🌐 **Network Security**
- **HTTPS Only** - All API calls over encrypted connections
- **Token Security** - LNBits tokens with appropriate scoping
- **Request Validation** - API request signature verification
- **Error Handling** - No sensitive data in error messages

### 🛡️ **Data Protection**
- **User-Scoped Storage** - Data isolation between users
- **Automatic Cleanup** - Session data cleared on logout
- **Profile Privacy** - Configurable profile information sharing
- **Key Rotation** - Support for updating authentication credentials

## API Reference

### AuthService Methods
```typescript
interface AuthService {
  // Core authentication
  login(credentials: LoginCredentials): Promise<void>
  logout(): Promise<void>
  initialize(): Promise<void>
  
  // Key management
  generateKeyPair(): Promise<{ pubkey: string, prvkey: string }>
  importPrivateKey(key: string): Promise<void>
  exportPrivateKey(): string | null
  
  // Profile management
  updateProfile(profile: UserMetadata): Promise<void>
  publishProfile(): Promise<void>
  
  // Reactive state (readonly)
  readonly isAuthenticated: ComputedRef<boolean>
  readonly currentUser: ComputedRef<User | null>
  readonly userDisplay: ComputedRef<UserDisplay>
  readonly isLoading: Ref<boolean>
  readonly error: Ref<Error | null>
}
```

### LoginCredentials Interface
```typescript
interface LoginCredentials {
  privateKey?: string      // Existing key (nsec or hex)
  generateNew?: boolean    // Generate new key pair
  password?: string        // For key encryption
  profile?: UserMetadata   // Initial profile data
}
```

## See Also

### Architecture Documentation
- **[[../01-architecture/authentication-architecture|🔐 Authentication Architecture]]** - Detailed architecture overview
- **[[../01-architecture/dependency-injection|⚙️ Dependency Injection]]** - Service container patterns
- **[[index|⚙️ Core Services Overview]]** - Related infrastructure services

### Module Documentation
- **[[../02-modules/base-module/index|🏗️ Base Module]]** - Authentication service registration
- **[[../04-development/security|🛡️ Security Guidelines]]** - Security best practices

---

**Tags:** #authentication #security #services #nostr #dependency-injection  
**Last Updated:** 2025-09-07  
**Author:** Development Team 