API Documentation

Manthra Integration Guide

Complete developer documentation for integrating Manthra's advanced protection system

Getting Started

Manthra provides comprehensive web application protection through behavioral analysis, advanced anti-debugging, and intelligent detection methods. Get started in minutes with our simple integration.

Quick Start

1 Add the script tag to your HTML
<script src="https://manthra.cc/get-script/YOUR_KEY" async></script>
2 Wait for Manthra to initialize
window.onManthraReady(function(manthra) {
  console.log('🛡️ Protection is now active!');
});
3 Customize protection (optional)
window.onManthraReady(function(manthra) {
  // Override violation handling
  manthra.handleViolation = function(type) {
    // Your custom logic here
    console.log('Security event:', type);
  };
});
Important: Always wait for Manthra to be ready before attempting to interact with the protection system. This ensures all security measures are properly initialized.

Detection API NEW

Manthra's new detection API provides robust methods for detecting when the protection system is loaded and handling security events in real-time.

Global Detection Methods

window.onManthraReady(callback)

Register a callback function to execute when Manthra is fully loaded and initialized. This is the recommended way to interact with Manthra.

Parameters:
callback (Function): Function to execute when Manthra is ready. Receives the Manthra object as the first parameter.
Example:
window.onManthraReady(function(manthra) {
  console.log('Manthra is ready:', manthra);

  // Override violation handlers
  const originalHandler = manthra.handleViolation;
  manthra.handleViolation = function(type) {
    // Send to analytics
    analytics.track('security_violation', { type: type });

    // Show custom message
    showCustomSecurityMessage(type);

    // Call original handler
    return originalHandler.call(this, type);
  };
});

window.ManthraLoaded

Global boolean flag indicating whether Manthra has been loaded and initialized successfully.

Type:
Boolean: true if Manthra is loaded, false or undefined otherwise.
Example:
if (window.ManthraLoaded) {
  console.log('Manthra is already loaded');
  // Direct access to window.Manthra
  window.Manthra.handleViolation('test');
} else {
  console.log('Manthra not yet loaded');
  // Use onManthraReady callback
  window.onManthraReady(function(manthra) {
    manthra.handleViolation('test');
  });
}

window.Manthra

Direct reference to the Manthra protection object. Only available after the protection system has been fully loaded.

Available Methods:
handleViolation(type): Manually trigger a security violation
handleDomainViolation(type): Handle domain-specific violations
stopProtection(): Stop the protection system
settings: Access current configuration settings
Warning: Do not access window.Manthra directly unless you've confirmed window.ManthraLoaded is true. Use window.onManthraReady() for safe access.

Events & Handlers

Manthra dispatches custom events and provides handler override capabilities for comprehensive integration with your application.

manthra:ready Event

Custom event dispatched when Manthra is fully loaded and initialized. Alternative to the callback-based approach.

Event Details:
event.detail.manthra: Reference to the Manthra protection object
Example:
window.addEventListener('manthra:ready', function(event) {
  const manthra = event.detail.manthra;
  console.log('Manthra ready event received:', manthra);

  // Your integration code here
  setupCustomProtection(manthra);
});

Violation Handlers

Customize how Manthra responds to security violations by overriding the built-in handlers:

window.onManthraReady(function(manthra) {
  // Override general violation detection
  const originalHandleViolation = manthra.handleViolation;
  manthra.handleViolation = function(type) {
    // Log to your analytics service
    analytics.track('security_violation', { 
      type: type,
      timestamp: Date.now(),
      userAgent: navigator.userAgent,
      url: window.location.href
    });

    // Show custom notification
    showSecurityNotification(`Security measure triggered: ${type}`);

    // Call original handler if needed
    return originalHandleViolation.call(this, type);
  };

  // Override domain violations
  const originalHandleDomainViolation = manthra.handleDomainViolation;
  manthra.handleDomainViolation = function(type) {
    console.log('Domain violation:', type);
    // Custom domain violation logic
    redirectToErrorPage();
    return originalHandleDomainViolation.call(this, type);
  };
});

Configuration

Configure Manthra's behavior through your dashboard settings or programmatic overrides.

Dashboard Configuration

Primary configuration is handled through the Manthra dashboard:

  • Domain Locking: Set the target domain for protection
  • Protection Features: Enable/disable specific detection methods
  • Response Actions: Configure redirect URLs and error pages
  • Detection Intervals: Set timing for protection checks

Runtime Configuration

