diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7c0b4a0857..12304d209e 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -88,6 +88,7 @@ Strategy: **layer-and-subsystem based**, not feature-by-feature. The Gradle buil | Shell | `termux:{termux-app,termux-shared,termux-view,termux-emulator}` | Embedded Termux shell and terminal. | | Plugin system | `plugin-api`, `plugin-api:plugin-builder`, `plugin-manager` | In-app plugin SDK + manager — `AndroidManifest.xml` `` contract, permissions, extensions. See [plugin-api.md](docs/plugin-api.md) for the API surface & compatibility policy. | | On-device AI | `llama-api`, `llama-impl` | llama.cpp integration, shipped as a per-flavor native AAR. | +| Security | `security` | Instant Hide emergency disguise (ADFA-40): gesture/sensor triggers mounted on the IDE base activity swap the app to a "Code Breaker" cryptogram game and mask it in Recents. Renders in Views, not Compose — a documented [ADR 0009](docs/adr/0009-jetpack-compose-for-new-ui.md) exception (see `security/README.md`). | | Cross-cutting | `eventbus`, `eventbus-android`, `eventbus-events`, `common`, `common-ui`, `common-compose`, `logger`, `resources`, `preferences`, `shared` | Shared infra and the event bus. `common-compose` holds the Compose theming any module can opt into (see [ADR 0009](docs/adr/0009-jetpack-compose-for-new-ui.md)); it is a leaf so modules that aren't Compose pay nothing. | | Testing | `testing:{android,unit,lsp,tooling,common}` | Shared test harnesses, split by what's under test. | diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 55c5fdec0f..c32751b004 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -451,6 +451,7 @@ dependencies { implementation(projects.lookup) implementation(projects.preferences) implementation(projects.resources) + implementation(projects.security) implementation(projects.treeview) implementation(projects.templatesApi) implementation(projects.templatesImpl) diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/AutomationEndToEndTest.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/AutomationEndToEndTest.kt index 8d0ba2fc8a..865dc282b3 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/AutomationEndToEndTest.kt +++ b/app/src/androidTest/kotlin/com/itsaky/androidide/AutomationEndToEndTest.kt @@ -4,7 +4,7 @@ import androidx.test.core.app.ActivityScenario import androidx.test.espresso.matcher.ViewMatchers.isNotEnabled import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.activities.SplashActivity +import com.itsaky.androidide.activities.LauncherActivity import com.itsaky.androidide.helper.advancePastWelcomeScreen import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByText import com.itsaky.androidide.helper.configureAutomationBuildPreferences @@ -49,7 +49,7 @@ class AutomationEndToEndTest : TestCase() { // ── Launch ── step("Launch app") { - ActivityScenario.launch(SplashActivity::class.java) + ActivityScenario.launch(LauncherActivity::class.java) Thread.sleep(LAUNCH_SETTLE_DELAY_MS) } diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/EndToEndTest.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/EndToEndTest.kt index a85d84c5c0..8ff552bd5a 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/EndToEndTest.kt +++ b/app/src/androidTest/kotlin/com/itsaky/androidide/EndToEndTest.kt @@ -4,7 +4,7 @@ import androidx.test.core.app.ActivityScenario import androidx.test.espresso.matcher.ViewMatchers.isNotEnabled import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.activities.SplashActivity +import com.itsaky.androidide.activities.LauncherActivity import com.itsaky.androidide.helper.advancePastWelcomeScreen import com.itsaky.androidide.helper.clickFirstAccessibilityNodeByText import com.itsaky.androidide.helper.configureAutomationBuildPreferences @@ -44,7 +44,7 @@ class EndToEndTest : TestCase() { // ── Launch ── step("Launch app") { - ActivityScenario.launch(SplashActivity::class.java) + ActivityScenario.launch(LauncherActivity::class.java) Thread.sleep(1000) } diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildFlagOffTest.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildFlagOffTest.kt index df799fa328..f2e3647720 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildFlagOffTest.kt +++ b/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildFlagOffTest.kt @@ -3,7 +3,7 @@ package com.itsaky.androidide import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry -import com.itsaky.androidide.activities.SplashActivity +import com.itsaky.androidide.activities.LauncherActivity import com.itsaky.androidide.activities.editor.EditorHandlerActivity import com.itsaky.androidide.app.configuration.IJdkDistributionProvider import com.itsaky.androidide.helper.isExperimentsFlagSet @@ -55,7 +55,7 @@ class QuickBuildFlagOffTest : TestCase() { runCatching { rebuildEditorToolbar() } }.run { step("Launch app") { - ActivityScenario.launch(SplashActivity::class.java) + ActivityScenario.launch(LauncherActivity::class.java) waitForMainHomeOrEditorUi(device.uiDevice) } diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildPipelineTest.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildPipelineTest.kt index 8a67cba619..6da2bea5d0 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildPipelineTest.kt +++ b/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildPipelineTest.kt @@ -5,7 +5,7 @@ import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiSelector -import com.itsaky.androidide.activities.SplashActivity +import com.itsaky.androidide.activities.LauncherActivity import com.itsaky.androidide.app.configuration.IJdkDistributionProvider import com.itsaky.androidide.helper.FakeInstalledPackages import com.itsaky.androidide.helper.ensureOnHomeScreenBeforeCreateProject @@ -366,7 +366,7 @@ class QuickBuildPipelineTest : TestCase() { packageSuffix: String, ) { step("Launch app") { - ActivityScenario.launch(SplashActivity::class.java) + ActivityScenario.launch(LauncherActivity::class.java) waitForMainHomeOrEditorUi(device.uiDevice) } diff --git a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildSmokeTest.kt b/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildSmokeTest.kt index ccc822b3be..2b74db33cb 100644 --- a/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildSmokeTest.kt +++ b/app/src/androidTest/kotlin/com/itsaky/androidide/QuickBuildSmokeTest.kt @@ -5,7 +5,7 @@ import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiSelector -import com.itsaky.androidide.activities.SplashActivity +import com.itsaky.androidide.activities.LauncherActivity import com.itsaky.androidide.activities.editor.EditorHandlerActivity import com.itsaky.androidide.app.configuration.IJdkDistributionProvider import com.itsaky.androidide.helper.FakeInstalledPackages @@ -136,7 +136,7 @@ class QuickBuildSmokeTest : TestCase() { } }.run { step("Launch app") { - ActivityScenario.launch(SplashActivity::class.java) + ActivityScenario.launch(LauncherActivity::class.java) waitForMainHomeOrEditorUi(device.uiDevice) } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7222fbdafc..df5f9cc0c8 100755 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -78,15 +78,102 @@ + + android:theme="@style/AppTheme.Splash" /> + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - onApplyWindowInsets(insets) - if (!eteUpdateDecorViewPaddingInLandscape || - view.resources.configuration.orientation != Configuration.ORIENTATION_LANDSCAPE - ) { - decorViewPadding?.also { p -> - // when switching from landscape to portrait, restore the original padding - view.setPadding(p.left, p.top, p.right, p.bottom) - } - return@OnApplyWindowInsetsListener insets - } - - if (decorViewPadding == null) { - Rect().apply { - left = view.paddingLeft - top = view.paddingTop - right = view.paddingRight - bottom = view.paddingBottom - }.also { paddings -> - decorViewPadding = paddings - } - } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - val systemBarInsets = insets.getInsets(WindowInsets.Type.systemBars()) - view.setPadding( - systemBarInsets.left, - 0, - systemBarInsets.right, - systemBarInsets.bottom - ) - } else { - @Suppress("DEPRECATION") - view.setPadding( - insets.stableInsetLeft, - 0, - insets.stableInsetRight, - insets.stableInsetBottom - ) - } - - insets - } - - override fun onCreate(savedInstanceState: Bundle?) { - applyEdgeToEdge() - super.onCreate(savedInstanceState) - } - - override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { - applyEdgeToEdge() - super.onCreate(savedInstanceState, persistentState) - } - - @SuppressLint("RestrictedApi") - private fun applyEdgeToEdge() { - this.window!!.apply { - addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) - @Suppress("DEPRECATION") - clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) - if (Build.VERSION.SDK_INT >= VERSION_CODES.P) { - attributes = attributes.apply { - layoutInDisplayCutoutMode = - WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES - } - } - } - - EdgeToEdgeUtils.applyEdgeToEdge(this, this.statusBarStyle, this.navigationBarStyle) - - ViewCompat.setOnApplyWindowInsetsListener( - this.window.decorView, - this.onApplyWindowInsetsListener - ) - - this.window.decorView.doOnAttach { onApplySystemBarInsets(getSystemBarInsets(it)) } - } - - /** - * Called when the window insets change. - * - * @param insets The window insets. These insets are not expected to be consumed. - */ - @CallSuper - protected open fun onApplyWindowInsets(insets: WindowInsetsCompat) { - this.systemBarInsets = getSystemBarInsets(insets) - } - - /** - * Called with the system bar insets when the decor view is attached to the window. - */ - protected open fun onApplySystemBarInsets(insets: Insets) {} - - fun closeKeyboard() { - // Get the current focused view; if none, create a new one so that we have a valid window token - val view = currentFocus ?: View(this) - // Retrieve the input method manager service - val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager - // Request to hide the keyboard from the window - inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) - } + /** + * Whether edge-to-edge should be applied to the activity. + */ + protected open var edgeToEdgeEnabled = true + + /** + * Whether the decor view padding should be updated to match the system bars in landscape orientation. + */ + protected open var eteUpdateDecorViewPaddingInLandscape = true + + /** + * Style for the status bar. + */ + protected open val statusBarStyle = EdgeToEdgeUtils.DEFAULT_STATUS_BAR_STYLE!! + + /** + * Style for the navigation bar. + */ + protected open val navigationBarStyle = EdgeToEdgeUtils.DEFAULT_NAVIGATION_BAR_STYLE!! + + /** + * Original padding of the window's decor view. + */ + protected open var decorViewPadding: Rect? = null + + /** + * Last window insets. + */ + protected open var systemBarInsets: Insets? = null + + override var enableSystemBarTheming: Boolean + get() = false + set( + @Suppress("UNUSED_PARAMETER") value, + ) { + throw UnsupportedOperationException("Use edgeToEdgeEnabled and systemBarStyles instead") + } + + private val log = LoggerFactory.getLogger(EdgeToEdgeIDEActivity::class.java) + + @SuppressLint("WrongConstant") + private val onApplyWindowInsetsListener = + OnApplyWindowInsetsListener { view, insets -> + onApplyWindowInsets(insets) + if (!eteUpdateDecorViewPaddingInLandscape || + view.resources.configuration.orientation != Configuration.ORIENTATION_LANDSCAPE + ) { + decorViewPadding?.also { p -> + // when switching from landscape to portrait, restore the original padding + view.setPadding(p.left, p.top, p.right, p.bottom) + } + return@OnApplyWindowInsetsListener insets + } + + if (decorViewPadding == null) { + Rect() + .apply { + left = view.paddingLeft + top = view.paddingTop + right = view.paddingRight + bottom = view.paddingBottom + }.also { paddings -> + decorViewPadding = paddings + } + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val systemBarInsets = insets.getInsets(WindowInsets.Type.systemBars()) + view.setPadding( + systemBarInsets.left, + 0, + systemBarInsets.right, + systemBarInsets.bottom, + ) + } else { + @Suppress("DEPRECATION") + view.setPadding( + insets.stableInsetLeft, + 0, + insets.stableInsetRight, + insets.stableInsetBottom, + ) + } + + insets + } + + override fun onCreate(savedInstanceState: Bundle?) { + applyEdgeToEdge() + super.onCreate(savedInstanceState) + } + + override fun onCreate( + savedInstanceState: Bundle?, + persistentState: PersistableBundle?, + ) { + applyEdgeToEdge() + super.onCreate(savedInstanceState, persistentState) + } + + @SuppressLint("RestrictedApi") + private fun applyEdgeToEdge() { + this.window!!.apply { + addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) + @Suppress("DEPRECATION") + clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) + if (Build.VERSION.SDK_INT >= VERSION_CODES.P) { + attributes = + attributes.apply { + layoutInDisplayCutoutMode = + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + } + } + } + + EdgeToEdgeUtils.applyEdgeToEdge(this, this.statusBarStyle, this.navigationBarStyle) + + ViewCompat.setOnApplyWindowInsetsListener( + this.window.decorView, + this.onApplyWindowInsetsListener, + ) + + this.window.decorView.doOnAttach { onApplySystemBarInsets(getSystemBarInsets(it)) } + } + + /** + * Called when the window insets change. + * + * @param insets The window insets. These insets are not expected to be consumed. + */ + @CallSuper + protected open fun onApplyWindowInsets(insets: WindowInsetsCompat) { + this.systemBarInsets = getSystemBarInsets(insets) + } + + /** + * Called with the system bar insets when the decor view is attached to the window. + */ + protected open fun onApplySystemBarInsets(insets: Insets) {} + + fun closeKeyboard() { + // Get the current focused view; if none, create a new one so that we have a valid window token + val view = currentFocus ?: View(this) + // Retrieve the input method manager service + val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + // Request to hide the keyboard from the window + inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) + } } diff --git a/app/src/main/java/com/itsaky/androidide/app/IDEApplication.kt b/app/src/main/java/com/itsaky/androidide/app/IDEApplication.kt index b1023aae41..1d9732c4a3 100755 --- a/app/src/main/java/com/itsaky/androidide/app/IDEApplication.kt +++ b/app/src/main/java/com/itsaky/androidide/app/IDEApplication.kt @@ -31,8 +31,10 @@ import com.itsaky.androidide.di.coreModule import com.itsaky.androidide.di.pluginModule import com.itsaky.androidide.di.quickBuildModule import com.itsaky.androidide.di.templateModule +import com.itsaky.androidide.floating.model.DockingManager import com.itsaky.androidide.handlers.GlitchTipDiagnosticsContext import com.itsaky.androidide.plugins.manager.core.PluginManager +import com.itsaky.androidide.security.InstantHide import com.itsaky.androidide.treesitter.TreeSitter import com.itsaky.androidide.utils.RecyclableObjectPool import com.itsaky.androidide.utils.VMUtils @@ -196,6 +198,11 @@ class IDEApplication : super.onCreate() registerActivityLifecycleCallbacks(this) + // Instant Hide (ADFA-40) on every activity. A hide closes the floating windows, which draw over + // other apps and would otherwise stay on top of the disguise. + InstantHide.register(this) { + DockingManager.windows.value.forEach { tab -> DockingManager.close(tab.id) } + } // @devs: looking to initialize a component at application startup? // first, decide whether the component you want to initialize can be diff --git a/app/src/main/java/com/itsaky/androidide/preferences/rootPrefExts.kt b/app/src/main/java/com/itsaky/androidide/preferences/rootPrefExts.kt index 7bc7ff3db5..4a7734159b 100644 --- a/app/src/main/java/com/itsaky/androidide/preferences/rootPrefExts.kt +++ b/app/src/main/java/com/itsaky/androidide/preferences/rootPrefExts.kt @@ -38,6 +38,7 @@ class ConfigurationPreferences( addPreference(BuildAndRunPreferences()) addPreference(TermuxPreferences()) addPreference(GitPreferencesScreen()) + addPreference(SecurityPreferencesScreen()) addPreference(PluginManagerEntry()) pluginSettingsPreferences().forEach { addPreference(it) } diff --git a/app/src/main/java/com/itsaky/androidide/preferences/securityPrefExts.kt b/app/src/main/java/com/itsaky/androidide/preferences/securityPrefExts.kt new file mode 100644 index 0000000000..1cb0293f78 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/preferences/securityPrefExts.kt @@ -0,0 +1,94 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.preferences + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import androidx.preference.Preference +import com.itsaky.androidide.resources.R +import com.itsaky.androidide.idetooltips.TooltipTag.PREFS_SECURITY +import com.itsaky.androidide.preferences.internal.SecurityPreferences +import com.itsaky.androidide.security.InstantHide +import kotlinx.parcelize.Parcelize + +@Parcelize +class SecurityPreferencesScreen( + override val key: String = "idepref_security", + override val title: Int = R.string.idepref_security_title, + override val summary: Int? = R.string.idepref_security_summary, + override val children: List = mutableListOf(), + override val tooltipTag: String = PREFS_SECURITY, +) : IPreferenceScreen() { + + init { + addPreference(EmergencyHidingConfig()) + } +} + +@Parcelize +class EmergencyHidingConfig( + override val key: String = "idepref_security_emergency", + override val title: Int = R.string.idepref_security_emergency_group, + override val children: List = mutableListOf(), +) : IPreferenceGroup() { + + init { + addPreference(InstantHide()) + } +} + +@Parcelize +class InstantHide( + override val key: String = SecurityPreferences.INSTANT_HIDE, + override val title: Int = R.string.idepref_security_instantHide_title, + override val summary: Int? = R.string.idepref_security_instantHide_summary, +) : SwitchPreference() { + + override fun onCreatePreference(context: Context): Preference { + val pref = super.onCreatePreference(context) as androidx.preference.SwitchPreference + pref.isChecked = SecurityPreferences.instantHideEnabled + return pref + } + + override fun onPreferenceChanged(preference: Preference, newValue: Any?): Boolean { + SecurityPreferences.instantHideEnabled = + newValue as Boolean? ?: SecurityPreferences.instantHideEnabled + // Apply the FLAG_SECURE policy to this already-resumed Settings window now: the armed-state + // contract is that screenshots/Recents are masked the moment Instant Hide is on, but + // applyScreenSecurity() otherwise only runs on the next onResume, leaving a gap right after + // arming. Also clears the flag immediately when the user turns it back off. + preference.context.findActivity()?.let(InstantHide::applyScreenSecurity) + return true + } +} + +/** + * The hosting [Activity], or null. A preference's context is whatever the host passed + * when the row was built -- today the Activity itself, but unwrapping the [ContextWrapper] chain + * keeps this correct if a themed wrapper is ever interposed, since a missed call would silently + * leave the window screenshotable. + */ +private fun Context.findActivity(): Activity? { + var ctx: Context? = this + while (ctx is ContextWrapper) { + if (ctx is Activity) return ctx + ctx = ctx.baseContext + } + return null +} diff --git a/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt b/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt index 88452a86ad..df0a4e18ab 100644 --- a/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt +++ b/app/src/main/java/com/itsaky/androidide/services/builder/GradleBuildService.kt @@ -42,9 +42,11 @@ import com.itsaky.androidide.managers.ToolsManager import com.itsaky.androidide.plugins.manager.services.IdeBuildServiceImpl import com.itsaky.androidide.preferences.internal.BuildPreferences import com.itsaky.androidide.preferences.internal.DevOpsPreferences +import com.itsaky.androidide.preferences.internal.SecurityPreferences import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.projects.builder.BuildService import com.itsaky.androidide.resources.R +import com.itsaky.androidide.security.NeutralNotifications import com.itsaky.androidide.services.ToolingServerNotStartedException import com.itsaky.androidide.services.builder.ToolingServerRunner.OnServerStartListener import com.itsaky.androidide.tasks.ifCancelledOrInterrupted @@ -405,6 +407,10 @@ class GradleBuildService : message: String, isProgress: Boolean, ): Notification { + // Instant Hide (ADFA-40): a build's progress must not reappear in the shade while disguised. + if (SecurityPreferences.isHiddenStateActive) { + return NeutralNotifications.build(this, BaseApplication.NOTIFICATION_GRADLE_BUILD_SERVICE) + } val ticker = getString(R.string.title_gradle_service_notification_ticker) val title = getString(R.string.title_gradle_service_notification) val launch = packageManager.getLaunchIntentForPackage(BuildConfig.APPLICATION_ID) diff --git a/app/src/test/java/com/itsaky/androidide/activities/DeepLinkSetupGateTest.kt b/app/src/test/java/com/itsaky/androidide/activities/DeepLinkSetupGateTest.kt index fa3c112f8f..37d932a2ed 100644 --- a/app/src/test/java/com/itsaky/androidide/activities/DeepLinkSetupGateTest.kt +++ b/app/src/test/java/com/itsaky/androidide/activities/DeepLinkSetupGateTest.kt @@ -40,7 +40,7 @@ import java.io.File /** * A deep link must not walk past setup. Both of DeepLinkActivity's targets sit beyond - * SplashActivity and OnboardingActivity, which are the only things enforcing terms, permissions, + * LauncherActivity and OnboardingActivity, which are the only things enforcing terms, permissions, * the JDK and SDK install, the low-storage check and the x86 exit -- so a link arriving on a fresh * install used to land the user in an editor that could not build (ADFA-5067 review). * @@ -60,7 +60,7 @@ class DeepLinkSetupGateTest { val next = shadowOf(activity).nextStartedActivity assertThat(next).isNotNull() - assertThat(next.component?.className).isEqualTo(SplashActivity::class.java.name) + assertThat(next.component?.className).isEqualTo(LauncherActivity::class.java.name) assertThat(activity.isFinishing).isTrue() } @@ -76,7 +76,7 @@ class DeepLinkSetupGateTest { val activity = Robolectric.buildActivity(DeepLinkActivity::class.java, intent).create().get() val next = shadowOf(activity).nextStartedActivity - assertThat(next.component?.className).isEqualTo(SplashActivity::class.java.name) + assertThat(next.component?.className).isEqualTo(LauncherActivity::class.java.name) assertThat(activity.isFinishing).isTrue() } diff --git a/idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt b/idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt index 13e05d7143..ff1b1749b1 100644 --- a/idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt +++ b/idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt @@ -48,6 +48,7 @@ object TooltipTag { const val PREFS_BUILD_RUN = "prefs.buildrun" const val PREFS_TERMUX = "prefs.termux" const val PREFS_GIT = "prefs.git" + const val PREFS_SECURITY = "prefs.security" const val PREFS_PLUGIN_MANAGER = "prefs.pluginmanager" const val PREFS_ABOUT = "prefs.about" const val PREFS_DEVOPTIONS = "prefs.devoptions" diff --git a/preferences/src/main/java/com/itsaky/androidide/preferences/internal/SecurityPreferences.kt b/preferences/src/main/java/com/itsaky/androidide/preferences/internal/SecurityPreferences.kt new file mode 100644 index 0000000000..5d15d5725d --- /dev/null +++ b/preferences/src/main/java/com/itsaky/androidide/preferences/internal/SecurityPreferences.kt @@ -0,0 +1,44 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.preferences.internal + +/** + * Preferences for the "Instant Hide" emergency security feature (ADFA-40). + * + * [instantHideEnabled] is the user-facing arm switch. [isHiddenStateActive] is internal runtime + * state: it records that the disguise is currently engaged, so the app re-enters the disguise on the + * next launch (surviving restarts/reboots) until the user performs the exit gesture. Both are backed + * by shared preferences, which persist across restarts and clear on uninstall. + */ +@Suppress("MemberVisibilityCanBePrivate") +object SecurityPreferences { + const val INSTANT_HIDE = "idepref_security_instantHide" + const val IS_HIDDEN_STATE = "idepref_security_isHiddenStateActive" + + var instantHideEnabled: Boolean + get() = prefManager.getBoolean(INSTANT_HIDE, false) + set(value) { + prefManager.putBoolean(INSTANT_HIDE, value) + } + + var isHiddenStateActive: Boolean + get() = prefManager.getBoolean(IS_HIDDEN_STATE, false) + set(value) { + prefManager.putBoolean(IS_HIDDEN_STATE, value) + } +} diff --git a/resources/src/main/res/drawable/ic_stealth_notification.xml b/resources/src/main/res/drawable/ic_stealth_notification.xml new file mode 100644 index 0000000000..145b80d17c --- /dev/null +++ b/resources/src/main/res/drawable/ic_stealth_notification.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/resources/src/main/res/values/security_strings.xml b/resources/src/main/res/values/security_strings.xml new file mode 100644 index 0000000000..031250a4fa --- /dev/null +++ b/resources/src/main/res/values/security_strings.xml @@ -0,0 +1,35 @@ + + + + + Security + Quickly disguise the IDE in an emergency + Emergency hiding + Instant Hide + Disguise the app as a puzzle game on a three-finger tap, screen off, face-down, or one minute + idle. A slow double three-finger tap returns to the IDE. + + + Code Breaker + Code Breaker - Cryptogram + Each blue letter represents an encrypted code. Replace each cipher letter with your guess. Your + decoded letters appear in green on the top row above each cipher letter. + Check Solution + Next Puzzle + Reset + Hint + Congratulations! Puzzle Solved! + Not quite right yet. Keep trying! + Revealed letter \"%1$c\" = \"%2$c\" + — %1$s + Letter Substitution Mapping: + Cipher Letter: + → Replace with: + Apply + + + Screenshot protection is off because the override file /sdcard/Download/CodeOnTheGo.mfs is + present. + diff --git a/security/README.md b/security/README.md new file mode 100644 index 0000000000..1817c78f0a --- /dev/null +++ b/security/README.md @@ -0,0 +1,105 @@ +# :security + +Instant Hide (ADFA-40): a single, eyes-free way to disguise the IDE for a user who may be in +danger. Any of four triggers swaps Code On The Go to a working offline cryptogram game ("Code +Breaker"), swaps the launcher name/icon, and masks the app in Recents. The disguise persists across +restarts and reboots until the user performs the exit gesture. Instant Hide is **off by default**; +the user arms it in Settings → Security. + +## Triggers (when armed) + +Owned by `SecurityController`. `InstantHide.register`, called from `IDEApplication`, mounts one on +every activity through `ActivityLifecycleCallbacks` and wraps its window callback to see its input, so +the triggers are live on every screen whatever its base class, the terminal included. The security +Settings screen implements `InstantHide.GesturesExempt`, so arming the feature there does not hide it. + +- **Three-finger tap** (`GestureDetectorHelper.ThreeFingerTapDetector`, fed every touch on the window). +- **Screen off** (`ACTION_SCREEN_OFF` broadcast; registered once and kept across `onPause`, since the + pause races the broadcast). +- **Face-down** (`FaceDownDetector`): gravity Z past a threshold, armed only by a face-up or upright + reading, so a phone already face down when a screen opens (held overhead, lying on your back) does + not fire. +- **60s inactivity**: a `Handler` reset by every touch, key and mouse event on the window. When it runs + out while the soft keyboard is showing or a dialog or popup has the focus, it starts again instead + of hiding, since those take input the window never sees. The keyboard opening or closing, and the + window getting the focus back, reset it too. A phone left like that still hides when its screen + times out. + +Any trigger calls `triggerInstantHide()`: set the hidden-state flag, swap to the stealth launcher +alias, close the floating windows (the `onHide` hook), mask the notifications (`NeutralNotifications`), +then `InstantHide.showDisguise`: launch `CryptogramActivity` (`NEW_TASK | CLEAR_TASK`), remove the app's +other tasks, finish the IDE screen. The disguise has a task affinity of its own because disabling the +default alias makes Android remove the task that alias started, about a second later, with everything +in it. + +While the flag is set, the same lifecycle callbacks send every activity but the disguise to it as it is +created or resumed, so no entry point can surface IDE UI. Entry points whose `onCreate` does work — +`LauncherActivity`, `DeepLinkActivity`, `ExternalFileInstallActivity`, `CrashHandlerActivity` — also +call `InstantHide.redirectIfHidden` and return, so the work never starts. The redirect reuses a running +disguise (`CLEAR_TOP | SINGLE_TOP`), so a link or file opened while hidden does not reset the puzzle. +The redirect removes the entry point's own task too, so Recents keeps one card, the disguise's. The +exit gesture (slow double three-finger tap) clears the flag, restores the default alias, returns to +the IDE, and removes the disguise's task. + +## Notifications + +On a hide, `NeutralNotifications.mask` removes the app's ordinary notifications. A +foreground-service notification cannot be removed while the service runs, so it is replaced under +the same id by one that shows only the disguise's name and a neutral icon. `GradleBuildService` and +`TermuxService` build that neutral notification themselves while the flag is set, so their updates do +not bring the IDE's text back. After the exit gesture each shows its own again on its next update. + +## Launcher aliases + +The real launcher activity is `LauncherActivity`, with no launcher filter. The default alias is named +`.activities.SplashActivity`, the launcher component from before Instant Hide, so home-screen icons +pinned to it survive the update on every launcher. The five stealth aliases share the target. The +disguise's Recents entry uses this device's stealth alias icon (`LauncherAliasManager.stealthIcon`). + +## Screenshot / Recents masking + +`FLAG_SECURE` is applied whenever Instant Hide is armed — it blocks screenshots and masks the Recents +thumbnail (a single flag; the two can't be separated). There is **no UI toggle**. The only override is +a QA escape hatch: if `/sdcard/Download/CodeOnTheGo.mfs` exists (`SecurityOverride`), `FLAG_SECURE` is +not applied and the app shows a one-time advisory, so QA can capture screenshots and bug reports. + +## Known limits + +The app's own name, ``, is fixed at install; only the launcher entry's name +and icon can be swapped, because each alias has its own label. Android shows the app's name wherever +it lists the app, so these still say "Code on the Go" while hidden: + +- The App info page, in Settings → Apps and two taps from the disguise: tap the title of its Recents + card, then App info. +- A screen reader's label for that Recents card: the Pixel launcher reads the app's name before the + task's title when the two differ, so TalkBack says "Code on the Go Code Breaker" aloud. + +Renaming the app would rename it everywhere, hidden or not, and tie the disguise's name to the IDE. + +## Pieces + +| File | Role | +|---|---| +| `GestureDetectorHelper.kt` | Three-finger tap + slow-double-three-finger-tap detectors (unit-tested). | +| `InstantHide.kt` | Mounts a controller on every activity and redirects to the disguise while hidden. | +| `FaceDownDetector.kt` | When a gravity reading completes a flip to face down (unit-tested). | +| `NeutralNotifications.kt` | Removes or neutralises the app's notifications while hidden (unit-tested). | +| `HideState.kt` | The armed and hidden flags, behind an interface tests can replace. | +| `LauncherAliasManager.kt` | Picks one of five stealth aliases per device (FNV-1a hash); enables/disables aliases. | +| `SecurityController.kt` | Owns the four triggers, the inactivity timer, and the `FLAG_SECURE` policy. | +| `SecurityOverride.kt` | The `CodeOnTheGo.mfs` magic-file check. | +| `CryptogramActivity.kt` + `FlowLayout.kt` + `res/layout/activity_cryptogram.xml` | The disguise game. | + +The on/off flag and hidden-state flag live in `:preferences` +(`preferences/.../internal/SecurityPreferences.kt`, `PreferenceManager`-backed). The Settings UI and +the launcher activity-aliases live in `:app`. User-facing strings live in `:resources` +(`security_strings.xml`) so they reach the Crowdin translation flow. + +## ADR 0009 exception (Views, not Compose) + +[ADR 0009](../docs/adr/0009-jetpack-compose-for-new-ui.md) requires new IDE UI to be Jetpack Compose. +The cryptogram disguise is a **deliberate, documented exception**: it is disposable camouflage ported +as-is from the Security Mockup prototype, not core IDE UI, and a Compose rebuild was explicitly out of +scope for ADFA-40. It is rendered in Views (XML + `FlowLayout`) with the game logic in the Activity. +It also, by design, omits the long-press help affordance (REVIEW.md §9) — surfacing IDE help on the +"game" would blow the disguise. A future Compose rebuild would be a separate change. diff --git a/security/build.gradle.kts b/security/build.gradle.kts new file mode 100644 index 0000000000..2e643a695e --- /dev/null +++ b/security/build.gradle.kts @@ -0,0 +1,22 @@ +import com.itsaky.androidide.build.config.BuildConfig + +plugins { + alias(libs.plugins.kotlin.android) + alias(libs.plugins.android.library) +} + +android { + namespace = "${BuildConfig.PACKAGE_NAME}.security" +} + +dependencies { + implementation(libs.androidx.appcompat.v171) + implementation(libs.androidx.core.ktx.v1120) + implementation(libs.google.material) + implementation(projects.preferences) + implementation(projects.resources) + + testImplementation(libs.tests.junit) + testImplementation(libs.tests.google.truth) + testImplementation(libs.tests.robolectric) +} diff --git a/security/src/main/AndroidManifest.xml b/security/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..813c95806a --- /dev/null +++ b/security/src/main/AndroidManifest.xml @@ -0,0 +1,19 @@ + + + + + + + + diff --git a/security/src/main/java/com/itsaky/androidide/security/CryptogramActivity.kt b/security/src/main/java/com/itsaky/androidide/security/CryptogramActivity.kt new file mode 100644 index 0000000000..5c06a4f440 --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/CryptogramActivity.kt @@ -0,0 +1,369 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +import android.app.ActivityManager +import android.content.Intent +import android.graphics.Typeface +import android.os.Build +import android.os.Bundle +import android.view.Gravity +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputMethodManager +import android.widget.ArrayAdapter +import android.widget.LinearLayout +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import com.itsaky.androidide.preferences.internal.SecurityPreferences +import com.itsaky.androidide.security.databinding.ActivityCryptogramBinding +import com.itsaky.androidide.resources.R as ResR + +/** + * The "Code Breaker" cryptogram disguise for Instant Hide (ADFA-40). A fully playable offline + * monoalphabetic-substitution puzzle that stands in for the IDE while hidden. The deliberate exit + * gesture (a slow double three-finger tap) returns to the IDE. + * + * Ported from the security mockup; the self-destruct half is intentionally omitted. + */ +class CryptogramActivity : AppCompatActivity() { + companion object { + private const val USER_LETTER_TEXT_SIZE_SP = 18f + private const val CIPHER_LETTER_TEXT_SIZE_SP = 14f + private const val PUNCTUATION_TEXT_SIZE_SP = 18f + private const val WORD_PADDING_START_PX = 4 + private const val WORD_PADDING_END_PX = 12 + private const val WORD_PADDING_VERTICAL_PX = 8 + private const val LETTER_PADDING_HORIZONTAL_PX = 3 + } + + private lateinit var binding: ActivityCryptogramBinding + + data class Puzzle( + val text: String, + val author: String, + ) + + private val puzzles = + listOf( + Puzzle("THE ONLY WAY TO DO GREAT WORK IS TO LOVE WHAT YOU DO.", "Steve Jobs"), + Puzzle("SIMPLICITY IS THE SOUL OF EFFICIENCY.", "Austin Freeman"), + Puzzle("CODE IS LIKE HUMOR. WHEN YOU HAVE TO EXPLAIN IT, IT IS BAD.", "Cory House"), + Puzzle("FIRST SOLVE THE PROBLEM THEN WRITE THE CODE.", "John Johnson"), + Puzzle("EXPERIENCE IS THE NAME EVERYONE GIVES TO THEIR MISTAKES.", "Oscar Wilde"), + Puzzle("MAKE IT WORK MAKE IT RIGHT MAKE IT FAST.", "Kent Beck"), + Puzzle( + "ANY FOOL CAN WRITE CODE THAT A COMPUTER CAN UNDERSTAND. GOOD PROGRAMMERS WRITE CODE THAT HUMANS CAN UNDERSTAND.", + "Martin Fowler", + ), + Puzzle("BEFORE SOFTWARE CAN BE REUSABLE IT FIRST HAS TO BE USABLE.", "Ralph Johnson"), + Puzzle("OPTIMISM IS AN OCCUPATIONAL HAZARD OF PROGRAMMING. FEEDBACK IS THE TREATMENT.", "Kent Beck"), + Puzzle("THE MOST DISASTROUS THING THAT YOU CAN EVER LEARN IS YOUR FIRST PROGRAMMING LANGUAGE.", "Alan Kay"), + Puzzle("TRUTH CAN ONLY BE FOUND IN ONE PLACE: THE CODE.", "Robert C. Martin"), + Puzzle( + "IT IS NOT AT ALL IMPORTANT TO GET IT RIGHT THE FIRST TIME. IT IS VITALLY IMPORTANT TO GET IT RIGHT THE LAST TIME.", + "Andrew Hunt", + ), + ) + + private var currentPuzzleIndex = 0 + private val cipherMap = mutableMapOf() // plain -> cipher + private val reverseCipherMap = mutableMapOf() // cipher -> plain + private val userReplacements = mutableMapOf() // cipher -> user-entered letter + + private lateinit var exitGestureDetector: GestureDetectorHelper.SlowDoubleThreeFingerTapDetector + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityCryptogramBinding.inflate(layoutInflater) + setContentView(binding.root) + + // Mask the task description so Recents shows the disguise's title and this device's stealth + // icon; without an icon it falls back to the application's, which is the IDE logo. + val label = getString(ResR.string.stealth_app_name) + val icon = LauncherAliasManager.stealthIcon(this) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + setTaskDescription( + ActivityManager.TaskDescription + .Builder() + .setLabel(label) + .apply { if (icon != 0) setIcon(icon) } + .build(), + ) + } else { + @Suppress("DEPRECATION") + setTaskDescription(ActivityManager.TaskDescription(label, icon)) + } + + exitGestureDetector = + GestureDetectorHelper.SlowDoubleThreeFingerTapDetector(this) { exitDisguiseMode() } + + binding.btnCheckSolution.setOnClickListener { checkSolution() } + binding.btnNextPuzzle.setOnClickListener { + currentPuzzleIndex = (currentPuzzleIndex + 1) % puzzles.size + loadPuzzle(currentPuzzleIndex) + } + binding.btnResetPuzzle.setOnClickListener { + userReplacements.clear() + renderPuzzleGrid() + binding.tvSolutionFeedback.text = "" + updateHintButtonState() + } + binding.btnHintLetter.setOnClickListener { revealHintLetter() } + binding.btnApplySub.setOnClickListener { applyCurrentSubstitution() } + + binding.editReplacementLetter.setOnEditorActionListener { _, actionId, event -> + if (actionId == EditorInfo.IME_ACTION_DONE || + actionId == EditorInfo.IME_ACTION_GO || + (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) + ) { + applyCurrentSubstitution() + dismissKeyboard() + true + } else { + false + } + } + + loadPuzzle(currentPuzzleIndex) + } + + private fun loadPuzzle(index: Int) { + val puzzle = puzzles[index] + binding.tvPuzzleAuthor.text = getString(ResR.string.puzzle_author_format, puzzle.author) + binding.tvSolutionFeedback.text = "" + userReplacements.clear() + + generateCipher() + + val cipherChars = + puzzle.text + .filter { it in 'A'..'Z' } + .map { cipherMap[it] ?: it } + .distinct() + .sorted() + .map { it.toString() } + + binding.spinnerCipherLetters.adapter = + ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, cipherChars) + + renderPuzzleGrid() + updateHintButtonState() + } + + private fun generateCipher() { + cipherMap.clear() + reverseCipherMap.clear() + val alphabet = ('A'..'Z').toList() + var shuffled = alphabet.shuffled() + + // Derangement: no letter may encrypt to itself. + while (alphabet.indices.any { alphabet[it] == shuffled[it] }) { + shuffled = alphabet.shuffled() + } + + for (i in alphabet.indices) { + cipherMap[alphabet[i]] = shuffled[i] + reverseCipherMap[shuffled[i]] = alphabet[i] + } + } + + private fun renderPuzzleGrid() { + val puzzle = puzzles[currentPuzzleIndex] + val container = binding.containerPuzzleGrid + container.removeAllViews() + + for (word in puzzle.text.split(" ")) { + val wordLayout = + LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + setPadding( + WORD_PADDING_START_PX, + WORD_PADDING_VERTICAL_PX, + WORD_PADDING_END_PX, + WORD_PADDING_VERTICAL_PX, + ) + } + + for (char in word) { + val letterCol = + LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + gravity = Gravity.CENTER_HORIZONTAL + setPadding(LETTER_PADDING_HORIZONTAL_PX, 0, LETTER_PADDING_HORIZONTAL_PX, 0) + } + + if (char in 'A'..'Z') { + val cipherChar = cipherMap[char] ?: char + val userChar = userReplacements[cipherChar] ?: '_' + + val tvUser = + TextView(this).apply { + text = userChar.toString() + textSize = USER_LETTER_TEXT_SIZE_SP + setTypeface(null, Typeface.BOLD) + setTextColor( + ContextCompat.getColor( + this@CryptogramActivity, + if (userChar != '_') R.color.success_green else R.color.placeholder_gray, + ), + ) + gravity = Gravity.CENTER + } + + val tvCipher = + TextView(this).apply { + text = cipherChar.toString() + textSize = CIPHER_LETTER_TEXT_SIZE_SP + setTextColor(ContextCompat.getColor(this@CryptogramActivity, R.color.cipher_letter_blue)) + gravity = Gravity.CENTER + } + + letterCol.addView(tvUser) + letterCol.addView(tvCipher) + + letterCol.isClickable = true + letterCol.setOnClickListener { + val adapter = binding.spinnerCipherLetters.adapter ?: return@setOnClickListener + val cipherStr = cipherChar.toString() + for (pos in 0 until adapter.count) { + if (adapter.getItem(pos)?.toString() == cipherStr) { + binding.spinnerCipherLetters.setSelection(pos) + focusAndOpenKeyboard() + break + } + } + } + } else { + val tvPunct = + TextView(this).apply { + text = char.toString() + textSize = PUNCTUATION_TEXT_SIZE_SP + setTextColor(ContextCompat.getColor(this@CryptogramActivity, R.color.pastel_text_dark)) + gravity = Gravity.CENTER + } + letterCol.addView(tvPunct) + } + + wordLayout.addView(letterCol) + } + + container.addView(wordLayout) + } + } + + private fun checkSolution() { + val solved = isPuzzleSolved() + binding.tvSolutionFeedback.setTextColor( + ContextCompat.getColor(this, if (solved) R.color.success_green else R.color.error_red), + ) + binding.tvSolutionFeedback.text = + getString(if (solved) ResR.string.puzzle_solved else ResR.string.puzzle_incorrect) + updateHintButtonState() + } + + private fun isPuzzleSolved(): Boolean { + val puzzle = puzzles[currentPuzzleIndex] + for (char in puzzle.text) { + if (char in 'A'..'Z') { + val cipherChar = cipherMap[char] ?: char + if (userReplacements[cipherChar] != char) { + return false + } + } + } + return true + } + + private fun updateHintButtonState() { + binding.btnHintLetter.isEnabled = !isPuzzleSolved() + } + + private fun revealHintLetter() { + val puzzle = puzzles[currentPuzzleIndex] + val unsolvedPlainLetters = + puzzle.text + .toList() + .filter { it in 'A'..'Z' } + .distinct() + .filter { + val cipher = cipherMap[it] ?: it + userReplacements[cipher] != it + } + + if (unsolvedPlainLetters.isNotEmpty()) { + val targetPlain = unsolvedPlainLetters.random() + val targetCipher = cipherMap[targetPlain] ?: targetPlain + userReplacements[targetCipher] = targetPlain + renderPuzzleGrid() + updateHintButtonState() + binding.tvSolutionFeedback.setTextColor(ContextCompat.getColor(this, R.color.cipher_letter_blue)) + binding.tvSolutionFeedback.text = getString(ResR.string.hint_used, targetCipher, targetPlain) + } + } + + private fun applyCurrentSubstitution() { + val selectedCipher = binding.spinnerCipherLetters.selectedItem as? String + val inputLetter = + binding.editReplacementLetter.text + .toString() + .trim() + .uppercase() + if (!selectedCipher.isNullOrEmpty() && inputLetter.isNotEmpty()) { + userReplacements[selectedCipher[0]] = inputLetter[0] + binding.editReplacementLetter.setText("") + renderPuzzleGrid() + updateHintButtonState() + } + } + + private fun focusAndOpenKeyboard() { + binding.editReplacementLetter.requestFocus() + val imm = getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager + imm?.showSoftInput(binding.editReplacementLetter, InputMethodManager.SHOW_IMPLICIT) + } + + private fun dismissKeyboard() { + val imm = getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager + imm?.hideSoftInputFromWindow(binding.editReplacementLetter.windowToken, 0) + binding.editReplacementLetter.clearFocus() + } + + /** Leaves the disguise and returns to the IDE via its launcher entry point. */ + private fun exitDisguiseMode() { + SecurityPreferences.isHiddenStateActive = false + LauncherAliasManager.setStealthMode(this, false) + + val launch = + packageManager.getLaunchIntentForPackage(packageName)?.apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + } + if (launch != null) { + startActivity(launch) + } + // The disguise has a task of its own; a plain finish would leave its card in Recents. + finishAndRemoveTask() + } + + override fun dispatchTouchEvent(ev: MotionEvent): Boolean { + exitGestureDetector.onTouchEvent(ev) + return super.dispatchTouchEvent(ev) + } +} diff --git a/security/src/main/java/com/itsaky/androidide/security/FaceDownDetector.kt b/security/src/main/java/com/itsaky/androidide/security/FaceDownDetector.kt new file mode 100644 index 0000000000..b473741c38 --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/FaceDownDetector.kt @@ -0,0 +1,53 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +/** + * Decides when the face-down trigger fires, from the gravity Z reading (about -9.8 with the screen + * fully facing down). It arms only on a face-up or upright reading, so a phone that is already screen + * down when the IDE opens - held overhead while lying on your back - never fires; it disarms on + * firing, so wobbling about the threshold fires once. + */ +internal class FaceDownDetector { + companion object { + const val FACE_DOWN_Z = -6.0f + + /** At or above this the screen faces up or stands upright, so the next flip down may fire. */ + const val ARMED_Z = 0.0f + } + + private var armed = false + + /** Forgets the last orientation, so a flip must again start from face up or upright. */ + fun reset() { + armed = false + } + + /** @return true when this reading completes a flip from face up or upright to face down. */ + fun onGravityZ(z: Float): Boolean { + if (z >= ARMED_Z) { + armed = true + return false + } + if (armed && z <= FACE_DOWN_Z) { + armed = false + return true + } + return false + } +} diff --git a/security/src/main/java/com/itsaky/androidide/security/FlowLayout.kt b/security/src/main/java/com/itsaky/androidide/security/FlowLayout.kt new file mode 100644 index 0000000000..634c6b0c05 --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/FlowLayout.kt @@ -0,0 +1,121 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +import android.content.Context +import android.util.AttributeSet +import android.view.View +import android.view.ViewGroup + +/** + * Lays out children in horizontal rows, wrapping to a new row whenever a child would exceed the + * available line width. Used by the cryptogram disguise grid so letter cells reflow at any font + * scale instead of being clipped. + */ +class FlowLayout + @JvmOverloads + constructor( + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0, + ) : ViewGroup(context, attrs, defStyleAttr) { + private val lines = mutableListOf>() + private val lineHeights = mutableListOf() + + override fun onMeasure( + widthMeasureSpec: Int, + heightMeasureSpec: Int, + ) { + val availableWidth = MeasureSpec.getSize(widthMeasureSpec) - paddingLeft - paddingRight + val widthMode = MeasureSpec.getMode(widthMeasureSpec) + + lines.clear() + lineHeights.clear() + + var currentLine = mutableListOf() + var currentLineWidth = 0 + var currentLineHeight = 0 + var maxLineWidth = 0 + + for (i in 0 until childCount) { + val child = getChildAt(i) + if (child.visibility == View.GONE) continue + + measureChild(child, widthMeasureSpec, heightMeasureSpec) + val childWidth = child.measuredWidth + val childHeight = child.measuredHeight + + if (currentLineWidth + childWidth > availableWidth && currentLine.isNotEmpty()) { + lines.add(currentLine) + lineHeights.add(currentLineHeight) + maxLineWidth = maxOf(maxLineWidth, currentLineWidth) + + currentLine = mutableListOf() + currentLineWidth = 0 + currentLineHeight = 0 + } + + currentLine.add(child) + currentLineWidth += childWidth + currentLineHeight = maxOf(currentLineHeight, childHeight) + } + + if (currentLine.isNotEmpty()) { + lines.add(currentLine) + lineHeights.add(currentLineHeight) + maxLineWidth = maxOf(maxLineWidth, currentLineWidth) + } + + val totalHeight = paddingTop + paddingBottom + lineHeights.sum() + val totalWidth = + if (widthMode == MeasureSpec.EXACTLY) { + MeasureSpec.getSize(widthMeasureSpec) + } else { + maxLineWidth + paddingLeft + paddingRight + } + + setMeasuredDimension( + resolveSize(totalWidth, widthMeasureSpec), + resolveSize(totalHeight, heightMeasureSpec), + ) + } + + override fun onLayout( + changed: Boolean, + l: Int, + t: Int, + r: Int, + b: Int, + ) { + var top = paddingTop + for (lineIdx in lines.indices) { + val line = lines[lineIdx] + val lineHeight = lineHeights[lineIdx] + var left = paddingLeft + + for (child in line) { + val childWidth = child.measuredWidth + val childHeight = child.measuredHeight + val childTop = top + (lineHeight - childHeight) / 2 + child.layout(left, childTop, left + childWidth, childTop + childHeight) + left += childWidth + } + top += lineHeight + } + } + } diff --git a/security/src/main/java/com/itsaky/androidide/security/GestureDetectorHelper.kt b/security/src/main/java/com/itsaky/androidide/security/GestureDetectorHelper.kt new file mode 100644 index 0000000000..4826b47b75 --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/GestureDetectorHelper.kt @@ -0,0 +1,133 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +import android.content.Context +import android.graphics.PointF +import android.view.MotionEvent +import kotlin.math.sqrt + +/** + * Touch-gesture detectors for the "Instant Hide" security feature (ADFA-40): a single, eyes-free + * gesture that disguises the IDE, and a deliberate counter-gesture that exits the disguise. + * + * Timing is read from [MotionEvent.getDownTime] / [MotionEvent.getEventTime] rather than the wall + * clock, so a gesture's duration is the input system's own measurement (and so the detectors are + * deterministically testable from synthesised events). + * + * The self-destruct circle detector from the original mockup is deliberately not ported here; + * self-destruct is out of scope for this change. + */ +object GestureDetectorHelper { + // Three-finger tap (enter disguise). + const val REQUIRED_POINTER_COUNT = 3 + const val MAX_TAP_DURATION_MS = 600L + const val MAX_TAP_DRIFT_DP = 50f + + // Slow double three-finger tap (exit disguise): the gap between the two taps. + const val MIN_DOUBLE_TAP_GAP_MS = 150L + const val MAX_DOUBLE_TAP_GAP_MS = 1600L + + /** + * Fires [onDetected] with the tap's up-event time when a single three-finger tap completes + * within [MAX_TAP_DURATION_MS] and with no pointer drifting more than [MAX_TAP_DRIFT_DP]. + */ + class ThreeFingerTapDetector( + context: Context, + private val onDetected: (upEventTime: Long) -> Unit, + ) { + private var maxPointerCount = 0 + private val initialPositions = mutableMapOf() + private var driftExceeded = false + private val maxDriftPx = MAX_TAP_DRIFT_DP * context.resources.displayMetrics.density + + fun onTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + maxPointerCount = 1 + driftExceeded = false + initialPositions.clear() + initialPositions[event.getPointerId(0)] = PointF(event.getX(0), event.getY(0)) + } + + MotionEvent.ACTION_POINTER_DOWN -> { + maxPointerCount = maxOf(maxPointerCount, event.pointerCount) + val idx = event.actionIndex + initialPositions[event.getPointerId(idx)] = PointF(event.getX(idx), event.getY(idx)) + } + + MotionEvent.ACTION_MOVE -> { + for (i in 0 until event.pointerCount) { + val init = initialPositions[event.getPointerId(i)] ?: continue + val dx = event.getX(i) - init.x + val dy = event.getY(i) - init.y + if (sqrt(dx * dx + dy * dy) > maxDriftPx) { + driftExceeded = true + } + } + } + + MotionEvent.ACTION_POINTER_UP -> { + maxPointerCount = maxOf(maxPointerCount, event.pointerCount) + } + + MotionEvent.ACTION_UP -> { + val duration = event.eventTime - event.downTime + if (maxPointerCount >= REQUIRED_POINTER_COUNT && + duration <= MAX_TAP_DURATION_MS && + !driftExceeded + ) { + onDetected(event.eventTime) + return true + } + } + + MotionEvent.ACTION_CANCEL -> { + initialPositions.clear() + } + } + return false + } + } + + /** + * Fires [onDetected] on two consecutive three-finger taps whose up-events are separated by a + * deliberate gap in [[MIN_DOUBLE_TAP_GAP_MS], [MAX_DOUBLE_TAP_GAP_MS]]. A tap outside that window + * becomes the new first tap rather than being discarded, so a mistimed attempt can be retried. + */ + class SlowDoubleThreeFingerTapDetector( + context: Context, + private val onDetected: () -> Unit, + ) { + private var firstTapUpTime = 0L + private val singleDetector = + ThreeFingerTapDetector(context) { upEventTime -> + if (firstTapUpTime > 0L) { + val gap = upEventTime - firstTapUpTime + if (gap in MIN_DOUBLE_TAP_GAP_MS..MAX_DOUBLE_TAP_GAP_MS) { + firstTapUpTime = 0L + onDetected() + return@ThreeFingerTapDetector + } + } + firstTapUpTime = upEventTime + } + + fun onTouchEvent(event: MotionEvent): Boolean = singleDetector.onTouchEvent(event) + } +} diff --git a/security/src/main/java/com/itsaky/androidide/security/HideState.kt b/security/src/main/java/com/itsaky/androidide/security/HideState.kt new file mode 100644 index 0000000000..5295cd1c02 --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/HideState.kt @@ -0,0 +1,42 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +import com.itsaky.androidide.preferences.internal.SecurityPreferences + +/** + * Instant Hide's two flags, read through here rather than from [SecurityPreferences] directly so a + * test can stand in for the preferences, which need the running application. + */ +internal interface HideState { + /** The user has armed Instant Hide. */ + val armed: Boolean + + /** The disguise is engaged. */ + var hidden: Boolean +} + +internal object PreferencesHideState : HideState { + override val armed: Boolean get() = SecurityPreferences.instantHideEnabled + + override var hidden: Boolean + get() = SecurityPreferences.isHiddenStateActive + set(value) { + SecurityPreferences.isHiddenStateActive = value + } +} diff --git a/security/src/main/java/com/itsaky/androidide/security/InstantHide.kt b/security/src/main/java/com/itsaky/androidide/security/InstantHide.kt new file mode 100644 index 0000000000..90a34c5f02 --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/InstantHide.kt @@ -0,0 +1,214 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +import android.app.Activity +import android.app.ActivityManager +import android.app.Application +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.view.KeyEvent +import android.view.KeyboardShortcutGroup +import android.view.Menu +import android.view.MotionEvent +import android.view.Window +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import java.util.WeakHashMap + +/** + * Instant Hide (ADFA-40) on every screen of the app. It is mounted once, from the Application, rather + * than on a base class, so a screen with another base class (the terminal, onboarding) or an entry + * point added later cannot be left out: while the disguise is engaged no activity but the disguise + * shows, and while it is armed every screen gets the triggers and FLAG_SECURE. + */ +object InstantHide { + /** + * A screen whose gestures and sensors must not hide the IDE: the security settings, where the user + * arms and practises them. FLAG_SECURE still applies there. + */ + interface GesturesExempt + + internal var state: HideState = PreferencesHideState + + private val controllers = WeakHashMap() + private var onHide: (Context) -> Unit = {} + + /** + * @param onHide closes what the app shows outside its activities, such as floating windows; runs on + * every hide, before the disguise starts. + */ + fun register( + application: Application, + onHide: (Context) -> Unit, + ) { + this.onHide = onHide + application.registerActivityLifecycleCallbacks(Callbacks) + } + + /** + * Shows the disguise and finishes [activity] if the disguise is engaged. An entry point whose + * onCreate does work calls this right after `super.onCreate` and returns when it is true, so the + * work never starts; the lifecycle callback has already redirected, and this does not repeat it. + */ + fun redirectIfHidden(activity: Activity): Boolean { + if (activity is CryptogramActivity || !state.hidden) return false + if (!activity.isFinishing) showDisguise(activity, disguiseIntent(activity)) + return true + } + + /** + * Brings the disguise forward. A running one is reused rather than recreated, so a link or a file + * opened while hidden does not reset the puzzle. + */ + fun disguiseIntent(context: Context): Intent = + Intent(context, CryptogramActivity::class.java).addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP, + ) + + /** Starts the disguise with a new puzzle, as a hide does. */ + fun newDisguiseIntent(context: Context): Intent = + Intent(context, CryptogramActivity::class.java).addFlags( + Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK, + ) + + /** + * Starts [disguise], removes the app's other tasks, and finishes [activity]. The disguise has a task of + * its own, so the IDE's task stays behind it in Recents unless removed here; [activity] is finished + * as well in case it runs in another app's task, which is not the app's to remove. + */ + fun showDisguise( + activity: Activity, + disguise: Intent, + ) { + activity.startActivity(disguise) + activity.getSystemService(ActivityManager::class.java)?.appTasks?.forEach { task -> + // A task can be gone by now: Android removes the one the disabled launcher alias started. + runCatching { + val base = task.taskInfo.baseIntent.component + if (base?.className != CryptogramActivity::class.java.name) task.finishAndRemoveTask() + } + } + activity.finish() + } + + /** Whether the soft keyboard shows over [activity]. Robolectric has no keyboard, so tests replace it. */ + internal var keyboardShown: (Activity) -> Boolean = ::softKeyboardShown + + internal fun softKeyboardShown(activity: Activity): Boolean = + ViewCompat.getRootWindowInsets(activity.window.decorView)?.isVisible(WindowInsetsCompat.Type.ime()) == true + + /** Re-applies FLAG_SECURE to [activity] at once, for a caller that has just armed or disarmed. */ + fun applyScreenSecurity(activity: Activity) { + controllers[activity]?.applyScreenSecurity() + } + + private object Callbacks : Application.ActivityLifecycleCallbacks { + override fun onActivityCreated( + activity: Activity, + savedInstanceState: Bundle?, + ) { + if (activity is CryptogramActivity || redirectIfHidden(activity)) return + val controller = + SecurityController( + activity, + gesturesEnabled = activity !is GesturesExempt, + onHide = onHide, + state = state, + keyboardShown = { keyboardShown(it) }, + ) + controllers[activity] = controller + activity.window.callback = InputWatcher(activity.window.callback, controller) + } + + override fun onActivityResumed(activity: Activity) { + // An IDE screen left in another app's task when the disguise engaged. + if (redirectIfHidden(activity)) return + controllers[activity]?.apply { + applyScreenSecurity() + onResume() + } + } + + override fun onActivityPaused(activity: Activity) { + controllers[activity]?.onPause() + } + + override fun onActivityDestroyed(activity: Activity) { + controllers.remove(activity)?.onDestroy() + } + + override fun onActivityStarted(activity: Activity) = Unit + + override fun onActivityStopped(activity: Activity) = Unit + + override fun onActivitySaveInstanceState( + activity: Activity, + outState: Bundle, + ) = Unit + } + + /** + * Passes every input the window receives to [controller] on its way to the activity: touches for the + * gestures, and all of it for the inactivity timer. + */ + private class InputWatcher( + private val delegate: Window.Callback, + private val controller: SecurityController, + ) : Window.Callback by delegate { + override fun dispatchTouchEvent(event: MotionEvent): Boolean { + controller.onTouchEvent(event) + return delegate.dispatchTouchEvent(event) + } + + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + controller.onUserInput() + return delegate.dispatchKeyEvent(event) + } + + override fun dispatchKeyShortcutEvent(event: KeyEvent): Boolean { + controller.onUserInput() + return delegate.dispatchKeyShortcutEvent(event) + } + + override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { + controller.onUserInput() + return delegate.dispatchGenericMotionEvent(event) + } + + override fun dispatchTrackballEvent(event: MotionEvent): Boolean { + controller.onUserInput() + return delegate.dispatchTrackballEvent(event) + } + + // Java default methods: forwarded by hand so the activity's own still run. + override fun onProvideKeyboardShortcuts( + data: MutableList?, + menu: Menu?, + deviceId: Int, + ) = delegate.onProvideKeyboardShortcuts(data, menu, deviceId) + + override fun onPointerCaptureChanged(hasCapture: Boolean) = delegate.onPointerCaptureChanged(hasCapture) + + override fun onWindowFocusChanged(hasFocus: Boolean) { + controller.onWindowFocusChanged(hasFocus) + delegate.onWindowFocusChanged(hasFocus) + } + } +} diff --git a/security/src/main/java/com/itsaky/androidide/security/LauncherAliasManager.kt b/security/src/main/java/com/itsaky/androidide/security/LauncherAliasManager.kt new file mode 100644 index 0000000000..0d5b732193 --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/LauncherAliasManager.kt @@ -0,0 +1,158 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +import android.content.ComponentName +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.provider.Settings +import android.util.Log + +/** + * Switches the launcher between the real IDE identity and a per-device "stealth" disguise identity, + * by toggling `` entries declared in the app manifest. The disguise variant is + * chosen deterministically from hardware identifiers so a given device always shows the same + * disguise icon/label. + * + * The aliases targeted here are declared in the app's `AndroidManifest.xml`, all pointing at the + * launcher activity (`LauncherActivity`). The default alias is named `.activities.SplashActivity`, + * the launcher component from before Instant Hide, so pinned home-screen icons survive the update. + */ +object LauncherAliasManager { + private const val TAG = "LauncherAliasManager" + private const val DEFAULT_ALIAS = "com.itsaky.androidide.activities.SplashActivity" + + private val STEALTH_ALIASES = + listOf( + "com.itsaky.androidide.StealthAliasActivity1", + "com.itsaky.androidide.StealthAliasActivity2", + "com.itsaky.androidide.StealthAliasActivity3", + "com.itsaky.androidide.StealthAliasActivity4", + "com.itsaky.androidide.StealthAliasActivity5", + ) + + /** + * Deterministic disguise index in `[0, modulo)` from an FNV-1a 32-bit hash of the device + * signature. Uses [Int.mod] (never negative) rather than `abs(hash) % modulo`, which would + * return a negative index for `hash == Int.MIN_VALUE`. + */ + internal fun stealthVariationIndex( + hardwareSignature: String, + modulo: Int, + ): Int { + var hash = 0x811c9dc5.toInt() + for (ch in hardwareSignature) { + hash = hash xor ch.code + hash *= 0x01000193 + } + return hash.mod(modulo) + } + + fun getStealthVariationIndex(context: Context): Int { + val androidId = + Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) ?: "fallback_id" + val signature = + "${Build.BOARD}_${Build.BRAND}_${Build.DEVICE}_${Build.HARDWARE}_${Build.MODEL}_${Build.PRODUCT}_$androidId" + return stealthVariationIndex(signature, STEALTH_ALIASES.size) + } + + /** + * The icon of this device's stealth alias, for the disguise's Recents entry; 0 when it cannot be + * read, which leaves the system default. + */ + fun stealthIcon(context: Context): Int = + runCatching { + val alias = ComponentName(context, STEALTH_ALIASES[getStealthVariationIndex(context)]) + context.packageManager.getActivityInfo(alias, PackageManager.MATCH_DISABLED_COMPONENTS).iconResource + }.getOrElse { + Log.e(TAG, "Failed to read the stealth alias icon", it) + 0 + } + + fun isStealthModeActive(context: Context): Boolean { + val defaultComponent = ComponentName(context, DEFAULT_ALIAS) + return context.packageManager.getComponentEnabledSetting(defaultComponent) == + PackageManager.COMPONENT_ENABLED_STATE_DISABLED + } + + /** Display label of whichever launcher alias is currently enabled, or "" if none resolves. */ + fun getCurrentLauncherLabel(context: Context): String { + val pm = context.packageManager + for (aliasName in listOf(DEFAULT_ALIAS) + STEALTH_ALIASES) { + val comp = ComponentName(context, aliasName) + val state = pm.getComponentEnabledSetting(comp) + val explicitlyEnabled = state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED + val defaultEnabled = + state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT && aliasName == DEFAULT_ALIAS + if (explicitlyEnabled || defaultEnabled) { + return try { + pm.getActivityInfo(comp, PackageManager.GET_META_DATA).loadLabel(pm).toString() + } catch (e: Exception) { + Log.e(TAG, "Failed to resolve label for $aliasName", e) + "" + } + } + } + return "" + } + + /** Enables the per-device stealth alias (and disables the default), or restores the default. */ + fun setStealthMode( + context: Context, + enableStealth: Boolean, + ) { + val pm = context.packageManager + val defaultComponent = ComponentName(context, DEFAULT_ALIAS) + val activeStealthAlias = STEALTH_ALIASES[getStealthVariationIndex(context)] + + try { + if (enableStealth) { + for (aliasName in STEALTH_ALIASES) { + val state = + if (aliasName == activeStealthAlias) { + PackageManager.COMPONENT_ENABLED_STATE_ENABLED + } else { + PackageManager.COMPONENT_ENABLED_STATE_DISABLED + } + pm.setComponentEnabledSetting(ComponentName(context, aliasName), state, PackageManager.DONT_KILL_APP) + } + pm.setComponentEnabledSetting( + defaultComponent, + PackageManager.COMPONENT_ENABLED_STATE_DISABLED, + PackageManager.DONT_KILL_APP, + ) + } else { + pm.setComponentEnabledSetting( + defaultComponent, + PackageManager.COMPONENT_ENABLED_STATE_ENABLED, + PackageManager.DONT_KILL_APP, + ) + for (aliasName in STEALTH_ALIASES) { + pm.setComponentEnabledSetting( + ComponentName(context, aliasName), + PackageManager.COMPONENT_ENABLED_STATE_DISABLED, + PackageManager.DONT_KILL_APP, + ) + } + } + } catch (e: Exception) { + Log.e(TAG, "Failed to update launcher aliases", e) + } + } +} diff --git a/security/src/main/java/com/itsaky/androidide/security/NeutralNotifications.kt b/security/src/main/java/com/itsaky/androidide/security/NeutralNotifications.kt new file mode 100644 index 0000000000..eecd6e5340 --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/NeutralNotifications.kt @@ -0,0 +1,67 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +import android.app.Notification +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import com.itsaky.androidide.resources.R as ResR + +/** + * What the IDE shows in the notification shade while the disguise is engaged (ADFA-40). An ordinary + * notification is removed. A foreground service's cannot be while the service runs, so it is + * replaced, under the same id, by [build]'s, which names the disguise and nothing that is running. + */ +object NeutralNotifications { + /** Removes or neutralises every notification the app is showing. */ + fun mask(context: Context) { + val manager = context.getSystemService(NotificationManager::class.java) ?: return + for (shown in manager.activeNotifications) { + if (shown.notification.flags and Notification.FLAG_FOREGROUND_SERVICE != 0) { + manager.notify(shown.tag, shown.id, build(context, shown.notification.channelId)) + } else { + manager.cancel(shown.tag, shown.id) + } + } + } + + /** + * The notification a foreground service shows while hidden. Services that update their own call + * this instead of building one, so an update does not bring the IDE's text back. + */ + fun build( + context: Context, + channelId: String, + ): Notification = + Notification + .Builder(context, channelId) + .setSmallIcon(ResR.drawable.ic_stealth_notification) + .setContentTitle(context.getString(ResR.string.stealth_app_name)) + .setShowWhen(false) + .setOngoing(true) + .setContentIntent( + PendingIntent.getActivity( + context, + 0, + InstantHide.disguiseIntent(context), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ), + ).build() +} diff --git a/security/src/main/java/com/itsaky/androidide/security/SecurityController.kt b/security/src/main/java/com/itsaky/androidide/security/SecurityController.kt new file mode 100644 index 0000000000..ada5677682 --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/SecurityController.kt @@ -0,0 +1,210 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +import android.app.Activity +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.hardware.Sensor +import android.hardware.SensorEvent +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import android.os.Handler +import android.os.Looper +import android.view.MotionEvent +import android.view.ViewTreeObserver +import android.view.WindowManager +import android.widget.Toast +import com.itsaky.androidide.resources.R as ResR + +/** + * Drives the Instant Hide (ADFA-40) triggers for one IDE activity: the three-finger tap, the + * screen-off broadcast, the face-down sensor, and the inactivity timer. Any of them engages the + * disguise. It also applies FLAG_SECURE while Instant Hide is armed (masking the IDE in Recents and + * blocking screenshots), unless the testing override file is present, in which case it leaves + * screenshots working and warns once. + * + * [InstantHide] mounts one on every activity and forwards its lifecycle and input. + * + * @param gesturesEnabled false where the triggers must not fire; FLAG_SECURE still applies. + * @param onHide runs on every hide, before the disguise starts. + * @param keyboardShown whether the soft keyboard shows over the activity. + */ +internal class SecurityController( + private val activity: Activity, + private val gesturesEnabled: Boolean, + private val onHide: (Context) -> Unit, + private val state: HideState, + private val keyboardShown: (Activity) -> Boolean, +) { + companion object { + private const val INACTIVITY_TIMEOUT_MS = 60_000L + } + + private val enabled: Boolean get() = state.armed + + private val triggersOn: Boolean get() = enabled && gesturesEnabled + + private var hideDetector: GestureDetectorHelper.ThreeFingerTapDetector? = null + private var screenOffReceiver: BroadcastReceiver? = null + + private val sensorManager = activity.getSystemService(Context.SENSOR_SERVICE) as? SensorManager + private val gravitySensor = + sensorManager?.getDefaultSensor(Sensor.TYPE_GRAVITY) + ?: sensorManager?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) + private val faceDown = FaceDownDetector() + + private val inactivityHandler = Handler(Looper.getMainLooper()) + private val inactivityRunnable = + Runnable { + if (userMayBeActive()) resetInactivityTimer() else triggerInstantHide() + } + + private var advisoryShown = false + + // Typing on the soft keyboard reaches the keyboard's window, and so does the key that closes it, so + // its opening and closing are the input this window sees. Either one lays the window out again. + private var keyboardWasShown = false + private val keyboardWatcher = + ViewTreeObserver.OnGlobalLayoutListener { + val shown = keyboardShown(activity) + if (shown != keyboardWasShown) { + keyboardWasShown = shown + onUserInput() + } + } + + private val sensorListener = + object : SensorEventListener { + override fun onSensorChanged(event: SensorEvent?) { + if (event == null || !triggersOn) return + if (event.sensor.type != Sensor.TYPE_GRAVITY && event.sensor.type != Sensor.TYPE_ACCELEROMETER) return + if (faceDown.onGravityZ(event.values[2])) triggerInstantHide() + } + + override fun onAccuracyChanged( + sensor: Sensor?, + accuracy: Int, + ) {} + } + + /** Applies the FLAG_SECURE policy. Safe to call on any activity; call on every resume. */ + fun applyScreenSecurity() { + val overridden = SecurityOverride.isScreenshotBlockingDisabled() + if (enabled && !overridden) { + activity.window.addFlags(WindowManager.LayoutParams.FLAG_SECURE) + } else { + activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) + } + if (enabled && overridden && !advisoryShown) { + advisoryShown = true + Toast.makeText(activity, ResR.string.instant_hide_screenshot_override, Toast.LENGTH_LONG).show() + } + } + + fun onResume() { + if (!gesturesEnabled) return + // The screen-off receiver must survive onPause (the pause races the screen-off broadcast), so + // it is registered once here and torn down only in onDestroy. + if (screenOffReceiver == null) { + screenOffReceiver = + object : BroadcastReceiver() { + override fun onReceive( + context: Context?, + intent: Intent?, + ) { + if (intent?.action == Intent.ACTION_SCREEN_OFF && enabled) triggerInstantHide() + } + } + activity.registerReceiver(screenOffReceiver, IntentFilter(Intent.ACTION_SCREEN_OFF)) + } + + if (enabled) { + hideDetector = GestureDetectorHelper.ThreeFingerTapDetector(activity) { triggerInstantHide() } + faceDown.reset() + gravitySensor?.let { sensorManager?.registerListener(sensorListener, it, SensorManager.SENSOR_DELAY_UI) } + keyboardWasShown = keyboardShown(activity) + activity.window.decorView.viewTreeObserver + .addOnGlobalLayoutListener(keyboardWatcher) + resetInactivityTimer() + } else { + hideDetector = null + } + } + + fun onPause() { + sensorManager?.unregisterListener(sensorListener) + activity.window.decorView.viewTreeObserver + .removeOnGlobalLayoutListener(keyboardWatcher) + stopInactivityTimer() + } + + fun onDestroy() { + sensorManager?.unregisterListener(sensorListener) + stopInactivityTimer() + screenOffReceiver?.let { + runCatching { activity.unregisterReceiver(it) } + screenOffReceiver = null + } + } + + fun onTouchEvent(ev: MotionEvent) { + if (!triggersOn) return + resetInactivityTimer() + hideDetector?.onTouchEvent(ev) + } + + /** Any input other than a touch on the activity's window: a key, a mouse or trackball move. */ + fun onUserInput() { + if (triggersOn) resetInactivityTimer() + } + + /** The window getting the focus back from a dialog or popup, which took input the window never saw. */ + fun onWindowFocusChanged(hasFocus: Boolean) { + if (hasFocus) onUserInput() + } + + private fun resetInactivityTimer() { + stopInactivityTimer() + if (triggersOn) inactivityHandler.postDelayed(inactivityRunnable, INACTIVITY_TIMEOUT_MS) + } + + /** + * Whether the user may still be at the screen although no input reached its window: typing on the + * soft keyboard, whose touches go to the keyboard's window, or working in a dialog or popup, which + * holds the focus. A phone left like that still hides when its screen times out, through the + * screen-off trigger. Closing either restarts the minute. + */ + private fun userMayBeActive(): Boolean = keyboardShown(activity) || !activity.hasWindowFocus() + + private fun stopInactivityTimer() = inactivityHandler.removeCallbacks(inactivityRunnable) + + private fun triggerInstantHide() { + // Every IDE activity keeps a screen-off receiver while paused, so one broadcast reaches them all; + // the first hides, and a second would restart the disguise and reset its puzzle. + if (!enabled || state.hidden || activity.isFinishing) return + state.hidden = true + LauncherAliasManager.setStealthMode(activity, true) + // Floating windows and notifications outlive the activity; they must not show the IDE. + runCatching { onHide(activity.applicationContext) } + runCatching { NeutralNotifications.mask(activity) } + InstantHide.showDisguise(activity, InstantHide.newDisguiseIntent(activity)) + } +} diff --git a/security/src/main/java/com/itsaky/androidide/security/SecurityOverride.kt b/security/src/main/java/com/itsaky/androidide/security/SecurityOverride.kt new file mode 100644 index 0000000000..c5e868657d --- /dev/null +++ b/security/src/main/java/com/itsaky/androidide/security/SecurityOverride.kt @@ -0,0 +1,40 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.security + +import android.os.Environment +import java.io.File + +/** + * A one-way, file-based escape hatch for the Instant Hide screenshot block (ADFA-40). Screenshot + * blocking is on by default whenever Instant Hide is armed; placing the magic file disables it, so + * QA can capture screenshots and bug reports still work. There is no UI path that weakens the block. + */ +object SecurityOverride { + /** Testing override file: `/sdcard/Download/CodeOnTheGo.mfs`. */ + private const val OVERRIDE_FILE_NAME = "CodeOnTheGo.mfs" + + /** True when the override file is present, i.e. FLAG_SECURE should NOT be applied. */ + fun isScreenshotBlockingDisabled(): Boolean = + runCatching { + File( + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), + OVERRIDE_FILE_NAME, + ).exists() + }.getOrDefault(false) +} diff --git a/security/src/main/res/drawable/ic_launcher_stealth_1.xml b/security/src/main/res/drawable/ic_launcher_stealth_1.xml new file mode 100644 index 0000000000..0569f8644a --- /dev/null +++ b/security/src/main/res/drawable/ic_launcher_stealth_1.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/security/src/main/res/drawable/ic_launcher_stealth_2.xml b/security/src/main/res/drawable/ic_launcher_stealth_2.xml new file mode 100644 index 0000000000..5c2d64a723 --- /dev/null +++ b/security/src/main/res/drawable/ic_launcher_stealth_2.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/security/src/main/res/drawable/ic_launcher_stealth_3.xml b/security/src/main/res/drawable/ic_launcher_stealth_3.xml new file mode 100644 index 0000000000..78b406ffd5 --- /dev/null +++ b/security/src/main/res/drawable/ic_launcher_stealth_3.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/security/src/main/res/drawable/ic_launcher_stealth_4.xml b/security/src/main/res/drawable/ic_launcher_stealth_4.xml new file mode 100644 index 0000000000..ee17812512 --- /dev/null +++ b/security/src/main/res/drawable/ic_launcher_stealth_4.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/security/src/main/res/drawable/ic_launcher_stealth_5.xml b/security/src/main/res/drawable/ic_launcher_stealth_5.xml new file mode 100644 index 0000000000..0d795e0028 --- /dev/null +++ b/security/src/main/res/drawable/ic_launcher_stealth_5.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/security/src/main/res/layout/activity_cryptogram.xml b/security/src/main/res/layout/activity_cryptogram.xml new file mode 100644 index 0000000000..b0797423a2 --- /dev/null +++ b/security/src/main/res/layout/activity_cryptogram.xml @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +