DragonFire Developer Portal

RWT Authentication

Beta v0.8.5

This guide covers the implementation of secure authentication using Rotational WebSockets (RWT) technology in Dragon Wallets, which combines secure token authentication with advanced socket management for optimal security and performance.

Overview

Rotational WebSockets (RWT) technology forms the foundation of Dragon Wallets' authentication system, providing superior security through token rotation and optimized mathematical patterns.

Key Features

  • Automatic token rotation with phi-resonant patterns
  • Multi-dimensional security with overlapping verification factors
  • Seamless integration with wallet operations and identity management
  • Defense against common attack vectors including replay and man-in-the-middle
  • High-performance authentication with minimal latency
  • Robust forward secrecy and compromise containment
  • Support for various authentication contexts and security levels
RWT Authentication Architecture
RWT Authentication Architecture

RWT Tokens

RWT tokens are secure, self-contained authentication credentials that carry identity information and access rights while supporting automatic rotation for enhanced security.

Token Structure

// Example RWT token structure (decoded)
{
  "header": {
    "typ": "RWT",                       // Token type
    "alg": "HS256",                     // Signing algorithm
    "rot": "phi",                       // Rotation pattern
    "kid": "key_789abc123def456"        // Key identifier
  },
  "payload": {
    "sub": "identity_123456",           // Subject (identity ID)
    "iss": "dragonfire_wallet",         // Issuer
    "aud": "service_789",               // Intended audience
    "iat": 1717789456,                  // Issued at timestamp
    "exp": 1717793056,                  // Expiration timestamp
    "nbf": 1717789456,                  // Not valid before timestamp
    "jti": "token_987654321",           // Unique token identifier
    "rot": {                            // Rotation information
      "idx": 0,                         // Current rotation index
      "max": 144,                       // Maximum rotations
      "int": 300                        // Rotation interval (seconds)
    },
    "scp": ["profile:read", "wallet:read"], // Token scope/permissions
    "cxt": {                            // Context information
      "purpose": "wallet_access",
      "device": "device_abc123",
      "ip": "192.168.1.100",
      "challenge": "c123456789"
    }
  },
  "signature": "...",                   // Token signature
  "rotation_key": "..."                 // Rotation-specific key (encrypted)
}

Token Protections

RWT tokens incorporate multiple security measures:

  • Digital Signatures: Cryptographically signed to prevent tampering
  • Automatic Rotation: Regular key rotation based on mathematical patterns
  • Context Binding: Tokens bound to specific devices, IPs, or contexts
  • Challenge-Response: Built-in challenge-response mechanism
  • Time Constraints: Strict validity periods with timestamp verification
  • Scope Limitation: Precise permission controls for limited access

Token Creation

Creating RWT tokens involves specifying the identity, permissions, and security parameters:

import { DragonFireClient } from '@dragonfire/client';
import { WalletClient } from '@dragonfire/wallet-client';

// Initialize the clients
const dragonfire = new DragonFireClient({
  apiKey: 'YOUR_API_KEY',
  region: 'us-west'
});
await dragonfire.connect();

const wallet = new WalletClient(dragonfire);

// Create an RWT authentication token
const rwtToken = await wallet.createRWTToken({
  identityId: 'identity_123456',           // Identity ID
  purpose: 'service_authentication',       // Authentication purpose
  audience: 'service_789',                 // Intended audience (service)
  scope: ['profile:read', 'wallet:read'],  // Token permissions
  expiresIn: 3600000,                      // Token lifetime (1 hour)
  metadata: {                              // Additional metadata
    deviceId: 'device_abc123',
    applicationName: 'Example App',
    ipAddress: '192.168.1.100'
  }
}, {
  rotationPattern: 'phi',                  // Phi-resonant rotation
  rotationInterval: 300000,                // Rotate every 5 minutes
  securityLevel: 'high',                   // High security level
  wrappedToken: true,                      // Create wrapped token
  challengeResponse: true                  // Enable challenge-response
});

Token Creation Options

Parameter Type Default Description
identityId string Required Identity ID for token subject
purpose string Required Authentication purpose
audience string Required Intended token audience
scope string[] [] Token permissions
expiresIn number 3600000 Token lifetime in milliseconds
metadata object {} Additional context metadata
rotationPattern string 'phi' Token rotation pattern
rotationInterval number 300000 Rotation interval in milliseconds
securityLevel string 'standard' Token security level
wrappedToken boolean false Create wrapped token
challengeResponse boolean false Enable challenge-response

Token Verification

Verifying RWT tokens involves checking the signature, validity period, rotation status, and other security factors:

// Verify an RWT token
const verificationResult = await wallet.verifyRWTToken(
  receivedToken,
  {
    expectedAudience: 'service_789',       // Expected audience
    expectedScope: ['profile:read'],       // Required permissions
    validateRotation: true,                // Check rotation status
    contextValidation: {                   // Context validation
      ipAddress: clientIp,
      deviceId: deviceId,
      validateFingerprint: true
    }
  }
);

// Check verification result
if (verificationResult.valid) {
  console.log('Token is valid');
  console.log('Identity ID:', verificationResult.identityId);
  console.log('Scope:', verificationResult.scope);
  console.log('Rotation index:', verificationResult.rotationIndex);
  console.log('Remaining validity:', verificationResult.remainingValidity);
} else {
  console.error('Token verification failed:', verificationResult.reason);
}

Direct Authentication

You can also use RWT tokens for direct authentication without manual verification:

// Authenticate with RWT token
const authResult = await wallet.authenticateWithRWT(
  receivedToken,
  {
    requiredPermissions: ['profile:read', 'wallet:read'],
    securityContext: {
      ipAddress: clientIp,
      userAgent: userAgent,
      deviceFingerprint: deviceFingerprint
    }
  }
);

// Check authentication result
if (authResult.authenticated) {
  // Authentication successful
  const identityId = authResult.identityId;
  const identity = await wallet.getIdentity(identityId);
  
  // Proceed with authenticated operations
} else {
  // Authentication failed
  console.error('Authentication failed:', authResult.reason);
}

Rotation Patterns

RWT tokens support various mathematical rotation patterns, each with unique security and performance characteristics.

Phi Pattern

Based on the Golden Ratio (φ = 1.618...), provides optimal balance between security and performance with naturally unpredictable intervals.

Pi Pattern

Based on Pi (π = 3.14159...), excellent for cyclical applications with strong cryptographic properties and periodic rotation.

Sqrt2 Pattern

Based on Square Root of 2 (√2 = 1.414...), optimized for high-throughput applications with efficient computational characteristics.

Sqrt3 Pattern

Based on Square Root of 3 (√3 = 1.732...), preferred for multi-party authentication with triangular verification properties.

E Pattern

Based on Euler's Number (e = 2.718...), ideal for growth-based applications with excellent statistical properties for continuous rotation.

Prime Pattern

Based on prime number sequences, provides strongest cryptographic security for high-security applications requiring maximum unpredictability.

Implementing Custom Rotation

// Configure custom token rotation pattern
const customRotationToken = await wallet.createRWTToken({
  identityId: 'identity_123456',
  purpose: 'high_security_authentication',
  audience: 'financial_service',
  scope: ['transactions:write'],
  expiresIn: 3600000
}, {
  // Custom rotation configuration
  rotationPattern: 'phi',               // Base pattern
  rotationInterval: 180000,             // Base interval (3 minutes)
  rotationConfig: {
    accelerationFactor: 0.8,            // Accelerate rotation over time
    jitterFactor: 0.1,                  // Add randomness to intervals
    adaptiveRotation: true,             // Adapt based on usage patterns
    minimumInterval: 60000,             // Minimum interval (1 minute)
    maximumInterval: 300000,            // Maximum interval (5 minutes)
    adaptationMetric: 'security_score'  // Adaptation metric
  },
  securityLevel: 'maximum'              // Maximum security
});

Security Features

RWT authentication includes numerous security features to protect against various attack vectors:

