# User Management Module

Linux user management system for multi-user MyAIDev Method deployment with isolated user environments.

## Overview

This module provides comprehensive Linux user management capabilities including:

- **User Creation**: Create Linux system users with restricted shells
- **Directory Management**: Set up isolated home directories with Claude Code configurations
- **Resource Limits**: Apply CPU, memory, and process limits
- **Disk Quotas**: Manage storage limits per user
- **Cleanup**: Safe deletion of users and their resources

## Architecture

### Services

#### LinuxUserService
Low-level Linux user operations using system commands (`useradd`, `userdel`, `id`).

**Features:**
- Create/delete Linux users
- Username sanitization
- Resource limit enforcement via `/etc/security/limits.d/`
- User existence checks

#### DirectoryService
Home directory and workspace management.

**Features:**
- `.claude/` configuration directory setup
- Workspace directory creation
- Ownership and permission management
- Shell configuration (`.bashrc`)

#### QuotaService
Disk quota management (optional - requires quota tools).

**Features:**
- Set soft/hard disk limits
- Monitor usage
- Fallback to directory size calculation if quotas unavailable

#### UserManagementService
High-level orchestration service integrating all components.

**Features:**
- Complete user environment setup
- Integrated error handling
- Automatic username sanitization
- Graceful degradation (quotas optional)

## Usage

### Basic User Creation

```typescript
import { Effect, ManagedRuntime } from "effect";
import { UserManagementService } from "./user-management";
import { createUserManagementLayer } from "./user-management/layers";

const layer = createUserManagementLayer();
const runtime = ManagedRuntime.make(layer);

const result = await runtime.runPromise(
  Effect.gen(function* () {
    const userMgmt = yield* UserManagementService;

    return yield* userMgmt.createUser({
      username: "john",
      email: "john@example.com",
      claudeApiKey: "sk-...",
      diskQuotaMB: 2048, // 2GB quota
      shell: "/bin/rbash", // Restricted bash
    });
  })
);

console.log(result);
// {
//   linuxUser: { username: "john", uid: 1001, gid: 1001, homeDir: "/home/john", ... },
//   homeDir: "/home/john",
//   claudeConfigPath: "/home/john/.claude",
//   workspacePath: "/home/john/workspace",
//   quotaApplied: true,
//   limitsApplied: true
// }
```

### Check Username Availability

```typescript
const available = await runtime.runPromise(
  Effect.gen(function* () {
    const userMgmt = yield* UserManagementService;
    return yield* userMgmt.isUsernameAvailable("john");
  })
);
```

### Delete User

```typescript
await runtime.runPromise(
  Effect.gen(function* () {
    const userMgmt = yield* UserManagementService;
    yield* userMgmt.deleteUser("john");
  })
);
```

## Integration with Authentication

The user management system is automatically integrated with the authentication system in `AuthService`:

```typescript
// In AuthService.register()
yield* userManagement.createUser({
  username: linuxUsername,
  email,
  shell: "/bin/rbash",
  diskQuotaMB: 2048,
}).pipe(
  Effect.catchAll((error) => {
    // Gracefully handle errors - don't fail registration
    console.error(`Failed to create Linux user:`, error);
    return Effect.succeed(void 0);
  })
);
```

When a user registers:
1. Database user record created
2. Linux user created with sanitized username
3. Home directory structure set up
4. Claude Code configuration initialized
5. Resource limits applied
6. Disk quotas set (if available)

## Directory Structure

Created for each user:

```
/home/{username}/
├── .claude/              # Claude Code configuration
│   ├── config.json       # API key, model settings
│   ├── sessions/         # Session storage
│   └── cache/            # Cache directory
├── workspace/            # User workspace
│   └── README.md         # Welcome message
└── .bashrc               # Shell configuration
```

## Security Features

### Restricted Shell
Users are created with `/bin/rbash` (restricted bash) by default:
- No `cd` command
- No path modification
- No redirection
- No command substitution

### Resource Limits
Per-user limits enforced via `/etc/security/limits.d/{username}.conf`:
- **Max open files**: 1024 (soft) / 2048 (hard)
- **Max processes**: 256 (soft) / 512 (hard)
- **Max memory**: 2GB (soft) / 4GB (hard)
- **Max CPU time**: 60s (soft) / 120s (hard) per process

### Disk Quotas (Optional)
If quota tools installed:
- **Soft limit**: 2GB (warning threshold)
- **Hard limit**: 3GB (absolute maximum)

### No Sudo Access
Created users have no sudo privileges and cannot escalate permissions.

## System Requirements

### Required
- Linux operating system (Ubuntu/Debian recommended)
- Node.js 18+
- Sudo access for server process

### Optional
- `quota` package for disk quota management

```bash
# Install quota tools (optional)
sudo apt-get install quota
sudo quotacheck -cum /
sudo quotaon -v /
```

## Error Handling

All services use Effect-TS for structured error handling:

```typescript
// LinuxUserError
{
  _tag: "LinuxUserError",
  message: "Failed to create user",
  cause: Error
}

// DirectoryError
{
  _tag: "DirectoryError",
  message: "Failed to setup home directory",
  cause: Error
}

// QuotaError
{
  _tag: "QuotaError",
  message: "Failed to set quota",
  cause: Error
}

// UserManagementError
{
  _tag: "UserManagementError",
  message: "Failed to create user environment",
  cause: Error
}
```

## Username Sanitization

Usernames are automatically sanitized to meet Linux requirements:

```typescript
// Example sanitization
"John Doe" → "john_doe"
"user@email.com" → "user_email_com"
"123user" → "u_123user"  // Must start with letter
"very-long-username-that-exceeds-limit" → "very_long_username_that_exce"  // Truncated to 32 chars
```

## Testing

```bash
# Run type checking
npm run typecheck:server

# Build
npm run build:server

# Test user creation (requires sudo)
node -e "
  import('./dist/server/user-management/index.js').then(async ({ UserManagementService }) => {
    const { Effect, ManagedRuntime } = await import('effect');
    const { createUserManagementLayer } = await import('./dist/server/user-management/layers.js');

    const layer = createUserManagementLayer();
    const runtime = ManagedRuntime.make(layer);

    const result = await runtime.runPromise(
      Effect.gen(function* () {
        const userMgmt = yield* UserManagementService;
        return yield* userMgmt.createUser({
          username: 'testuser',
          email: 'test@example.com',
          diskQuotaMB: 1024,
        });
      })
    );

    console.log('User created:', result);
  });
"
```

## Production Considerations

### Security
- ✅ Users run with restricted shells
- ✅ Resource limits prevent DoS
- ✅ No sudo access
- ✅ Directory isolation
- ⚠️ Consider additional AppArmor/SELinux profiles

### Performance
- User creation takes 1-3 seconds
- Quota checks are fast if using quota tools
- Directory size calculation (fallback) can be slow for large directories

### Monitoring
- Check `/etc/security/limits.d/` for limit configurations
- Monitor disk usage with `quota` command
- Audit log records user creation in database

### Cleanup
When deleting users:
1. Home directory removed (`rm -rf /home/{username}`)
2. User deleted from system (`userdel`)
3. Limits configuration removed
4. Database records remain for audit trail

## Troubleshooting

### "Failed to create Linux user"
- Ensure server has sudo access
- Check if username already exists: `id username`
- Verify useradd command available

### "Quota system not available"
- Install quota tools: `sudo apt-get install quota`
- Or system will fallback to directory size monitoring

### "Permission denied" errors
- Server process needs sudo for user management
- Consider running with sudo or configuring sudoers file

### "Directory already exists"
- Previous user not fully cleaned up
- Manually remove: `sudo rm -rf /home/username`

## Future Enhancements

- [ ] User suspension/reactivation
- [ ] Disk usage monitoring dashboard
- [ ] Automated cleanup of inactive users
- [ ] User groups for shared resources
- [ ] Network namespace isolation
- [ ] Container-based isolation option

## License

Same as MyAIDev Method project.
