# WebSocket SSH Tunnel - Bridge Mode Testing Guide

This document provides comprehensive testing tools and examples for the wsssht bridge mode functionality.

## Overview

Bridge mode provides a **pure transport layer** for WebSocket communication. Unlike other modes, bridge mode does NOT handle tunnel logic - it simply establishes a WebSocket connection and passes ALL messages through stdin/stdout with proper channel identification.

In bridge mode:

- **Pure Transport Layer**: Establishes WebSocket connection to wssshd server
- **Message Passing**: Passes ALL messages from stdin to WebSocket (to server) with channel routing
- **Response Handling**: Passes ALL messages from WebSocket to stdout (from server) with channel identification
- **Channel Routing**: Automatically routes data/control messages to appropriate channels
- **No Tunnel Logic**: Does NOT open local ports or handle tunnel-specific logic
- **No Protocol Logic**: Does NOT send tunnel requests or handle tunnel responses
- **Client Responsibility**: All protocol logic must be implemented by the client application

## Test Scripts

### 1. `test_bridge_mode.sh` - Automated Test Script

A comprehensive automated test script that demonstrates basic bridge mode functionality.

#### Usage:
```bash
# Basic test with default settings
./test_bridge_mode.sh

# Custom client and server
./test_bridge_mode.sh --client-id myclient --host example.com

# With debug output
./test_bridge_mode.sh --debug

# Show help
./test_bridge_mode.sh --help
```

#### Features:
- ✅ Automatic wsssht startup in bridge mode
- ✅ Sends tunnel_request to establish tunnel
- ✅ Waits for tunnel_ack confirmation
- ✅ Sends data message with test string
- ✅ Receives and displays tunnel_response
- ✅ Sends tunnel_close to clean up
- ✅ Monitors and displays all JSON responses
- ✅ Colored output for easy reading
- ✅ Error handling and process management
- ✅ Configurable via environment variables

#### Environment Variables:
```bash
export CLIENT_ID="myclient"        # Client ID
export WSSSHD_HOST="example.com"   # wssshd server hostname
export WSSSHD_PORT="9898"          # wssshd server port
export DEBUG="1"                   # Enable debug output
```

### 2. `test_bridge_interactive.sh` - Interactive Test Script

An interactive testing tool that allows manual JSON command input and real-time response monitoring.

#### Usage:
```bash
# Start interactive mode
./test_bridge_interactive.sh start

# Send specific commands
./test_bridge_interactive.sh status
./test_bridge_interactive.sh quit

# Monitor responses only
./test_bridge_interactive.sh monitor

# Show available commands
./test_bridge_interactive.sh commands
```

#### Interactive Mode Features:
- ✅ Manual JSON command input
- ✅ Real-time response monitoring
- ✅ Command history and help
- ✅ JSON validation
- ✅ Process management and cleanup

## Message Format Examples

### Messages Sent to Server (via stdin)
Any text string is forwarded to the server with automatic channel detection:

#### Control Channel Messages
```json
{"type":"tunnel_request","client_id":"myclient","timestamp":1640995200}
```
**Automatically detected as control channel and sent to control WebSocket channel**

#### Data Channel Messages
```json
{"type":"tunnel_data","data":"base64_encoded_data","timestamp":1640995200}
```
**Automatically detected as data channel and sent to data WebSocket channel**

### Messages Received from Server (via stdout)
All messages are wrapped with channel identification:

#### Control Channel Response
```json
{"type":"message_received","channel":"control","message":"{\"type\":\"tunnel_response\",\"status\":\"success\"}","timestamp":1640995200}
```

#### Data Channel Response
```json
{"type":"message_received","channel":"data","message":"base64_encoded_response_data","timestamp":1640995200}
```

#### WebSocket Events
```json
{"type":"websocket_connected","socket":5,"timestamp":1640995200}
{"type":"ping_received","timestamp":1640995200}
{"type":"pong_received","timestamp":1640995200}
```

### Tunnel Control Channel Messages

These are messages received from the wssshd server and forwarded as JSON through stdout:

#### Tunnel Data Message
```json
{"type":"tunnel_data","message":"{\"request_id\":\"abc123\",\"data\":\"server_response_data\"}","timestamp":1640995200}
```

#### Tunnel Response Message
```json
{"type":"tunnel_response","message":"{\"request_id\":\"abc123\",\"status\":\"success\"}","timestamp":1640995200}
```

#### Tunnel Close Message
```json
{"type":"tunnel_close","message":"{\"request_id\":\"abc123\",\"reason\":\"connection_closed\"}","timestamp":1640995200}
```

#### WebSocket Close Message
```json
{"type":"websocket_close","timestamp":1640995200}
```

#### WebSocket Connection Closed
```json
{"type":"websocket_connection_closed","timestamp":1640995200}
```

