initial commit

This commit is contained in:
Timur Gordon
2025-07-29 01:15:23 +02:00
commit 7d7ff0f0ab
108 changed files with 24713 additions and 0 deletions

View File

@@ -0,0 +1,136 @@
# Circles WebSocket Client
A WebSocket client for connecting to Circles servers with authentication support. Available in both CLI and WebAssembly (WASM) versions.
## CLI Usage
### Installation
Build the CLI binary:
```bash
cargo build --bin circles_client --release
```
### Configuration
Create a `.env` file in the `cmd/` directory:
```bash
# cmd/.env
PRIVATE_KEY=your_actual_private_key_hex_here
```
Or set the environment variable directly:
```bash
export PRIVATE_KEY=your_actual_private_key_hex_here
```
### Usage
```bash
# Basic usage - connects and enters interactive mode
circles_client ws://localhost:8080
# Execute a single Rhai script
circles_client -s "print('Hello from Rhai!')" ws://localhost:8080
# Execute a script from file
circles_client -f script.rhai ws://localhost:8080
# Increase verbosity (can be used multiple times)
circles_client -v ws://localhost:8080
circles_client -vv ws://localhost:8080
```
### Features
- **Authentication**: Automatically loads private key and completes secp256k1 authentication flow
- **Script Execution**: Supports both inline scripts (`-s`) and script files (`-f`)
- **Interactive Mode**: When no script is provided, enters interactive REPL mode
- **Verbosity Control**: Use `-v` flags to increase logging detail
- **Cross-platform**: Works on all platforms supported by Rust and tokio-tungstenite
## WebAssembly (WASM) Usage
### Build and Serve
1. Install Trunk:
```bash
cargo install trunk
```
2. Build the WASM version:
```bash
trunk build --release
```
3. Serve the application:
```bash
trunk serve
```
The application will be available at `http://localhost:8080`
### Usage in Browser
1. Open the served page in your browser
2. Enter the WebSocket server URL
3. Choose either:
- Execute a Rhai script directly
- Enter interactive mode (type 'exit' or 'quit' to leave)
### Features
- **Browser Integration**: Uses browser's WebSocket implementation
- **Interactive Mode**: Browser-based input/output using prompts
- **Error Handling**: Browser console logging
- **Cross-browser**: Works in all modern browsers supporting WebAssembly
## Common Features
Both versions share the same core functionality:
- **WebSocket Connection**: Connects to Circles WebSocket server
- **Authentication**: Handles secp256k1 authentication
- **Script Execution**: Executes Rhai scripts
- **Interactive Mode**: Provides REPL-like interface
- **Error Handling**: Comprehensive error reporting
- **Logging**: Detailed logging at different verbosity levels
### Interactive Mode
When run without `-s` or `-f` flags, the client enters interactive mode where you can:
- Enter Rhai scripts line by line
- Type `exit` or `quit` to close the connection
- Use Ctrl+C to terminate
### Examples
```bash
# Connect to local development server
circles_client ws://localhost:8080
# Connect to secure WebSocket with verbose logging
circles_client -v wss://circles.example.com/ws
# Execute a simple calculation
circles_client -s "let result = 2 + 2; print(result);" ws://localhost:8080
# Load and execute a complex script
circles_client -f examples/complex_script.rhai ws://localhost:8080
```
### Error Handling
The client provides clear error messages for common issues:
- Missing or invalid private key
- Connection failures
- Authentication errors
- Script execution errors
### Dependencies
- `tokio-tungstenite`: WebSocket client implementation
- `secp256k1`: Cryptographic authentication
- `clap`: Command-line argument parsing
- `env_logger`: Logging infrastructure
- `dotenv`: Environment variable loading

View File

