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
Maintainers
Readme
react-native-shield
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-shieldor
yarn add react-native-shieldAndroid 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 profilescheckCloned- Detect device cloningcheckSecondaryUser- Detect secondary user accountscheckRooted- Detect root accesscheckEmulator- Detect emulator/simulatorcheckDebuggable- Detect debuggable buildscheckDeveloperMode- Detect developer modecheckUSBDebugging- Detect USB debuggingcheckVPN- Detect VPN connectionscheckHooked- Detect hooking frameworkscheckTampered- Detect system tamperingcheckVirtualSpace- Detect virtual spacescheckSuspiciousApps- Detect suspicious appscheckSandbox- Detect sandbox environments
Advanced Security Checks
checkDebuggerAttached- Detect active debuggercheckRunningInBackground- Detect background executioncheckProxy- Detect proxy settingscheckNetworkMonitoring- Detect network monitoringcheckBiometricCompromised- Detect biometric compromisecheckPerformanceAnomaly- Detect performance anomaliescheckRuntimeIntegrity- Detect runtime integrity issuescheckInternet- Test internet connectivity
Performance Options
includeRootDetails- Include detailed root detection infoenableFastMode- Enable fast mode for quicker resultsenableDetailedChecks- Enable comprehensive security checksincludeUserMessages- 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 resultsoptions.intervalMs?- Interval time in milliseconds for periodic checks (default: 30000ms)options.config?- Configuration object for detectEnvironment functionoptions.enabled?- Whether the hook should be active (default: true)
Returns:
result- Current detection result or nullisLoading- Whether a detection is currently in progresserror- Any error that occurred during detectionrunDetection- 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 activeoptions.scanInterval?- How often to run scans (default: 5 minutes)options.scanConfig?- Configuration for scansoptions.trackHistory?- Whether to maintain historyoptions.onMetricsUpdate?- Callback for metrics updatesoptions.onThreatDetected?- Callback for threat detection
Returns:
metrics- Current security metricsisScanning- Whether scanning is activerunScan- Manual scan triggergenerateReport- Report generation functionclearHistory- History clearing function
useOneTimeSecurityScan(options?: UseOneTimeSecurityScanOptions): UseOneTimeSecurityScanReturn
React hook for single security scans.
Parameters:
options.config?- Scan configurationoptions.preset?- Industry preset to useoptions.onComplete?- Completion callbackoptions.onError?- Error callback
Returns:
result- Scan resultisScanning- Whether scanning is activeerror- Any error that occurredscanOnce- Manual scan triggerclearResult- Result clearing function
useAppStateShield(options?: UseAppStateShieldOptions): UseAppStateShieldReturn
React hook for app lifecycle-aware security monitoring.
Parameters:
options.onResult?- Callback function to handle detection resultsoptions.config?- Configuration object for detectEnvironment functionoptions.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 stateisDetecting- Whether a detection is currently in progresslastResult- Last detection resulterror- Any error that occurred during detectiondetectionCount- Number of detections performedrunDetection- 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 checkswithAllChecks()- Enable all available checksenableRealTimeMonitoring(interval)- Enable periodic monitoringenablePerformanceOptimizations()- Enable performance modewithCustomResponses(responses)- Set custom threat responseswithUserMessaging(include, details)- Configure user messagesforUseCase(useCase)- Configure for specific industries
Static Methods:
SecurityConfigBuilder.create()- Create new builderSecurityConfigBuilder.preset(type)- Create with preset
SecurityConfig
Convenience functions for common configurations.
Functions:
SecurityConfig.builder()- Create new builderSecurityConfig.preset(type)- Create preset configurationSecurityConfig.forBanking()- Banking-optimized configSecurityConfig.forGaming()- Gaming-optimized configSecurityConfig.forHealthcare()- Healthcare-optimized configSecurityConfig.forEcommerce()- E-commerce-optimized configSecurityConfig.forSocial()- Social media-optimized config
INDUSTRY_PRESETS
Pre-configured industry-specific security presets.
Available Presets:
BANKING- High-security for financial applicationsGAMING- Anti-cheat optimized for gamingHEALTHCARE- HIPAA-compliant medical applicationsE_COMMERCE- PCI DSS ready for shopping appsSOCIAL_MEDIA- User privacy focused social appsENTERPRISE- Corporate security with MDM integration
Error Handling
ShieldError
Enhanced error class with detailed information.
Properties:
code- Error classification codeseverity- Error severity levelsuggestion- Suggested resolutiontimestamp- When error occurredcontext- Additional error context
ErrorRecoveryUtils
Automatic error recovery utilities.
Functions:
ErrorRecoveryUtils.createRecoveryActions(error)- Generate recovery actionsErrorRecoveryUtils.executeRecovery(actions)- Execute recovery actionsErrorRecoveryUtils.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:
- Creating an issue in the GitHub repository
- Emailing the maintainer directly at [email protected]
License
MIT © atul7017128880
Made with ❤️ using react-native-builder-bob
