🔒 Production Security Guide

Essential security measures for deploying Techtree Avatar in production environments

🎯 Security Overview

⚠️ Important: Before deploying to production, you MUST implement proper security measures. Unsecured deployments can lead to:
• Unauthorized API usage and cost overruns
• Data breaches and privacy violations
• Service abuse and reputation damage
• Legal compliance issues
CRITICAL

API Key Exposure

Exposed API keys can lead to unlimited usage and massive costs

HIGH

Domain Spoofing

Unauthorized domains can embed your avatar without permission

MEDIUM

Rate Limit Abuse

Attackers can overwhelm your service with excessive requests

LOW

Data Injection

Malicious input can compromise avatar responses

✅ Pre-Production Security Checklist

Complete ALL items before going live:

🔐 Authentication & Authorization

🛡️ Input Validation

⚡ Rate Limiting

🔍 Monitoring & Logging

🔧 Step-by-Step Security Implementation

Domain Whitelisting

First, request domain whitelisting for your production environment:

Domain Whitelist Request Form

Secure API Integration

Never expose API keys in client-side code. Use a secure backend proxy:

❌ INSECURE - Don't do this:

// Never put API keys in client-side JavaScript!
const apiKey = "tta_prod_abcd1234..."; // ❌ EXPOSED TO USERS

fetch('https://api.ttavatar.com/chat', {
    headers: {
        'Authorization': `Bearer ${apiKey}` // ❌ VISIBLE IN BROWSER
    }
});
                            

✅ SECURE - Do this instead:

// Client-side: Call your own backend
fetch('/api/avatar/chat', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${userToken}` // ✅ User token, not API key
    },
    body: JSON.stringify({ message: userInput })
});

// Backend (Node.js example):
app.post('/api/avatar/chat', authenticateUser, async (req, res) => {
    // ✅ API key stored securely on backend
    const response = await fetch('https://api.ttavatar.com/chat', {
        headers: {
            'Authorization': `Bearer ${process.env.TTAVATAR_API_KEY}`
        },
        body: JSON.stringify(req.body)
    });

    res.json(await response.json());
});
                            

Input Validation & Sanitization

Always validate and sanitize user inputs:

function sanitizeInput(input) {
    // Remove potentially dangerous content
    return input
        .replace(/<script[^>]*>.*?<\/script>/gi, '') // Remove scripts
        .replace(/javascript:/gi, '') // Remove javascript: URLs
        .replace(/on\w+\s*=/gi, '') // Remove event handlers
        .trim()
        .substring(0, 1000); // Limit length
}

function validateMessage(message) {
    if (!message || typeof message !== 'string') {
        throw new Error('Invalid message format');
    }

    if (message.length > 1000) {
        throw new Error('Message too long');
    }

    // Check for inappropriate content
    const inappropriatePatterns = [
        /\b(hate|violence|illegal)\b/i
        // Add your content filters
    ];

    for (const pattern of inappropriatePatterns) {
        if (pattern.test(message)) {
            throw new Error('Inappropriate content detected');
        }
    }

    return sanitizeInput(message);
}

// Usage
try {
    const cleanMessage = validateMessage(userInput);
    // Send to avatar API
} catch (error) {
    console.error('Input validation failed:', error.message);
    // Show user-friendly error
}
                            

Rate Limiting Implementation

Prevent abuse with client-side and server-side rate limiting:

class RateLimiter {
    constructor(maxRequests = 10, timeWindow = 60000) {
        this.maxRequests = maxRequests;
        this.timeWindow = timeWindow;
        this.requests = [];
    }

    isAllowed() {
        const now = Date.now();

        // Remove old requests outside time window
        this.requests = this.requests.filter(
            time => now - time < this.timeWindow
        );

        // Check if limit exceeded
        if (this.requests.length >= this.maxRequests) {
            return false;
        }

        // Record this request
        this.requests.push(now);
        return true;
    }

    getRetryAfter() {
        if (this.requests.length === 0) return 0;

        const oldestRequest = Math.min(...this.requests);
        const waitTime = this.timeWindow - (Date.now() - oldestRequest);
        return Math.max(0, Math.ceil(waitTime / 1000));
    }
}

// Usage
const rateLimiter = new RateLimiter(10, 60000); // 10 requests per minute

function sendMessage(message) {
    if (!rateLimiter.isAllowed()) {
        const retryAfter = rateLimiter.getRetryAfter();
        showError(`Rate limit exceeded. Try again in ${retryAfter} seconds.`);
        return;
    }

    // Send message to avatar
    callAvatarAPI(message);
}
                            

Security Headers & CSP

Add security headers to protect against common attacks:

// Express.js example
app.use((req, res, next) => {
    // Prevent clickjacking
    res.setHeader('X-Frame-Options', 'DENY');

    // XSS protection
    res.setHeader('X-XSS-Protection', '1; mode=block');

    // Prevent MIME sniffing
    res.setHeader('X-Content-Type-Options', 'nosniff');

    // Enforce HTTPS
    res.setHeader('Strict-Transport-Security',
        'max-age=31536000; includeSubDomains; preload');

    // Content Security Policy
    res.setHeader('Content-Security-Policy',
        "default-src 'self'; " +
        "script-src 'self' 'unsafe-inline'; " +
        "style-src 'self' 'unsafe-inline'; " +
        "connect-src 'self' https://api.ttavatar.com; " +
        "frame-ancestors 'none';"
    );

    next();
});

// HTML meta tags
<meta http-equiv="Content-Security-Policy"
      content="default-src 'self'; connect-src 'self' https://api.ttavatar.com">
                            

Error Handling & Logging

Implement comprehensive error handling and security logging:

class SecurityLogger {
    static log(event, data = {}) {
        const logEntry = {
            timestamp: new Date().toISOString(),
            event,
            ip: this.getClientIP(),
            userAgent: navigator.userAgent,
            ...data
        };

        // Send to your logging service
        fetch('/api/security/log', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(logEntry)
        });

        console.warn('Security event:', logEntry);
    }

    static getClientIP() {
        // This would typically be done on the server
        return 'client-side';
    }
}

// Usage examples
try {
    const response = await callAvatarAPI(message);
    if (!response.ok) {
        SecurityLogger.log('api_error', {
            status: response.status,
            endpoint: '/avatar/chat'
        });
    }
} catch (error) {
    SecurityLogger.log('api_failure', {
        error: error.message,
        endpoint: '/avatar/chat'
    });

    // Show user-friendly error
    showError('Sorry, the avatar is temporarily unavailable.');
}

// Rate limit violations
if (!rateLimiter.isAllowed()) {
    SecurityLogger.log('rate_limit_exceeded', {
        endpoint: '/avatar/chat',
        limit: rateLimiter.maxRequests
    });
}

// Suspicious input
if (isSuspiciousInput(userInput)) {
    SecurityLogger.log('suspicious_input', {
        input: userInput.substring(0, 100) // Log sample only
    });
}
                            

📊 Security Monitoring

🔍 Real-time Security Metrics

Monitor these key security indicators:

0
Failed Requests
0
Rate Limits Hit
0
Blocked IPs
100%
Uptime

⚠️ Security Alerts to Monitor

📈
Unusual traffic spikes
Sudden increases in API calls could indicate abuse
🚫
High error rates
Many failed requests might indicate an attack
🎯
Multiple failed authentications
Could indicate credential stuffing or brute force
🤖
Bot-like behavior patterns
Automated requests with regular intervals

🚨 Incident Response Plan

If you detect a security incident:

Immediate Response (0-15 minutes)

  • Document the incident with timestamps
  • Preserve logs and evidence
  • Block malicious IPs if identified
  • Contact Techtree Avatar security team: rr.startech.innovation@gmail.com

Assessment (15-60 minutes)

  • Determine scope and impact
  • Identify affected users/systems
  • Check for data breach or privacy violations
  • Review security logs for patterns

Containment (1-4 hours)

  • Implement additional security measures
  • Increase monitoring and alerting
  • Consider temporarily reducing service availability
  • Update security configurations

Recovery & Lessons Learned

  • Restore normal operations gradually
  • Monitor for recurring issues
  • Update security procedures
  • Conduct post-incident review
🛡️ Security Support
For security-related questions or incidents:
Email: rr.startech.innovation@gmail.com
Subject: [SECURITY] Your issue description
Response time: Critical issues within 4 hours
Include: Domain, API key ID (not the key itself), timestamps, and logs