# Jackbox Game Picker API Integration

This document describes how the Kosmi/IRC relay integrates with the Jackbox Game Picker API for live voting and game notifications.

## Features

### 1. Vote Detection
The relay automatically detects when users vote on games using the `thisgame++` or `thisgame--` syntax in either Kosmi or IRC chat.

**How it works:**
- Users type `thisgame++` to upvote the current game
- Users type `thisgame--` to downvote the current game
- Votes are case-insensitive
- The relay filters out relayed messages (messages with `[irc]` or `[kosmi]` prefix) to prevent duplicate votes
- Only votes from actual users in each chat are sent to the API

### 2. Game Notifications
When a new game is added to the Jackbox session via the API, the relay receives a webhook notification and broadcasts it to both Kosmi and IRC chats.

**Example notification:**
```
🎮 Coming up next: Fibbage 4!
```

## Configuration

Add the following section to your `matterbridge.toml`:

```toml
[jackbox]
# Enable Jackbox integration for vote detection and game notifications
Enabled=true

# Jackbox API URL
APIURL="http://localhost:5000"

# Admin password for API authentication
AdminPassword="your_admin_password_here"

# Webhook server port (for receiving game notifications)
WebhookPort=3001

# Webhook secret for signature verification
WebhookSecret="your_webhook_secret_here"
```

### Configuration Options

- **Enabled**: Set to `true` to enable the integration, `false` to disable
- **APIURL**: The URL of your Jackbox Game Picker API (e.g., `http://localhost:5000`)
- **AdminPassword**: Your API admin password (used to authenticate and get a JWT token)
- **WebhookPort**: Port for the webhook server to listen on (default: 3001)
- **WebhookSecret**: Shared secret for webhook signature verification (must match the secret configured in the API)

## Setup Steps

### 1. Configure the Relay

Edit `matterbridge.toml` and add the Jackbox configuration section with your API URL, admin password, and webhook secret.

### 2. Register the Webhook

After starting the relay, register the webhook with the Jackbox API:

```bash
# Get JWT token
curl -X POST "http://localhost:5000/api/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"apiKey": "your_admin_password"}'

# Register webhook (use the JWT token from above)
curl -X POST "http://localhost:5000/api/webhooks" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Kosmi/IRC Relay",
    "url": "http://your-relay-host:3001/webhook/jackbox",
    "secret": "your_webhook_secret_here",
    "events": ["game.added"]
  }'
```

**Important:** Replace `your-relay-host` with the actual hostname or IP address where your relay is running. If the API and relay are on the same machine, you can use `localhost`.

### 3. Test the Integration

#### Test Vote Detection

1. Start an active session in the Jackbox API with some games played
2. Send a message in Kosmi or IRC: `thisgame++`
3. Check the relay logs for: `Detected vote from <username>: up`
4. Verify the vote was recorded in the API

#### Test Game Notifications

1. Add a game to the active session via the Jackbox API
2. Both Kosmi and IRC chats should receive a notification: `🎮 Coming up next: <game title>!`

## How It Works

### Vote Flow

1. User sends a message containing `thisgame++` or `thisgame--` in Kosmi or IRC
2. The bridge detects the vote pattern (case-insensitive)
3. The bridge checks if the message is relayed (has `[irc]` or `[kosmi]` prefix)
4. If not relayed, the bridge extracts the username and vote type
5. The bridge sends the vote to the Jackbox API via HTTP POST to `/api/votes/live`
6. The API records the vote and associates it with the current game based on timestamp

### Notification Flow

1. A game is added to an active session in the Jackbox API
2. The API sends a webhook POST request to `http://your-relay-host:3001/webhook/jackbox`
3. The webhook includes an HMAC-SHA256 signature in the `X-Webhook-Signature` header
4. The relay verifies the signature using the configured webhook secret
5. If valid, the relay parses the `game.added` event
6. The relay broadcasts the game announcement to all connected bridges (Kosmi and IRC)

## Security

### Webhook Signature Verification

All incoming webhooks are verified using HMAC-SHA256 signatures to ensure they come from the legitimate Jackbox API.

**How it works:**
1. The API computes `HMAC-SHA256(webhook_secret, request_body)`
2. The signature is sent in the `X-Webhook-Signature` header as `sha256=<hex_signature>`
3. The relay computes the expected signature using the same method
4. The relay uses timing-safe comparison to verify the signatures match
5. If verification fails, the webhook is rejected with a 401 Unauthorized response

### JWT Authentication

The relay authenticates with the Jackbox API using the admin password to obtain a JWT token. This token is:
- Cached to avoid re-authentication on every vote
- Automatically refreshed if it expires (detected via 401 response)
- Valid for 24 hours (configurable in the API)

## Troubleshooting

### Votes Not Being Recorded

**Possible causes:**
- No active session in the Jackbox API
- Vote timestamp doesn't match any played game
- Duplicate vote within 1 second
- Authentication failure

**Check:**
1. Relay logs for vote detection: `grep "Detected vote" logs/matterbridge.log`
2. Relay logs for API errors: `grep "Failed to send vote" logs/matterbridge.log`
3. API logs for incoming vote requests

### Webhooks Not Being Received

**Possible causes:**
- Webhook URL is not accessible from the API server
- Webhook not registered in the API
- Signature verification failing
- Firewall blocking the webhook port

**Check:**
1. Verify webhook is registered: `GET /api/webhooks` (with JWT token)
2. Test webhook manually: `POST /api/webhooks/test/:id` (with JWT token)
3. Check webhook logs in API: `GET /api/webhooks/:id/logs` (with JWT token)
4. Verify webhook server is listening: `curl http://localhost:3001/health`
5. Check relay logs for signature verification errors

### Authentication Failures

**Possible causes:**
- Incorrect admin password in configuration
- API is not running or not accessible

**Check:**
1. Verify API URL is correct and accessible
2. Test authentication manually:
   ```bash
   curl -X POST "http://localhost:5000/api/auth/login" \
     -H "Content-Type: application/json" \
     -d '{"apiKey": "your_admin_password"}'
   ```
3. Check relay logs for authentication errors

## Logs

The relay logs all Jackbox-related activity with the `jackbox` prefix:

```
[jackbox] Initializing Jackbox integration...
[jackbox] Successfully authenticated with Jackbox API
[jackbox] Starting Jackbox webhook server on port 3001
[kosmi] Detected vote from Anonymous Llama: up
[jackbox] Vote recorded for Fibbage 4: Anonymous Llama - 5👍 2👎
[jackbox] Broadcasting Jackbox message: 🎮 Coming up next: Quiplash 3!
```

## Disabling the Integration

To disable the Jackbox integration, set `Enabled=false` in the `[jackbox]` section of `matterbridge.toml` and restart the relay.

The relay will continue to function normally for Kosmi ↔ IRC message relay without any Jackbox features.

