npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-native-shield

v2.4.0

Published

Android security library for React Native apps - detect rooted devices, emulators, debug modes, VPN connections, and other security threats

Downloads

98

Readme

react-native-shield

npm version License: MIT Platform

A comprehensive React Native library for device security detection and environment validation. Ensure your app runs only on safe, trusted devices by detecting rooted devices, emulators, debug modes, VPN connections, and other security threats.

Features

🔒 Comprehensive Security Detection

  • Root/jailbreak detection
  • Emulator/simulator detection
  • Debug mode detection
  • Developer options detection
  • VPN connection detection
  • USB debugging detection
  • Device cloning detection
  • Virtual space detection
  • Suspicious app detection
  • Runtime integrity checks
  • Network monitoring detection
  • Biometric compromise detection
  • Performance anomaly detection

Performance Optimized

  • Fast mode for real-time checks
  • Configurable security levels
  • Parallel execution support
  • Built-in caching mechanism
  • Minimal battery impact

🎯 Developer Friendly

  • TypeScript support
  • Multiple configuration presets
  • Detailed security reports
  • User-friendly messages
  • Comprehensive documentation

Installation

npm install react-native-shield

or

yarn add react-native-shield

Android Setup

No additional setup required - the library uses autolinking.

Usage

Basic Usage

import Shield, { detectEnvironment } from 'react-native-shield';

// Simple security check
const result = await detectEnvironment();

// Check if device is in a secure environment
if (result.isInsecureEnvironment) {
  // Handle insecure environment
  console.log('Device security issues detected:', result.messages);
} else {
  console.log('Device is secure');
}

React Hook Usage

import { useShield } from 'react-native-shield';

function SecurityMonitor() {
  const { result, isLoading, error, runDetection } = useShield({
    intervalMs: 30000, // Check every 30 seconds
    config: {
      checkRooted: true,
      checkEmulator: true,
      checkVPN: true,
      includeUserMessages: true,
    },
    onResult: (result) => {
      if (result.isInsecureEnvironment) {
        console.warn('Security threats detected!');
        // Handle security alerts
      }
    },
  });

  if (isLoading) {
    return <Text>Checking device security...</Text>;
  }

  if (error) {
    return <Text>Error: {error}</Text>;
  }

  return (
    <View>
      <Text>Security Status: {result?.isInsecureEnvironment ? '⚠️ Insecure' : '✅ Secure'}</Text>
      <Button title="Check Now" onPress={runDetection} />
    </View>
  );
}

Using Configuration Presets

import Shield, { detectEnvironment, DEFAULT_PRESETS } from 'react-native-shield';

// Fast mode - quick security check
const fastResult = await detectEnvironment(DEFAULT_PRESETS.FAST);

// Balanced mode - recommended for most apps
const balancedResult = await detectEnvironment(DEFAULT_PRESETS.BALANCED);

// Comprehensive mode - maximum security
const comprehensiveResult = await detectEnvironment(DEFAULT_PRESETS.COMPREHENSIVE);

Custom Configuration

import Shield, { detectEnvironment } from 'react-native-shield';

const customConfig = {
  checkRooted: true,
  checkEmulator: true,
  checkDebuggable: true,
  checkVPN: true,
  checkInternet: true,
  includeUserMessages: true,
  includeRootDetails: true,
};

const result = await detectEnvironment(customConfig);

Advanced Usage with Error Handling

import Shield, { detectEnvironment, ShieldError, ErrorRecoveryUtils } from 'react-native-shield';