### Advanced Commands

#### Custom Command with Data
```json
{"command":"custom","timestamp":1640995200,"data":"additional_info"}
```
**Response:**
```json
{"type":"command_received","command":"{\"command\":\"custom\",\"timestamp\":1640995200,\"data\":\"additional_info\"}","timestamp":1640995200}
```

#### Help Request
```json
{"command":"help","timestamp":1640995200}
```
**Response:**
```json
{"type":"command_received","command":"{\"command\":\"help\",\"timestamp\":1640995200}","timestamp":1640995200}
```

## Bridge Mode Workflow

### 1. Starting Bridge Mode
```bash
./wssshtools/wsssht --bridge --clientid myclient --wssshd-host mbetter.nexlab.net
```

### 2. Initial Responses
Bridge mode sends initial status messages:
```json
{"type":"bridge_started","client_id":"myclient","host":"mbetter.nexlab.net","port":9898,"timestamp":1640995200}
{"type":"websocket_connected","socket":5,"timestamp":1640995200}
{"type":"bridge_ready","message":"Pure transport layer active","timestamp":1640995200}
```

### 3. Message Exchange
Send protocol messages via stdin, receive responses via stdout:
```bash
# Send tunnel request (control channel)
echo '{"type":"tunnel_request","client_id":"myclient","request_id":"req123","tunnel":"any","tunnel_control":"any","service":"ssh","timestamp":1640995200}' | ./wssshtools/wsssht --bridge --clientid myclient --wssshd-host mbetter.nexlab.net

# Receive tunnel acknowledgment (control channel)
{"type":"message_received","channel":"control","message":"{\"type\":\"tunnel_ack\",\"request_id\":\"req123\"}","timestamp":1640995200}

# Send data (data channel) - hex-encoded
echo '{"type":"tunnel_data","request_id":"req123","data":"48656c6c6f","timestamp":1640995200}' | ./wssshtools/wsssht --bridge --clientid myclient --wssshd-host mbetter.nexlab.net

# Receive data response (data channel)
{"type":"message_received","channel":"data","message":"{\"type\":\"tunnel_response\",\"request_id\":\"req123\",\"data\":\"response_data\"}","timestamp":1640995200}

# Send tunnel close (control channel)
echo '{"type":"tunnel_close","request_id":"req123","timestamp":1640995200}' | ./wssshtools/wsssht --bridge --clientid myclient --wssshd-host mbetter.nexlab.net
```

### 4. Transport Layer Operation
While bridge mode is active:
- **Pure Transport**: Only handles WebSocket connection and message routing
- **Channel Routing**: Automatically detects and routes messages to control/data channels
- **No Protocol Logic**: Does NOT interpret or handle tunnel protocol
- **Client Responsibility**: Your application implements all protocol logic

## Testing Scenarios

### Scenario 1: Basic Connectivity Test
```bash
# Test basic bridge mode startup and shutdown
./test_bridge_mode.sh --client-id testclient --host mbetter.nexlab.net
```

### Scenario 2: Interactive Control
```bash
# Start interactive session
./test_bridge_interactive.sh start

# In interactive mode, try:
> {"command":"status","timestamp":1640995200}
> {"command":"ping","timestamp":1640995200}
> quit
```

### Scenario 3: Programmatic Integration
```bash
#!/bin/bash
# Example of programmatic integration

# Start wsssht in background
./wssshtools/wsssht --bridge --clientid myclient --wssshd-host mbetter.nexlab.net &
WSSSHT_PID=$!

# Send commands programmatically
echo '{"command":"status","timestamp":'$(date +%s)'}' > /proc/$WSSSHT_PID/fd/0

# Read responses
while read -r response; do
    echo "Response: $response"
    # Parse JSON and handle accordingly
done < /proc/$WSSSHT_PID/fd/1

# Cleanup
kill $WSSSHT_PID
```

### Scenario 4: Tunnel Control Channel Testing
```bash
# Test tunnel control channel messages
./test_bridge_interactive.sh start

# In interactive mode, you can observe:
# - tunnel_data messages when server sends data
# - tunnel_response messages for server responses
# - tunnel_close messages when tunnel closes
# - websocket_close messages for WebSocket events

# Example: Monitor for 30 seconds to see control messages
timeout 30 ./test_bridge_interactive.sh monitor
```

### Scenario 5: Error Handling
```bash
# Test with invalid client ID
./test_bridge_mode.sh --client-id invalid_client

# Test with unreachable host
./test_bridge_mode.sh --host unreachable.example.com

# Test timeout scenarios
timeout 10 ./test_bridge_mode.sh
```

## Troubleshooting

### Common Issues