window.onManthraReady(function(manthra) {
  // Access current settings
  console.log('Current settings:', manthra.settings);

  // Settings are read-only and configured via dashboard
  // You can only override violation handlers at runtime
  manthra.handleViolation = function(type) {
    console.log('Custom handling for:', type);
    // Your custom logic here
  };
});

Integration Examples

Basic Website Integration

<!DOCTYPE html>
<html>
<head>
  <title>My Protected Website</title>
</head>
<body>
  <h1>Welcome to My Protected Site</h1>

  <!-- Manthra Protection Script -->
  <script src="https://manthra.cc/get-script/YOUR_KEY" async></script>

  <script>
    window.onManthraReady(function(manthra) {
      console.log('✅ Website is now protected by Manthra');

      // Optional: Add protection status indicator
      document.body.insertAdjacentHTML('beforeend', 
        '<div style="position:fixed;bottom:10px;right:10px;background:#10b981;color:white;padding:8px;border-radius:4px;font-size:12px;">🛡️ Protected</div>'
      );
    });
  </script>
</body>
</html>

Advanced Integration with Analytics

class SecurityManager {
  constructor() {
    this.violations = [];
    this.initManthra();
  }

  initManthra() {
    window.onManthraReady((manthra) => {
      console.log('🛡️ Security manager initialized');

      // Override violation handler
      const originalHandler = manthra.handleViolation;
      manthra.handleViolation = (type) => {
        this.logViolation(type);
        this.showUserFriendlyMessage(type);

        // Decide whether to call original handler
        if (this.shouldBlockViolation(type)) {
          return originalHandler.call(manthra, type);
        }
      };
    });
  }

  logViolation(type) {
    const violation = {
      type: type,
      timestamp: Date.now(),
      url: window.location.href,
      userAgent: navigator.userAgent,
      sessionId: this.getSessionId()
    };

    this.violations.push(violation);

    // Send to analytics service
    if (typeof gtag !== 'undefined') {
      gtag('event', 'security_violation', {
        violation_type: type,
        custom_parameter: 'manthra_protection'
      });
    }

    // Send to your backend
    fetch('/api/security-log', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(violation)
    }).catch(console.error);
  }

  showUserFriendlyMessage(type) {
    const messages = {
      'devtools': 'For security reasons, developer tools are not allowed.',
      'debugging': 'Debugging is restricted on this application.',
      'inspection': 'Code inspection is not permitted.'
    };

    const message = messages[type] || 'Security measure activated.';
    this.displayNotification(message);
  }

  shouldBlockViolation(type) {
    // Custom logic to determine if violation should be blocked
    const allowedInDevelopment = ['devtools'];
    const isDevelopment = window.location.hostname === 'localhost';

    return !(isDevelopment && allowedInDevelopment.includes(type));
  }

  displayNotification(message) {
    // Create and show a user-friendly notification
    const notification = document.createElement('div');
    notification.style.cssText = `
      position: fixed; top: 20px; right: 20px; z-index: 10000;
      background: linear-gradient(135deg, #ef4444, #dc2626);
      color: white; padding: 16px 20px; border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      font-family: system-ui; font-size: 14px;
      max-width: 300px; animation: slideIn 0.3s ease;
    `;
    notification.textContent = message;

    document.body.appendChild(notification);
    setTimeout(() => notification.remove(), 5000);
  }

  getSessionId() {
    return sessionStorage.getItem('sessionId') || 
           Math.random().toString(36).substr(2, 9);
  }
}

// Initialize security manager
const securityManager = new SecurityManager();

React Integration Hook

import { useEffect, useState } from 'react';

function useManthra() {
  const [isLoaded, setIsLoaded] = useState(false);
  const [manthra, setManthra] = useState(null);
  const [violations, setViolations] = useState([]);

  useEffect(() => {
    if (window.ManthraLoaded) {
      setIsLoaded(true);
      setManthra(window.Manthra);
    } else {
      window.onManthraReady((manthraInstance) => {
        setIsLoaded(true);
        setManthra(manthraInstance);

        // Setup violation tracking
        const originalHandler = manthraInstance.handleViolation;
        manthraInstance.handleViolation = function(type) {
          setViolations(prev => [...prev, {
            type,
            timestamp: Date.now()
          }]);

          return originalHandler.call(this, type);
        };
      });
    }
  }, []);

  return { isLoaded, manthra, violations };
}

