RWT API Reference
Version 2.1.3The Rotational WebSockets (RWT) API provides secure, high-performance socket connections between client applications and the DragonFire service, with built-in token rotation and authentication.
Overview
Rotational WebSockets (RWT) is a protocol built on top of standard WebSockets that adds security through token rotation, encryption, and authentication. It's the primary communication protocol for DragonFire client applications to exchange data with the DragonFire service.
Core Features
- Token Rotation: Automatic rotation of security tokens based on mathematical patterns
- Secure Channels: Multiple isolated communication channels within a single connection
- Phi-based Encryption: Encryption using phi-based mathematical algorithms
- Automatic Reconnection: Intelligent reconnection with session persistence
- Binary and Text Support: Communication with both binary and text payloads
Protocol Architecture
Client SDK Requirements
To use the RWT API, you'll need the DragonFire RWT Client SDK:
# Using npm
npm install @dragonfire/rwt-client
# Using yarn
yarn add @dragonfire/rwt-client
Authentication
RWT connections use a token-based authentication system with automatic rotation for enhanced security.
Initialization with DragonFire Client
RWT connections are authenticated using the DragonFire client instance:
import { DragonFireClient } from '@dragonfire/client';
import { RWTClient } from '@dragonfire/rwt-client';
// Initialize and connect DragonFire client
const dragonfire = new DragonFireClient({
apiKey: 'YOUR_API_KEY',
region: 'us-west'
});
await dragonfire.connect();
// Initialize RWT client with the DragonFire connection
const rwt = new RWTClient(dragonfire);
Token Rotation
RWT uses automatic token rotation to enhance security. Tokens are regenerated based on a phi-resonant sequence:
// Configure token rotation (optional - has sensible defaults)
rwt.configureTokenRotation({
interval: 60000, // Rotate tokens every 60 seconds
pattern: 'fibonacci', // Use Fibonacci sequence for rotation timing
renewThreshold: 0.8 // Renew tokens at 80% of their lifetime
});
Token Rotation Security
Unlike traditional authentication methods that use long-lived tokens, RWT tokens are continuously rotated using mathematical patterns based on the golden ratio. This makes token prediction virtually impossible, even if previous tokens are compromised.
Connection Management
The RWT API provides methods for establishing, maintaining, and terminating secure WebSocket connections.
Establishing a Connection
connect()
Establishes an RWT connection to the DragonFire service.
Syntax
async connect(options?: RWTConnectionOptions): Promise
Parameters
Name | Type | Description |
---|---|---|
options | RWTConnectionOptions | Optional. Additional connection options. |
Returns
A Promise that resolves to an RWTConnection object representing the established connection.
Example
// Establish an RWT connection
const connection = await rwt.connect({
protocol: 'v2', // Protocol version
compressionLevel: 3, // Compression level (0-9)
binaryType: 'arraybuffer', // Binary data type
timeout: 10000 // Connection timeout (ms)
});
Errors
RWTConnectionError
: Thrown if the connection cannot be establishedRWTAuthenticationError
: Thrown if authentication failsRWTTimeoutError
: Thrown if the connection attempt times out
Connection Status
getStatus()
Gets the current status of the RWT connection.
Syntax
getStatus(): RWTConnectionStatus
Returns
An RWTConnectionStatus object with the following properties:
state
: The current connection state ('connected', 'connecting', 'disconnected', 'error')latency
: Current round-trip latency in millisecondsuptime
: Connection duration in millisecondstokenRotations
: Number of token rotations performedcompressionRatio
: Current data compression ratio
Example
const status = rwt.getStatus();
console.log(`Connection state: ${status.state}`);
console.log(`Latency: ${status.latency}ms`);
console.log(`Token rotations: ${status.tokenRotations}`);
Disconnecting
disconnect()
Terminates the RWT connection.
Syntax
async disconnect(options?: RWTDisconnectionOptions): Promise
Parameters
Name | Type | Description |
---|---|---|
options | RWTDisconnectionOptions | Optional. Configuration options for disconnection. |
Example
// Graceful disconnection
await rwt.disconnect({
waitForPending: true, // Wait for pending operations to complete
code: 1000, // Normal closure code
reason: 'User initiated disconnect'
});
Automatic Reconnection
Configure automatic reconnection behavior:
// Enable automatic reconnection
rwt.configureReconnection({
enabled: true,
maxAttempts: 10,
baseDelay: 1000, // Base delay in ms
maxDelay: 30000, // Maximum delay in ms
backoffFactor: 1.5, // Exponential backoff factor
jitter: 0.2, // Random jitter factor (0-1)
preserveSession: true // Maintain session across reconnects
});
Messaging
The RWT API provides methods for sending and receiving messages over the WebSocket connection.
Sending Messages
send()
Sends a message through the RWT connection.
Syntax
async send(data: any, options?: SendOptions): Promise
Parameters
Name | Type | Description |
---|---|---|
data | any | The data to send. Can be a string, ArrayBuffer, TypedArray, or plain object (will be JSON-serialized). |
options | SendOptions | Optional. Configuration options for the send operation. |
Returns
A Promise that resolves to a SendResult object with information about the sent message.
Example
// Send a simple text message
const result = await rwt.send('Hello DragonFire!');
// Send JSON data
await rwt.send({
type: 'user-action',
action: 'login',
userId: 'user123',
timestamp: Date.now()
}, {
priority: 'high', // Message priority
compress: true, // Enable compression
channel: 'auth', // Send on 'auth' channel
encrypt: true // Encrypt the message
});
Errors
RWTSendError
: Thrown if the message cannot be sentRWTDisconnectedError
: Thrown if the connection is not establishedRWTEncodingError
: Thrown if data cannot be encoded properly
Receiving Messages
There are multiple ways to receive messages:
Event-based Receiving
// Listen for messages
rwt.on('message', (data, metadata) => {
console.log('Received message:', data);
console.log('Channel:', metadata.channel);
console.log('Sender:', metadata.sender);
});
// Listen for messages on a specific channel
rwt.on('message:auth', (data, metadata) => {
console.log('Received auth message:', data);
});
Promise-based Receiving
// Wait for a specific message
const message = await rwt.waitForMessage({
type: 'response',
timeout: 5000, // Wait up to 5 seconds
channel: 'auth' // Listen on 'auth' channel
});
console.log('Received response:', message.data);
Message Filtering
// Listen with filter
rwt.onMessage({
channel: 'notifications',
filter: msg => msg.priority === 'high'
}, (data) => {
console.log('High priority notification:', data);
});
Channels
RWT supports multiple logical communication channels within a single connection, allowing for organized message routing and handling.
Channel Management
createChannel()
Creates a new message channel for organized communication.
Syntax
createChannel(name: string, options?: ChannelOptions): RWTChannel
Parameters
Name | Type | Description |
---|---|---|
name | string | The name of the channel to create. |
options | ChannelOptions | Optional. Configuration options for the channel. |
Returns
An RWTChannel object representing the created channel.
Example
// Create a channel for data synchronization
const dataChannel = rwt.createChannel('data-sync', {
priority: 'normal',
encryption: true,
compression: true,
bufferSize: 64 * 1024 // 64KB buffer
});
Using Channels
Channels provide a simplified interface for sending and receiving channel-specific messages:
// Create authentication channel
const authChannel = rwt.createChannel('auth', {
encryption: true,
priority: 'high'
});
// Send on the channel
await authChannel.send({
action: 'verify',
token: userToken
});
// Listen on the channel
authChannel.onMessage((data) => {
console.log('Auth channel message:', data);
});
// Wait for specific message on channel
const response = await authChannel.waitForMessage({
type: 'verify-response',
timeout: 5000
});
Channel Lifecycle
Manage the lifecycle of channels:
// Close a channel when no longer needed
await authChannel.close();
// Reopen a closed channel
await authChannel.open();
// Check if channel is active
if (authChannel.isActive()) {
// Use the channel
}
// Get all active channels
const channels = rwt.getChannels();
console.log(`Active channels: ${channels.length}`);
Encryption
RWT provides built-in encryption capabilities to secure sensitive data transmission.
Encryption Configuration
Configure encryption settings for RWT connections:
// Configure encryption
rwt.configureEncryption({
algorithm: 'AES-GCM', // Encryption algorithm
keySize: 256, // Key size in bits
keyRotation: {
enabled: true,
interval: 3600000, // Rotate keys every hour
pattern: 'phi-based' // Use phi-based rotation pattern
},
payloadEncryption: 'auto' // 'always', 'never', or 'auto'
});
Message-level Encryption
Control encryption on a per-message basis:
// Send with explicit encryption
await rwt.send(sensitiveData, {
encrypt: true, // Explicitly encrypt this message
encryptionLevel: 'maximum' // Use maximum encryption strength
});
// Send without encryption for non-sensitive data
await rwt.send(publicData, {
encrypt: false // Skip encryption for this message
});
End-to-End Encryption
For maximum security, enable end-to-end encryption:
// Enable end-to-end encryption
await rwt.enableE2E({
keyExchangeMethod: 'ECDHE', // Elliptic Curve Diffie-Hellman Exchange
curve: 'P-256', // Curve to use for key exchange
verificationCallback: (fingerprint) => {
// Verify the remote fingerprint
return isValidFingerprint(fingerprint);
}
});
// Send with end-to-end encryption
await rwt.send(sensitiveData, {
endToEnd: true // Use end-to-end encryption
});
Events
RWT provides a comprehensive event system for monitoring connection state, message delivery, and other important occurrences.
Connection Events
Event | Description | Callback Parameters |
---|---|---|
connect | Fired when a connection is established | (connectionInfo: object) |
disconnect | Fired when a connection is closed | (code: number, reason: string) |
reconnect | Fired when a connection is re-established | (attempt: number, success: boolean) |
error | Fired on connection errors | (error: Error) |
Message Events
Event | Description | Callback Parameters |
---|---|---|
message | Fired when any message is received | (data: any, metadata: object) |
message:{channel} | Fired when a message is received on a specific channel | (data: any, metadata: object) |
send | Fired when a message is sent | (data: any, metadata: object) |
Security Events
Event | Description | Callback Parameters |
---|---|---|
token-rotate | Fired when the authentication token is rotated | (tokenInfo: object) |
key-rotate | Fired when encryption keys are rotated | (keyInfo: object) |
security-warning | Fired when potential security issues are detected | (warning: object) |
Subscribing to Events
// Basic event subscription
rwt.on('connect', (info) => {
console.log('Connected with ID:', info.connectionId);
});
// Subscribe to channel-specific message events
rwt.on('message:system', (data) => {
console.log('System message:', data);
});
// Subscribe with a once handler (fires only once)
rwt.once('token-rotate', (info) => {
console.log('First token rotation complete');
});
// Subscribe with filtering
rwt.on('message', {
filter: (data) => data.type === 'alert'
}, (data) => {
console.log('Alert received:', data.message);
});
Unsubscribing from Events
// Store reference to handler for later removal
const handler = (data) => {
console.log('Message received:', data);
};
// Subscribe with handler
rwt.on('message', handler);
// Unsubscribe specific handler
rwt.off('message', handler);
// Unsubscribe all handlers for an event
rwt.off('message');
// Unsubscribe all event handlers
rwt.offAll();
Error Handling
The RWT API provides structured error handling for managing different types of failures.
Error Types
RWT defines several error types for specific scenarios:
Error Class | Description | Common Causes |
---|---|---|
RWTError | Base error class for all RWT errors | General RWT-related issues |
RWTConnectionError | Error establishing or maintaining connection | Network issues, server unavailable |
RWTAuthenticationError | Authentication failed | Invalid API key, expired token |
RWTSendError | Error sending a message | Connection closed, invalid data format |
RWTTimeoutError | Operation timed out | Slow network, unresponsive service |
RWTEncryptionError | Error with message encryption | Invalid keys, unsupported algorithm |
Error Handling Examples
// Try-catch error handling
try {
await rwt.connect();
await rwt.send(message);
} catch (error) {
if (error instanceof RWTConnectionError) {
console.error('Connection error:', error.message);
} else if (error instanceof RWTAuthenticationError) {
console.error('Authentication error:', error.message);
} else if (error instanceof RWTSendError) {
console.error('Failed to send message:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
// Event-based error handling
rwt.on('error', (error) => {
console.error('RWT error:', error.message);
// Check if error has recovery info
if (error.recovery) {
console.log(`Recovery suggested: ${error.recovery.strategy}`);
console.log(`Retry in: ${error.recovery.retryAfterMs}ms`);
}
});
Error Properties
RWT errors include useful properties for diagnosis and recovery:
try {
await rwt.send(message);
} catch (error) {
console.error(`Error: ${error.message}`);
console.error(`Error code: ${error.code}`);
console.error(`Operation: ${error.operation}`);
// Detailed information
console.error(`Details: ${JSON.stringify(error.details)}`);
// Recovery information
if (error.canRetry()) {
console.log(`Retry recommended in ${error.retryAfterMs}ms`);
// Automatic retry
setTimeout(() => {
rwt.send(message).catch(handleError);
}, error.retryAfterMs);
}
}