#### 1. "wsssht binary not found"
```bash
# Build wsssht first
cd wssshtools
make clean && make

# Or update path in test scripts
WSSSHT="/path/to/wsssht"
```

#### 2. "Failed to establish tunnel"
- Check client ID is registered with wssshd
- Verify wssshd server is running and accessible
- Check network connectivity

#### 3. "No response received"
- Bridge mode may not be fully initialized
- Check if wsssht process is still running
- Verify JSON command format

#### 4. "Invalid JSON"
- Ensure JSON is properly formatted
- Check for missing quotes or brackets
- Use `jq` to validate JSON: `echo '{"test":"data"}' | jq .`

### Debug Mode
Enable debug output for detailed information:
```bash
./test_bridge_mode.sh --debug
# or
DEBUG=1 ./test_bridge_interactive.sh start
```

## Integration Examples

### Python Integration (Pure Transport Layer)
```python
import subprocess
import json
import time

def send_protocol_message(message_type, **kwargs):
    """Send protocol message to wsssht bridge mode (pure transport layer)"""
    cmd = [
        './wssshtools/wsssht',
        '--bridge',
        '--clientid', 'myclient',
        '--wssshd-host', 'mbetter.nexlab.net'
    ]

    proc = subprocess.Popen(
        cmd,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )

    # Create protocol message
    message = {
        'type': message_type,
        'timestamp': int(time.time()),
        **kwargs
    }
    json_msg = json.dumps(message)
    proc.stdin.write(json_msg + '\n')
    proc.stdin.flush()

    # Read responses (your application handles the protocol)
    while True:
        response = proc.stdout.readline().strip()
        if not response:
            break
        parsed = json.loads(response)
        print(f"Received: {parsed}")

        # Your application implements protocol logic here
        if parsed['type'] == 'message_received':
            server_msg = json.loads(parsed['message'])
            if server_msg.get('type') == 'tunnel_response':
                print("Tunnel established!")
                return True
            elif server_msg.get('type') == 'error':
                print(f"Error: {server_msg.get('message')}")
                return False

    return False

# Usage - your application handles the protocol
success = send_protocol_message('tunnel_request', client_id='myclient')
```

### Node.js Integration (Pure Transport Layer)
```javascript
const { spawn } = require('child_process');

function startBridgeMode() {
    const wsssht = spawn('./wssshtools/wsssht', [
        '--bridge',
        '--clientid', 'myclient',
        '--wssshd-host', 'mbetter.nexlab.net'
    ]);

    // Send protocol message (your application handles the protocol)
    const tunnelRequest = JSON.stringify({
        type: 'tunnel_request',
        client_id: 'myclient',
        timestamp: Math.floor(Date.now() / 1000)
    });

    wsssht.stdin.write(tunnelRequest + '\n');

    // Handle responses (your application handles the protocol)
    wsssht.stdout.on('data', (data) => {
        const response = JSON.parse(data.toString().trim());
        console.log('Received:', response);

        // Your application implements protocol logic here
        if (response.type === 'message_received') {
            const serverMessage = JSON.parse(response.message);
            if (serverMessage.type === 'tunnel_response') {
                console.log('Tunnel established!');
            } else if (serverMessage.type === 'tunnel_data') {
                // Handle tunnel data
                console.log('Received data:', serverMessage.data);
            }
        }
    });

    wsssht.stderr.on('data', (data) => {
        console.error('Error:', data.toString());
    });

    return wsssht;
}

// Usage - your application handles the protocol
const proc = startBridgeMode();

// Cleanup on exit
process.on('SIGINT', () => {
    proc.kill();
    process.exit();
});
```

## Best Practices

### 1. Message Format
- Any text format is supported (JSON, plain text, custom protocols)
- Handle responses asynchronously in your application
- Implement proper message framing for your protocol

### 2. Error Handling
- Check process exit codes
- Monitor for WebSocket connection status
- Validate message formats in your application

### 3. Resource Management
- Properly terminate wsssht processes
- Handle signals gracefully
- Clean up file descriptors

### 4. Security
- Validate input data in your application
- Use secure WebSocket connections (wss://)
- Implement proper authentication in your protocol

### 5. Channel Management
- Use appropriate message types for control vs data channels
- Handle channel-specific routing in your application
- Monitor both channels for complete protocol implementation

## Files Created

- `test_bridge_mode.sh` - Automated test script
- `test_bridge_interactive.sh` - Interactive test script
- `BRIDGE_MODE_TESTING.md` - This documentation

## Next Steps

1. **Build wsssht**: Ensure wsssht is compiled and executable
2. **Configure wssshd**: Set up wssshd server with client registration
3. **Run tests**: Use the provided test scripts to verify functionality
4. **Integrate**: Use the examples to integrate bridge mode into your applications

For additional support, refer to the main wsssht documentation or check the project repository.