try {
  const securityCheck = await detectEnvironment({
    checkRooted: true,
    checkEmulator: true,
    includeUserMessages: true,
  });

  if (securityCheck.isInsecureEnvironment) {
    // Display security warnings to user
    securityCheck.messages?.forEach(message => {
      switch (message.severity) {
        case 'critical':
          // Block app functionality
          showCriticalAlert(message.title, message.message);
          break;
        case 'high':
          // Show warning but allow usage
          showWarningAlert(message.title, message.message);
          break;
        default:
          // Log for debugging
          console.warn(message.message);
      }
    });
  }
} catch (error) {
  if (error instanceof ShieldError) {
    console.error('Shield Error:', error.message);
    console.log('Suggestion:', error.suggestion);

    // Get and execute recovery actions
    const recoveryActions = ErrorRecoveryUtils.createRecoveryActions(error);
    const recoveryResult = await ErrorRecoveryUtils.executeRecovery(recoveryResult);

    if (recoveryResult.success) {
      console.log('Recovery successful:', recoveryResult.message);
    }
  } else {
    console.error('Security check failed:', error);
  }
}

One-Time Security Scan

import { useOneTimeSecurityScan } from 'react-native-shield';

function SecurityCheckButton() {
  const {
    result,
    isScanning,
    scanOnce,
    error
  } = useOneTimeSecurityScan({
    preset: 'BANKING',
    onComplete: (result) => {
      if (result.isInsecureEnvironment) {
        showSecurityAlert(result);
      }
    },
    onError: (error) => {
      console.error('Scan failed:', error);
    }
  });

  const handleScan = async () => {
    const result = await scanOnce();
    console.log('Security scan completed:', result);
  };

  return (
    <View>
      <Button
        title="Security Scan"
        onPress={handleScan}
        disabled={isScanning}
      />
      {result && (
        <Text>
          Security Score: {result.scanMetadata?.overallScore}/100
          {result.isInsecureEnvironment ? ' ⚠️ Insecure' : ' ✅ Secure'}
        </Text>
      )}
      {error && <Text style={{color: 'red'}}>Error: {error}</Text>}
    </View>
  );
}

App State Shield Hook

The useAppStateShield hook provides automatic security detection that responds to app lifecycle changes. It integrates React Native's AppState API with security monitoring to automatically trigger detectEnvironment calls when the app transitions between active, inactive, and background states.

Hook Parameters

interface UseAppStateShieldOptions {
  onResult?: (result: DetectEnvironmentResult) => void;
  config?: DetectEnvironmentConfig;
  enabled?: boolean;
  debounceMs?: number;
  triggerOnStateChange?: 'all' | 'toActive' | 'toBackground' | 'activeOnly' | 'backgroundOnly';
  includeCurrentState?: boolean;
}

Hook Return Value

interface UseAppStateShieldReturn {
  currentState: AppStateStatus;
  isDetecting: boolean;
  lastResult: DetectEnvironmentResult | null;
  error: string | null;
  detectionCount: number;
  runDetection: () => Promise<void>;
}

Usage Examples

import { useAppStateShield } from 'react-native-shield';

function SecurityMonitor() {
  const {
    currentState,
    isDetecting,
    lastResult,
    detectionCount
  } = useAppStateShield({
    onResult: (result) => {
      if (result.isInsecureEnvironment) {
        console.warn('Security threats detected:', result.messages);
        // Handle security threats
      }
    },
    config: { checkRooted: true, checkEmulator: true }
  });

  return (
    <View>
      <Text>App State: {currentState}</Text>
      <Text>Detections: {detectionCount}</Text>
      {isDetecting && <Text>Checking security...</Text>}
      {lastResult?.isInsecureEnvironment && (
        <Text style={{color: 'red'}}>⚠️ Security threats detected!</Text>
      )}
    </View>
  );
}

// Detect only when app becomes active
function ActiveStateSecurity() {
  const { runDetection } = useAppStateShield({
    onResult: handleSecurityResult,
    triggerOnStateChange: 'toActive',
    debounceMs: 2000,
    config: { enableFastMode: true }
  });

  return (
    <View>
      <Text>Security check runs when app becomes active</Text>
      <Button title="Manual Check" onPress={runDetection} />
    </View>
  );
}

