package studio.daybreak.mail; import android.Manifest; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.WebView; import android.webkit.WebStorage; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.biometric.BiometricManager; import androidx.biometric.BiometricPrompt; import com.getcapacitor.BridgeActivity; import javax.crypto.Cipher; public class MainActivity extends BridgeActivity { private static final int UNLOCK_REQUEST_CODE = 705; private FrameLayout appLockOverlay; private TextView appLockMessage; private Button appLockButton; private boolean appLocked; private boolean awaitingUnlockResult; private boolean pgpAuthInProgress; private boolean pgpAuthPaused; private long pgpAuthPauseAt; private boolean activityResumed; private boolean vaultRecoveryRequired; private final Handler appLockHandler = new Handler(Looper.getMainLooper()); private final Runnable delayedAppLock = () -> { if (!activityResumed && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView(); }; private final Runnable lockAfterPgpAuth = () -> { if (!activityResumed && pgpAuthPaused && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView(); }; @Override public void onCreate(Bundle savedInstanceState) { registerPlugin(EpMailPlugin.class); super.onCreate(savedInstanceState); hardenWebView(); AndroidAccountVault.INSTANCE.initialize(getApplicationContext()); try { AndroidAccountVault.INSTANCE.read(); } catch (Exception storageError) { vaultRecoveryRequired = true; createVaultRecoveryOverlay(); return; } createAppLockOverlay(); if (isAppLockEnabled()) lockWebView(); if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701); } } @Override public void onResume() { super.onResume(); if (vaultRecoveryRequired) return; activityResumed = true; appLockHandler.removeCallbacks(delayedAppLock); appLockHandler.removeCallbacks(lockAfterPgpAuth); pgpAuthPaused = false; if (!appLocked) getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE); if (isAppLockEnabled() && appLocked) { lockWebView(); configureUnlockButton(); } } @Override public void onPause() { activityResumed = false; if (!vaultRecoveryRequired && isAppLockEnabled() && !pgpAuthInProgress) { int delaySeconds = appLockDelaySeconds(); if (delaySeconds == 0) { lockWebView(); } else { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); appLockHandler.postDelayed(delayedAppLock, delaySeconds * 1000L); } } else if (!vaultRecoveryRequired && isAppLockEnabled() && pgpAuthInProgress) { pgpAuthPaused = true; pgpAuthPauseAt = SystemClock.elapsedRealtime(); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } super.onPause(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode != UNLOCK_REQUEST_CODE) return; awaitingUnlockResult = false; if (resultCode == RESULT_OK && isAppLockEnabled()) unlockWebView(true); else updateAppLockMessage("Unlock with your Android screen lock to view mail."); } @Override public void onDestroy() { appLockHandler.removeCallbacks(delayedAppLock); appLockHandler.removeCallbacks(lockAfterPgpAuth); super.onDestroy(); } public void onAppLockSettingChanged(boolean enabled) { runOnUiThread(() -> { appLockHandler.removeCallbacks(delayedAppLock); appLockHandler.removeCallbacks(lockAfterPgpAuth); pgpAuthPaused = false; if (!enabled) { awaitingUnlockResult = false; unlockWebView(false); } else if (activityResumed) { appLocked = false; } else { lockWebView(); } }); } private int appLockDelaySeconds() { try { int delay = AndroidAccountVault.INSTANCE.appLockDelaySeconds(); AndroidAppLockPolicy.INSTANCE.requireValidDelay(delay); return delay; } catch (Exception ignored) { return 0; } } public void authenticatePgpCipher(Cipher cipher, BiometricPrompt.AuthenticationCallback callback) { int authenticators = BiometricManager.Authenticators.BIOMETRIC_STRONG; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { authenticators |= BiometricManager.Authenticators.DEVICE_CREDENTIAL; } BiometricPrompt.PromptInfo.Builder prompt = new BiometricPrompt.PromptInfo.Builder() .setTitle("Unlock OpenPGP key") .setSubtitle("Confirm to release this key's passphrase") .setAllowedAuthenticators(authenticators) .setConfirmationRequired(true); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { prompt.setNegativeButtonText("Cancel"); } BiometricPrompt biometricPrompt = new BiometricPrompt( this, ContextCompat.getMainExecutor(this), new BiometricPrompt.AuthenticationCallback() { @Override public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) { finishPgpAuthentication(); callback.onAuthenticationSucceeded(result); } @Override public void onAuthenticationFailed() { callback.onAuthenticationFailed(); } @Override public void onAuthenticationError(int errorCode, CharSequence errString) { finishPgpAuthentication(); callback.onAuthenticationError(errorCode, errString); } } ); pgpAuthInProgress = true; try { biometricPrompt.authenticate( prompt.build(), new BiometricPrompt.CryptoObject(cipher) ); } catch (RuntimeException error) { pgpAuthInProgress = false; throw error; } } private void finishPgpAuthentication() { pgpAuthInProgress = false; if (!pgpAuthPaused) return; long elapsed = SystemClock.elapsedRealtime() - pgpAuthPauseAt; long remaining = Math.max(1000L, appLockDelaySeconds() * 1000L - elapsed); appLockHandler.postDelayed(lockAfterPgpAuth, remaining); } public void clearLocalWebData() { if (getBridge() == null || getBridge().getWebView() == null) return; getBridge().getWebView().clearCache(true); WebStorage.getInstance().deleteAllData(); } private boolean isAppLockEnabled() { try { return AndroidAccountVault.INSTANCE.appLockEnabled(); } catch (Exception ignored) { // If the encrypted setting cannot be read, prefer locking over exposing stale UI. return true; } } private void hardenWebView() { if (getBridge() == null || getBridge().getWebView() == null) return; WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG); WebView webView = getBridge().getWebView(); android.webkit.WebSettings settings = webView.getSettings(); settings.setAllowFileAccess(false); settings.setAllowContentAccess(false); settings.setAllowFileAccessFromFileURLs(false); settings.setAllowUniversalAccessFromFileURLs(false); settings.setGeolocationEnabled(false); settings.setJavaScriptCanOpenWindowsAutomatically(false); settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW); } private void createVaultRecoveryOverlay() { View content = findViewById(android.R.id.content); if (!(content instanceof FrameLayout)) return; FrameLayout overlay = new FrameLayout(this); overlay.setBackgroundColor(Color.rgb(25, 21, 18)); overlay.setClickable(true); overlay.setFocusable(true); LinearLayout panel = new LinearLayout(this); panel.setOrientation(LinearLayout.VERTICAL); panel.setGravity(Gravity.CENTER); panel.setPadding(dp(28), dp(28), dp(28), dp(28)); TextView title = new TextView(this); title.setText("Saved data could not be opened"); title.setTextColor(Color.rgb(238, 230, 215)); title.setTextSize(21); title.setGravity(Gravity.CENTER); panel.addView(title, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); TextView details = new TextView(this); details.setText("ep-mail could not decrypt its saved local data. It has not been reset or replaced. Try restoring the same device/app state if available. If you cannot recover it, open Android App info and clear ep-mail data to start fresh; this permanently removes saved accounts, cached mail, drafts, queued sends, DAV settings, and OpenPGP keys. Attachments already saved to Downloads remain there."); details.setTextColor(Color.rgb(210, 199, 181)); details.setTextSize(14); details.setGravity(Gravity.CENTER); LinearLayout.LayoutParams detailsParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); detailsParams.topMargin = dp(16); panel.addView(details, detailsParams); Button settingsButton = new Button(this); settingsButton.setText("Open Android App info"); settingsButton.setOnClickListener(view -> { try { startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName()))); } catch (Exception ignored) { // Keep the recovery instructions visible if Settings cannot be launched. } }); LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); buttonParams.gravity = Gravity.CENTER_HORIZONTAL; buttonParams.topMargin = dp(24); panel.addView(settingsButton, buttonParams); overlay.addView(panel, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)); ((FrameLayout) content).addView(overlay, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); if (getBridge() != null && getBridge().getWebView() != null) { getBridge().getWebView().getSettings().setJavaScriptEnabled(false); } } private void createAppLockOverlay() { View content = findViewById(android.R.id.content); if (!(content instanceof FrameLayout)) return; appLockOverlay = new FrameLayout(this); appLockOverlay.setBackgroundColor(Color.rgb(25, 21, 18)); appLockOverlay.setClickable(true); appLockOverlay.setFocusable(true); LinearLayout panel = new LinearLayout(this); panel.setOrientation(LinearLayout.VERTICAL); panel.setGravity(Gravity.CENTER); panel.setPadding(dp(28), dp(28), dp(28), dp(28)); TextView title = new TextView(this); title.setText("ep-mail is locked"); title.setTextColor(Color.rgb(238, 230, 215)); title.setTextSize(22); title.setGravity(Gravity.CENTER); panel.addView(title, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); appLockMessage = new TextView(this); appLockMessage.setText("Unlock with your Android screen lock to view mail."); appLockMessage.setTextColor(Color.rgb(185, 171, 151)); appLockMessage.setTextSize(15); appLockMessage.setGravity(Gravity.CENTER); LinearLayout.LayoutParams messageParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); messageParams.topMargin = dp(12); panel.addView(appLockMessage, messageParams); appLockButton = new Button(this); appLockButton.setText("Unlock"); appLockButton.setOnClickListener(view -> requestDeviceUnlock()); LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); buttonParams.gravity = Gravity.CENTER_HORIZONTAL; buttonParams.topMargin = dp(24); panel.addView(appLockButton, buttonParams); FrameLayout.LayoutParams panelParams = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER); appLockOverlay.addView(panel, panelParams); appLockOverlay.setVisibility(View.GONE); ((FrameLayout) content).addView(appLockOverlay, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); } private void requestDeviceUnlock() { if (awaitingUnlockResult) return; KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (keyguard == null || !keyguard.isDeviceSecure()) { updateAppLockMessage("Set a PIN, pattern, or password in Android Settings to unlock ep-mail."); configureUnlockButton(); return; } configureUnlockButton(); Intent confirmIntent = keyguard.createConfirmDeviceCredentialIntent( "Unlock ep-mail", "Confirm your Android screen lock to view mail." ); if (confirmIntent == null) { updateAppLockMessage("Android could not start screen-lock verification. Try again after unlocking your device."); return; } awaitingUnlockResult = true; try { startActivityForResult(confirmIntent, UNLOCK_REQUEST_CODE); } catch (Exception error) { awaitingUnlockResult = false; updateAppLockMessage("Could not start Android screen-lock verification. Try again."); } } private void configureUnlockButton() { if (appLockButton == null) return; KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (keyguard != null && keyguard.isDeviceSecure()) { appLockButton.setText("Unlock"); appLockButton.setOnClickListener(view -> requestDeviceUnlock()); } else { appLockButton.setText("Open security settings"); appLockButton.setOnClickListener(view -> startActivity( new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS))); } } private void lockWebView() { appLocked = true; getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); if (appLockOverlay != null) appLockOverlay.setVisibility(View.VISIBLE); if (getBridge() != null) { WebView webView = getBridge().getWebView(); webView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); webView.getSettings().setJavaScriptEnabled(false); } } private void unlockWebView(boolean reload) { appLocked = false; getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE); if (getBridge() != null) { WebView webView = getBridge().getWebView(); webView.getSettings().setJavaScriptEnabled(true); webView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); if (reload) webView.reload(); } if (appLockOverlay != null) appLockOverlay.setVisibility(View.GONE); if (appLockButton != null) { appLockButton.setText("Unlock"); appLockButton.setOnClickListener(view -> requestDeviceUnlock()); } } private void updateAppLockMessage(String message) { if (appLockMessage != null) appLockMessage.setText(message); } private int dp(int value) { return Math.round(value * getResources().getDisplayMetrics().density); } }