Health Monitoring

Continuous token health monitoring with automatic revocation of compromised tokens and adaptive security measures.

Forward Secrecy

Implements perfect forward secrecy to prevent decryption of past communications if current keys are compromised.

Context Binding

Binds tokens to specific contexts such as device, IP address, or application to prevent token theft and unauthorized use.

Replay Protection

Advanced replay protection with nonce tracking and timestamp verification to prevent token reuse attacks.

Audit Logging

Comprehensive audit logging of all token operations for security monitoring, compliance, and forensic analysis.

Behavioral Analysis

Real-time behavioral analysis to detect unusual authentication patterns and potential token compromise.

Security Level Configuration

// Configure token security levels
await wallet.configureTokenSecurity({
  standardLevel: {
    rotationPattern: 'phi',
    rotationInterval: 300000,    // 5 minutes
    contextBinding: 'basic',     // Basic context binding
    replayProtection: true,
    forwardSecrecy: true,
    auditLevel: 'standard'
  },
  highLevel: {
    rotationPattern: 'phi',
    rotationInterval: 180000,    // 3 minutes
    contextBinding: 'enhanced',  // Enhanced context binding
    replayProtection: true,
    forwardSecrecy: true,
    challengeResponse: true,
    behavioralAnalysis: true,
    auditLevel: 'detailed'
  },
  maximumLevel: {
    rotationPattern: 'prime',
    rotationInterval: 60000,     // 1 minute
    contextBinding: 'strict',    // Strict context binding
    replayProtection: true,
    forwardSecrecy: true,
    challengeResponse: true,
    behavioralAnalysis: true,
    multiFactorRequired: true,
    healthMonitoring: 'continuous',
    tokenCompartmentalization: true,
    auditLevel: 'forensic'
  }
});

Integration with Services

RWT authentication can be integrated with various services for seamless, secure authentication:

// Create a service integration token
const serviceToken = await wallet.createServiceToken({
  identityId: 'identity_123456',
  serviceId: 'payment_processor',
  integrationLevel: 'deep',              // Deep integration
  permissions: [
    'profile:read',
    'wallet:read',
    'payments:initiate'
  ],
  validityPeriod: 2592000000,            // 30 days
  metadata: {
    serviceType: 'payment',
    integrationPurpose: 'recurring_billing'
  }
}, {
  rotationPattern: 'phi',
  securityLevel: 'high'
});

// Create a cross-service authentication context
const authContext = await wallet.createCrossServiceContext({
  primaryService: 'wallet_service',
  connectedServices: [
    {
      serviceId: 'identity_service',
      requiredPermissions: ['identity:verify']
    },
    {
      serviceId: 'payment_processor',
      requiredPermissions: ['payments:process']
    }
  ],
  contextPurpose: 'payment_flow',
  expiresIn: 600000                      // 10 minutes
});

// Authenticate across multiple services
const multiServiceAuth = await wallet.authenticateWithContext(
  authContext.id,
  receivedToken,
  {
    currentService: 'payment_processor',
    operationId: 'payment_12345',
    verifyServiceChain: true
  }
);

Service Authentication Flow

RWT Service Authentication Flow
RWT Service Authentication Flow

Multi-Factor Authentication

RWT authentication can be combined with multi-factor authentication for enhanced security:

// Configure multi-factor authentication for wallet
await wallet.configureMultiFactorAuth({
  identityId: 'identity_123456',
  methods: [
    {
      type: 'app',                    // Authenticator app
      isRequired: true,               // Required method
      priority: 'primary'             // Primary authentication
    },
    {
      type: 'email',                  // Email verification
      isRequired: false,              // Optional method
      priority: 'secondary'           // Secondary authentication
    },
    {
      type: 'sms',                    // SMS verification
      isRequired: false,              // Optional method
      priority: 'secondary'           // Secondary authentication
    }
  ],
  policyConfig: {
    requiredMethodCount: 2,           // Require 2 methods
    highValueThreshold: 1000,         // Require MFA for transactions above $1000
    allowRememberDevice: true,        // Allow remembering device
    rememberDeviceDuration: 2592000   // Remember for 30 days
  }
});

