# Browser-Based Authentication Guide

## Overview
The Kosmi bridge now supports **fully automated email/password authentication** using headless Chrome via chromedp. No manual token extraction needed!

## Quick Start

### 1. Configure Email/Password
Edit `matterbridge.toml`:

```toml
[kosmi.hyperspaceout]
RoomURL="https://app.kosmi.io/room/@hyperspaceout"
Email="your-email@example.com"
Password="your-password"
```

### 2. Run the Bot
```bash
./irc-kosmi-relay -conf matterbridge.toml
```

That's it! The bot will:
1. Launch headless Chrome
2. Navigate to Kosmi
3. Log in with your credentials
4. Extract the JWT token from localStorage
5. Use the token for authenticated connections
6. Automatically refresh the token daily (checks for expiry 7 days in advance)

## How It Works

### Initial Login
When you start the bot with Email/Password configured:
1. **Browser Launch**: Headless Chrome starts (no visible window)
2. **Navigation**: Goes to https://app.kosmi.io
3. **Login Flow**:
   - Clicks "Login" button
   - Clicks "Login with Email"
   - Fills in email and password
   - Submits the form
4. **Token Extraction**: Reads `localStorage.getItem('token')`
5. **Token Parsing**: Extracts expiry time from JWT
6. **Connection**: Uses token for WebSocket authentication

### Automatic Token Refresh
- **Daily Check**: Every 24 hours, the bot checks if the token is still valid
- **Expiry Buffer**: Refreshes 7 days before expiration
- **Seamless**: Happens in the background without disconnecting
- **Logging**: You'll see "Checking token expiry..." in debug logs

## Requirements

### System Requirements
- **Chrome/Chromium**: Must be installed on your system
  - macOS: Usually pre-installed or via Homebrew: `brew install chromium`
  - Linux: `sudo apt install chromium-browser` or `sudo yum install chromium`
  - Windows: Download from https://www.chromium.org/getting-involved/download-chromium/

### Go Dependencies
- `github.com/chromedp/chromedp` - Automatically installed with `go get`

## Configuration Options

### Option 1: Email/Password (Recommended)
```toml
Email="your-email@example.com"
Password="your-password"
```
- ✅ Fully automated
- ✅ Auto-refresh
- ✅ No manual intervention
- ⚠️ Requires Chrome/Chromium
- ⚠️ Stores credentials in config file

### Option 2: Manual Token
```toml
Token="eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9..."
```
- ✅ No browser required
- ✅ No credentials in config
- ❌ Manual extraction needed
- ❌ Must update when expired (~1 year)

### Option 3: Anonymous
```toml
# Leave both empty
Email=""
Password=""
Token=""
```
- ✅ No setup needed
- ❌ Limited permissions
- ❌ Can't access private rooms

## Troubleshooting

### "Browser automation failed"
**Possible causes:**
1. Chrome/Chromium not installed
2. Chrome/Chromium not in PATH
3. Network issues
4. Kosmi website changed

**Solutions:**
```bash
# Check if Chrome is installed
which chromium || which google-chrome || which chrome

# Install Chrome (macOS)
brew install chromium

# Install Chrome (Ubuntu/Debian)
sudo apt install chromium-browser

# Install Chrome (CentOS/RHEL)
sudo yum install chromium
```

### "No token found in localStorage after login"
**Possible causes:**
1. Login failed (wrong credentials)
2. Kosmi's login flow changed
3. Page didn't fully load

**Solutions:**
- Verify credentials are correct
- Check bot logs for detailed error messages
- Try manual token extraction as fallback

### "Token expired or expiring soon"
This is normal! The bot will automatically refresh the token. If refresh fails:
- Check Chrome is still installed
- Check network connectivity
- Restart the bot to force a fresh login

### Headless Chrome Issues
If you see Chrome-related errors:

```bash
# Set environment variable for debugging
export CHROMEDP_DISABLE_GPU=1

# Or run with visible browser (for debugging)
export CHROMEDP_NO_HEADLESS=1
```

## Security Considerations

### Credential Storage
- Credentials are stored in **plain text** in `matterbridge.toml`
- Ensure config file has restrictive permissions:
  ```bash
  chmod 600 matterbridge.toml
  ```
- Do not commit config with real credentials to version control
- Consider using environment variables:
  ```bash
  export KOSMI_EMAIL="your-email@example.com"
  export KOSMI_PASSWORD="your-password"
  ```

### Browser Automation
- Headless Chrome runs with minimal privileges
- No data is stored or cached
- Browser closes immediately after token extraction
- Token is kept in memory only

### Token Security
- Tokens are JWT (JSON Web Tokens) signed by Kosmi
- Valid for ~1 year
- Can be revoked by logging out in browser
- Treat tokens like passwords

## Advanced Configuration

### Custom Chrome Path
If Chrome is installed in a non-standard location:

```go
// In browser_auth.go, modify NewContext call:
opts := append(chromedp.DefaultExecAllocatorOptions[:],
    chromedp.ExecPath("/path/to/chrome"),
)
ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
```

### Timeout Adjustment
If login takes longer than 60 seconds:

```go
// In browser_auth.go, modify timeout:
ctx, cancel = context.WithTimeout(ctx, 120*time.Second)
```

### Refresh Interval
To check token more/less frequently:

```go
// In kosmi.go, modify ticker:
ticker := time.NewTicker(12 * time.Hour) // Check twice daily
```

## Comparison with Manual Token

| Feature | Browser Auth | Manual Token |
|---------|-------------|--------------|
| Setup Complexity | Easy | Medium |
| Automation | Full | None |
| Token Refresh | Automatic | Manual |
| Dependencies | Chrome | None |
| Security | Credentials in config | Token in config |
| Maintenance | Low | Medium |

## Logs to Expect

### Successful Login
```
INFO Using browser automation for email/password authentication
INFO Obtaining authentication token via browser automation...
INFO ✅ Successfully obtained token via browser automation
INFO Token expires in: 365d
INFO ✅ Browser authentication successful
INFO Successfully connected to Kosmi
```

### Daily Token Check
```
DEBUG Checking token expiry...
DEBUG Token check complete
```

### Token Refresh (when expiring)
```
INFO Token expired or expiring soon, will refresh
INFO Obtaining authentication token via browser automation...
INFO ✅ Successfully obtained token via browser automation
INFO Token expires in: 365d
```

## Migration from Manual Token

If you're currently using manual token:

1. **Add credentials** to config:
   ```toml
   Email="your-email@example.com"
   Password="your-password"
   ```

2. **Remove or comment out Token**:
   ```toml
   #Token="..."
   ```

3. **Restart the bot**

The bot will automatically switch to browser-based auth!

## Performance Impact

- **Initial Login**: ~5-10 seconds (one-time per start)
- **Token Refresh**: ~5-10 seconds (once per year, or when expiring)
- **Daily Check**: <1ms (just checks expiry time)
- **Memory**: +50-100MB during browser operation (released after)
- **CPU**: Minimal (browser runs briefly)

## Conclusion

Browser-based authentication provides the best balance of:
- ✅ Full automation
- ✅ Reliable token refresh
- ✅ Simple configuration
- ✅ Low maintenance

For production use, this is the **recommended authentication method**.