// Background-only monitoring
function BackgroundSecurity() {
  useAppStateShield({
    triggerOnStateChange: 'backgroundOnly',
    config: {
      checkVPN: true,
      checkInternet: true,
      enableFastMode: true
    },
    onResult: (result) => {
      if (result.isVPNActive) {
        console.log('VPN activated in background');
      }
    }
  });

  return <Text>Monitoring security in background...</Text>;
}

useShield Hook

The useShield hook provides a React-friendly way to integrate continuous security monitoring into your React Native components. It automatically handles periodic security checks, state management, and cleanup.

Hook Parameters

interface UseShieldOptions {
  onResult?: (result: DetectEnvironmentResult) => void;
  intervalMs?: number;
  config?: DetectEnvironmentConfig;
  enabled?: boolean;
}

Hook Return Value

interface UseShieldReturn {
  result: DetectEnvironmentResult | null;
  isLoading: boolean;
  error: string | null;
  runDetection: () => Promise<void>;
}

Advanced Usage Examples

import { useShield, DEFAULT_PRESETS } from 'react-native-shield';

function SecurityDashboard() {
  // Fast security checks every 10 seconds
  const { result, isLoading } = useShield({
    intervalMs: 10000,
    config: DEFAULT_PRESETS.FAST,
    onResult: (result) => {
      if (result.isInsecureEnvironment) {
        // Send alert to security dashboard
        sendSecurityAlert(result);
      }
    },
  });

  return (
    <View>
      <Text>Rooted: {result?.isRooted ? 'Yes' : 'No'}</Text>
      <Text>Emulator: {result?.isEmulator ? 'Yes' : 'No'}</Text>
      <Text>VPN Active: {result?.isVPNActive ? 'Yes' : 'No'}</Text>
      {isLoading && <Text>Checking...</Text>}
    </View>
  );
}

// Custom configuration for specific security concerns
function BankingSecurity() {
  const { result, runDetection } = useShield({
    config: {
      checkRooted: true,
      checkEmulator: true,
      checkDebuggerAttached: true,
      checkBiometricCompromised: true,
      checkRuntimeIntegrity: true,
      includeUserMessages: true,
      enableDetailedChecks: true,
    },
    intervalMs: 60000, // Check every minute for banking apps
    onResult: (result) => {
      if (result.isInsecureEnvironment) {
        // Block sensitive operations
        blockBankingOperations();
      }
    },
  });

  return (
    <TouchableOpacity onPress={runDetection}>
      <Text>Run Security Check</Text>
    </TouchableOpacity>
  );
}

// Disabled hook with manual control
function ManualSecurityCheck() {
  const { result, runDetection } = useShield({
    enabled: false, // Manual control only
    config: DEFAULT_PRESETS.BALANCED,
  });

  const handleSecurityCheck = async () => {
    await runDetection();
    // Handle result
    if (result?.isInsecureEnvironment) {
      showSecurityWarning();
    }
  };

  return (
    <Button
      title="Check Device Security"
      onPress={handleSecurityCheck}
    />
  );
}

Error Handling

The hook gracefully handles various edge cases:

function ErrorHandlingExample() {
  const { error, result } = useShield({
    intervalMs: 500, // Too short - will show warning
    config: {}, // Valid config
    onResult: (result) => {
      console.log('Security check completed');
    },
  });

  useEffect(() => {
    if (error) {
      // Handle configuration errors
      console.warn('Shield configuration warning:', error);
    }
  }, [error]);

  return <Text>Check console for errors</Text>;
}

Security Metrics Hook

The useSecurityMetrics hook provides comprehensive security analytics and monitoring capabilities with historical tracking and trend analysis.

Hook Parameters

interface UseSecurityMetricsOptions {
  enabled?: boolean;
  scanInterval?: number;
  scanConfig?: DetectEnvironmentConfig;
  trackHistory?: boolean;
  maxHistorySize?: number;
  onMetricsUpdate?: (metrics: SecurityMetrics) => void;
  onThreatDetected?: (result: DetectEnvironmentResult) => void;
}

