# Terminal Mirror Mac Agent

The Mac Agent connects your local Mac terminal to the Terminal Mirror web interface, allowing authorized users to execute commands remotely through secure Google OAuth authentication.

## Features

- 🔐 **Google OAuth Integration** - Validates user tokens before command execution
- 👥 **User Authorization System** - Role-based access control with configurable permissions
- 🛡️ **Command Filtering** - Restrict dangerous commands and limit user access
- 📊 **Real-time Logging** - Comprehensive audit trail of all commands and sessions
- ⚡ **HTTP Polling** - Reliable communication with web server via HTTP requests
- 🔄 **Auto-reconnect** - Handles network interruptions gracefully

## Quick Start

1. **Setup the Mac Agent**:
   ```bash
   cd mac-agent
   npm run setup
   ```

2. **Deploy Backend Updates**:
   ```bash
   cd ..
   npm run deploy
   ```

3. **Start the Agent**:
   ```bash
   npm start
   ```

4. **Test Terminal Access**:
   - Visit https://www.igori.eu
   - Log in with your Google account
   - Try terminal commands - they'll execute on your Mac!

## Configuration

### Environment Variables (.env)
```bash
# Web Server Connection
WEB_SERVER_HTTP=https://www.igori.eu
AGENT_SECRET=mac-agent-secret-2024
AGENT_ID=mac-primary

# Polling Settings
POLL_INTERVAL=2000              # How often to check for commands (ms)
COMMAND_TIMEOUT=30000           # Command execution timeout (ms)
MAX_CONCURRENT_COMMANDS=3       # Max simultaneous commands

# Logging
LOG_LEVEL=info                  # Logging level (debug, info, warn, error)
```

### User Authorization (authorized-users.json)

The agent uses a role-based permission system:

**Roles:**
- `admin` - Full terminal access with all commands
- `user` - Limited command set for safety
- `guest` - Read-only commands only

**Example User Configuration:**
```json
{
  "users": {
    "your-email@gmail.com": {
      "role": "admin",
      "permissions": ["terminal", "admin", "logs"],
      "allowedCommands": "*",
      "maxSessions": 3,
      "active": true
    }
  }
}
```

## Security Features

### Command Filtering
- **Role-based commands** - Users can only run commands allowed by their role
- **Dangerous command blocking** - Commands like `rm -rf`, `sudo`, `format` are restricted
- **Execution timeout** - Commands are automatically killed after timeout

### Authentication
- **Google OAuth validation** - Every command requires valid Google token
- **User whitelist** - Only explicitly authorized users can access Mac terminal
- **Session limits** - Configurable maximum concurrent sessions per user

### Audit Trail
All activity is logged including:
- User authentication events
- Command executions with full context
- Error conditions and security violations
- Agent status and health information

## API Endpoints

The Mac Agent communicates with these PHP backend endpoints:

- `GET /php-backend/api/mac-agent-poll.php` - Poll for queued commands
- `POST /php-backend/api/mac-agent-response.php` - Submit command results

## Scripts

- `npm run setup` - Interactive setup and configuration
- `npm start` - Start the HTTP polling agent
- `npm run dev` - Start with auto-restart on file changes
- `npm run websocket` - Start the WebSocket version (if needed)

## Troubleshooting

### Agent Not Connecting
1. Check `.env` configuration
2. Verify web server URL is accessible
3. Ensure agent secret matches backend configuration
4. Check logs in `logs/http-agent.log`

### Commands Not Executing
1. Verify user is in `authorized-users.json`
2. Check user role permissions
3. Ensure command is in allowed commands list
4. Check for command timeout issues

### Authentication Errors
1. Verify Google OAuth is working on web interface
2. Check that user email matches authorized users exactly
3. Ensure access token is being passed correctly

## Logs

Agent logs are stored in `logs/http-agent.log` and include:
- Connection status
- Command processing
- Authentication events
- Error conditions

Log rotation is automatic (10MB max, 5 files retained).

## Production Deployment

For production use, consider:

1. **Run as Service** - Use `pm2` or system service to keep agent running
2. **Monitor Health** - Set up monitoring for agent connectivity
3. **Secure Configuration** - Use strong agent secrets and limit user access
4. **Regular Updates** - Keep dependencies and configuration current

Example with PM2:
```bash
npm install -g pm2
pm2 start http-agent.js --name "terminal-mirror-agent"
pm2 startup
pm2 save
```

## Security Considerations

⚠️ **Important Security Notes:**

1. **User Authorization** - Only add trusted users to authorized-users.json
2. **Command Restrictions** - Use role-based command filtering appropriately
3. **Network Security** - Ensure HTTPS communication with web server
4. **Access Monitoring** - Regularly review logs for suspicious activity
5. **System Isolation** - Consider running agent in restricted user context