// Usage in React component
function ProtectedApp() {
  const { isLoaded, manthra, violations } = useManthra();

  useEffect(() => {
    if (isLoaded && manthra) {
      console.log('React app is now protected by Manthra');
    }
  }, [isLoaded, manthra]);

  return (
    <div>
      <header>
        {isLoaded ? (
          <div className="protection-status">
            🛡️ Protected by Manthra
          </div>
        ) : (
          <div className="loading-protection">
            Loading protection...
          </div>
        )}
      </header>

      {/* Your app content */}
      <main>
        <h1>My Protected React App</h1>
      </main>

      {/* Optional: Show violations in development */}
      {process.env.NODE_ENV === 'development' && (
        <div className="debug-violations">
          <h3>Security Events: {violations.length}</h3>
          {violations.map((v, i) => (
            <div key={i}>{v.type} at {new Date(v.timestamp).toLocaleTimeString()}</div>
          ))}
        </div>
      )}
    </div>
  );
}

Troubleshooting

Common Issues

Manthra Not Loading

If window.onManthraReady never executes, check these common causes:

  • Verify your API key is correct and active
  • Ensure the domain is whitelisted in your dashboard
  • Check browser console for script loading errors
  • Confirm the script tag is properly formatted
  • Check for ad blockers or security extensions blocking the script
Debug Helper:
// Add timeout fallback for debugging
const loadingTimeout = setTimeout(() => {
  if (!window.ManthraLoaded) {
    console.error('Manthra failed to load within 10 seconds');
    console.log('Check:', {
      scriptExists: !!document.querySelector('script[src*="get-script"]'),
      networkErrors: 'Check browser network tab',
      adBlocker: 'Check if ad blocker is active',
      domainConfig: 'Verify domain is configured in dashboard'
    });
  }
}, 10000);

window.onManthraReady(function(manthra) {
  clearTimeout(loadingTimeout);
  console.log('✅ Manthra loaded successfully');
});

Domain Configuration Issues

If you see "Domain locking is required - no target domain configured":

  • Go to your Manthra dashboard settings
  • Add your exact domain to the allowed domains list
  • Include subdomains if necessary (e.g., both "example.com" and "www.example.com")
  • Wait 2-3 minutes for configuration changes to propagate
  • Clear browser cache if the issue persists

Testing & Validation

// Comprehensive Manthra test suite
function validateManthraIntegration() {
  console.log('🔍 Testing Manthra integration...');

  const tests = {
    scriptLoaded: !!document.querySelector('script[src*="get-script"]'),
    globalVariableSet: typeof window.onManthraReady === 'function',
    manthraLoaded: !!window.ManthraLoaded,
    manthraObject: !!window.Manthra
  };

  console.table(tests);

  if (tests.manthraLoaded && tests.manthraObject) {
    console.log('✅ Manthra integration successful');

    // Test available methods
    const availableMethods = ['handleViolation', 'handleDomainViolation', 'stopProtection'];
    availableMethods.forEach(method => {
      console.log(`${method} available:`, typeof window.Manthra[method] === 'function');
    });

  } else if (tests.scriptLoaded && tests.globalVariableSet) {
    console.log('⏳ Manthra loading in progress...');
  } else {
    console.log('❌ Manthra integration issues detected');
  }

  return tests;
}

// Run validation
window.onManthraReady(function(manthra) {
  console.log('🛡️ Manthra ready! Running validation...');
  validateManthraIntegration();

  // Log protection details
  console.log('Protection info:', {
    settings: manthra.settings || {},
    isRunning: manthra.isRunning,
    availableMethods: Object.getOwnPropertyNames(manthra).filter(name => 
      typeof manthra[name] === 'function'
    )
  });
});

// Also run immediate validation
setTimeout(validateManthraIntegration, 1000);

Performance Monitoring

// Monitor Manthra's performance impact
function monitorManthraPerformance() {
  const startTime = performance.now();

  window.onManthraReady(function(manthra) {
    const loadTime = performance.now() - startTime;
    console.log(`Manthra loaded in ${loadTime.toFixed(2)}ms`);

    // Monitor ongoing performance
    const observer = new PerformanceObserver((list) => {
      list.getEntries().forEach((entry) => {
        if (entry.name.includes('manthra')) {
          console.log('Manthra performance:', entry);
        }
      });
    });

    observer.observe({ entryTypes: ['measure', 'navigation'] });
  });
}

monitorManthraPerformance();