// Create token with MFA requirement
const mfaToken = await wallet.createRWTToken({
  identityId: 'identity_123456',
  purpose: 'high_security_auth',
  audience: 'financial_service',
  scope: ['transactions:write'],
  expiresIn: 3600000
}, {
  rotationPattern: 'phi',
  rotationInterval: 300000,
  securityLevel: 'high',
  requireMfa: true,                  // Require MFA verification
  mfaMethods: ['app']                // Require authenticator app
});

// Generate MFA challenge
const mfaChallenge = await wallet.generateMFAChallenge({
  identityId: 'identity_123456',
  method: 'app',
  purpose: 'token_authentication',
  tokenId: mfaToken.id
});

// Verify MFA response and activate token
const activationResult = await wallet.verifyMFAAndActivateToken({
  challengeId: mfaChallenge.id,
  response: '123456',               // OTP code from authenticator app
  tokenId: mfaToken.id
});

Supported MFA Methods

Dragon Wallets supports various multi-factor authentication methods:

  • app: Time-based one-time password (TOTP) via authenticator app
  • email: One-time verification codes sent via email
  • sms: One-time verification codes sent via SMS
  • push: Push notifications to mobile devices for approval
  • biometric: Fingerprint, facial recognition, or other biometric verification
  • security_key: Hardware security keys (FIDO2/WebAuthn)
  • backup_codes: One-time backup codes for recovery

Security Best Practices

Follow these best practices when implementing RWT authentication:

Use High Security Levels

Always use the highest security level appropriate for the sensitivity of the protected resources.

Enable Token Rotation

Always use token rotation with appropriate intervals based on the security requirements of your application.

Implement Multi-Factor Authentication

Use multi-factor authentication for sensitive operations and high-value transactions to prevent unauthorized access.

Enforce Context Validation

Always validate the authentication context, including device, IP address, and user agent, to prevent token theft.

Limit Token Scope

Restrict token permissions to the minimum required for the specific operation to limit potential damage from compromised tokens.

Implement Token Monitoring

Monitor token usage and implement automatic revocation for suspicious activities or multiple failed verification attempts.

Security Checklist

Use phi-resonant token rotation for optimal security
Implement multi-factor authentication for sensitive operations
Enable context validation to prevent token theft
Use challenge-response mechanisms for critical authentication
Limit token scope to minimum required permissions
Set appropriate token expiration periods
Implement comprehensive audit logging
Enable token health monitoring
Implement automatic revocation for suspicious activities
Use secure transport (HTTPS) for all token operations

Code Examples

Complete Authentication Flow

import { DragonFireClient } from '@dragonfire/client';
import { WalletClient } from '@dragonfire/wallet-client';

async function implementSecureAuthentication() {
  // Initialize the clients
  const dragonfire = new DragonFireClient({
    apiKey: 'YOUR_API_KEY',
    region: 'us-west'
  });
  await dragonfire.connect();
  
  const wallet = new WalletClient(dragonfire);
  
  try {
    // Step 1: Load the user's wallet and identity
    const userWallet = await wallet.loadWallet('wallet_123456');
    const identity = await wallet.getIdentity('identity_123456');
    console.log('Loaded wallet and identity for:', identity.displayName);
    
    // Step 2: Configure multi-factor authentication
    await wallet.configureMultiFactorAuth({
      identityId: identity.id,
      methods: [
        { type: 'app', isRequired: true, priority: 'primary' },
        { type: 'email', isRequired: false, priority: 'secondary' }
      ],
      policyConfig: {
        requiredMethodCount: 1,
        highValueThreshold: 1000,
        allowRememberDevice: true,
        rememberDeviceDuration: 2592000
      }
    });
    console.log('Configured MFA for identity');
    
    // Step 3: Create an RWT token for authentication
    const rwtToken = await wallet.createRWTToken({
      identityId: identity.id,
      purpose: 'app_authentication',
      audience: 'example_app',
      scope: ['profile:read', 'wallet:read'],
      expiresIn: 3600000,
      metadata: {
        deviceId: 'device_abc123',
        applicationName: 'Example App',
        ipAddress: '192.168.1.100'
      }
    }, {
      rotationPattern: 'phi',
      rotationInterval: 300000,
      securityLevel: 'high',
      wrappedToken: true,
      requireMfa: true,
      mfaMethods: ['app']
    });
    console.log('Created RWT token:', rwtToken.id);
    
    // Step 4: Generate MFA challenge
    const mfaChallenge = await wallet.generateMFAChallenge({
      identityId: identity.id,
      method: 'app',
      purpose: 'token_authentication',
      tokenId: rwtToken.id
    });
    console.log('Generated MFA challenge:', mfaChallenge.id);
    
    // Step 5: Verify MFA response (in a real scenario, this would come from the user)
    const mfaCode = '123456'; // Simulated code from authenticator app
    const activationResult = await wallet.verifyMFAAndActivateToken({
      challengeId: mfaChallenge.id,
      response: mfaCode,
      tokenId: rwtToken.id
    });
    console.log('Token activated:', activationResult.activated);
    
    // Step 6: Use the token for authentication
    const clientIp = '192.168.1.100'; // Simulated client IP
    const userAgent = 'Mozilla/5.0 Example Browser'; // Simulated user agent
    
    const authResult = await wallet.authenticateWithRWT(
      rwtToken.token,
      {
        requiredPermissions: ['profile:read'],
        securityContext: {
          ipAddress: clientIp,
          userAgent: userAgent,
          deviceId: 'device_abc123'
        }
      }
    );
    
    if (authResult.authenticated) {
      console.log('Authentication successful');
      console.log('Identity:', authResult.identityId);
      console.log('Permissions:', authResult.permissions);
      
      // Step 7: Use authenticated identity to access protected resources
      const userProfile = await wallet.getIdentityProfile(
        authResult.identityId,
        {
          includeAttributes: true,
          includeCredentials: false
        }
      );
      console.log('Retrieved user profile');
      
      // Step 8: Manage token rotation (normally handled automatically)
      const rotationResult = await wallet.rotateRWTToken(rwtToken.id);
      console.log('Rotated token:', rotationResult.rotationIndex);
    } else {
      console.error('Authentication failed:', authResult.reason);
    }
    
    return {
      identityId: identity.id,
      tokenId: rwtToken.id,
      authenticationSuccessful: authResult.authenticated
    };
  } catch (error) {
    console.error('Authentication implementation error:', error);
    throw error;
  } finally {
    await dragonfire.disconnect();
  }
}

// Execute the authentication implementation
implementSecureAuthentication()
  .then(result => console.log('Authentication implementation completed:', result))
  .catch(error => console.error('Authentication implementation failed:', error));

Token Management for Services

import { DragonFireClient } from '@dragonfire/client';
import { WalletClient } from '@dragonfire/wallet-client';