Hook Return Value

interface UseSecurityMetricsReturn {
  metrics: SecurityMetrics | null;
  isScanning: boolean;
  lastScanResult: DetectEnvironmentResult | null;
  runScan: () => Promise<void>;
  generateReport: () => string;
  clearHistory: () => void;
}

Usage Example

import { useSecurityMetrics } from 'react-native-shield';

function SecurityAnalytics() {
  const {
    metrics,
    isScanning,
    generateReport
  } = useSecurityMetrics({
    scanInterval: 300000, // 5 minutes
    trackHistory: true,
    onThreatDetected: (result) => {
      console.warn('Security threats detected:', result.messages);
    }
  });

  if (isScanning) {
    return <Text>Analyzing security metrics...</Text>;
  }

  return (
    <View>
      <Text>Overall Score: {metrics?.overallScore}/100</Text>
      <Text>Threat Level: {metrics?.threatLevel}</Text>
      <Text>Performance Impact: {metrics?.performanceImpact}</Text>
      <Button
        title="Generate Report"
        onPress={() => console.log(generateReport())}
      />
    </View>
  );
}

Configuration Builder

The SecurityConfigBuilder provides a fluent API for creating complex security configurations with industry-specific presets and customizations.

Usage Examples

import { SecurityConfig } from 'react-native-shield';

// Banking app configuration
const bankingConfig = SecurityConfig
  .forBanking()
  .enableRealTimeMonitoring(60000)
  .withCustomResponses({
    rooted: 'block',
    emulator: 'block'
  })
  .build();

// Custom configuration
const customConfig = SecurityConfig
  .builder()
  .forEnvironment('production')
  .withThreatLevel('high')
  .withAllChecks()
  .enablePerformanceOptimizations()
  .withUserMessaging(true, true)
  .build();

// Use with hooks
const { result } = useShield({
  config: bankingConfig,
  onResult: (result) => handleSecurityResult(result)
});

Industry-Specific Presets

import { INDUSTRY_PRESETS } from 'react-native-shield';

// Available presets
const presets = {
  BANKING: 'High-security for financial applications',
  GAMING: 'Anti-cheat optimized for gaming',
  HEALTHCARE: 'HIPAA-compliant medical applications',
  E_COMMERCE: 'PCI DSS ready for shopping apps',
  SOCIAL_MEDIA: 'User privacy focused social apps',
  ENTERPRISE: 'Corporate security with MDM integration'
};

// Use a preset
const bankingPreset = INDUSTRY_PRESETS.BANKING;
console.log('Compliance notes:', bankingPreset.complianceNotes);
console.log('Threat level:', bankingPreset.threatLevel);

Error Handling & Recovery

The library includes comprehensive error handling with automatic recovery mechanisms:

import { detectEnvironment, ShieldError, ErrorRecoveryUtils } from 'react-native-shield';

try {
  const result = await detectEnvironment(config);
} catch (error) {
  if (error instanceof ShieldError) {
    // Enhanced error information
    console.log('Error code:', error.code);
    console.log('Severity:', error.severity);
    console.log('Suggestion:', error.suggestion);
    console.log('Context:', error.context);

    // Automatic recovery
    const recoveryActions = ErrorRecoveryUtils.createRecoveryActions(error);
    const recoveryResult = await ErrorRecoveryUtils.executeRecovery(recoveryActions);

    if (recoveryResult.success) {
      console.log('Recovery successful!');
    }
  }
}

Configuration Options