@@ -0,0 +1,118 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Circles WebSocket Client</title>
<link data-trunk rel="rust" href="../Cargo.toml" data-wasm-opt="z" />
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
margin: 20px;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.input-group {
margin-bottom: 20px;
}
input[type="text"] {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
width: 100%;
margin-top: 8px;
}
button {
background: #007bff;
color: white;
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: #0056b3;
}
pre {
background: #f5f5f5;
padding: 15px;
border-radius: 4px;
overflow-x: auto;
}
</style>
</head>
<body>
<div class="container">
<h1>Circles WebSocket Client</h1>
<div class="input-group">
<label for="ws-url">WebSocket URL:</label>
<input type="text" id="ws-url" placeholder="ws://localhost:8080">
</div>
<div class="input-group">
<label for="script">Rhai Script:</label>
<input type="text" id="script" placeholder="Enter Rhai script here">
</div>
<button id="run-script">Run Script</button>
<button id="run-interactive">Interactive Mode</button>
<div id="output" style="margin-top: 20px;">
<h2>Output:</h2>
<pre id="output-content"></pre>
</div>
</div>
<script type="module">
// Trunk will inject the necessary JS to load the WASM module.
// The wasm_bindgen functions will be available on the `window` object.
async function main() {
// The `wasm_bindgen` object is exposed globally by the Trunk-injected script.
const { start_client } = wasm_bindgen;
document.getElementById('run-script').addEventListener('click', async () => {
const url = document.getElementById('ws-url').value;
const script = document.getElementById('script').value;
if (!url) {
alert('Please enter a WebSocket URL');
return;
}
try {
// The init function is called automatically by Trunk's setup.
const result = await start_client(url, script);
document.getElementById('output-content').textContent = result;
} catch (error) {
console.error('Error:', error);
document.getElementById('output-content').textContent = `Error: ${error}`;
}
});
document.getElementById('run-interactive').addEventListener('click', async () => {
const url = document.getElementById('ws-url').value;
if (!url) {
alert('Please enter a WebSocket URL');
return;
}
try {
// The init function is called automatically by Trunk's setup.
await start_client(url, null);
} catch (error) {
console.error('Error:', error);
alert(`Error: ${error}`);
}
});
}
// The `wasm_bindgen` function is a promise that resolves when the WASM is loaded.
wasm_bindgen('./pkg/circle_client_ws_bg.wasm').then(main).catch(console.error);
</script>
</body>
</html>

View File

