RWT (Rotational WebSockets)
RWT (Rotational WebSockets) is DragonFire's advanced WebSocket protocol that combines secure token authentication with high-performance socket connections.
Introduction
Traditional WebSockets lack built-in security mechanisms and can struggle with high-frequency data streams or complex relational data. RWT addresses these limitations by implementing a rotational security model and optimized data transport layer.
RWT is designed for:
- Real-time applications requiring secure communications
- High-frequency data streams (financial data, sensor networks, etc.)
- Applications that need seamless reconnection handling
- Complex data structures that benefit from intelligent serialization
Key Features
Rotational Token Security
Tokens rotate based on harmonic time intervals, making packet interception useless without the rotation key.
Optimized Binary Transport
Efficient binary serialization reduces payload size while maintaining structured data relationships.
Auto-Reconnection
Intelligent connection management with exponential backoff and session recovery.
Multi-Channel Support
Create logical data channels over a single connection for organized data streams.
Architecture
RWT is built on a layered architecture that extends WebSockets with enhanced security and performance features:
Layers
- Transport Layer: Standard WebSocket connection with TLS
- Security Layer: Rotational token system and encryption
- Message Layer: Binary message encoding and protocol handling
- Channel Layer: Logical channel management
- Application Layer: User API and event handling
Rotational Security Model
The core innovation of RWT is its rotational security model:
- Initial connection uses standard authentication (JWT, OAuth, etc.)
- Upon successful authentication, a rotation seed is exchanged
- Tokens rotate based on harmonic mathematical sequences
- Each message requires the current valid token
- Token rotation schedule is determined by a shared algorithm known only to client and server
Installation
To install the RWT library, use npm or yarn:
# Using npm
npm install @dragonfire/rwt
# Using yarn
yarn add @dragonfire/rwt
Server components are available as separate packages:
# Server implementation for Node.js
npm install @dragonfire/rwt-server
# Integration for Express.js
npm install @dragonfire/rwt-express
Basic Usage
Here's a simple example of how to create an RWT connection:
Client-side Implementation
import { RWTClient } from '@dragonfire/rwt';
// Create a new RWT client
const rwt = new RWTClient({
endpoint: 'wss://api.example.com/socket',
authToken: 'user-auth-token', // Initial authentication token
rotationKey: 'user-rotation-key', // Used for token rotation algorithm
channels: ['data', 'control'] // Optional channel definitions
});
// Connect to the server
rwt.connect()
.then(() => {
console.log('Connected to RWT server');
})
.catch(err => {
console.error('Connection failed:', err);
});
// Send a message on a specific channel
rwt.send('data', { type: 'request', data: { id: 123 } });
// Listen for messages on a channel
rwt.on('data', message => {
console.log('Received data:', message);
});
// Handle connection events
rwt.on('connect', () => {
console.log('Connected');
});
rwt.on('disconnect', reason => {
console.log('Disconnected:', reason);
});
// Close the connection when done
rwt.disconnect();
Server-side Implementation (Node.js)
import { RWTServer } from '@dragonfire/rwt-server';
import express from 'express';
import http from 'http';
const app = express();
const server = http.createServer(app);
// Create RWT server instance
const rwtServer = new RWTServer({
server, // Attach to existing HTTP server
path: '/socket', // WebSocket endpoint path
authHandler: async (token) => {
// Validate the authentication token
// Return user data if valid, null if invalid
const user = await validateToken(token);
return user ? {
id: user.id,
rotationKey: user.rotationKey
} : null;
}
});
// Handle channel messages
rwtServer.channel('data', (client, message) => {
console.log(`Received from client ${client.id}:`, message);
// Send a response back to the client
client.send('data', { type: 'response', data: { id: message.data.id } });
});
// Start the server
server.listen(3000, () => {
console.log('RWT server running on port 3000');
});
Advanced Usage
Custom Rotation Algorithms
You can customize the token rotation algorithm for enhanced security:
import { RWTClient, TokenRotators } from '@dragonfire/rwt';
// Create a client with a custom token rotator
const rwt = new RWTClient({
endpoint: 'wss://api.example.com/socket',
authToken: 'user-auth-token',
rotationKey: 'user-rotation-key',
tokenRotator: TokenRotators.fibonacci, // Use Fibonacci sequence for rotation
// Or create your own:
// tokenRotator: (seed, counter) => {
// return someCustomAlgorithm(seed, counter);
// }
});
Binary Data Handling
RWT supports efficient binary data transmission:
// Send binary data
const buffer = new ArrayBuffer(32);
// ... fill buffer with data
rwt.sendBinary('data', buffer);
// Receive binary data
rwt.on('data', (message, isBinary) => {
if (isBinary) {
// Handle binary data
const view = new DataView(message);
// Process binary data...
} else {
// Handle JSON message
console.log(message);
}
});
Channel Groups
Organize channels into logical groups:
const rwt = new RWTClient({
// ... other options
channelGroups: {
market: ['stocks', 'forex', 'crypto'],
system: ['status', 'alerts']
}
});
// Subscribe to all channels in a group
rwt.subscribeGroup('market');
// Listen to all messages from a group
rwt.onGroup('market', (channel, message) => {
console.log(`Received ${channel} update:`, message);
});
Security
RWT implements multiple layers of security to protect data in transit:
Transport Security
- Always use TLS (wss://) for encrypted transport
- HTTP Strict Transport Security (HSTS) recommended for production
Authentication
- Initial authentication using industry-standard tokens (JWT, OAuth)
- Server-side validation of user credentials before establishing connection
Rotational Token System
- Tokens change based on time and a shared rotation algorithm
- Each message must include the current valid token
- Intercepted tokens become invalid quickly
- Token rotation parameters can be customized for security needs
Message Encryption
- Optional end-to-end encryption of message payloads
- Support for multiple encryption algorithms
Security Best Practices
- Never hardcode rotation keys in client-side code
- Implement proper key management for rotation keys
- Use server-side validation for all incoming messages
- Implement message rate limiting to prevent DoS attacks
Examples
Real-time Dashboard
A simple example of using RWT for a real-time dashboard:
// dashboard.js
import { RWTClient } from '@dragonfire/rwt';
// Initialize RWT client
const rwt = new RWTClient({
endpoint: 'wss://dashboard-api.example.com/socket',
authToken: userAuthToken,
rotationKey: userRotationKey,
channels: ['metrics', 'alerts', 'status']
});
// Connect to the server
await rwt.connect();
// Request initial data
rwt.send('metrics', { type: 'subscribe', metrics: ['cpu', 'memory', 'network'] });
// Update UI when new metrics arrive
rwt.on('metrics', data => {
updateDashboardUI(data);
});
// Display alerts
rwt.on('alerts', alert => {
showAlertNotification(alert);
});
// Update connection status
rwt.on('status', status => {
updateConnectionStatus(status);
});
// Cleanup on page unload
window.addEventListener('beforeunload', () => {
rwt.disconnect();
});
View more examples in our SDK Examples
Next Steps
- Explore the complete RWT API Reference
- Learn about Rotational Web Tokens
- Download the RWT SDK
- Check out the HexStream Protocol
- Try the Interactive RWT Demo