Basic Security Checks

  • checkWorkProfile - Detect Android work profiles
  • checkCloned - Detect device cloning
  • checkSecondaryUser - Detect secondary user accounts
  • checkRooted - Detect root access
  • checkEmulator - Detect emulator/simulator
  • checkDebuggable - Detect debuggable builds
  • checkDeveloperMode - Detect developer mode
  • checkUSBDebugging - Detect USB debugging
  • checkVPN - Detect VPN connections
  • checkHooked - Detect hooking frameworks
  • checkTampered - Detect system tampering
  • checkVirtualSpace - Detect virtual spaces
  • checkSuspiciousApps - Detect suspicious apps
  • checkSandbox - Detect sandbox environments

Advanced Security Checks

  • checkDebuggerAttached - Detect active debugger
  • checkRunningInBackground - Detect background execution
  • checkProxy - Detect proxy settings
  • checkNetworkMonitoring - Detect network monitoring
  • checkBiometricCompromised - Detect biometric compromise
  • checkPerformanceAnomaly - Detect performance anomalies
  • checkRuntimeIntegrity - Detect runtime integrity issues
  • checkInternet - Test internet connectivity

Performance Options

  • includeRootDetails - Include detailed root detection info
  • enableFastMode - Enable fast mode for quicker results
  • enableDetailedChecks - Enable comprehensive security checks
  • includeUserMessages - Include user-friendly messages

Security Presets

🚀 Fast Mode

Ultra-fast security checks for real-time validation:

  • Root detection
  • Emulator detection
  • Debug mode detection
  • Developer options detection

⚖️ Balanced Mode (Recommended)

Balanced security and performance for most applications:

  • All basic security checks
  • VPN detection
  • USB debugging detection
  • Virtual space detection
  • Suspicious app detection
  • Internet connectivity check

🛡️ Comprehensive Mode

Maximum security for high-security applications:

  • All available security checks
  • Detailed root analysis
  • Runtime integrity checks
  • Biometric compromise detection
  • Performance anomaly detection
  • Network monitoring detection

🔧 Development Mode

Full security analysis for development and debugging:

  • Comprehensive security checks
  • Detailed reporting
  • User-friendly messages
  • Root detection details

Platform Support

| Platform | Status | Notes | |----------|--------|-------| | Android | ✅ Supported | Full security suite with TurboModule | | iOS | ❌ Not supported | Library is Android-only | | Expo | ❌ Not supported | Requires native modules |

API Reference

detectEnvironment(config?: DetectEnvironmentConfig): Promise<DetectEnvironmentResult>

Main security detection function.

Parameters:

  • config (optional): Configuration object for security checks

Returns:

  • Promise resolving to security analysis results

testInternetConnection(): Promise<ConnectionResult>

Test internet connectivity and network configuration.

useShield(options?: UseShieldOptions): UseShieldReturn

React hook for periodic security environment detection.

Parameters:

  • options.onResult? - Callback function to handle detection results
  • options.intervalMs? - Interval time in milliseconds for periodic checks (default: 30000ms)
  • options.config? - Configuration object for detectEnvironment function
  • options.enabled? - Whether the hook should be active (default: true)

Returns:

  • result - Current detection result or null
  • isLoading - Whether a detection is currently in progress
  • error - Any error that occurred during detection
  • runDetection - Function to manually trigger a detection

testVpnConnection(): Promise<VpnResult>

Test VPN connection status and configuration.

useSecurityMetrics(options?: UseSecurityMetricsOptions): UseSecurityMetricsReturn

React hook for security analytics and monitoring.

Parameters:

  • options.enabled? - Whether metrics collection is active
  • options.scanInterval? - How often to run scans (default: 5 minutes)
  • options.scanConfig? - Configuration for scans
  • options.trackHistory? - Whether to maintain history
  • options.onMetricsUpdate? - Callback for metrics updates
  • options.onThreatDetected? - Callback for threat detection

Returns:

  • metrics - Current security metrics
  • isScanning - Whether scanning is active
  • runScan - Manual scan trigger
  • generateReport - Report generation function
  • clearHistory - History clearing function

useOneTimeSecurityScan(options?: UseOneTimeSecurityScanOptions): UseOneTimeSecurityScanReturn

React hook for single security scans.