@@ -0,0 +1,342 @@
#![cfg_attr(target_arch = "wasm32", no_main)]
use hero_websocket_client::CircleWsClientBuilder;
#[cfg(not(target_arch = "wasm32"))]
use std::env;
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
#[cfg(not(target_arch = "wasm32"))]
use std::io::{self, Write};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
use web_sys::{console, window};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::spawn_local;
#[cfg(not(target_arch = "wasm32"))]
use clap::{Arg, ArgAction, Command};
#[cfg(not(target_arch = "wasm32"))]
use dotenv::dotenv;
#[cfg(not(target_arch = "wasm32"))]
use env_logger;
#[cfg(not(target_arch = "wasm32"))]
use tokio;
#[cfg(not(target_arch = "wasm32"))]
use log::{error, info};
#[derive(Debug)]
struct Args {
ws_url: String,
script: Option<String>,
script_path: Option<String>,
verbose: u8,
no_timestamp: bool,
}
#[cfg(not(target_arch = "wasm32"))]
fn parse_args() -> Args {
let matches = Command::new("circles_client")
.version("0.1.0")
.about("WebSocket client for Circles server")
.arg(
Arg::new("url")
.help("WebSocket server URL")
.required(true)
.index(1),
)
.arg(
Arg::new("script")
.short('s')
.long("script")
.value_name("SCRIPT")
.help("Rhai script to execute")
.conflicts_with("script_path"),
)
.arg(
Arg::new("script_path")
.short('f')
.long("file")
.value_name("FILE")
.help("Path to Rhai script file")
.conflicts_with("script"),
)
.arg(
Arg::new("verbose")
.short('v')
.long("verbose")
.help("Increase verbosity (can be used multiple times)")
.action(ArgAction::Count),
)
.arg(
Arg::new("no_timestamp")
.long("no-timestamp")
.help("Remove timestamps from log output")
.action(ArgAction::SetTrue),
)
.get_matches();
Args {
ws_url: matches.get_one::<String>("url").unwrap().clone(),
script: matches.get_one::<String>("script").cloned(),
script_path: matches.get_one::<String>("script_path").cloned(),
verbose: matches.get_count("verbose"),
no_timestamp: matches.get_flag("no_timestamp"),
}
}
#[cfg(not(target_arch = "wasm32"))]
fn setup_logging(verbose: u8, no_timestamp: bool) {
let log_level = match verbose {
0 => "warn,hero_websocket_client=info",
1 => "info,hero_websocket_client=debug",
2 => "debug",
_ => "trace",
};
std::env::set_var("RUST_LOG", log_level);
// Configure env_logger with or without timestamps
if no_timestamp {
env_logger::Builder::from_default_env()
.format_timestamp(None)
.init();
} else {
env_logger::init();
}
}
#[cfg(not(target_arch = "wasm32"))]
fn load_private_key() -> Result<String, Box<dyn std::error::Error>> {
// Try to load from .env file first
if let Ok(_) = dotenv() {
if let Ok(key) = env::var("PRIVATE_KEY") {
return Ok(key);
}
}
// Try to load from cmd/.env file
let cmd_env_path = Path::new("cmd/.env");
if cmd_env_path.exists() {
dotenv::from_path(cmd_env_path)?;
if let Ok(key) = env::var("PRIVATE_KEY") {
return Ok(key);
}
}
Err("PRIVATE_KEY not found in environment or .env files".into())
}
#[cfg(target_arch = "wasm32")]
async fn run_interactive_mode(client: hero_websocket_client::CircleWsClient) -> Result<(), Box<dyn std::error::Error>> {
console::log_1(&"Entering interactive mode. Type 'exit' or 'quit' to leave.".into());
console::log_1(&"🔄 Interactive mode - Enter Rhai scripts (type 'exit' or 'quit' to leave):\n".into());
// In wasm32, we need to use browser's console for input/output
let window = window().expect("Window not available");
let input = window.prompt_with_message("Enter Rhai script (or 'exit' to quit):")
.map_err(|e| format!("Failed to get input: {:#?}", e))? // Use debug formatting
.unwrap_or_default();
// Handle empty or exit cases
if input == "exit" || input == "quit" {
console::log_1(&"👋 Goodbye!".into());
return Ok(());
}
// Execute the script
match client.play(input).await {
Ok(result) => {
console::log_1(&format!("📤 Result: {}", result.output).into());
}
Err(e) => {
console::log_1(&format!("❌ Script execution failed: {}", e).into());
}
}
Ok(())
}
#[cfg(target_arch = "wasm32")]
async fn execute_script(client: hero_websocket_client::CircleWsClient, script: String) -> Result<(), Box<dyn std::error::Error>> {
console::log_1(&format!("Executing script: {}", script).into());
match client.play(script).await {
Ok(result) => {
console::log_1(&result.output.into());
Ok(())
}
Err(e) => {
console::log_1(&format!("Script execution failed: {}", e).into());
Err(e.into())
}
}
}
#[cfg(target_arch = "wasm32")]
pub async fn start_client(url: &str, script: Option<String>) -> Result<(), Box<dyn std::error::Error>> {
// Build client
let mut client = CircleWsClientBuilder::new(url.to_string())
.build();
// Connect to WebSocket server
console::log_1(&"🔌 Connecting to WebSocket server...".into());
if let Err(e) = client.connect().await {
console::log_1(&format!("❌ Failed to connect: {}", e).into());
return Err(e.into());
}
console::log_1(&"✅ Connected successfully".into());
// Authenticate with server
if let Err(e) = client.authenticate().await {
console::log_1(&format!("❌ Authentication failed: {}", e).into());
return Err(e.into());
}
console::log_1(&"✅ Authentication successful".into());
// Handle script execution
if let Some(script) = script {
execute_script(client, script).await
} else {
run_interactive_mode(client).await
}
}
#[cfg(not(target_arch = "wasm32"))]
async fn execute_script(client: hero_websocket_client::CircleWsClient, script: String) -> Result<(), Box<dyn std::error::Error>> {
info!("Executing script: {}", script);
match client.play(script).await {
Ok(result) => {
println!("{}", result.output);
Ok(())
}
Err(e) => {
error!("Script execution failed: {}", e);
Err(e.into())
}
}
}
#[cfg(not(target_arch = "wasm32"))]
async fn load_script_from_file(path: &str) -> Result<String, Box<dyn std::error::Error>> {
let script = tokio::fs::read_to_string(path).await?;
Ok(script)
}
#[cfg(not(target_arch = "wasm32"))]
async fn run_interactive_mode(client: hero_websocket_client::CircleWsClient) -> Result<(), Box<dyn std::error::Error>> {
println!("\n🔄 Interactive mode - Enter Rhai scripts (type 'exit' or 'quit' to leave):\n");
loop {
print!("Enter Rhai script (or 'exit' to quit): ");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let input = input.trim().to_string();
if input == "exit" || input == "quit" {
println!("\n👋 Goodbye!");
return Ok(());
}
match client.play(input).await {
Ok(result) => {
println!("\n📤 Result: {}", result.output);
}
Err(e) => {
error!("❌ Script execution failed: {}", e);
println!("\n❌ Script execution failed: {}", e);
}
}
println!();
}
}
#[cfg(not(target_arch = "wasm32"))]
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = parse_args();
setup_logging(args.verbose, args.no_timestamp);
info!("🚀 Starting Circles WebSocket client");
info!("📡 Connecting to: {}", args.ws_url);
// Load private key from environment
let private_key = match load_private_key() {
Ok(key) => {
info!("🔑 Private key loaded from environment");
key
}
Err(e) => {
error!("❌ Failed to load private key: {}", e);
eprintln!("Error: {}", e);
eprintln!("Please set PRIVATE_KEY in your environment or create a cmd/.env file with:");
eprintln!("PRIVATE_KEY=your_private_key_here");
std::process::exit(1);
}
};
// Build client with private key
let mut client = CircleWsClientBuilder::new(args.ws_url.clone())
.with_keypair(private_key)
.build();
// Connect to WebSocket server
info!("🔌 Connecting to WebSocket server...");
if let Err(e) = client.connect().await {
error!("❌ Failed to connect: {}", e);
eprintln!("Connection failed: {}", e);
std::process::exit(1);
}
info!("✅ Connected successfully");
// Authenticate with server
info!("🔐 Authenticating with server...");
match client.authenticate().await {
Ok(true) => {
info!("✅ Authentication successful");
println!("🔐 Authentication successful");
}
Ok(false) => {
error!("❌ Authentication failed");
eprintln!("Authentication failed");
std::process::exit(1);
}
Err(e) => {
error!("❌ Authentication error: {}", e);
eprintln!("Authentication error: {}", e);
std::process::exit(1);
}
}
// Determine execution mode
let result = if let Some(script) = args.script {
// Execute provided script and exit
execute_script(client, script).await
} else if let Some(script_path) = args.script_path {
// Load script from file and execute
match load_script_from_file(&script_path).await {
Ok(script) => execute_script(client, script).await,
Err(e) => {
error!("❌ Failed to load script from file '{}': {}", script_path, e);
eprintln!("Failed to load script file: {}", e);
std::process::exit(1);
}
}
} else {
// Enter interactive mode
run_interactive_mode(client).await
};
// Handle any errors from execution
if let Err(e) = result {
error!("❌ Execution failed: {}", e);
std::process::exit(1);
}
info!("🏁 Client finished successfully");
Ok(())
}