Skip to content

Bridge API Reference

Complete API reference for the Bridge Validation system.

BridgeValidator Class

The BridgeValidator class handles session validation with Flowless.

Constructor

typescript
class BridgeValidator {
  constructor(config?: {
    flowlessApiUrl?: string;
    validationSecret?: string;
    timeout?: number;
    retryAttempts?: number;
  })
}

Parameters:

ParameterTypeDefaultDescription
flowlessApiUrlstringprocess.env.FLOWLESS_API_URLFlowless API URL
validationSecretstringprocess.env.BRIDGE_VALIDATION_SECRETBridge secret key
timeoutnumber5000Request timeout (ms)
retryAttemptsnumber3Number of retry attempts

Example:

typescript
import { BridgeValidator } from './lib/auth/bridge-validator';

const validator = new BridgeValidator({
  flowlessApiUrl: 'https://your-instance.pubflow.com',
  validationSecret: 'your-bridge-secret',
  timeout: 5000,
  retryAttempts: 3
});

Methods

validateSession()

Validates a session with Flowless backend.

typescript
async validateSession(sessionId: string): Promise<ValidationResult>

Parameters:

ParameterTypeRequiredDescription
sessionIdstring✅ YesSession ID to validate

Returns: Promise<ValidationResult>

typescript
interface ValidationResult {
  success: boolean;
  session?: SessionData;
  error?: string;
  cached?: boolean;
}

interface SessionData {
  user_id: string;
  email: string;
  name: string;
  user_type?: string;
  organization_id?: string;
  permissions?: string[];
  expires_at?: string;
  validated_at: string;
}

Example:

typescript
const result = await validator.validateSession('session_123');

if (result.success && result.session) {
  console.log('User ID:', result.session.user_id);
  console.log('Email:', result.session.email);
  console.log('Cached:', result.cached);
} else {
  console.error('Validation failed:', result.error);
}

healthCheck()

Checks the health of the Flowless connection.

typescript
async healthCheck(): Promise<HealthCheckResult>

Returns: Promise<HealthCheckResult>

typescript
interface HealthCheckResult {
  success: boolean;
  latency?: number;
  error?: string;
}

Example:

typescript
const health = await validator.healthCheck();

if (health.success) {
  console.log(`✅ Flowless is healthy (${health.latency}ms)`);
} else {
  console.error(`❌ Flowless is down: ${health.error}`);
}

Validation Modes

Configure security levels for session validation.

Environment Variable

env
VALIDATION_MODE=STANDARD

Available Modes

ModeIP CheckUser-Agent CheckDevice ID CheckUse Case
DISABLEDDevelopment only
STANDARDBasic security
ADVANCEDRecommended
STRICTMaximum security

Example:

typescript
// In your environment config
const config = {
  VALIDATION_MODE: 'ADVANCED' // IP + User-Agent validation
};

Caching

The Bridge Validator automatically caches valid sessions using LRU cache.

Cache Configuration

env
SESSION_VALIDATION_CACHE_TTL=300  # 5 minutes

Cache Behavior

  • Cache Hit: Returns cached session data (1-2ms)
  • Cache Miss: Validates with Flowless (20-50ms)
  • Auto-Invalidation: Cache expires after TTL
  • Max Size: 1000 sessions (configurable)

Example:

typescript
// First call - Cache MISS (validates with Flowless)
const result1 = await validator.validateSession('session_123');
console.log('Cached:', result1.cached); // false

// Second call - Cache HIT (returns from cache)
const result2 = await validator.validateSession('session_123');
console.log('Cached:', result2.cached); // true

Error Handling

Common Errors

ErrorStatusDescriptionSolution
Session ID is required400Missing session IDProvide session ID
Invalid session401Session not found or expiredRe-authenticate user
Bridge secret mismatch403Invalid bridge secretCheck BRIDGE_VALIDATION_SECRET
Flowless unreachable503Cannot connect to FlowlessCheck FLOWLESS_API_URL

Example:

typescript
try {
  const result = await validator.validateSession(sessionId);
  
  if (!result.success) {
    // Handle validation failure
    console.error('Validation failed:', result.error);
    return { error: result.error };
  }
  
  // Success
  return { user: result.session };
  
} catch (error) {
  // Handle network/system errors
  console.error('System error:', error);
  return { error: 'Service unavailable' };
}

Best Practices

  1. Use caching - Reduces latency and Flowless load
  2. Set appropriate TTL - Balance security and performance
  3. Use VALIDATION_MODE=STRICT in production
  4. Handle errors gracefully - Provide clear error messages
  5. Monitor health - Regular health checks
  6. Log validation attempts - Track failed validations

See Also

Released under the MIT License.