async function implementServiceAuthentication() {
  // Initialize the clients
  const dragonfire = new DragonFireClient({
    apiKey: 'YOUR_API_KEY',
    region: 'us-west'
  });
  await dragonfire.connect();
  
  const wallet = new WalletClient(dragonfire);
  
  try {
    // Step 1: Load identity
    const identity = await wallet.getIdentity('identity_123456');
    console.log('Loaded identity for:', identity.displayName);
    
    // Step 2: Register service integration
    const serviceRegistration = await wallet.registerServiceIntegration({
      identityId: identity.id,
      serviceName: 'E-Commerce Platform',
      serviceId: 'ecommerce_service',
      description: 'Integration with Example E-Commerce Platform',
      serviceUrl: 'https://example-ecommerce.com',
      allowedScopes: [
        'profile:read',
        'wallet:read',
        'payments:initiate'
      ],
      integrationLevel: 'deep',
      dataSharing: {
        profileData: 'selective',
        walletData: 'minimal',
        transactionData: 'necessary'
      }
    });
    console.log('Registered service integration:', serviceRegistration.id);
    
    // Step 3: Create long-lived service token
    const serviceToken = await wallet.createServiceToken({
      identityId: identity.id,
      serviceId: serviceRegistration.serviceId,
      integrationLevel: serviceRegistration.integrationLevel,
      permissions: serviceRegistration.allowedScopes,
      validityPeriod: 2592000000, // 30 days
      metadata: {
        serviceType: 'ecommerce',
        integrationPurpose: 'shopping_platform'
      }
    }, {
      rotationPattern: 'phi',
      rotationInterval: 86400000, // Daily rotation
      securityLevel: 'high',
      allowRefresh: true, // Allow token refresh
      refreshRequiresMfa: true // MFA required for refresh
    });
    console.log('Created service token:', serviceToken.id);
    
    // Step 4: Create service-specific access policies
    await wallet.configureServiceAccessPolicy({
      serviceId: serviceRegistration.serviceId,
      policies: {
        highValueTransactions: {
          threshold: 1000,
          requireMfa: true,
          requireApproval: true
        },
        dataAccess: {
          profileAccess: 'selective',
          walletAccess: 'read_only',
          transactionHistoryAccess: 'limited'
        },
        securityControls: {
          ipRestriction: true,
          allowedIps: ['203.0.113.0/24'], // Example IP range
          deviceBinding: true,
          sessionTimeout: 3600 // 1 hour
        }
      }
    });
    console.log('Configured service access policies');
    
    // Step 5: Simulate service authentication request
    console.log('Simulating service authentication request...');
    
    const authResult = await wallet.authenticateService({
      token: serviceToken.token,
      serviceId: serviceRegistration.serviceId,
      requestContext: {
        ipAddress: '203.0.113.45', // Within allowed range
        operation: 'view_profile',
        requestTime: new Date().toISOString()
      }
    });
    
    if (authResult.authenticated) {
      console.log('Service authentication successful');
      console.log('Authenticated for identity:', authResult.identityId);
      console.log('Granted permissions:', authResult.permissions);
      
      // Step 6: Simulate high-value transaction requiring MFA
      console.log('Simulating high-value transaction request...');
      
      const transactionRequest = await wallet.createServiceOperationRequest({
        serviceId: serviceRegistration.serviceId,
        operationType: 'payment',
        operationDetails: {
          amount: 1500, // Above high-value threshold
          currency: 'USD',
          recipient: 'merchant_456',
          description: 'Premium subscription'
        },
        tokenId: serviceToken.id
      });
      
      if (transactionRequest.requiresMfa) {
        console.log('Transaction requires MFA verification');
        
        // Generate MFA challenge
        const mfaChallenge = await wallet.generateServiceMFAChallenge({
          identityId: identity.id,
          serviceId: serviceRegistration.serviceId,
          operationId: transactionRequest.id,
          method: 'app'
        });
        
        // Verify MFA (simulated)
        const mfaVerification = await wallet.verifyServiceMFA({
          challengeId: mfaChallenge.id,
          response: '123456', // Simulated MFA code
          serviceId: serviceRegistration.serviceId,
          operationId: transactionRequest.id
        });
        
        if (mfaVerification.verified) {
          console.log('MFA verification successful, transaction approved');
        } else {
          console.log('MFA verification failed, transaction rejected');
        }
      }
    } else {
      console.error('Service authentication failed:', authResult.reason);
    }
    
    return {
      identityId: identity.id,
      serviceId: serviceRegistration.serviceId,
      tokenId: serviceToken.id,
      authenticationSuccessful: authResult.authenticated
    };
  } catch (error) {
    console.error('Service authentication error:', error);
    throw error;
  } finally {
    await dragonfire.disconnect();
  }
}

// Execute the service authentication implementation
implementServiceAuthentication()
  .then(result => console.log('Service authentication implementation completed:', result))
  .catch(error => console.error('Service authentication implementation failed:', error));