licensechain 1.0.4

LicenseChain Rust SDK for license management and validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# LicenseChain Rust SDK

[![License](https://img.shields.io/badge/license-Elastic--2.0-blue.svg)](LICENSE)
[![Rust](https://img.shields.io/badge/Rust-1.85+-blue.svg)](https://www.rust-lang.org/)
[![Crates.io](https://img.shields.io/crates/v/licensechain)](https://crates.io/crates/licensechain)
[![Documentation](https://docs.rs/licensechain/badge.svg)](https://docs.rs/licensechain)

Official Rust SDK for LicenseChain - Secure license management for Rust applications.

## ๐Ÿš€ Features

- **๐Ÿ” Secure Authentication** - User registration, login, and session management
- **๐Ÿ“œ License Management** - Create, validate, update, and revoke licenses
- **๐Ÿ›ก๏ธ Hardware ID Validation** - Prevent license sharing and unauthorized access
- **๐Ÿ”” Webhook Support** - Real-time license events and notifications
- **๐Ÿ“Š Analytics Integration** - Track license usage and performance metrics
- **โšก High Performance** - Optimized for production workloads
- **๐Ÿ”„ Async Operations** - Non-blocking HTTP requests and data processing
- **๐Ÿ› ๏ธ Easy Integration** - Simple API with comprehensive documentation

## ๐Ÿ“ฆ Installation

### Method 1: Cargo (Recommended)

Add to your `Cargo.toml`:

```toml
[dependencies]
licensechain = "1.0.4"
```

### Method 2: Git Repository

```toml
[dependencies]
licensechain = { git = "https://github.com/LicenseChain/LicenseChain-Rust-SDK.git" }
```

### Method 3: Local Path

```toml
[dependencies]
licensechain = { path = "path/to/licensechain" }
```

## ๐Ÿš€ Quick Start

### Basic Setup

```rust
use licensechain_sdk::{LicenseChainClient, LicenseChainConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize the client
    let config = LicenseChainConfig::new()
        .api_key("your-api-key")
        .app_name("your-app-name")
        .version("1.0.0");
        
    let mut client = LicenseChainClient::new(config);
    
    // Connect to LicenseChain
    client.connect().await?;
    println!("Connected to LicenseChain successfully!");
    
    Ok(())
}
```

### User Authentication

```rust
// Register a new user
match client.register("username", "password", "email@example.com").await {
    Ok(user) => {
        println!("User registered successfully!");
        println!("User ID: {}", user.id);
    }
    Err(e) => eprintln!("Registration failed: {}", e),
}

// Login existing user
match client.login("username", "password").await {
    Ok(user) => {
        println!("User logged in successfully!");
        println!("Session ID: {}", user.session_id);
    }
    Err(e) => eprintln!("Login failed: {}", e),
}
```

### License Management

```rust
// Validate a license
match client.validate_license("LICENSE-KEY-HERE").await {
    Ok(license) => {
        println!("License is valid!");
        println!("License Key: {}", license.key);
        println!("Status: {}", license.status);
        println!("Expires: {}", license.expires);
        println!("Features: {:?}", license.features);
        println!("User: {}", license.user);
    }
    Err(e) => eprintln!("License validation failed: {}", e),
}

// Get user's licenses
match client.get_user_licenses().await {
    Ok(licenses) => {
        println!("Found {} licenses:", licenses.len());
        for (i, license) in licenses.iter().enumerate() {
            println!("  {}. {} - {} (Expires: {})", 
                i + 1, license.key, license.status, license.expires);
        }
    }
    Err(e) => eprintln!("Failed to get licenses: {}", e),
}
```

### Hardware ID Validation

```rust
// Get hardware ID (automatically generated)
let hardware_id = client.get_hardware_id();
println!("Hardware ID: {}", hardware_id);

// Validate hardware ID with license
match client.validate_hardware_id("LICENSE-KEY-HERE", &hardware_id).await {
    Ok(is_valid) => {
        if is_valid {
            println!("Hardware ID is valid for this license!");
        } else {
            println!("Hardware ID is not valid for this license.");
        }
    }
    Err(e) => eprintln!("Hardware ID validation failed: {}", e),
}
```

### Webhook Integration

```rust
// Set up webhook handler
client.set_webhook_handler(|event, data| {
    println!("Webhook received: {}", event);
    
    match event.as_str() {
        "license.created" => {
            if let Some(license_key) = data.get("licenseKey") {
                println!("New license created: {}", license_key);
            }
        }
        "license.updated" => {
            if let Some(license_key) = data.get("licenseKey") {
                println!("License updated: {}", license_key);
            }
        }
        "license.revoked" => {
            if let Some(license_key) = data.get("licenseKey") {
                println!("License revoked: {}", license_key);
            }
        }
        _ => {}
    }
});

// Start webhook listener
client.start_webhook_listener().await?;
```

## ๐ŸŒ API Endpoints

Use the canonical LicenseChain API base URL `https://api.licensechain.app/v1`. The SDK also accepts the root host and normalizes requests to the same API version.

### Base URL
```
https://api.licensechain.app/v1
```

### Available Endpoints

All endpoints use the `/v1` prefix:

- **Health Check**: `GET /v1/health`
- **Authentication**:
  - `POST /v1/auth/register` - Register new user
  - `POST /v1/auth/login` - User login
  - `GET /v1/auth/me` - Get current user
  - `POST /v1/auth/logout` - User logout
- **Applications**:
  - `GET /v1/apps` - List all apps
  - `GET /v1/apps/:id` - Get app by ID
  - `POST /v1/apps` - Create new app
  - `PUT /v1/apps/:id` - Update app
  - `DELETE /v1/apps/:id` - Delete app
- **Licenses**:
  - `GET /v1/licenses` - List licenses
  - `GET /v1/licenses/:id` - Get license by ID
  - `POST /v1/apps/:id/licenses` - Create license
  - `POST /v1/licenses/verify` - Verify license key
  - `PATCH /v1/licenses/:id` - Update license
  - `PATCH /v1/licenses/:id/revoke` - Revoke license
- **Webhooks**:
  - `GET /v1/webhooks` - List webhooks
  - `POST /v1/webhooks` - Create webhook
  - `GET /v1/webhooks/:id` - Get webhook by ID
  - `PUT /v1/webhooks/:id` - Update webhook
  - `DELETE /v1/webhooks/:id` - Delete webhook
- **Analytics**:
  - `GET /v1/analytics/stats` - Get analytics data

> **Note**: The SDK accepts either the root host or the canonical `/v1` base and normalizes endpoint calls automatically.

## ๐Ÿ“š API Reference

### LicenseChainClient

#### Constructor

```rust
let config = LicenseChainConfig::new()
    .api_key("your-api-key")
    .app_name("your-app-name")
    .version("1.0.0")
    .base_url("https://api.licensechain.app/v1"); // Optional
    
let mut client = LicenseChainClient::new(config);
```

#### Methods

##### Connection Management

```rust
// Connect to LicenseChain
client.connect().await?;

// Disconnect from LicenseChain
client.disconnect().await?;

// Check connection status
let is_connected = client.is_connected();
```

##### User Authentication

```rust
// Register a new user
let user = client.register(username, password, email).await?;

// Login existing user
let user = client.login(username, password).await?;

// Logout current user
client.logout().await?;

// Get current user info
let user = client.get_current_user().await?;
```

##### License Management

```rust
// Validate a license
let license = client.validate_license(license_key).await?;

// Get user's licenses
let licenses = client.get_user_licenses().await?;

// Create a new license
let license = client.create_license(app_id, user_email, metadata).await?;

// Update a license
let license = client.update_license(license_key, updates).await?;

// Revoke a license
client.revoke_license(license_key).await?;

// Extend a license
let license = client.extend_license(license_key, days).await?;
```

##### Hardware ID Management

```rust
// Get hardware ID
let hardware_id = client.get_hardware_id();

// Validate hardware ID
let is_valid = client.validate_hardware_id(license_key, &hardware_id).await?;

// Bind hardware ID to license
client.bind_hardware_id(license_key, &hardware_id).await?;
```

##### Webhook Management

```rust
// Set webhook handler
client.set_webhook_handler(handler);

// Start webhook listener
client.start_webhook_listener().await?;

// Stop webhook listener
client.stop_webhook_listener().await?;
```

##### Analytics

```rust
// Track event
let mut properties = HashMap::new();
properties.insert("level".to_string(), "1".to_string());
properties.insert("playerCount".to_string(), "10".to_string());
client.track_event("app.started", properties).await?;

// Get analytics data
let analytics = client.get_analytics(time_range).await?;
```

## ๐Ÿ”ง Configuration

### Environment Variables

Set these in your environment or through your build process:

```bash
# Required
export LICENSECHAIN_API_KEY=your-api-key
export LICENSECHAIN_APP_NAME=your-app-name
export LICENSECHAIN_APP_VERSION=1.0.0

# Optional
export LICENSECHAIN_BASE_URL=https://api.licensechain.app/v1
export LICENSECHAIN_DEBUG=true
```

### Advanced Configuration

```rust
let config = LicenseChainConfig::new()
    .api_key("your-api-key")
    .app_name("your-app-name")
    .version("1.0.0")
    .base_url("https://api.licensechain.app/v1")
    .timeout(Duration::from_secs(30))  // Request timeout
    .retries(3)                        // Number of retry attempts
    .debug(false)                      // Enable debug logging
    .user_agent("MyApp/1.0.0");       // Custom user agent
```

## ๐Ÿ›ก๏ธ Security Features

### Hardware ID Protection

The SDK automatically generates and manages hardware IDs to prevent license sharing:

```rust
// Hardware ID is automatically generated and stored
let hardware_id = client.get_hardware_id();

// Validate against license
let is_valid = client.validate_hardware_id(license_key, &hardware_id).await?;
```

### Secure Communication

- All API requests use HTTPS
- API keys are securely stored and transmitted
- Session tokens are automatically managed
- Webhook signatures are verified

### License Validation

- Real-time license validation
- Hardware ID binding
- Expiration checking
- Feature-based access control

## ๐Ÿ“Š Analytics and Monitoring

### Event Tracking

```rust
// Track custom events
let mut properties = HashMap::new();
properties.insert("level".to_string(), "1".to_string());
properties.insert("playerCount".to_string(), "10".to_string());
client.track_event("app.started", properties).await?;

// Track license events
let mut license_properties = HashMap::new();
license_properties.insert("licenseKey".to_string(), "LICENSE-KEY".to_string());
license_properties.insert("features".to_string(), "premium,unlimited".to_string());
client.track_event("license.validated", license_properties).await?;
```

### Performance Monitoring

```rust
// Get performance metrics
let metrics = client.get_performance_metrics().await?;
println!("API Response Time: {}ms", metrics.average_response_time);
println!("Success Rate: {:.2}%", metrics.success_rate * 100.0);
println!("Error Count: {}", metrics.error_count);
```

## ๐Ÿ”„ Error Handling

### Custom Error Types

```rust
match client.validate_license("invalid-key").await {
    Ok(license) => {
        // Handle valid license
    }
    Err(LicenseChainError::InvalidLicense) => {
        eprintln!("License key is invalid");
    }
    Err(LicenseChainError::ExpiredLicense) => {
        eprintln!("License has expired");
    }
    Err(LicenseChainError::NetworkError(e)) => {
        eprintln!("Network connection failed: {}", e);
    }
    Err(e) => {
        eprintln!("LicenseChain error: {}", e);
    }
}
```

### Retry Logic

```rust
// Automatic retry for network errors
let config = LicenseChainConfig::new()
    .api_key("your-api-key")
    .app_name("your-app-name")
    .version("1.0.0")
    .retries(3)                        // Retry up to 3 times
    .timeout(Duration::from_secs(30)); // Wait 30 seconds for each request
```

## ๐Ÿงช Testing

### Unit Tests

```bash
# Run tests
cargo test

# Run tests with output
cargo test -- --nocapture

# Run specific test
cargo test test_validate_license
```

### Integration Tests

```bash
# Test with real API
cargo test --test integration_tests
```

## ๐Ÿ“ Examples

See the `examples/` directory:

- `basic_usage.rs` โ€” Basic SDK usage
- `license_assertion_jwks.rs` โ€” `POST /v1/licenses/verify` then RS256 **`license_token`** via JWKS (`cargo run --example license_assertion_jwks`; JWKS at `https://api.licensechain.app/v1/licenses/jwks`)
- `jwks_only.rs` โ€” token + `license_jwks_uri` only (`cargo run --example jwks_only`; [JWKS_EXAMPLE_PRIORITY]https://docs.licensechain.app/)

## ๐Ÿค Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

1. Clone the repository
2. Install Rust 1.85 or later
3. Build: `cargo build`
4. Test: `cargo test`

## ๐Ÿ“„ License

This project is licensed under the Elastic License 2.0 (ELv2) โ€” see the [LICENSE](LICENSE) file for details.

## ๐Ÿ†˜ Support

- **Documentation**: [https://docs.licensechain.app/en/sdk]https://docs.licensechain.app/en/sdk
- **Issues**: [GitHub Issues]https://github.com/LicenseChain/LicenseChain-Rust-SDK/issues
- **Discord**: [LicenseChain Discord]https://discord.gg/licensechain
- **Email**: support@licensechain.app

## ๐Ÿ”— Related Projects

- [LicenseChain JavaScript SDK]https://github.com/LicenseChain/LicenseChain-JavaScript-SDK
- [LicenseChain Python SDK]https://github.com/LicenseChain/LicenseChain-Python-SDK
- [LicenseChain Node.js SDK]https://github.com/LicenseChain/LicenseChain-NodeJS-SDK
---

**Made with โค๏ธ for the Rust community**

## LicenseChain API (v1)

This SDK targets the **LicenseChain HTTP API v1** implemented by the LicenseChain API service.

- **Production base URL:** https://api.licensechain.app/v1
- **API reference:** [docs.licensechain.app]https://docs.licensechain.app/
- **Baseline REST mapping (documented for integrators):**
  - GET /health
  - POST /auth/register
  - POST /licenses/verify
  - PATCH /licenses/:id/revoke
  - PATCH /licenses/:id/activate
  - PATCH /licenses/:id/extend
  - GET /analytics/stats