Skip to content

Advanced Features

// Returns: Future<List<String>>
// A comprehensive list of all risk factors detected across all scans
// Includes cumulative security concerns, not just current threats
final 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
// 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 days
final 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 results
for (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
// Returns: Future<void>
// Updates the scan interval in seconds
await AlphynSdk.setInterval(60.0); // Set to 60 seconds
print('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.

// 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

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.

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 events
final 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
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,
),
);
},
),
);
}
}

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 message
  • details: Additional details

The SDK emits various event types through the stream:

Initialization Events:

  • initComplete - SDK initialization completed successfully
  • initFailed - SDK initialization failed
  • firstInit - First-time initialization
  • invalidAppKey - Invalid application key provided

Security Events:

  • threatDetected - Security threat identified
  • secureDevice - Device verified as secure
  • scanSuccess - Security scan completed successfully
  • scanResponse - Scan results are available
  • scanFailed - Security scan failed
  • riskFactorDetected - Risk factor detected during scan

Network Events:

  • networkInit - Network initialization
  • networkMtls - Mutual TLS connection established
  • jwtAuthSuccess - JWT authentication successful
  • networkError - Network connectivity error
  • authFailed - Authentication failed
  • requestFailed - API request failed

Storage Events:

  • keystoreSuccess - Keystore operation successful
  • keystoreFailed - Keystore operation failed
  • keyExchangeSuccess - Key exchange completed
  • keysFoundStorage - Existing keys found in storage
  • keysCreatedNew - New keys created

Other Events:

  • invalidDateOrTime - Invalid date/time detected
  • callbackSuccess - Callback operation successful
  • callbackFailed - Callback operation failed
  1. Always cancel subscriptions in dispose() to prevent memory leaks
  2. Handle errors in the stream’s onError callback
  3. Filter events based on your needs (e.g., only listen to threat events)
  4. Update UI safely by checking mounted before calling setState()
  5. Limit event history to prevent memory issues (keep only last N events)
  • securityEvents() - Returns a Stream<AlphynCallbackResult> that emits security events from the native SDK. Works on both Android and iOS.