Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Android: root only when chosen, and only to start the shell helper
Bee991f9b8b0098
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d84fb9..9256fd3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -42,6 +42,11 @@ change things that need a step from you, and its notes say so.calls and alarms. A new post from the same app shows as usual.- Android: turning off notification access, or a force stop, no longercrashes the app.+- **Root is opt-in.** On a rooted phone, NectarLink asked for root every+ time it started and ran its Elevated helper as root. Root is now a choice in+ Elevated setup (**Use root**), offered only on rooted phones, and the helper+ runs as the shell user either way, with the same permissions as through+ Wireless debugging.- Android: Phone as webcam no longer crashes the app when its previewcomes back (the same fix covers the QR scanner and Continuity Camera).- Android: on Hive, the category chips at the top of Settings and thediff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.ktindex 615aec0..2c3f771 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt@@ -68,11 +68,15 @@ object Elevated {data class Failed(val reason: Reason) : State}- enum class Reason { WrongCode, NoPairingDialog, NotPaired, Other }+ enum class Reason { WrongCode, NoPairingDialog, NotPaired, RootDenied, Other }private const val TAG = "Elevated"private const val PREFS = "elevated"private const val PAIRED = "paired"+ /** Set up through root (the user chose Use root) rather than Wireless debugging. */+ private const val ROOT = "root"+ /** The shell user, which the helper runs as however it's started. */+ private const val SHELL_UID = "2000"private val _state = MutableStateFlow<State>(State.NotSetUp)val state: StateFlow<State> = _state.asStateFlow()@@ -89,7 +93,7 @@ object Elevated {@Volatile private var helper: Pair<Int, String>? = null@Volatile private var screenOffRequested = false- /** True when the active Elevated helper was launched directly via Root (`su`). */+ /** True when the running helper was started through root (`su`), not Wireless debugging. */@Volatile var rootActive: Boolean = falseprivate set@@ -107,14 +111,45 @@ object Elevated {paths.any { runCatching { java.io.File(it).exists() }.getOrDefault(false) }}- /** Checks whether a `su` binary (Magisk, KernelSU, APatch) is present on the device. */+ /**+ * Whether a `su` binary (Magisk, KernelSU, APatch) is on the phone, so+ * Elevated may offer root as a way to start. Only looks for the file:+ * nothing asks for root until the user picks it.+ */fun isRootAvailable(): Boolean = rootAvailableCached+ /** Whether the user set Elevated up through root. */+ private fun usesRoot() = isRootAvailable() && prefs().getBoolean(ROOT, false)++ private fun prefs() = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++ /**+ * Sets Elevated up through root, as the user asked (instead of pairing+ * Wireless debugging). The root manager asks once; after that Elevated+ * starts by itself, also after a restart and away from Wi-Fi. The helper+ * still runs as the shell user, with the same permissions either way.+ */+ suspend fun setUpWithRoot(): Boolean = withContext(Dispatchers.IO) {+ if (!isRootAvailable()) return@withContext false+ val started = lock.withLock {+ if (running) return@withLock true+ _state.value = State.Starting+ tryStartWithRootLocked()+ }+ prefs().edit { putBoolean(ROOT, started) }+ if (started) {+ cancelRetry()+ } else {+ _state.value = State.Failed(Reason.RootDenied)+ }+ started+ }+fun init(context: Context) {this.context = context.applicationContextwatchWirelessDebugging()scope.launch(Dispatchers.IO) {- if (paired() || isRootAvailable()) {+ if (paired() || usesRoot()) {_state.value = State.Waitingstart()}@@ -150,9 +185,10 @@ object Elevated {}.onFailure { Log.i(TAG, "can't watch wireless debugging", it) }}- /** Tries again later, while it can still work: paired, not running, on Wi-Fi. */+ /** Tries again later, while it can still work: set up, not running, on Wi-Fi (or through root). */private fun scheduleRetry() {- if (!paired() || running || !onWifi() || BankingPause.isPaused(context)) return+ if (!(paired() || usesRoot()) || running || BankingPause.isPaused(context)) return+ if (!usesRoot() && !onWifi()) returnval wait = RETRY_MS[retryAttempt.coerceAtMost(RETRY_MS.lastIndex)]retryAttempt++retryJob?.cancel()@@ -241,9 +277,9 @@ object Elevated {// ---- Starting ----- /** Connects and starts the input helper (when set up or rooted; again after it stopped). */+ /** Connects and starts the input helper (when set up; again after it stopped). */suspend fun start(): Boolean = withContext(Dispatchers.IO) {- if (!paired() && !isRootAvailable()) return@withContext false+ if (!paired() && !usesRoot()) return@withContext false// Paused for a banking app: debugging stays off until it's over// (BankingPause starts Elevated again then).if (BankingPause.isPaused(context)) {@@ -253,7 +289,7 @@ object Elevated {val started = lock.withLock {if (running) return@withLock true_state.value = State.Starting- if (tryStartWithRootLocked()) {+ if (usesRoot() && tryStartWithRootLocked()) {return@withLock true}if (!paired()) {@@ -296,29 +332,24 @@ object Elevated {}/**- * Attempts to launch [InputServer] directly via `su` (Magisk / KernelSU / APatch)- * without requiring Wireless Debugging.+ * Starts [InputServer] through `su` (Magisk, KernelSU, APatch), without+ * Wireless debugging. It runs as the shell user, as through Wireless+ * debugging: root only starts it. A root manager that can't switch to+ * that user fails here rather than run the helper as root.*/private fun tryStartWithRootLocked(): Boolean {if (!isRootAvailable()) return false- val idOk = runCatching {- val check = ProcessBuilder("su", "-c", "id").redirectErrorStream(true).start()- val finished = check.waitFor(4, java.util.concurrent.TimeUnit.SECONDS)- if (!finished) {- check.destroyForcibly()- false- } else {- val out = check.inputStream.bufferedReader().readText()- check.exitValue() == 0 && out.contains("uid=0")- }- }.getOrDefault(false)- if (!idOk) return false-+ val uid = asShell("id -u")?.trim()+ if (uid != SHELL_UID) {+ Log.i(TAG, "root can't start the helper as the shell user (got ${uid ?: "nothing"})")+ return false+ }+ grants().forEach { asShell(it) }return runCatching {val token = ByteArray(24).also(SecureRandom()::nextBytes).joinToString("") { "%02x".format(it) }val apk = context.applicationInfo.sourceDirval cmd = "CLASSPATH=$apk app_process /system/bin ${InputServer::class.java.name} $token"- val proc = ProcessBuilder("su", "-c", cmd).start()+ val proc = ProcessBuilder("su", SHELL_UID, "-c", cmd).start()rootProcess = procval output = proc.inputStream.bufferedReader()val first = output.readLine().orEmpty()@@ -327,26 +358,35 @@ object Elevated {"root helper said ${first.ifEmpty { "nothing" }}"}rootActive = true- context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit { putBoolean(PAIRED, true) }connectSocketLocked(port, token)Thread {runCatching { output.lineSequence().forEach { line -> Log.d(TAG, "root-helper: $line") } }input = nullrootActive = falserunCatching { socket?.close() }- if (_state.value == State.Running) _state.value = if (paired()) State.Waiting else State.NotSetUp+ if (_state.value == State.Running) _state.value = State.WaitingonChange()scheduleRetry()}.start()true}.onFailure {- Log.i(TAG, "root helper start failed, falling back to wireless debugging", it)+ Log.i(TAG, "the helper didn't start through root", it)runCatching { rootProcess?.destroyForcibly() }rootProcess = nullrootActive = false}.getOrDefault(false)}+ /** Runs [command] as the shell user through `su`; its output, or null if it didn't run. */+ private fun asShell(command: String): String? = runCatching {+ val process = ProcessBuilder("su", SHELL_UID, "-c", command).redirectErrorStream(true).start()+ if (!process.waitFor(SU_WAIT_S, java.util.concurrent.TimeUnit.SECONDS)) {+ process.destroyForcibly()+ return null+ }+ process.inputStream.bufferedReader().readText().takeIf { process.exitValue() == 0 }+ }.getOrNull()+/** Wireless debugging back on, when NectarLink may (granted at the first start). */private fun turnOnWirelessDebugging() {if (context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) != PackageManager.PERMISSION_GRANTED) return@@ -358,38 +398,44 @@ object Elevated {}.onFailure { Log.i(TAG, "can't turn on wireless debugging", it) }}- private fun launch(adb: Connection) {+ /** What the shell grants NectarLink once, before the helper starts (however it starts). */+ private fun grants(): List<String> = buildList {+ val pkg = context.packageName// Turning wireless debugging back on later is NectarLink's to do.if (context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) != PackageManager.PERMISSION_GRANTED) {- run(adb, "pm grant ${context.packageName} ${Manifest.permission.WRITE_SECURE_SETTINGS}")+ add("pm grant $pkg ${Manifest.permission.WRITE_SECURE_SETTINGS}")}// Lets Telecom bind the calling companion: mute, speaker, hold and// the keypad from a PC.if (!CallCompanion.allowed(context) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {- run(adb, "appops set ${context.packageName} ${CallCompanion.OP_NAME} allow")+ add("appops set $pkg ${CallCompanion.OP_NAME} allow")}// Lets the notification listener read one-time codes in notifications// Android 15+ marks sensitive, and refreshes the listener registration// so NotificationManagerService updates its trusted-listener UID set.if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {if (!NotificationListener.canReadSensitive(context)) {- run(adb, "appops set ${context.packageName} ${NotificationListener.OP_SENSITIVE_NAME} allow")+ add("appops set $pkg ${NotificationListener.OP_SENSITIVE_NAME} allow")}if (NotificationListener.hasAccess(context)) {- run(adb, "cmd notification allow_listener ${context.packageName}/${NotificationListener::class.java.name}")+ add("cmd notification allow_listener $pkg/${NotificationListener::class.java.name}")}}// Lets PCs toggle Do Not Disturb / silent mode and screen brightness without extra prompts.if (context.getSystemService(android.app.NotificationManager::class.java)?.isNotificationPolicyAccessGranted == false) {- run(adb, "cmd notification allow_dnd ${context.packageName}")+ add("cmd notification allow_dnd $pkg")}if (!Settings.System.canWrite(context)) {- run(adb, "appops set ${context.packageName} WRITE_SETTINGS allow")+ add("appops set $pkg WRITE_SETTINGS allow")}// Pause for banking apps sees which app is in front; only for those using it.if (BankingPause.apps(context).isNotEmpty() && !BankingPause.hasUsageAccess(context)) {- run(adb, "appops set ${context.packageName} GET_USAGE_STATS allow")+ add("appops set $pkg GET_USAGE_STATS allow")}+ }++ private fun launch(adb: Connection) {+ grants().forEach { run(adb, it) }val token = ByteArray(24).also(SecureRandom()::nextBytes).joinToString("") { "%02x".format(it) }val apk = context.applicationInfo.sourceDirval command = "CLASSPATH=$apk app_process /system/bin ${InputServer::class.java.name} $token"@@ -519,7 +565,7 @@ object Elevated {socket = nullshell = nullrootProcess = null- _state.value = if (paired()) State.Waiting else State.NotSetUp+ _state.value = if (paired() || usesRoot()) State.Waiting else State.NotSetUponChange()}@@ -528,7 +574,10 @@ object Elevated {cancelRetry()screenOffRequested = falsestop()- context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit { putBoolean(PAIRED, false) }+ prefs().edit {+ putBoolean(PAIRED, false)+ putBoolean(ROOT, false)+ }runCatching { adb?.close() }adb = nullAdbKey.delete(context.noBackupFilesDir.resolve("adb"))@@ -720,6 +769,8 @@ object Elevated {private const val ADB_WIFI = "adb_wifi_enabled"private const val DISCOVERY_MS = 10_000Lprivate const val CONNECT_MS = 10_000L+ /** How long a `su` command may take; the first one waits for the root manager's prompt. */+ private const val SU_WAIT_S = 30L/** Waits between attempts to start again; the last one repeats. */private val RETRY_MS = longArrayOf(2_000L, 5_000L, 10_000L, 20_000L, 40_000L, 60_000L)}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.ktindex f292cc0..484e8b4 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt@@ -1202,10 +1202,13 @@ private fun ElevatedAccess() {Elevated.State.NotSetUp -> R.string.elevated_not_set_upElevated.State.Waiting -> R.string.elevated_waitingElevated.State.Starting -> R.string.elevated_starting- Elevated.State.Running -> R.string.elevated_running- is Elevated.State.Failed ->- if ((state as Elevated.State.Failed).reason == Elevated.Reason.NotPaired) R.string.elevated_not_paired- else R.string.elevated_failed+ Elevated.State.Running ->+ if (Elevated.rootActive) R.string.elevated_running_root else R.string.elevated_running+ is Elevated.State.Failed -> when ((state as Elevated.State.Failed).reason) {+ Elevated.Reason.NotPaired -> R.string.elevated_not_paired+ Elevated.Reason.RootDenied -> R.string.elevated_root_failed+ else -> R.string.elevated_failed+ }},),style = MaterialTheme.typography.bodySmall,@@ -1242,6 +1245,19 @@ private fun ElevatedAccess() {}}}+ // Root only when the user picks it, and only on a rooted phone.+ val rootOffered = Elevated.isRootAvailable() &&+ (state == Elevated.State.NotSetUp || state is Elevated.State.Failed)+ if (rootOffered) {+ Text(+ stringResource(R.string.elevated_root_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ OutlinedButton(onClick = { scope.launch { Elevated.setUpWithRoot() } }) {+ Text(stringResource(R.string.elevated_use_root))+ }+ }}if (steps) {AlertDialog(diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xmlindex 54f6395..bb06320 100644--- a/android/app/src/main/res/values-zh-rCN/strings.xml+++ b/android/app/src/main/res/values-zh-rCN/strings.xml@@ -86,6 +86,10 @@<string name="elevated_failed">无法启动,请确认无线调试已开启,然后重试。</string><string name="elevated_not_paired">手机已忘记NectarLink的配对信息,请重新设置。</string><string name="elevated_set_up">设置</string>+ <string name="elevated_use_root">使用Root</string>+ <string name="elevated_root_hint">这台手机已Root,Elevated也可以改用Root启动:无需配对,重启后或离开Wi-Fi时也会自动恢复。权限与使用无线调试时相同。</string>+ <string name="elevated_running_root">已通过Root开启:电脑的鼠标和键盘就像真实的触摸屏和键盘一样工作。</string>+ <string name="elevated_root_failed">未获得Root授权,或Root管理器无法以shell用户身份启动NectarLink的辅助程序。你可以改用无线调试进行设置。</string><string name="elevated_turn_off">关闭</string><string name="elevated_try_again">重试</string><string name="elevated_steps_title">设置无线调试</string>diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex a3ef2f5..ce6b65e 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -92,6 +92,10 @@<string name="elevated_failed">Couldn\'t start it. Check that Wireless debugging is on, then try again.</string><string name="elevated_not_paired">The phone forgot NectarLink\'s pairing. Set it up again.</string><string name="elevated_set_up">Set up</string>+ <string name="elevated_use_root">Use root</string>+ <string name="elevated_root_hint">This phone is rooted, so Elevated can start through root instead: no pairing, and it comes back by itself after a restart or away from Wi-Fi. It gets the same permissions as with Wireless debugging.</string>+ <string name="elevated_running_root">On, through root: your PC\'s mouse and keyboard work like a real touchscreen and keyboard.</string>+ <string name="elevated_root_failed">Root wasn\'t allowed, or your root manager can\'t start NectarLink\'s helper as the shell user. You can set it up with Wireless debugging instead.</string><string name="elevated_turn_off">Turn off</string><string name="elevated_try_again">Try again</string><string name="elevated_steps_title">Set up Wireless debugging</string>diff --git a/docs/guide/faq.md b/docs/guide/faq.mdindex b7e4851..0d9e30a 100644--- a/docs/guide/faq.md+++ b/docs/guide/faq.md@@ -40,7 +40,9 @@ Yes. You can pair two or more phones (for example, a personal phone and a work p### Do I need to root my phone to use NectarLink?-No. Nothing in NectarLink uses or requires root access. Every everyday feature works at the default `Standard` power level using normal Android permissions, and advanced features (`Elevated`) use Android's official built-in Wireless Debugging (`UID 2000` shell user).+No. Every everyday feature works at the default `Standard` power level using normal Android permissions, and advanced features (`Elevated`) use Android's own Wireless Debugging, which runs a small helper as the shell user (`UID 2000`).++If your phone is already rooted (Magisk, KernelSU or APatch), you can choose **Use root** when setting up Elevated instead. NectarLink then starts the same helper through root, still as the shell user with the same permissions, so it needs no pairing and comes back by itself after a restart or away from Wi-Fi. NectarLink never asks for root unless you choose this.### Why does Android 13+ gray out the Notification access or Accessibility switch ("Restricted settings")?