npm package: @hookbox-io/cli
Description: 📦 hookbox - Test Webhooks Locally.
Author: capythulhu
Latest version: 1.3.75

# 📦 hookbox CLI

A webhook testing CLI tool. Create public URLs for your local development and receive webhooks in real-time via WebSocket connections.

## Installation

Install it globally:

```bash
npm install -g @hookbox-io/cli
```

## Quick Start

1. **Start listening for webhooks:**

   ```bash
   hookbox start
   ```

2. **Forward webhooks to your local application:**
   ```bash
   hookbox start --forward localhost:3000
   ```

## Commands

### `hookbox init`

Initialize a new hookbox instance and save credentials locally.

### `hookbox start [options]`

Start listening for webhooks with real-time WebSocket connection.

**Options:**

- `-f, --forward <address>` - Forward webhooks to a local address (e.g., localhost:8080)

**Features:**

- Real-time webhook delivery via WebSocket
- Connection timeout protection (15 seconds)
- Graceful connection management and cleanup
- Keep-alive ping/pong to maintain connection
- Webhook rules support (see below)

### `hookbox purge`

Delete saved hookbox credentials.

### `hookbox rule`

Manage webhook response rules using natural language.

#### `hookbox rule list`

List all webhook rules currently configured. Shows:

- Rule names
- Conditions in a tree format
- Response details (status, headers, body preview)
- Beautiful color-coded display

Example output:

```
📋 Webhook Rules (2/10):

1. Respond 204 for Authorization header
   Conditions:
   └─ Header Authorization exists
   Response:
   └─ Status 204

2. Stripe webhook handler
   Conditions:
   ├─ URL contains stripe
   └─ Method equals POST
   Response:
   └─ Status 200, 1 header, JSON body
```

#### `hookbox rule add <description>`

Add a new webhook rule using natural language description. Uses AI to convert your description into a proper rule.

**Examples:**

```bash
hookbox rule add "Return 204 when Authorization header exists"
hookbox rule add "Respond with {success: true} for Stripe webhooks"
hookbox rule add "Timeout when request body contains test=true"
```

#### `hookbox rule remove <description>`

Remove a webhook rule by describing which rule to remove. Uses AI to identify the matching rule.

**Examples:**

```bash
hookbox rule remove "The authorization header rule"
hookbox rule remove "The Stripe webhook handler"
```

### `hookbox help`

Show help information.

## Webhook Rules

Webhook rules allow you to configure custom HTTP responses for incoming webhooks based on specific conditions. This powerful feature enables you to simulate various API behaviors without running any local code.

### Overview

- **Maximum 10 rules** per hookbox instance
- **AI-powered** natural language rule creation
- **Multiple weighted responses** for simulating random behaviors
- **Automatic rule loading** when connecting with `hookbox start`
- Rules only affect HTTP responses, webhooks are always displayed in CLI

### Creating Rules

#### Using Natural Language (Recommended)

The easiest way to create rules is using natural language descriptions:

```bash
# Basic examples
hookbox rule add "Return 204 when Authorization header exists"
hookbox rule add "Respond with {success: true} for POST requests to /webhook"
hookbox rule add "Return 404 for any URL containing /test"

# Advanced examples with multiple conditions
hookbox rule add "Return {ok: true} for Stripe webhooks with valid signature"
hookbox rule add "Timeout when request body contains test=true"
hookbox rule add "Return 401 if Authorization header doesn't start with Bearer"

# Weighted responses (new!)
hookbox rule add "randomly return either 200 or 500 (50/50 chance)"
hookbox rule add "return 200 most of the time (80%) but occasionally timeout (20%)"
hookbox rule add "simulate flaky service: 70% success, 20% retry, 10% timeout"
```

#### Manual JSON Configuration

Create or edit `rules.json` in your config directory:

```json
[
  {
    "name": "Basic authentication check",
    "conditions": [
      {
        "type": "header",
        "field": "Authorization",
        "operator": "exists"
      }
    ],
    "responses": [
      {
        "weight": 1,
        "status": 204
      }
    ]
  }
]
```

### Rule Structure

#### Conditions

Rules can match on multiple conditions (all must match):

**1. Method Conditions**

```json
{
  "type": "method",
  "operator": "equals",
  "value": "POST"
}
```

**2. Header Conditions**

```json
{
  "type": "header",
  "field": "Authorization",
  "operator": "exists|equals|contains|regex",
  "value": "Bearer token123" // optional for "exists" operator
}
```

**3. URL Conditions**

```json
{
  "type": "url",
  "operator": "equals|contains|regex",
  "value": "/webhook"
}
```

**4. Body Conditions**

```json
{
  "type": "body",
  "path": "user.email", // optional, for JSON bodies
  "operator": "exists|equals|contains|regex",
  "value": "test@example.com"
}
```

#### Weighted Responses

Rules now support multiple weighted responses for simulating various scenarios:

```json
{
  "name": "Simulate flaky payment service",
  "conditions": [
    { "type": "url", "operator": "contains", "value": "/payment" }
  ],
  "responses": [
    {
      "weight": 70,
      "status": 200,
      "body": { "status": "success", "id": "pay_123" }
    },
    {
      "weight": 20,
      "status": 503,
      "headers": { "Retry-After": "5" },
      "body": { "error": "Service temporarily unavailable" }
    },
    {
      "weight": 10,
      "timeout": true
    }
  ]
}
```

### Complete Examples

#### 1. Stripe Webhook Handler

```bash
hookbox rule add "Return {received: true} with 200 status for POST requests from stripe.com"
```

Generates:

```json
{
  "name": "Return received:true with 200 status for POST requests from stripe.com",
  "conditions": [
    { "type": "method", "operator": "equals", "value": "POST" },
    { "type": "url", "operator": "contains", "value": "stripe.com" }
  ],
  "responses": [
    {
      "weight": 1,
      "status": 200,
      "body": { "received": true }
    }
  ]
}
```

#### 2. Authentication Required

```bash
hookbox rule add "Return 401 with {error: 'Unauthorized'} when Authorization header is missing"
```

#### 3. Rate Limiting Simulation

```bash
hookbox rule add "80% return 200, 20% return 429 with rate limit error for /api endpoints"
```

#### 4. A/B Testing

```bash
hookbox rule add "50% return {version: 'A'}, 50% return {version: 'B'} for GET /experiment"
```

#### 5. Complex Service Simulation

```bash
hookbox rule add "For POST /orders: 60% success with order ID, 20% validation error, 10% payment failed, 10% timeout"
```

### Managing Rules

#### List All Rules

```bash
hookbox rule list
```

Output shows rules with weighted responses:

```
📋 Webhook Rules (3/10):

1. Simulate flaky payment service
   Conditions:
   └─ URL contains /payment
   Responses (3):
   ├─ 70% chance (weight: 70)
   │   Status 200, JSON body
   ├─ 20% chance (weight: 20)
   │   Status 503, 1 header, JSON body
   └─ 10% chance (weight: 10)
       Timeout
```

#### Remove Rules

```bash
# Remove by description
hookbox rule remove "The payment service rule"
hookbox rule remove "The authentication check"
```

### Advanced Features

#### 1. JSON Path Matching

Match nested fields in JSON request bodies:

```bash
hookbox rule add "Return 403 when request body user.role is not 'admin'"
```

#### 2. Regex Patterns

Use regular expressions for complex matching:

```bash
hookbox rule add "Return 400 for URLs matching regex '^/api/v[0-9]+/deprecated'"
```

#### 3. Custom Headers

Return custom headers in responses:

```bash
hookbox rule add "Return 301 with Location header pointing to /v2 for /v1 endpoints"
```

#### 4. Timeout Simulation

Test timeout handling:

```bash
hookbox rule add "Timeout for requests with X-Test-Timeout header"
```

### Use Cases

