From ad54c80f36fbf00fe3dd3532163707db150585df Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 9 Aug 2026 15:50:09 +0000 Subject: [PATCH 1/4] Fix reported bugs from the Abloq-MDM tracker on PreBuild 0.5.1 Bug fixes only; no version bumps and no new features. App blocking (Abloq-MDM #30, #25.2) - Restore bulk selection: ticking a checkbox stages the change instead of opening a per-app hide/lock dialog and immediately saving, so many apps can be marked in one pass and committed with Save. - Stop the list jumping back to the top after each app: refreshing no longer clears the search box or swaps the list for a spinner, and the scroll state is hoisted so it survives the rebuild. - Unchecking an app now actually removes it. The saved set was unioned with the previous one, so deselection was impossible and blocked apps were never unhidden. - Guard setPackagesSuspended behind an API check (minSdk is 22). App store (#17, #21) - Fix the crash on opening the store after adding a package that is already installed: the package appeared both as installed and as a custom entry, and the duplicate LazyColumn key threw. - Custom packages that are installed are no longer filtered out, and resolved entries keep isCustomPackage, so they reach the custom tab. - Single-APK installs now request unattended install; without it Android 12+ answered the commit with STATUS_PENDING_USER_ACTION and the install was silently dropped. - Handle STATUS_PENDING_USER_ACTION in InstallReceiver and read the package name from EXTRA_PACKAGE_NAME instead of a key that was never set. - Close the download flow when it finishes. It stayed open forever, so the package was never released from the in-flight guard and further update attempts were ignored. - Keep FLAG_UPDATE_CURRENT on API 31+ and key the PendingIntent by session id rather than a fixed request code of 0. Kiosk (#25.3, #25.4, #25.5) - Make the kiosk management screen scrollable; on shorter screens the action-button toggles were laid out on top of each other and unreachable. - Fix the flashlight only ever switching on: the state was persisted via Settings.Global, which requires WRITE_SECURE_SETTINGS and always threw. Track the torch state in-process from the framework torch callback and pick the camera that actually reports a flash unit. - Re-apply the lock task allowlist and retry when it is missing, instead of leaving the device sitting on the kiosk screen unlocked, and fail closed when kiosk settings cannot be read. Removal (#28) - Clear all user restrictions and the package's own uninstall block before clearing device ownership. DISALLOW_UNINSTALL_APPS and DISALLOW_APPS_CONTROL survived removal and could no longer be cleared once ownership was gone, which left the app installed and un-removable with its protections already off. - Isolate each policy teardown so one failure no longer aborts removal. Internal VPN after reboot (#29) - Add a boot task that restores the firewall VPN when it was active before the reboot; START_STICKY does not cover a power cycle. - Re-assert the boot receiver on start, as it ships disabled and was only enabled during first-time password setup. Navigation bar overlap (#1) - Inset the dashboard settings button and the kiosk bottom bar for the navigation bar; targetSdk 36 forces edge-to-edge, so they were drawn underneath the navigation buttons. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01WKeZ6SjfkeLU7qf1YbBVLY --- .../secureguard/mdm/SecureGuardApplication.kt | 28 ++++++ .../mdm/appblocker/AppBlockerState.kt | 2 + .../mdm/appblocker/AppBlockerViewModel.kt | 99 +++++++++++++------ .../mdm/appblocker/ui/AppSelectionScreen.kt | 18 ++-- .../mdm/astore/downloader/AstoreDownloader.kt | 11 +++ .../mdm/astore/installer/AppInstaller.kt | 38 +++++-- .../secureguard/mdm/astore/ui/AstoreScreen.kt | 6 +- .../mdm/astore/ui/AstoreViewModel.kt | 69 +++++++------ .../mdm/boot/impl/FirewallVpnBootTask.kt | 63 ++++++++++++ .../mdm/boot/registry/BootTaskRegistry.kt | 7 +- .../secureguard/mdm/kiosk/ui/KioskActivity.kt | 33 +++++-- .../mdm/kiosk/ui/KioskManagementScreen.kt | 11 ++- .../secureguard/mdm/kiosk/ui/KioskScreen.kt | 94 ++++++++++++------ .../mdm/receivers/InstallReceiver.kt | 26 ++++- .../ui/screens/dashboard/DashboardScreen.kt | 8 +- .../mdm/ui/screens/settings/SettingsScreen.kt | 18 +++- .../ui/screens/settings/SettingsViewModel.kt | 65 ++++++++++-- 17 files changed, 471 insertions(+), 125 deletions(-) create mode 100644 app/src/main/java/com/secureguard/mdm/boot/impl/FirewallVpnBootTask.kt diff --git a/app/src/main/java/com/secureguard/mdm/SecureGuardApplication.kt b/app/src/main/java/com/secureguard/mdm/SecureGuardApplication.kt index 2aeaac8..16126d1 100644 --- a/app/src/main/java/com/secureguard/mdm/SecureGuardApplication.kt +++ b/app/src/main/java/com/secureguard/mdm/SecureGuardApplication.kt @@ -1,6 +1,9 @@ package com.secureguard.mdm +import android.content.ComponentName +import android.content.pm.PackageManager import com.emanuelef.remote_capture.PCAPdroid +import com.secureguard.mdm.boot.BootCompletedReceiver import com.secureguard.mdm.utils.AppLogger import dagger.hilt.android.HiltAndroidApp import java.security.SecureRandom @@ -14,6 +17,31 @@ class SecureGuardApplication : PCAPdroid() { AppLogger.init(this) AppLogger.i("Application", "App started. Logger initialized.") setupGlobalSslTrust() + ensureBootReceiverEnabled() + } + + /** + * The receiver ships disabled in the manifest and is switched on when the password is + * first created. Installs that never went through that path (upgrades from an older + * build) had it left disabled, so no boot task ever ran and nothing was restored after + * a reboot. Re-asserting it on every start is idempotent and cheap. + */ + private fun ensureBootReceiverEnabled() { + try { + val receiver = ComponentName(this, BootCompletedReceiver::class.java) + if (packageManager.getComponentEnabledSetting(receiver) != + PackageManager.COMPONENT_ENABLED_STATE_ENABLED + ) { + packageManager.setComponentEnabledSetting( + receiver, + PackageManager.COMPONENT_ENABLED_STATE_ENABLED, + PackageManager.DONT_KILL_APP + ) + AppLogger.i("Application", "BootCompletedReceiver enabled.") + } + } catch (e: Exception) { + AppLogger.e("Application", "Failed to enable BootCompletedReceiver: ${e.message}") + } } private fun setupGlobalSslTrust() { diff --git a/app/src/main/java/com/secureguard/mdm/appblocker/AppBlockerState.kt b/app/src/main/java/com/secureguard/mdm/appblocker/AppBlockerState.kt index 59ceaf9..d17a823 100644 --- a/app/src/main/java/com/secureguard/mdm/appblocker/AppBlockerState.kt +++ b/app/src/main/java/com/secureguard/mdm/appblocker/AppBlockerState.kt @@ -24,6 +24,8 @@ sealed class AppBlockerEvent { data class OnFilterChanged(val newFilter: AppFilterType) : AppBlockerEvent() data class OnAppSelectionChanged(val packageName: String, val isBlocked: Boolean) : AppBlockerEvent() data class OnAppSuspensionChanged(val packageName: String, val isSuspended: Boolean) : AppBlockerEvent() + /** Clears both the block and the suspend flag for an app (unchecking its row). */ + data class OnAppDeselected(val packageName: String) : AppBlockerEvent() object OnSaveRequest : AppBlockerEvent() // יישמר מיידית object OnDismissPasswordPrompt : AppBlockerEvent() // נשאר למקרה שימוש עתידי, לא מזיק data class OnAddPackageManually(val packageName: String) : AppBlockerEvent() diff --git a/app/src/main/java/com/secureguard/mdm/appblocker/AppBlockerViewModel.kt b/app/src/main/java/com/secureguard/mdm/appblocker/AppBlockerViewModel.kt index 26eb6d5..672cfbc 100644 --- a/app/src/main/java/com/secureguard/mdm/appblocker/AppBlockerViewModel.kt +++ b/app/src/main/java/com/secureguard/mdm/appblocker/AppBlockerViewModel.kt @@ -70,6 +70,7 @@ class AppBlockerViewModel @Inject constructor( is AppBlockerEvent.OnFilterChanged -> onFilterChanged(event.newFilter) is AppBlockerEvent.OnAppSelectionChanged -> onAppSelectionChanged(event.packageName, event.isBlocked) is AppBlockerEvent.OnAppSuspensionChanged -> onAppSuspensionChanged(event.packageName, event.isSuspended) + is AppBlockerEvent.OnAppDeselected -> onAppDeselected(event.packageName) is AppBlockerEvent.OnSaveRequest -> saveAndApplyChanges() // קריאה ישירה is AppBlockerEvent.OnUnblockSelectedRequest -> unblockSelectedApps() // קריאה ישירה is AppBlockerEvent.OnUnsuspendSelectedRequest -> unsuspendSelectedApps() // קריאה ישירה @@ -83,8 +84,15 @@ class AppBlockerViewModel @Inject constructor( } fun loadAllData() { + // A refresh must not clear the search box or swap the list out for a spinner: + // both rebuild the LazyColumn from scratch and throw the user back to the top + // of a list that can be hundreds of apps long. + refreshData(showSpinner = _uiState.value.displayedAppsForSelection.isEmpty()) + } + + private fun refreshData(showSpinner: Boolean) { viewModelScope.launch { - _uiState.update { it.copy(isLoading = true, searchQuery = "") } + if (showSpinner) _uiState.update { it.copy(isLoading = true) } allAppsMasterList = getInstalledApps() allBlockedAppsMasterList = getBlockedAppsFromCache() allSuspendedAppsMasterList = getSuspendedAppsFromCache() @@ -240,6 +248,13 @@ class AppBlockerViewModel @Inject constructor( applyFilter() } + private fun onAppDeselected(packageName: String) { + allAppsMasterList = allAppsMasterList.map { + if (it.packageName == packageName) it.copy(isBlocked = false, isSuspended = false) else it + } + applyFilter() + } + private fun onAppSuspensionChanged(packageName: String, isSuspended: Boolean) { if (isSuspended && CRITICAL_SYSTEM_PACKAGES.contains(packageName)) { val criticalAppInfos = allAppsMasterList.filter { it.packageName == packageName } @@ -256,24 +271,31 @@ class AppBlockerViewModel @Inject constructor( viewModelScope.launch(Dispatchers.IO) { val oldBlockedSet = settingsRepository.getBlockedAppPackages() val oldSuspendedSet = settingsRepository.getSuspendedAppPackages() - val newlySelectedApps = allAppsMasterList.filter { it.isBlocked }.map { it.packageName }.toSet() - val newlySuspendedApps = allAppsMasterList.filter { it.isSuspended }.map { it.packageName }.toSet() - val finalBlockedSet = oldBlockedSet + newlySelectedApps - val finalSuspendedSet = (oldSuspendedSet + newlySuspendedApps) - finalBlockedSet + // The master list is the source of truth for every package it covers, so + // clearing a checkbox actually removes the app. Packages the list does not + // cover (e.g. a blocked app that has since been uninstalled) are carried + // over untouched instead of being silently dropped. + val knownPackages = allAppsMasterList.map { it.packageName }.toSet() + val selectedBlocked = allAppsMasterList.filter { it.isBlocked }.map { it.packageName }.toSet() + val selectedSuspended = allAppsMasterList.filter { it.isSuspended }.map { it.packageName }.toSet() - val combinedSet = finalBlockedSet + finalSuspendedSet - if (combinedSet.contains(OWN_PACKAGE)) { - Log.w(TAG, "Skipping own package from block/suspend lists") - } + val finalBlockedSet = ((oldBlockedSet - knownPackages) + selectedBlocked) - OWN_PACKAGE + val finalSuspendedSet = + ((((oldSuspendedSet - knownPackages) + selectedSuspended) - finalBlockedSet)) - OWN_PACKAGE if (finalBlockedSet == oldBlockedSet && finalSuspendedSet == oldSuspendedSet) { Log.d(TAG, "No changes to save.") return@launch } + val blockedToAdd = finalBlockedSet - oldBlockedSet + val blockedToRemove = oldBlockedSet - finalBlockedSet + val suspendedToAdd = finalSuspendedSet - oldSuspendedSet + val suspendedToRemove = oldSuspendedSet - finalSuspendedSet + // Check for critical system apps (block/suspend) - val criticalApps = (newlySelectedApps + newlySuspendedApps).filter { CRITICAL_SYSTEM_PACKAGES.contains(it) } + val criticalApps = (blockedToAdd + suspendedToAdd).filter { CRITICAL_SYSTEM_PACKAGES.contains(it) } if (criticalApps.isNotEmpty()) { val criticalAppInfos = allAppsMasterList.filter { criticalApps.contains(it.packageName) } withContext(Dispatchers.Main) { @@ -282,25 +304,33 @@ class AppBlockerViewModel @Inject constructor( return@launch } - settingsRepository.setBlockedAppPackages(finalBlockedSet - OWN_PACKAGE) - settingsRepository.setSuspendedAppPackages(finalSuspendedSet - OWN_PACKAGE) + settingsRepository.setBlockedAppPackages(finalBlockedSet) + settingsRepository.setSuspendedAppPackages(finalSuspendedSet) - val appsToCache = allAppsMasterList.filter { - combinedSet.contains(it.packageName) && !oldBlockedSet.contains(it.packageName) && !oldSuspendedSet.contains(it.packageName) - } - appsToCache.forEach { cacheAppInfo(it) } + // Only evict apps that are no longer protected at all — an app moving from + // suspended to blocked appears in both "removed" and "added" sets and must + // keep its cached name and icon. + val noLongerProtected = + (blockedToRemove + suspendedToRemove) - finalBlockedSet - finalSuspendedSet + removeAppsFromCache(noLongerProtected.toList()) - val packagesToUnsuspend = oldSuspendedSet - finalSuspendedSet - packagesToUnsuspend.forEach { packageName -> + val newlyProtected = blockedToAdd + suspendedToAdd + allAppsMasterList.filter { newlyProtected.contains(it.packageName) }.forEach { cacheAppInfo(it) } + + blockedToRemove.forEach { packageName -> try { - dpm.setPackagesSuspended(adminComponentName, arrayOf(packageName), false) - Log.d(TAG, "Set suspended state for $packageName to false (auto)") + dpm.setApplicationHidden(adminComponentName, packageName, false) + Log.d(TAG, "Set hidden state for $packageName to false (deselected)") } catch (e: Exception) { - Log.w(TAG, "Could not unsuspend $packageName", e) + Log.w(TAG, "Could not unhide $packageName", e) } } - newlySelectedApps.forEach { packageName -> + suspendedToRemove.forEach { packageName -> + setPackagesSuspendedSafely(packageName, false) + } + + blockedToAdd.forEach { packageName -> try { dpm.setApplicationHidden(adminComponentName, packageName, true) Log.d(TAG, "Set hidden state for $packageName to true") @@ -309,16 +339,25 @@ class AppBlockerViewModel @Inject constructor( } } - newlySuspendedApps.forEach { packageName -> - try { - dpm.setPackagesSuspended(adminComponentName, arrayOf(packageName), true) - Log.d(TAG, "Set suspended state for $packageName to true") - } catch (e: Exception) { - Log.w(TAG, "Could not change suspended state for $packageName", e) - } + suspendedToAdd.forEach { packageName -> + setPackagesSuspendedSafely(packageName, true) } - withContext(Dispatchers.Main) { loadAllData() } + withContext(Dispatchers.Main) { refreshData(showSpinner = false) } + } + } + + /** + * setPackagesSuspended is API 24+; minSdk is 22, and a missing method raises + * NoSuchMethodError rather than an Exception, so the version has to be checked. + */ + private fun setPackagesSuspendedSafely(packageName: String, suspended: Boolean) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return + try { + dpm.setPackagesSuspended(adminComponentName, arrayOf(packageName), suspended) + Log.d(TAG, "Set suspended state for $packageName to $suspended") + } catch (e: Exception) { + Log.w(TAG, "Could not change suspended state for $packageName", e) } } diff --git a/app/src/main/java/com/secureguard/mdm/appblocker/ui/AppSelectionScreen.kt b/app/src/main/java/com/secureguard/mdm/appblocker/ui/AppSelectionScreen.kt index 4fb730d..a3436c3 100644 --- a/app/src/main/java/com/secureguard/mdm/appblocker/ui/AppSelectionScreen.kt +++ b/app/src/main/java/com/secureguard/mdm/appblocker/ui/AppSelectionScreen.kt @@ -5,6 +5,7 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Add @@ -41,6 +42,8 @@ fun AppSelectionScreen( val snackbarHostState = remember { SnackbarHostState() } var showAddPackageDialog by remember { mutableStateOf(false) } var showActionChoiceDialog by remember { mutableStateOf(null) } + // Hoisted so the scroll position survives the list being rebuilt after a save. + val listState = rememberLazyListState() LaunchedEffect(Unit) { viewModel.loadAllData() @@ -91,17 +94,18 @@ fun AppSelectionScreen( CircularProgressIndicator() } } else { - LazyColumn(modifier = Modifier.fillMaxSize()) { + LazyColumn(modifier = Modifier.fillMaxSize(), state = listState) { items(items = uiState.displayedAppsForSelection, key = { it.packageName }) { appInfo -> AppSelectionRow( appInfo = appInfo, + // Ticking a box only stages the change, so many apps can be + // marked in one pass and committed together with Save. Use the + // row itself when you want to suspend instead of block. onCheckedChange = { isChecked -> - // Changes are applied only on save, not immediately if (isChecked) { - showActionChoiceDialog = appInfo + viewModel.onEvent(AppBlockerEvent.OnAppSelectionChanged(appInfo.packageName, true)) } else { - // For unchecking, we don't immediately apply changes - // The user must save to apply the deselection + viewModel.onEvent(AppBlockerEvent.OnAppDeselected(appInfo.packageName)) } }, onActionClick = { showActionChoiceDialog = appInfo } @@ -144,15 +148,15 @@ fun AppSelectionScreen( AppSelectionActionChoiceDialog( appInfo = appInfo, onDismiss = { showActionChoiceDialog = null }, + // Staged only — saving here reloaded the whole list after every single app, + // which is what threw the user back to the top of the list each time. onChooseBlock = { showActionChoiceDialog = null viewModel.onEvent(AppBlockerEvent.OnAppSelectionChanged(appInfo.packageName, true)) - viewModel.onEvent(AppBlockerEvent.OnSaveRequest) }, onChooseSuspend = { showActionChoiceDialog = null viewModel.onEvent(AppBlockerEvent.OnAppSuspensionChanged(appInfo.packageName, true)) - viewModel.onEvent(AppBlockerEvent.OnSaveRequest) } ) } diff --git a/app/src/main/java/com/secureguard/mdm/astore/downloader/AstoreDownloader.kt b/app/src/main/java/com/secureguard/mdm/astore/downloader/AstoreDownloader.kt index 9f123b9..1746203 100644 --- a/app/src/main/java/com/secureguard/mdm/astore/downloader/AstoreDownloader.kt +++ b/app/src/main/java/com/secureguard/mdm/astore/downloader/AstoreDownloader.kt @@ -217,6 +217,12 @@ class AstoreDownloader @Inject constructor( trySend(AstoreDownloadProgress.Error(lastException?.message ?: "Download failed after $maxRetries attempts")) } + // The work is finished here. Without this close() the flow stayed open on + // awaitClose forever, so the collector never returned, the package was never + // released from activeInstalls, and every later attempt to update it was + // dropped by the in-flight guard — the update just appeared to hang. + close() + awaitClose { connections[urlString]?.disconnect() } }.flowOn(Dispatchers.IO) @@ -387,6 +393,11 @@ class AstoreDownloader @Inject constructor( try { val packageInstaller = context.packageManager.packageInstaller val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL) + // Without this, Android 12+ answers the commit with STATUS_PENDING_USER_ACTION + // instead of installing, which is why single-APK updates never landed. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + params.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) + } val sessionId = packageInstaller.createSession(params) session = packageInstaller.openSession(sessionId) diff --git a/app/src/main/java/com/secureguard/mdm/astore/installer/AppInstaller.kt b/app/src/main/java/com/secureguard/mdm/astore/installer/AppInstaller.kt index 2a55e3c..510aef7 100644 --- a/app/src/main/java/com/secureguard/mdm/astore/installer/AppInstaller.kt +++ b/app/src/main/java/com/secureguard/mdm/astore/installer/AppInstaller.kt @@ -77,6 +77,11 @@ class AppInstaller @Inject constructor( // Create installation session val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL) + // As device owner we can install unattended; without this Android 12+ replies + // with STATUS_PENDING_USER_ACTION rather than performing the install. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + params.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) + } params.setAppPackageName(packageName) val sessionId = packageInstaller.createSession(params) @@ -90,15 +95,19 @@ class AppInstaller @Inject constructor( } } - // Commit session + // Commit session. + // FLAG_UPDATE_CURRENT must be kept on API 31+ as well, and the session id is + // used as the request code: with a fixed code of 0 every install reused the + // first PendingIntent, so status callbacks were delivered against a stale + // intent and concurrent installs clobbered each other. val intent = Intent(context, InstallReceiver::class.java) - val flags = if (Build.VERSION.SDK_INT >= 31) { - 33554432 // FLAG_MUTABLE + val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } - - val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, flags) + + val pendingIntent = PendingIntent.getBroadcast(context, sessionId, intent, flags) session.commit(pendingIntent.intentSender) session.close() session = null @@ -164,6 +173,11 @@ class AppInstaller @Inject constructor( // Create installation session val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL) + // As device owner we can install unattended; without this Android 12+ replies + // with STATUS_PENDING_USER_ACTION rather than performing the install. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + params.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) + } params.setAppPackageName(packageName) val sessionId = packageInstaller.createSession(params) @@ -200,15 +214,19 @@ class AppInstaller @Inject constructor( return@withContext InstallResult.Failure("No APK files found in archive") } - // Commit session + // Commit session. + // FLAG_UPDATE_CURRENT must be kept on API 31+ as well, and the session id is + // used as the request code: with a fixed code of 0 every install reused the + // first PendingIntent, so status callbacks were delivered against a stale + // intent and concurrent installs clobbered each other. val intent = Intent(context, InstallReceiver::class.java) - val flags = if (Build.VERSION.SDK_INT >= 31) { - 33554432 // FLAG_MUTABLE + val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } - - val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, flags) + + val pendingIntent = PendingIntent.getBroadcast(context, sessionId, intent, flags) session.commit(pendingIntent.intentSender) session.close() session = null diff --git a/app/src/main/java/com/secureguard/mdm/astore/ui/AstoreScreen.kt b/app/src/main/java/com/secureguard/mdm/astore/ui/AstoreScreen.kt index 441121a..84dfb31 100644 --- a/app/src/main/java/com/secureguard/mdm/astore/ui/AstoreScreen.kt +++ b/app/src/main/java/com/secureguard/mdm/astore/ui/AstoreScreen.kt @@ -183,7 +183,9 @@ fun AstoreScreen( when (selectedTab) { 0 -> { // Custom packages tab - show custom packages from settings - val customPackages = uiState.apps.filter { it.isCustomPackage } + // distinctBy guards the LazyColumn key below: a duplicate packageName + // throws rather than rendering, taking the whole store down. + val customPackages = uiState.apps.filter { it.isCustomPackage }.distinctBy { it.packageName } if (customPackages.isEmpty()) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Column(horizontalAlignment = Alignment.CenterHorizontally) { @@ -221,7 +223,7 @@ fun AstoreScreen( } 1 -> { // Updates tab - only show apps with updates - val appsWithUpdates = uiState.apps.filter { it.updateAvailable } + val appsWithUpdates = uiState.apps.filter { it.updateAvailable }.distinctBy { it.packageName } if (uiState.isCheckingUpdates && appsWithUpdates.isEmpty()) { // Still checking for updates diff --git a/app/src/main/java/com/secureguard/mdm/astore/ui/AstoreViewModel.kt b/app/src/main/java/com/secureguard/mdm/astore/ui/AstoreViewModel.kt index d0998ed..2e83de9 100644 --- a/app/src/main/java/com/secureguard/mdm/astore/ui/AstoreViewModel.kt +++ b/app/src/main/java/com/secureguard/mdm/astore/ui/AstoreViewModel.kt @@ -148,15 +148,20 @@ class AstoreViewModel @Inject constructor( } } - // Keep custom packages that aren't in appList + // Keep custom packages. A custom package that is also installed appears in + // both lists; emitting both produced two entries with the same packageName, + // and LazyColumn's key = { it.packageName } throws on the duplicate, crashing + // the store on open. The custom entry wins so its metadata is preserved. val customApps = currentState.apps.filter { it.isCustomPackage } - + val customPackageNames = customApps.map { it.packageName }.toSet() + currentState.copy( - isLoading = false, - isRefreshing = false, - apps = mergedApps + customApps, + isLoading = false, + isRefreshing = false, + apps = (mergedApps.filter { it.packageName !in customPackageNames } + customApps) + .distinctBy { it.packageName }, isCheckingUpdates = true - ) + ) } // Step 2: Load custom packages first (they should always be visible) @@ -177,36 +182,41 @@ class AstoreViewModel @Inject constructor( AppLogger.d(TAG, "Loading ${customPackages.size} custom packages") - // Get current installed packages to filter out already installed ones - val currentApps = _uiState.value.apps.map { it.packageName }.toSet() - - // Filter custom packages that aren't already installed - val packagesToFetch = customPackages.filter { it !in currentApps } - + // Only skip packages already resolved as custom entries. Filtering against every + // known package meant a custom package that happened to be installed was dropped + // here and never reached the custom tab, so it could be added but never installed + // or updated from it. + val alreadyResolved = _uiState.value.apps + .filter { it.isCustomPackage } + .map { it.packageName } + .toSet() + + val packagesToFetch = customPackages.filter { it !in alreadyResolved } + if (packagesToFetch.isEmpty()) { return } - // Fetch details for each custom package - val customApps = packagesToFetch.mapNotNull { packageName -> + // Fetch details for each custom package. Every entry must carry + // isCustomPackage = true, otherwise it is filtered off the custom tab and + // re-fetched on every load; and a lookup that yields nothing still gets a basic + // entry so the package the user added does not silently disappear. + val customApps = packagesToFetch.map { packageName -> + val fallback = AppMetadata( + packageName = packageName, + title = packageName, + versionName = "", + versionCode = 0, + isInstalled = false, + isCustomPackage = true + ) try { val appInfo = appStoreService.getCustomPackageDetails(packageName) - if (appInfo != null) { - // Check source availability - val sources = appStoreService.checkSourceAvailability(packageName) - appInfo.copy(availableSources = sources) - } else null + val sources = appStoreService.checkSourceAvailability(packageName) + (appInfo ?: fallback).copy(availableSources = sources, isCustomPackage = true) } catch (e: Exception) { AppLogger.e(TAG, "Failed to get custom package details for $packageName", e) - // Add basic entry anyway - AppMetadata( - packageName = packageName, - title = packageName, - versionName = "", - versionCode = 0, - isInstalled = false, - isCustomPackage = true - ) + fallback } } @@ -404,6 +414,9 @@ class AstoreViewModel @Inject constructor( updateAppProgress(packageName, 0, false) _uiState.update { it.copy(error = context.getString(R.string.astore_error_update_failed, e.localizedMessage)) } } finally { + // Never leave a row spinning: if the flow ends without a terminal event + // the progress state would otherwise stay stuck on "downloading". + updateAppProgress(packageName, 0, false) activeInstalls.remove(packageName) } } diff --git a/app/src/main/java/com/secureguard/mdm/boot/impl/FirewallVpnBootTask.kt b/app/src/main/java/com/secureguard/mdm/boot/impl/FirewallVpnBootTask.kt new file mode 100644 index 0000000..22941ab --- /dev/null +++ b/app/src/main/java/com/secureguard/mdm/boot/impl/FirewallVpnBootTask.kt @@ -0,0 +1,63 @@ +package com.secureguard.mdm.boot.impl + +import android.content.Context +import android.content.Intent +import android.net.VpnService +import android.preference.PreferenceManager +import androidx.core.content.ContextCompat +import com.secureguard.mdm.boot.api.BootTask +import com.secureguard.mdm.firewall.AppFirewallVpnService +import com.secureguard.mdm.utils.FileLogger +import dagger.hilt.android.qualifiers.ApplicationContext +import javax.inject.Inject + +/** + * Brings the internal firewall VPN back up after a reboot. + * + * AppFirewallVpnService returns START_STICKY, which only covers the service being killed + * while the system is running — nothing restarted it after a power cycle, so the VPN was + * silently down until the user opened the firewall screen and toggled it again. + */ +class FirewallVpnBootTask @Inject constructor( + @ApplicationContext private val context: Context +) : BootTask { + + override suspend fun onBootCompleted() { + val prefs = PreferenceManager.getDefaultSharedPreferences(context) + if (!prefs.getBoolean(PREF_FIREWALL_ACTIVE, false)) { + FileLogger.log(TAG, "Firewall was not active before reboot. Nothing to do.") + return + } + + val blockedApps = prefs.getStringSet(AppFirewallVpnService.PREF_FIREWALL_BLOCKED_APPS, emptySet()) + if (blockedApps.isNullOrEmpty()) { + FileLogger.log(TAG, "Firewall active but no apps are blocked. Nothing to do.") + return + } + + // VpnService.prepare returns null once consent has been granted, and consent + // survives a reboot. If it returns non-null the consent dialog is required and + // cannot be shown from here, so the service is left alone. + if (VpnService.prepare(context) != null) { + FileLogger.log(TAG, "VPN consent is not granted; cannot restore firewall silently.") + return + } + + try { + FileLogger.log(TAG, "Restoring firewall VPN for ${blockedApps.size} app(s).") + ContextCompat.startForegroundService( + context, + Intent(context, AppFirewallVpnService::class.java) + ) + } catch (e: Exception) { + FileLogger.log(TAG, "Failed to restore firewall VPN: ${e.message}") + } + } + + companion object { + private const val TAG = "FirewallVpnBootTask" + + /** Written by the firewall screen when the user turns the firewall on or off. */ + const val PREF_FIREWALL_ACTIVE = "firewall_vpn_active" + } +} diff --git a/app/src/main/java/com/secureguard/mdm/boot/registry/BootTaskRegistry.kt b/app/src/main/java/com/secureguard/mdm/boot/registry/BootTaskRegistry.kt index b3a6f1f..f5422e7 100644 --- a/app/src/main/java/com/secureguard/mdm/boot/registry/BootTaskRegistry.kt +++ b/app/src/main/java/com/secureguard/mdm/boot/registry/BootTaskRegistry.kt @@ -1,6 +1,7 @@ package com.secureguard.mdm.boot.registry import com.secureguard.mdm.boot.api.BootTask +import com.secureguard.mdm.boot.impl.FirewallVpnBootTask import com.secureguard.mdm.boot.impl.NetfreeWatchdogBootTask import com.secureguard.mdm.boot.impl.ShowToastOnBootTask import javax.inject.Inject @@ -9,10 +10,12 @@ import javax.inject.Singleton @Singleton class BootTaskRegistry @Inject constructor( showToastOnBootTask: ShowToastOnBootTask, - netfreeWatchdogBootTask: NetfreeWatchdogBootTask + netfreeWatchdogBootTask: NetfreeWatchdogBootTask, + firewallVpnBootTask: FirewallVpnBootTask ) { val allBootTasks: List = listOf( showToastOnBootTask, - netfreeWatchdogBootTask + netfreeWatchdogBootTask, + firewallVpnBootTask ) } \ No newline at end of file diff --git a/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskActivity.kt b/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskActivity.kt index 4911627..62e9089 100644 --- a/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskActivity.kt +++ b/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskActivity.kt @@ -62,9 +62,15 @@ class KioskActivity : ComponentActivity() { } lifecycleScope.launch { - val kioskEnabled = settingsRepository.isKioskModeEnabled() - val chosenLauncher = settingsRepository.getChosenHomeLauncherPackage() - val dontShowAgain = settingsRepository.shouldNotShowHomeChoiceAgain() + // A failure reading settings used to abort before setContent ran, leaving the + // launcher-replacing activity blank and the device effectively unlocked. + // Fail closed instead: assume the kiosk is on and still draw it. + val kioskEnabled = runCatching { settingsRepository.isKioskModeEnabled() }.getOrElse { e -> + Log.e("KioskActivity", "Failed to read kiosk state; assuming enabled.", e) + true + } + val chosenLauncher = runCatching { settingsRepository.getChosenHomeLauncherPackage() }.getOrNull() + val dontShowAgain = runCatching { settingsRepository.shouldNotShowHomeChoiceAgain() }.getOrDefault(false) // הפעל משימות BOOT רק אם הן עוד לא הופעלו בתהליך זה (קורה בדרך כלל בשיגור כ-Launcher) if (isLaunchedAsHome) { @@ -107,8 +113,8 @@ class KioskActivity : ComponentActivity() { } // הצג את מסך הקיוסק - val isSingleEnabled = settingsRepository.isSingleWebsiteKioskEnabled() - val singleUrl = settingsRepository.getSingleWebsiteKioskUrl() + val isSingleEnabled = runCatching { settingsRepository.isSingleWebsiteKioskEnabled() }.getOrDefault(false) + val singleUrl = runCatching { settingsRepository.getSingleWebsiteKioskUrl() }.getOrDefault("") setContent { SecureGuardTheme { @@ -164,6 +170,19 @@ class KioskActivity : ComponentActivity() { return@launch } + // If we are not on the lock-task allowlist there is nothing to fall back on + // and the device sits on the kiosk screen completely unlocked. That happens + // whenever the allowlist was lost (a reboot before it was re-applied, or an + // owner change), so re-apply it and try once more instead of giving up. + if (!kioskLockManager.isLockTaskPermitted()) { + Log.w("KioskActivity", "Lock task not permitted; re-applying lock task packages.") + try { + kioskLockManager.setLockTaskPackages() + } catch (e: Exception) { + Log.e("KioskActivity", "Failed to re-apply lock task packages", e) + } + } + if (kioskLockManager.isLockTaskPermitted()) { // בדוק אם אנחנו כבר ב-Lock Task if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { @@ -171,10 +190,12 @@ class KioskActivity : ComponentActivity() { try { startLockTask() } catch (e: Exception) { - e.printStackTrace() + Log.e("KioskActivity", "startLockTask failed", e) } } } + } else { + Log.e("KioskActivity", "Kiosk is enabled but lock task is still not permitted.") } } } diff --git a/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskManagementScreen.kt b/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskManagementScreen.kt index 0c9caee..acd1685 100644 --- a/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskManagementScreen.kt +++ b/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskManagementScreen.kt @@ -4,7 +4,9 @@ import com.secureguard.mdm.ui.theme.SecureGuardTheme import android.widget.Toast import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight @@ -70,10 +72,15 @@ fun KioskManagementScreen( CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) } } else { + // The card list is taller than the viewport on shorter screens. + // Without a scroll container, Arrangement.spacedBy has to + // distribute negative free space, which draws the action-button + // toggles stacked on top of each other and out of reach. Column( modifier = Modifier .fillMaxSize() .padding(padding) + .verticalScroll(rememberScrollState()) .padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { @@ -277,7 +284,9 @@ fun KioskManagementScreen( } } - Spacer(modifier = Modifier.weight(1f)) + // A weighted spacer cannot be measured inside a scrollable + // Column (its height is unbounded), so use a fixed gap. + Spacer(modifier = Modifier.height(8.dp)) if (uiState.isKioskModeEnabled) { Button( diff --git a/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskScreen.kt b/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskScreen.kt index b272948..7881f5f 100644 --- a/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskScreen.kt +++ b/app/src/main/java/com/secureguard/mdm/kiosk/ui/KioskScreen.kt @@ -366,6 +366,7 @@ private fun KioskBottomBar( Row( modifier = Modifier .fillMaxWidth() + .navigationBarsPadding() .padding(horizontal = 24.dp, vertical = 20.dp), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically @@ -454,42 +455,79 @@ private fun openVolumePanel(context: Context) { } } +/** + * Tracks the torch state in-process. + * + * The previous implementation persisted the state with Settings.Global.putInt, which + * requires WRITE_SECURE_SETTINGS. The write always threw a SecurityException, so the + * stored state stayed 0 and every tap re-ran setTorchMode(id, true) — the flashlight + * could be switched on but never off. The real state is instead mirrored from the + * framework's own torch callback, which also keeps us in sync when something else + * (or the camera being opened) turns the torch off. + */ @RequiresApi(Build.VERSION_CODES.M) -private fun toggleFlashlight(context: Context) { - val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as? CameraManager - if (cameraManager == null) { - Log.w(TAG_KIOSK_UI, "CameraManager not available") - return +private object FlashlightController { + + @Volatile + private var torchOn: Boolean = false + private var registered: Boolean = false + + private val torchCallback = object : CameraManager.TorchCallback() { + override fun onTorchModeChanged(cameraId: String, enabled: Boolean) { + if (cameraId == flashCameraId) torchOn = enabled + } + + override fun onTorchModeUnavailable(cameraId: String) { + if (cameraId == flashCameraId) torchOn = false + } } - try { - val cameraId = cameraManager.cameraIdList.firstOrNull() - if (cameraId == null) { - Log.w(TAG_KIOSK_UI, "No camera ID for flashlight") - return + + @Volatile + private var flashCameraId: String? = null + + /** Returns the first camera that actually reports a flash unit. */ + private fun resolveFlashCameraId(cameraManager: CameraManager): String? { + flashCameraId?.let { return it } + val id = cameraManager.cameraIdList.firstOrNull { candidate -> + cameraManager.getCameraCharacteristics(candidate) + .get(android.hardware.camera2.CameraCharacteristics.FLASH_INFO_AVAILABLE) == true } - val isEnabled = cameraManager.getCameraCharacteristics(cameraId) - .get(android.hardware.camera2.CameraCharacteristics.FLASH_INFO_AVAILABLE) == true - if (!isEnabled) { - Log.w(TAG_KIOSK_UI, "Flash not available on this device") + flashCameraId = id + return id + } + + fun toggle(context: Context) { + val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as? CameraManager + if (cameraManager == null) { + Log.w(TAG_KIOSK_UI, "CameraManager not available") return } - val torchOn = android.provider.Settings.Global.getInt( - context.contentResolver, - "kiosk_flashlight_state", - 0 - ) == 1 - cameraManager.setTorchMode(cameraId, !torchOn) - android.provider.Settings.Global.putInt( - context.contentResolver, - "kiosk_flashlight_state", - if (torchOn) 0 else 1 - ) - Log.d(TAG_KIOSK_UI, "Flashlight toggled to ${!torchOn}") - } catch (e: Exception) { - Log.w(TAG_KIOSK_UI, "Failed to toggle flashlight", e) + try { + val cameraId = resolveFlashCameraId(cameraManager) + if (cameraId == null) { + Log.w(TAG_KIOSK_UI, "Flash not available on this device") + return + } + + if (!registered) { + // Delivered on the main looper; seeds torchOn with the current state. + cameraManager.registerTorchCallback(torchCallback, null) + registered = true + } + + val newState = !torchOn + cameraManager.setTorchMode(cameraId, newState) + torchOn = newState + Log.d(TAG_KIOSK_UI, "Flashlight toggled to $newState") + } catch (e: Exception) { + Log.w(TAG_KIOSK_UI, "Failed to toggle flashlight", e) + } } } +@RequiresApi(Build.VERSION_CODES.M) +private fun toggleFlashlight(context: Context) = FlashlightController.toggle(context) + @Composable private fun BottomBarButton( icon: androidx.compose.ui.graphics.vector.ImageVector, diff --git a/app/src/main/java/com/secureguard/mdm/receivers/InstallReceiver.kt b/app/src/main/java/com/secureguard/mdm/receivers/InstallReceiver.kt index 8a30e82..71981b2 100644 --- a/app/src/main/java/com/secureguard/mdm/receivers/InstallReceiver.kt +++ b/app/src/main/java/com/secureguard/mdm/receivers/InstallReceiver.kt @@ -14,8 +14,32 @@ class InstallReceiver : BroadcastReceiver() { @RequiresApi(Build.VERSION_CODES.M) override fun onReceive(context: Context, intent: Intent) { val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1) + + // The installer asks for confirmation instead of installing whenever the session + // could not run unattended. This was previously treated as a plain failure, so + // the install was simply dropped and the user only saw an error. + if (status == PackageInstaller.STATUS_PENDING_USER_ACTION) { + val confirmationIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableExtra(Intent.EXTRA_INTENT) + } + if (confirmationIntent != null) { + confirmationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + try { + context.startActivity(confirmationIntent) + } catch (e: Exception) { + Toast.makeText(context, context.getString(R.string.update_toast_failed), Toast.LENGTH_LONG).show() + } + } + return + } + if (status == PackageInstaller.STATUS_SUCCESS) { - val installedPackageName = intent.getStringExtra("package_name") + // The framework reports the package under EXTRA_PACKAGE_NAME; the old + // "package_name" key was always absent, so this never matched. + val installedPackageName = intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME) // אם החבילה שהותקנה היא NoPhone, הקפץ בקשה להגדיר כברירת מחדל if (installedPackageName == "org.fossify.phone") { diff --git a/app/src/main/java/com/secureguard/mdm/ui/screens/dashboard/DashboardScreen.kt b/app/src/main/java/com/secureguard/mdm/ui/screens/dashboard/DashboardScreen.kt index 29b24fe..941258d 100644 --- a/app/src/main/java/com/secureguard/mdm/ui/screens/dashboard/DashboardScreen.kt +++ b/app/src/main/java/com/secureguard/mdm/ui/screens/dashboard/DashboardScreen.kt @@ -115,7 +115,13 @@ fun DashboardScreen( if (uiState.isSettingsButtonVisible) { Button( onClick = { viewModel.onEvent(DashboardEvent.OnSettingsClicked) }, - modifier = Modifier.fillMaxWidth().padding(16.dp) + // targetSdk 35+ forces edge-to-edge, so the window no longer insets + // itself for the system bars. Without this the button is drawn + // underneath the navigation buttons and cannot be tapped. + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(16.dp) ) { Text(stringResource(id = R.string.dashboard_button_settings)) } diff --git a/app/src/main/java/com/secureguard/mdm/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/secureguard/mdm/ui/screens/settings/SettingsScreen.kt index ffa5bed..b19a475 100644 --- a/app/src/main/java/com/secureguard/mdm/ui/screens/settings/SettingsScreen.kt +++ b/app/src/main/java/com/secureguard/mdm/ui/screens/settings/SettingsScreen.kt @@ -98,9 +98,21 @@ fun SettingsScreen( } LaunchedEffect(Unit) { - viewModel.triggerUninstallEvent.collectLatest { - val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:${context.packageName}")) - context.startActivity(intent) + viewModel.triggerUninstallEvent.collectLatest { + val packageUri = Uri.parse("package:${context.packageName}") + val intent = Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + try { + context.startActivity(intent) + } catch (e: Exception) { + // Some OEM builds do not expose ACTION_UNINSTALL_PACKAGE to third parties. + context.startActivity( + Intent(Intent.ACTION_DELETE, packageUri).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + ) + } } } diff --git a/app/src/main/java/com/secureguard/mdm/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/secureguard/mdm/ui/screens/settings/SettingsViewModel.kt index c756851..7a06db2 100644 --- a/app/src/main/java/com/secureguard/mdm/ui/screens/settings/SettingsViewModel.kt +++ b/app/src/main/java/com/secureguard/mdm/ui/screens/settings/SettingsViewModel.kt @@ -538,29 +538,82 @@ class SettingsViewModel @Inject constructor( } } + /** + * Clears every user restriction currently set by this admin. Reads the live set from + * the framework so restrictions applied by features no longer present in the UI state + * are removed too. + */ + private fun clearAllUserRestrictions() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return + val restrictions = try { + dpm.getUserRestrictions(adminComponentName) + } catch (e: Exception) { + AppLogger.w("SettingsVM", "Could not read user restrictions", e) + return + } + restrictions.keySet().forEach { key -> + try { + dpm.clearUserRestriction(adminComponentName, key) + } catch (e: Exception) { + AppLogger.w("SettingsVM", "Could not clear restriction $key", e) + } + } + } + private fun initiateRemoval() { viewModelScope.launch { try { - // Remove all protection features + // Remove all protection features. Each one is isolated: a single failing + // policy used to abort the whole removal, leaving the device owner in + // place with the protections already half torn down. _uiState.value.protectionCategoryToggles.flatMap { it.toggles }.forEach { - it.feature.applyPolicy(context, dpm, adminComponentName, false) - settingsRepository.setFeatureState(it.feature.id, false) + try { + it.feature.applyPolicy(context, dpm, adminComponentName, false) + settingsRepository.setFeatureState(it.feature.id, false) + } catch (e: Exception) { + AppLogger.w("SettingsVM", "Could not clear policy ${it.feature.id}", e) + } } // Unhide blocked apps val blockedApps = settingsRepository.getBlockedAppPackages() blockedApps.forEach { packageName -> - dpm.setApplicationHidden(adminComponentName, packageName, false) + try { + dpm.setApplicationHidden(adminComponentName, packageName, false) + } catch (e: Exception) { + AppLogger.w("SettingsVM", "Could not unhide $packageName", e) + } } // Unsuspend apps val suspendedApps = settingsRepository.getSuspendedAppPackages() - suspendedApps.forEach { packageName -> - dpm.setPackagesSuspended(adminComponentName, arrayOf(packageName), false) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + suspendedApps.forEach { packageName -> + try { + dpm.setPackagesSuspended(adminComponentName, arrayOf(packageName), false) + } catch (e: Exception) { + AppLogger.w("SettingsVM", "Could not unsuspend $packageName", e) + } + } } settingsRepository.removeAppsFromCache((blockedApps + suspendedApps).toList()) settingsRepository.setBlockedAppPackages(emptySet()) settingsRepository.setSuspendedAppPackages(emptySet()) + // Drop every remaining user restriction rather than relying on the + // feature toggles above having covered them. DISALLOW_UNINSTALL_APPS and + // DISALLOW_APPS_CONTROL in particular make the package un-removable, and + // once device ownership is gone they can no longer be cleared — which is + // exactly how the app ended up stuck on the device with its protections + // already disabled. + clearAllUserRestrictions() + + // Also make sure nothing still marks this package as protected. + try { + dpm.setUninstallBlocked(adminComponentName, context.packageName, false) + } catch (e: Exception) { + AppLogger.w("SettingsVM", "Could not clear own uninstall block", e) + } + // Clear device owner (this removes admin privileges) dpm.clearDeviceOwnerApp(context.packageName) From 8dbf5fd2a21837b3bb102b68460f2dc3216ef963 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 9 Aug 2026 16:59:16 +0000 Subject: [PATCH 2/4] Add GitHub Actions workflow to build the APK Builds the debug and unsigned release APKs on pushes and pull requests and uploads both as artifacts, so changes are compile-verified in CI. Installs the NDK explicitly (the project runs ndk-build via app/src/main/jni/Android.mk and does not pin ndkVersion) and marks gradlew executable, as it is committed without the executable bit. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01WKeZ6SjfkeLU7qf1YbBVLY --- .github/workflows/build-apk.yml | 66 +++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 .github/workflows/build-apk.yml diff --git a/.github/workflows/build-apk.yml b/.github/workflows/build-apk.yml new file mode 100644 index 0000000..882716d --- /dev/null +++ b/.github/workflows/build-apk.yml @@ -0,0 +1,66 @@ +name: Build APK + +on: + push: + branches: + - main + - PreBuild + - Pre-Release + - 'claude/**' + pull_request: + workflow_dispatch: + +concurrency: + group: build-apk-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + name: Assemble debug and release APKs + runs-on: ubuntu-latest + timeout-minutes: 60 + + steps: + - name: Check out the repository + uses: actions/checkout@v4 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + + - name: Set up the Android SDK + uses: android-actions/setup-android@v3 + + # The project builds native code through ndk-build (app/src/main/jni/Android.mk) + # and does not pin ndkVersion, so the NDK has to be present before AGP looks for it. + - name: Install the NDK + run: sdkmanager --install "ndk;27.2.12479018" "cmake;3.22.1" + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + # gradlew is committed without the executable bit. + - name: Make gradlew executable + run: chmod +x ./gradlew + + - name: Assemble debug APK + run: ./gradlew --no-daemon --stacktrace assembleDebug + + - name: Assemble release APK (unsigned) + run: ./gradlew --no-daemon --stacktrace assembleRelease + + - name: Upload debug APK + uses: actions/upload-artifact@v4 + with: + name: abloq-debug-apk + path: app/build/outputs/apk/debug/*.apk + if-no-files-found: error + + - name: Upload release APK + uses: actions/upload-artifact@v4 + with: + name: abloq-release-apk-unsigned + path: app/build/outputs/apk/release/*.apk + if-no-files-found: error From 03268039ac28bc94f56f9c48e96fcb426830cbf5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 9 Aug 2026 17:01:58 +0000 Subject: [PATCH 3/4] Do not pin the daemon JVM to the JetBrains vendor gradle/gradle-daemon-jvm.properties pinned toolchainVendor=jetbrains, which was picked up from the IDE's bundled runtime. Gradle has no toolchain download URL for that vendor, so the build fails outright on any machine without a JetBrains JDK already installed: Unable to download toolchain matching the requirements ({languageVersion=21, vendor=JetBrains, ...}) from 'null' Keep the Java 21 requirement and drop the vendor pin; the JetBrains Runtime still satisfies it. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01WKeZ6SjfkeLU7qf1YbBVLY --- gradle/gradle-daemon-jvm.properties | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties index 382c699..6df6a95 100644 --- a/gradle/gradle-daemon-jvm.properties +++ b/gradle/gradle-daemon-jvm.properties @@ -1,3 +1,9 @@ #This file is generated by updateDaemonJvm -toolchainVendor=jetbrains +# +#toolchainVendor is deliberately left unset. Pinning it to "jetbrains" (picked up +#from the IDE's bundled runtime) makes the build fail anywhere a JetBrains JDK is +#not already installed, because Gradle has no download URL for that vendor: +# Unable to download toolchain matching the requirements +# ({languageVersion=21, vendor=JetBrains, ...}) +#Any JDK 21 satisfies the build, including the JetBrains Runtime. toolchainVersion=21 From a9eba9bfca41dd3cd431290b3e718d0061de34a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 9 Aug 2026 17:09:35 +0000 Subject: [PATCH 4/4] Fix unresolved R.string.update_channel_prebuild The default locale defined the string as update_channel_PreRelease while the code and values-en use update_channel_prebuild. A resource missing from the default locale is stripped by AAPT: warn: removing resource string/update_channel_prebuild without required default value e: SettingsScreen.kt:745:52 Unresolved reference 'update_channel_prebuild' so the branch did not compile. Rename the default-locale key to match the name the code references; nothing referenced the old key. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01WKeZ6SjfkeLU7qf1YbBVLY --- app/src/main/res/values/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 119636f..11fd918 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -249,7 +249,7 @@ ערוץ עדכון הגדרות עדכון ערוץ יציב - ערוץ PreRelease + ערוץ PreRelease הסבר מומלץ לבחור בערוץ יציב, אך אם אתה מעונין בפיצ\'רים החדשים מיד שהם יוצאים, אתה יכול לבחור בערוץ הPreRelease. הגדר FRP מותאם אישית