|
| 1 | +# Pubky Noise Integration Guide |
| 2 | + |
| 3 | +This guide covers integrating the Pubky Noise library into your application for secure, authenticated communication. |
| 4 | + |
| 5 | +## Quick Start |
| 6 | + |
| 7 | +### Installation |
| 8 | + |
| 9 | +Add to your `Cargo.toml`: |
| 10 | + |
| 11 | +```toml |
| 12 | +[dependencies] |
| 13 | +pubky-noise = "0.7" |
| 14 | +``` |
| 15 | + |
| 16 | +### Basic Usage |
| 17 | + |
| 18 | +```rust |
| 19 | +use pubky_noise::prelude::*; |
| 20 | +use std::sync::Arc; |
| 21 | + |
| 22 | +// Create key providers |
| 23 | +let client_ring = Arc::new(DummyRing::new([1u8; 32], "client_kid")); |
| 24 | +let server_ring = Arc::new(DummyRing::new([2u8; 32], "server_kid")); |
| 25 | + |
| 26 | +// Create client and server |
| 27 | +let client = NoiseClient::<_, ()>::new_direct("client_kid", b"device", client_ring); |
| 28 | +let server = NoiseServer::<_, ()>::new_direct("server_kid", b"device", server_ring); |
| 29 | +``` |
| 30 | + |
| 31 | +## Core Concepts |
| 32 | + |
| 33 | +### Key Providers |
| 34 | + |
| 35 | +The `RingKeyProvider` trait provides cryptographic keys for the Noise handshake: |
| 36 | + |
| 37 | +```rust |
| 38 | +pub trait RingKeyProvider: Send + Sync { |
| 39 | + fn get_private_key(&self) -> Result<[u8; 32], NoiseError>; |
| 40 | + fn get_public_key(&self) -> Result<[u8; 32], NoiseError>; |
| 41 | + fn get_key_id(&self) -> &str; |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +For testing, use `DummyRing`. For production, implement this trait with secure key storage. |
| 46 | + |
| 47 | +### Handshake Patterns |
| 48 | + |
| 49 | +**IK Pattern** (known server key): |
| 50 | +- Client already knows the server's static public key |
| 51 | +- Faster handshake (2 messages instead of 3) |
| 52 | +- Use when connecting to known servers |
| 53 | + |
| 54 | +**XX Pattern** (trust-on-first-use): |
| 55 | +- Neither party knows the other's key in advance |
| 56 | +- 3-message handshake |
| 57 | +- Use for peer-to-peer connections |
| 58 | + |
| 59 | +### Error Handling |
| 60 | + |
| 61 | +All errors are typed and include error codes for FFI compatibility: |
| 62 | + |
| 63 | +```rust |
| 64 | +use pubky_noise::{NoiseError, NoiseErrorCode}; |
| 65 | + |
| 66 | +match result { |
| 67 | + Err(e) => { |
| 68 | + let code = e.code(); // For FFI/mobile |
| 69 | + let msg = e.message(); // Human-readable |
| 70 | + |
| 71 | + if e.is_retryable() { |
| 72 | + if let Some(delay) = e.retry_after_ms() { |
| 73 | + // Wait and retry |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + Ok(value) => { /* success */ } |
| 78 | +} |
| 79 | +``` |
| 80 | + |
| 81 | +### Rate Limiting |
| 82 | + |
| 83 | +Protect your server from DoS attacks: |
| 84 | + |
| 85 | +```rust |
| 86 | +use pubky_noise::{RateLimiter, RateLimiterConfig}; |
| 87 | + |
| 88 | +// Use default config or customize |
| 89 | +let limiter = RateLimiter::new(RateLimiterConfig::default()); |
| 90 | + |
| 91 | +// Or use predefined configs |
| 92 | +let strict = RateLimiter::new(RateLimiterConfig::strict()); |
| 93 | +let lenient = RateLimiter::new(RateLimiterConfig::lenient()); |
| 94 | + |
| 95 | +// Check before accepting connections |
| 96 | +let client_ip = "192.168.1.1".parse().unwrap(); |
| 97 | +if limiter.check_and_record(&client_ip) { |
| 98 | + // Accept connection |
| 99 | +} else { |
| 100 | + // Reject - rate limited |
| 101 | +} |
| 102 | +``` |
| 103 | + |
| 104 | +## Mobile Integration |
| 105 | + |
| 106 | +### Using NoiseManager |
| 107 | + |
| 108 | +The `NoiseManager` provides a high-level API for mobile applications: |
| 109 | + |
| 110 | +```rust |
| 111 | +use pubky_noise::{NoiseManager, MobileConfig, ConnectionStatus}; |
| 112 | + |
| 113 | +let config = MobileConfig { |
| 114 | + auto_reconnect: true, |
| 115 | + reconnect_interval_ms: 5000, |
| 116 | + max_reconnect_attempts: 10, |
| 117 | + // ... |
| 118 | +}; |
| 119 | + |
| 120 | +let manager = NoiseManager::new(config, key_provider); |
| 121 | +``` |
| 122 | + |
| 123 | +### FFI Bindings |
| 124 | + |
| 125 | +Enable UniFFI bindings with the `uniffi_macros` feature: |
| 126 | + |
| 127 | +```toml |
| 128 | +[dependencies] |
| 129 | +pubky-noise = { version = "0.7", features = ["uniffi_macros"] } |
| 130 | +``` |
| 131 | + |
| 132 | +## Session Management |
| 133 | + |
| 134 | +### Session IDs |
| 135 | + |
| 136 | +Sessions are identified by a unique 64-bit ID: |
| 137 | + |
| 138 | +```rust |
| 139 | +use pubky_noise::SessionId; |
| 140 | + |
| 141 | +let session = SessionId::new(); |
| 142 | +println!("Session: {}", session.id()); |
| 143 | +``` |
| 144 | + |
| 145 | +### Thread-Safe Session Manager |
| 146 | + |
| 147 | +For multi-threaded applications: |
| 148 | + |
| 149 | +```rust |
| 150 | +use pubky_noise::{ThreadSafeSessionManager, NoiseRole}; |
| 151 | +use std::sync::Arc; |
| 152 | + |
| 153 | +let manager = Arc::new(ThreadSafeSessionManager::new()); |
| 154 | + |
| 155 | +// Add a session |
| 156 | +manager.add_session(session_id, noise_link, NoiseRole::Initiator); |
| 157 | + |
| 158 | +// Get and use a session |
| 159 | +if let Some(session) = manager.get_session(&session_id) { |
| 160 | + // Use the session |
| 161 | +} |
| 162 | +``` |
| 163 | + |
| 164 | +## Storage-Backed Messaging |
| 165 | + |
| 166 | +For reliable message delivery with persistence (requires `storage-queue` feature): |
| 167 | + |
| 168 | +```rust |
| 169 | +use pubky_noise::{StorageBackedMessaging, MessageQueue, RetryConfig}; |
| 170 | + |
| 171 | +let queue = MessageQueue::new(storage_backend); |
| 172 | +let retry_config = RetryConfig { |
| 173 | + max_retries: 5, |
| 174 | + base_delay_ms: 1000, |
| 175 | + max_delay_ms: 30000, |
| 176 | +}; |
| 177 | +``` |
| 178 | + |
| 179 | +## Security Considerations |
| 180 | + |
| 181 | +1. **Key Storage**: Never hardcode private keys. Use secure storage (Keychain/Keystore). |
| 182 | + |
| 183 | +2. **Rate Limiting**: Always enable rate limiting on servers. |
| 184 | + |
| 185 | +3. **Session Expiry**: Configure appropriate session timeouts. |
| 186 | + |
| 187 | +4. **Error Messages**: Don't expose internal error details to clients. |
| 188 | + |
| 189 | +## Examples |
| 190 | + |
| 191 | +See the `examples/` directory for complete working examples: |
| 192 | + |
| 193 | +- `basic_handshake.rs` - Simple client-server handshake |
| 194 | +- `xx_pattern.rs` - XX pattern handshake |
| 195 | +- `streaming.rs` - Streaming data over Noise |
| 196 | +- `server_example.rs` - Production server setup |
| 197 | +- `mobile_manager.rs` - Mobile app integration |
| 198 | +- `storage_queue.rs` - Reliable messaging with storage |
| 199 | + |
| 200 | +## Troubleshooting |
| 201 | + |
| 202 | +### Common Errors |
| 203 | + |
| 204 | +| Error | Cause | Solution | |
| 205 | +|-------|-------|----------| |
| 206 | +| `RateLimited` | Too many connection attempts | Wait and retry with backoff | |
| 207 | +| `IdentityVerify` | Key verification failed | Check keys match expected | |
| 208 | +| `Timeout` | Connection timed out | Check network, increase timeout | |
| 209 | +| `RemoteStaticMissing` | Server key not available | Use XX pattern or fetch key first | |
| 210 | + |
| 211 | +### Debug Logging |
| 212 | + |
| 213 | +Enable tracing for debugging: |
| 214 | + |
| 215 | +```rust |
| 216 | +// Add tracing subscriber in your app |
| 217 | +tracing_subscriber::fmt::init(); |
| 218 | +``` |
| 219 | + |
| 220 | +## API Reference |
| 221 | + |
| 222 | +See the [API documentation](https://docs.rs/pubky-noise) for complete reference. |
0 commit comments