1. **Testing Webhooks**: Simulate provider responses without running code
2. **Chaos Engineering**: Introduce controlled failures and delays
3. **Development**: Quick webhook endpoint creation without backend
4. **Load Testing**: Test how your system handles various responses
5. **Documentation**: Create live webhook examples
6. **Debugging**: Isolate webhook issues with controlled responses

### Tips

- Use descriptive rule names for easy management
- Test rules with `hookbox rule list` before relying on them
- Remove unused rules to stay under the 10-rule limit
- Combine multiple conditions for precise matching
- Use weighted responses to simulate real-world scenarios
- Rules persist between sessions (stored in `rules.json`)

### Limitations

- Maximum 10 rules per hookbox instance
- All conditions must match (AND logic, no OR support)
- Rules execute in order, first match wins
- Body matching requires valid JSON for path-based conditions
- Regex patterns must be valid Go regular expressions

## Examples

```bash
# Initialize a new hookbox instance (optional)
hookbox init

# Start listening for webhooks
hookbox start

# Forward webhooks to local Express server
hookbox start -f localhost:3000

# Forward to a specific endpoint
hookbox start -f localhost:8080/webhooks

# Manage rules
hookbox rule list
hookbox rule add "Return 404 for any URL containing /test"
hookbox rule remove "The test URL rule"

# Clean up credentials
hookbox purge
```

## How it Works

1. **Initialize**: Creates a unique UUID and secure password
2. **Connect**: Establishes authenticated WebSocket connection to hookbox.io servers
3. **Configure**: Optionally set up webhook response rules using natural language
4. **Receive**: Gets webhooks delivered in real-time via WebSocket
5. **Display**: Shows beautiful webhook output with syntax highlighting
6. **Forward**: Optionally forwards requests to your local development server
7. **Rules**: Optionally applies custom response rules based on webhook content

## Connection Management

### Real-time WebSocket Features

- **Authentication**: Secure connection with UUID and password
- **Keep-alive**: Automatic ping/pong every 30 seconds to maintain connection
- **Graceful shutdown**: Clean disconnection on Ctrl+C

### Error Handling

- Connection timeout protection (15 seconds)
- Helpful error messages for common issues
- Clear feedback for authentication failures

**Note**: If the connection is lost, you'll need to restart the CLI. The connection will be maintained as long as possible using keep-alive pings.

## Features

- 🚀 **Quick Setup** - Get started in seconds
- 🔒 **Secure** - Authenticated WebSocket connections
- 🪝 **Real-time** - Instant webhook delivery via WebSocket
- 📱 **Cross-platform** - Works on Windows, macOS, and Linux
- 🎨 **Beautiful logging** - Fancy webhook display with colors and emojis
- 🛡️ **Error handling** - Clear error messages and guidance
- 📋 **Custom Rules** - Configure webhook responses without code changes
- 🤖 **AI-Powered** - Natural language rule management with OpenAI

## Data Storage

Credentials are stored in platform-specific locations:

- **macOS**: `~/Library/Application Support/hookbox/credentials.json`
- **Linux**: `~/.config/hookbox/credentials.json`
- **Windows**: `%APPDATA%\hookbox\credentials.json`

Rules (optional) are stored in the same directory as `rules.json`.

## Troubleshooting

**WebSocket connection issues:**

- Check your internet connection
- Verify firewall settings
- Try reinitializing with `hookbox purge && hookbox init`

**Connection lost:**

- The CLI will exit when the connection is lost
- Simply run `hookbox start` again to reconnect

**Can't forward to localhost:**

- Ensure your local server is running
- Check the port number is correct
- Verify the application accepts external connections

**Authentication errors:**

- Try running `hookbox init` again to get fresh credentials
- Check if your hookbox instance has expired

**Rule management issues:**

- Make sure you have initialized hookbox first (`hookbox init`)
- Maximum of 10 rules allowed - remove some before adding new ones
- Use descriptive language when adding/removing rules

## Support

Visit [hookbox.io](https://hookbox.io) for more information and support.