Advanced Features
Advanced Features
Section titled “Advanced Features”Get All Risk Factors
Section titled “Get All Risk Factors”// Returns: Future<List<String>>// A comprehensive list of all risk factors detected across all scans// Includes cumulative security concerns, not just current threatsfinal riskFactors = await AlphynSdk.getAllRiskFactors();print('Total Risk Factors: ${riskFactors.length}');
// Example output:// [// 'COMMON_SUSPICIOUS_PATH',// 'SIMULATOR_ENVIRONMENT',// 'SIMULATOR_RUNTIME',// 'DEBUGGER_SYSTEM_CHECK',// 'DEBUGGER_PROCESS_CHECK',// 'DEBUGGER_EXCEPTION_CHECK',// 'VPN_IN_USE',// 'FRIDA_DETECTED',// 'FRIDA_SERVER_RUNNING'// ]
for (var factor in riskFactors) { print('Risk Factor: $factor');}Purpose: Returns a complete list of all security risk factors detected. This includes:
- Historical security issues
- Cumulative risk assessment data
- All threat categories identified
- Device security profile information
Use this for:
- Comprehensive security reporting
- Risk scoring and analysis
- Security dashboards
- Historical threat tracking
Get All Scan Results with Date Filtering
Section titled “Get All Scan Results with Date Filtering”// Returns: Future<List<String>>// A list of all scan results, optionally filtered by date range// Each string represents a complete scan report from a specific time
// Get all scan results (no filter)final allResults = await AlphynSdk.getAllScanResults();
// Get scan results from the last 7 daysfinal lastWeek = DateTime.now().subtract(Duration(days: 7));final recentResults = await AlphynSdk.getAllScanResults( startEpochMs: lastWeek.millisecondsSinceEpoch, endEpochMs: DateTime.now().millisecondsSinceEpoch,);
print('Total scans: ${allResults.length}');print('Recent scans (7 days): ${recentResults.length}');
// Example output:// [// 'ScanResult(date: 2025-11-20 11:21:29 +0000, detections: ["Detection: COMMON_SUSPICIOUS_PATH Severity: HIGH", "Detection: SIMULATOR_RUNTIME Severity: CRITICAL"])',// 'ScanResult(date: 2025-11-20 11:21:30 +0000, detections: ["Detection: FRIDA_DETECTED, FRIDA_SERVER_RUNNING Severity: CRITICAL"])'// ]
// Parse scan resultsfor (var scanResult in recentResults) { print('Scan: $scanResult');
// Extract date and detections from the string if (scanResult.contains('date:')) { // Parse the scan result string as needed }}Purpose: Retrieves historical scan data with optional date range filtering. This allows you to:
- Analyze security trends over time
- Generate historical security reports
- Track security improvements or degradation
- Export scan history for compliance
- Filter scans by specific time periods
Parameters:
startEpochMs(optional): Beginning of the date range in milliseconds since epoch (inclusive)endEpochMs(optional): End of the date range in milliseconds since epoch (inclusive)- If both omitted: Returns all available scan results
Update Scan Interval
Section titled “Update Scan Interval”// Returns: Future<void>// Updates the scan interval in seconds
await AlphynSdk.setInterval(60.0); // Set to 60 secondsprint('Scan interval updated to 60 seconds');Purpose: Updates the interval between automatic security scans. This allows you to:
- Adjust scan frequency based on app state
- Balance between security coverage and performance
- Reduce battery usage when appropriate
Parameters:
intervalSeconds(required): The new interval in seconds (must be greater than 8)
Note: The interval must be greater than 8 seconds. Attempting to set a lower value will result in an error.
Get Security Modules
Section titled “Get Security Modules”// Returns: Future<List<String>>// A list of security modules loaded by the SDK
final modules = await AlphynSdk.getModules();print('Loaded modules: ${modules.length}');
for (var module in modules) { print('Module: $module');}
// Example output: ['NetworkSecurity', 'DeviceIntegrity', 'AppVerification']Purpose: Retrieves the list of security modules currently loaded by the SDK. This provides:
- Visibility into which security checks are active
- Debugging information for troubleshooting
- Verification that expected modules are loaded
Use this for:
- Security auditing
- Diagnostics and troubleshooting
- Verifying SDK configuration
Security Event Listeners (Cross-Platform)
Section titled “Security Event Listeners (Cross-Platform)”The SDK provides a stream-based security event listener that works on both Android and iOS. This allows you to receive real-time security events from the native SDK in a reactive, Flutter-friendly way.
Using Security Events Stream
Section titled “Using Security Events Stream”The securityEvents() method returns a Stream<AlphynCallbackResult> that emits security events from the native SDK. This works on both Android and iOS.
import 'package:alphyn_sdk/alphyn_sdk.dart';import 'dart:async';
// Subscribe to security eventsfinal subscription = AlphynSdk.securityEvents().listen( (event) { print('Event Type: ${event.originalEventType}'); print('Operation: ${event.operationType}'); print('Result: ${event.operationResult}'); print('Message: ${event.message}'); print('Details: ${event.details}');
// Handle different event types switch (event.originalEventType) { case AlphynEventType.threatDetected: print('🚨 Threat detected!'); handleThreat(event); break; case AlphynEventType.scanSuccess: print('✅ Scan completed successfully'); break; case AlphynEventType.initComplete: print('✅ SDK initialized'); break; case AlphynEventType.networkError: print('⚠️ Network error occurred'); break; default: print('Event: ${event.originalEventType}'); } }, onError: (error) { print('Error in security events stream: $error'); },);
// Don't forget to cancel the subscription when done// subscription.cancel();Key Points:
- Works on both Android and iOS
- Automatically set up when you first access the stream
- Multiple subscribers can listen to the same stream
- Events are emitted on the main thread
- Always cancel subscriptions in
dispose()to prevent memory leaks
Complete Example
Section titled “Complete Example”import 'package:flutter/material.dart';import 'package:alphyn_sdk/alphyn_sdk.dart';import 'dart:async';
class SecurityMonitor extends StatefulWidget { @override _SecurityMonitorState createState() => _SecurityMonitorState();}
class _SecurityMonitorState extends State<SecurityMonitor> { StreamSubscription<AlphynCallbackResult>? _subscription; List<AlphynCallbackResult> _events = [];
@override void initState() { super.initState(); _setupListener(); }
void _setupListener() { // Subscribe to security events stream _subscription = AlphynSdk.securityEvents().listen( (event) { setState(() { _events.insert(0, event); // Add to beginning // Keep only last 50 events if (_events.length > 50) { _events = _events.take(50).toList(); } }); }, onError: (error) { print('Security events error: $error'); }, ); }
@override void dispose() { _subscription?.cancel(); super.dispose(); }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Security Monitor')), body: ListView.builder( itemCount: _events.length, itemBuilder: (context, index) { final event = _events[index]; return ListTile( title: Text(event.originalEventType.name), subtitle: Text(event.message), trailing: Icon( event.operationResult == OperationResult.success ? Icons.check_circle : Icons.error, color: event.operationResult == OperationResult.success ? Colors.green : Colors.red, ), ); }, ), ); }}Event Types
Section titled “Event Types”Events are of type AlphynCallbackResult with the following properties:
operationType: The type of operation (OperationType.initialization,OperationType.securityScan, etc.)operationResult: The result (OperationResult.success,OperationResult.failure,OperationResult.threatDetected)originalEventType: The specific event type (AlphynEventType.initComplete,AlphynEventType.threatDetected, etc.)message: Human-readable messagedetails: Additional details
Available Event Types
Section titled “Available Event Types”The SDK emits various event types through the stream:
Initialization Events:
initComplete- SDK initialization completed successfullyinitFailed- SDK initialization failedfirstInit- First-time initializationinvalidAppKey- Invalid application key provided
Security Events:
threatDetected- Security threat identifiedsecureDevice- Device verified as securescanSuccess- Security scan completed successfullyscanResponse- Scan results are availablescanFailed- Security scan failedriskFactorDetected- Risk factor detected during scan
Network Events:
networkInit- Network initializationnetworkMtls- Mutual TLS connection establishedjwtAuthSuccess- JWT authentication successfulnetworkError- Network connectivity errorauthFailed- Authentication failedrequestFailed- API request failed
Storage Events:
keystoreSuccess- Keystore operation successfulkeystoreFailed- Keystore operation failedkeyExchangeSuccess- Key exchange completedkeysFoundStorage- Existing keys found in storagekeysCreatedNew- New keys created
Other Events:
invalidDateOrTime- Invalid date/time detectedcallbackSuccess- Callback operation successfulcallbackFailed- Callback operation failed
Best Practices
Section titled “Best Practices”- Always cancel subscriptions in
dispose()to prevent memory leaks - Handle errors in the stream’s
onErrorcallback - Filter events based on your needs (e.g., only listen to threat events)
- Update UI safely by checking
mountedbefore callingsetState() - Limit event history to prevent memory issues (keep only last N events)
API Reference
Section titled “API Reference”securityEvents()- Returns aStream<AlphynCallbackResult>that emits security events from the native SDK. Works on both Android and iOS.