Parameters:

  • options.config? - Scan configuration
  • options.preset? - Industry preset to use
  • options.onComplete? - Completion callback
  • options.onError? - Error callback

Returns:

  • result - Scan result
  • isScanning - Whether scanning is active
  • error - Any error that occurred
  • scanOnce - Manual scan trigger
  • clearResult - Result clearing function

useAppStateShield(options?: UseAppStateShieldOptions): UseAppStateShieldReturn

React hook for app lifecycle-aware security monitoring.

Parameters:

  • options.onResult? - Callback function to handle detection results
  • options.config? - Configuration object for detectEnvironment function
  • options.enabled? - Whether the hook should be active (default: true)
  • options.debounceMs? - Debounce delay in milliseconds for rapid state changes (default: 1000ms)
  • options.triggerOnStateChange? - Which state transitions should trigger detection (default: 'all')
  • options.includeCurrentState? - Whether to run detection on mount with current state (default: false)

Returns:

  • currentState - Current app state
  • isDetecting - Whether a detection is currently in progress
  • lastResult - Last detection result
  • error - Any error that occurred during detection
  • detectionCount - Number of detections performed
  • runDetection - Function to manually trigger a detection

SecurityConfigBuilder

Fluent API for building security configurations.

Methods:

  • forEnvironment(env) - Set environment (development/production/testing)
  • withThreatLevel(level) - Set threat level (low/medium/high/critical)
  • withChecks(checks) - Enable specific checks
  • withAllChecks() - Enable all available checks
  • enableRealTimeMonitoring(interval) - Enable periodic monitoring
  • enablePerformanceOptimizations() - Enable performance mode
  • withCustomResponses(responses) - Set custom threat responses
  • withUserMessaging(include, details) - Configure user messages
  • forUseCase(useCase) - Configure for specific industries

Static Methods:

  • SecurityConfigBuilder.create() - Create new builder
  • SecurityConfigBuilder.preset(type) - Create with preset

SecurityConfig

Convenience functions for common configurations.

Functions:

  • SecurityConfig.builder() - Create new builder
  • SecurityConfig.preset(type) - Create preset configuration
  • SecurityConfig.forBanking() - Banking-optimized config
  • SecurityConfig.forGaming() - Gaming-optimized config
  • SecurityConfig.forHealthcare() - Healthcare-optimized config
  • SecurityConfig.forEcommerce() - E-commerce-optimized config
  • SecurityConfig.forSocial() - Social media-optimized config

INDUSTRY_PRESETS

Pre-configured industry-specific security presets.

Available Presets:

  • BANKING - High-security for financial applications
  • GAMING - Anti-cheat optimized for gaming
  • HEALTHCARE - HIPAA-compliant medical applications
  • E_COMMERCE - PCI DSS ready for shopping apps
  • SOCIAL_MEDIA - User privacy focused social apps
  • ENTERPRISE - Corporate security with MDM integration

Error Handling

ShieldError

Enhanced error class with detailed information.

Properties:

  • code - Error classification code
  • severity - Error severity level
  • suggestion - Suggested resolution
  • timestamp - When error occurred
  • context - Additional error context

ErrorRecoveryUtils

Automatic error recovery utilities.

Functions:

  • ErrorRecoveryUtils.createRecoveryActions(error) - Generate recovery actions
  • ErrorRecoveryUtils.executeRecovery(actions) - Execute recovery actions
  • ErrorRecoveryUtils.formatErrorMessage(error) - Format error for display

Examples

Check out the example directory for a complete implementation showing how to integrate react-native-shield into your React Native app.

Contributing

We welcome contributions! Please see our Contributing Guide for details:

Security Reporting

If you discover any security vulnerabilities, please report them responsibly by:

  1. Creating an issue in the GitHub repository
  2. Emailing the maintainer directly at [email protected]

License

MIT © atul7017128880


Made with ❤️ using react-native-builder-bob