Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
feat(android): start Elevated through Shizuku (#110)
Beef8d7000016e0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 78adf7d..9080816 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -49,6 +49,12 @@ change things that need a step from you, and its notes say so.(`docs/technical/tailscale.md` has the command). Thanks to[@waytoo-average](https://github.com/waytoo-average)([#105](https://github.com/thtbee/nectarlink/pull/105)).+- **Elevated through Shizuku.** If you use Shizuku, **Use Shizuku** in+ Elevated's settings starts it through Shizuku instead of NectarLink's own+ Wireless debugging pairing, so it keeps working away from Wi-Fi while+ Shizuku runs. Shizuku asks once whether NectarLink may use it. The helper+ still runs as the shell user, never as root+ ([#110](https://github.com/thtbee/nectarlink/issues/110)).- **Pick the SIM for a call from the PC.** On a phone with two SIMs, theCalls page has **Call with** under the dial pad. It starts on the phone'sdefault SIM for calls and remembers your pick for each phone. Before,diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.ktsindex 13345c8..6f8db34 100644--- a/android/app/build.gradle.kts+++ b/android/app/build.gradle.kts@@ -207,6 +207,9 @@ dependencies {// Elevated: the phone's own wireless debugging (pairing and shell).implementation(libs.libadb.android)implementation(libs.conscrypt.android)+ // Or through Shizuku, when the user picks it (#110).+ implementation(libs.shizuku.api)+ implementation(libs.shizuku.provider)// UniFFI's Kotlin bindings call the core through JNA.implementation(libs.jna) { artifact { type = "aar" } }testImplementation(libs.junit)diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.proindex 246a74b..001546f 100644--- a/android/app/proguard-rules.pro+++ b/android/app/proguard-rules.pro@@ -38,6 +38,10 @@public static void main(java.lang.String[]);}-keep class app.nectarlink.android.elevated.SurfaceControl { *; }+# Shizuku creates the Elevated service by name, with a Context (ShizukuShell.kt).+-keep class app.nectarlink.android.elevated.ShizukuShell {+ public <init>(android.content.Context);+}# Conscrypt (used by Elevated wireless ADB TLS handshake)-keep class org.conscrypt.** { *; }diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 34a7162..052f46e 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -218,6 +218,17 @@android:name=".media.PcMedia$CommandReceiver"android:exported="false" />+ <!-- Shizuku hands NectarLink its Binder through this (Elevated through+ Shizuku, #110). Only callers that may act across users (Shizuku,+ the system) can reach it. -->+ <provider+ android:name="rikka.shizuku.ShizukuProvider"+ android:authorities="${applicationId}.shizuku"+ android:enabled="true"+ android:exported="true"+ android:multiprocess="false"+ android:permission="android.permission.INTERACT_ACROSS_USERS_FULL" />+<!-- Opening received files on Android 8–9 (later versions use MediaStore),and images from a PC on the clipboard. --><providerdiff --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 1ebec89..4e54304 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@@ -69,13 +69,15 @@ object Elevated {data class Failed(val reason: Reason) : State}- enum class Reason { WrongCode, NoPairingDialog, NotPaired, RootDenied, Other }+ enum class Reason { WrongCode, NoPairingDialog, NotPaired, RootDenied, ShizukuNotRunning, ShizukuDenied, ShizukuRoot, 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"+ /** Set up through Shizuku (the user chose Use Shizuku), see [ShizukuElevated]. */+ private const val SHIZUKU = "shizuku"/** The shell user, which the helper runs as however it's started. */private const val SHELL_UID = "2000"/** The version [compileIfUpdated] last asked Android to compile. */@@ -102,6 +104,10 @@ object Elevated {@Volatile var rootActive: Boolean = falseprivate set+ /** True when the running helper was started through Shizuku. */+ @Volatile var shizukuActive: Boolean = false+ private set+val running: Boolean get() = input != nullprivate val rootAvailableCached: Boolean by lazy {@@ -126,6 +132,12 @@ object Elevated {/** Whether the user set Elevated up through root. */private fun usesRoot() = isRootAvailable() && prefs().getBoolean(ROOT, false)+ /** Whether the user set Elevated up through Shizuku. */+ fun usesShizuku(): Boolean = prefs().getBoolean(SHIZUKU, false)++ /** Set up one way or another, so it should start whenever it can. */+ private fun isSetUp() = paired() || usesRoot() || usesShizuku()+private fun prefs() = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)/**@@ -150,11 +162,41 @@ object Elevated {started}+ /**+ * Sets Elevated up through Shizuku, as the user asked: Shizuku asks once+ * whether NectarLink may use it, and from then on Elevated starts through+ * it whenever Shizuku runs. The helper runs as the shell user, as through+ * Wireless debugging; a Shizuku running as root isn't used.+ */+ suspend fun setUpWithShizuku(): Boolean = withContext(Dispatchers.IO) {+ ShizukuElevated.requestPermission()?.let { problem ->+ _state.value = State.Failed(reasonFor(problem))+ return@withContext false+ }+ prefs().edit { putBoolean(SHIZUKU, true) }+ held = false+ val started = lock.withLock {+ if (running && !shizukuActive) stopLocked()+ if (running) return@withLock true+ _state.value = State.Starting+ tryStartWithShizukuLocked()+ }+ if (started) cancelRetry()+ started+ }+fun init(context: Context) {this.context = context.applicationContextwatchWirelessDebugging()+ // Shizuku's service comes after the app on a boot, and again whenever+ // it's restarted: start then, if Elevated goes through it.+ runCatching {+ ShizukuElevated.watch {+ if (usesShizuku() && !held && !running) scope.launch { start() }+ }+ }.onFailure { Log.i(TAG, "can't watch for Shizuku", it) }scope.launch(Dispatchers.IO) {- if (paired() || usesRoot()) {+ if (isSetUp()) {_state.value = State.Waitingstart()}@@ -197,10 +239,11 @@ object Elevated {}.onFailure { Log.i(TAG, "can't watch wireless debugging", it) }}- /** Tries again later, while it can still work: set up, not running, on Wi-Fi (or through root). */+ /** Tries again later, while it can still work: set up, not running, on Wi-Fi (or through root or Shizuku). */private fun scheduleRetry() {- if (held || !(paired() || usesRoot()) || running || BankingPause.isPaused(context)) return- if (!usesRoot() && !onWifi()) return+ if (held || !isSetUp() || running || BankingPause.isPaused(context)) return+ val withoutWifi = usesRoot() || (usesShizuku() && ShizukuElevated.allowed())+ if (!withoutWifi && !onWifi()) returnval wait = RETRY_MS[retryAttempt.coerceAtMost(RETRY_MS.lastIndex)]retryAttempt++retryJob?.cancel()@@ -360,10 +403,14 @@ object Elevated {if (usesRoot() && tryStartWithRootLocked()) {return@withLock true}+ if (usesShizuku() && tryStartWithShizukuLocked()) {+ return@withLock true+ }if (!paired()) {// No wireless debugging set up: a PC this phone is plugged into can start it.if (startOverUsbLocked()) return@withLock true- _state.value = State.NotSetUp+ // Through Shizuku, the state says why it didn't start, or that it waits for Shizuku.+ if (!usesShizuku()) _state.value = State.NotSetUpreturn@withLock false}turnOnWirelessDebugging()@@ -448,6 +495,43 @@ object Elevated {}.getOrDefault(false)}+ /**+ * Starts [InputServer] through Shizuku ([ShizukuElevated]). Leaves the+ * state saying why when it can't: Shizuku not running (it waits for it),+ * not allowed, or running as root.+ */+ private suspend fun tryStartWithShizukuLocked(): Boolean {+ val token = ByteArray(24).also(SecureRandom()::nextBytes).joinToString("") { "%02x".format(it) }+ val port = ShizukuElevated.startHelper(context, grants(), token).getOrElse { e ->+ val problem = (e as? ShizukuElevated.ShizukuProblem)?.problem+ if (problem == null) Log.i(TAG, "the helper didn't start through Shizuku", e)+ _state.value = when (problem) {+ ShizukuElevated.Problem.NotRunning -> State.Waiting+ null -> State.Failed(Reason.Other)+ else -> State.Failed(reasonFor(problem))+ }+ return false+ }+ return runCatching {+ shizukuActive = true+ connectSocketLocked(port, token)+ Log.i(TAG, "started through Shizuku")+ true+ }.getOrElse {+ Log.w(TAG, "the helper started through Shizuku didn't answer", it)+ shizukuActive = false+ ShizukuElevated.stop()+ _state.value = State.Failed(Reason.Other)+ false+ }+ }++ private fun reasonFor(problem: ShizukuElevated.Problem) = when (problem) {+ ShizukuElevated.Problem.NotRunning -> Reason.ShizukuNotRunning+ ShizukuElevated.Problem.Denied -> Reason.ShizukuDenied+ ShizukuElevated.Problem.Root -> Reason.ShizukuRoot+ }+/** 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()@@ -523,7 +607,7 @@ object Elevated {runCatching { output.lineSequence().forEach { line -> Log.d(TAG, "helper: $line") } }input = nullrunCatching { socket?.close() }- if (_state.value == State.Running) _state.value = if (paired()) State.Waiting else State.NotSetUp+ if (_state.value == State.Running) _state.value = if (isSetUp()) State.Waiting else State.NotSetUponChange()scheduleRetry()}.start()@@ -565,8 +649,9 @@ object Elevated {}if (socket === local) {input = null+ shizukuActive = falserunCatching { local.close() }- if (_state.value == State.Running) _state.value = if (paired()) State.Waiting else State.NotSetUp+ if (_state.value == State.Running) _state.value = if (isSetUp()) State.Waiting else State.NotSetUponChange()scheduleRetry()}@@ -679,6 +764,8 @@ object Elevated {private fun stopLocked() {screenOffRequested = falserootActive = false+ if (shizukuActive) ShizukuElevated.stop()+ shizukuActive = falseinput = nullhelper = nullrunCatching { socket?.close() }@@ -688,7 +775,7 @@ object Elevated {socket = nullshell = nullrootProcess = null- _state.value = if (paired() || usesRoot()) State.Waiting else State.NotSetUp+ _state.value = if (isSetUp()) State.Waiting else State.NotSetUponChange()}@@ -700,6 +787,7 @@ object Elevated {prefs().edit {putBoolean(PAIRED, false)putBoolean(ROOT, false)+ putBoolean(SHIZUKU, false)}runCatching { adb?.close() }adb = nulldiff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/ShizukuShell.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/ShizukuShell.ktnew file mode 100644index 0000000..872aa71--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/ShizukuShell.kt@@ -0,0 +1,313 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.elevated++import android.content.ComponentName+import android.content.Context+import android.content.ServiceConnection+import android.content.pm.PackageManager+import android.os.Binder+import android.os.IBinder+import android.os.Parcel+import android.util.Log+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull+import rikka.shizuku.Shizuku+import java.util.concurrent.Executors+import java.util.concurrent.TimeUnit+import kotlin.concurrent.thread+import kotlin.system.exitProcess++/**+ * Starting Elevated through [Shizuku](https://shizuku.rikka.app/) (#110),+ * for phones where it already runs: Shizuku keeps a process with the+ * shell's permissions alive after it's started once, so Elevated needn't+ * hold Wireless debugging itself, and keeps working away from Wi-Fi.+ *+ * Shizuku starts [ShizukuShell] in a process of its own, as its own user,+ * and hands NectarLink a Binder to it. Through that it runs the same grants+ * and starts the same [InputServer] as the other ways do. Like root, it's+ * only used when that user is the shell (Shizuku started through Wireless+ * debugging or a PC), never when Shizuku runs as root.+ */+object ShizukuElevated {+ /** Shizuku's own app. */+ const val PACKAGE = "moe.shizuku.privileged.api"++ private const val TAG = "Elevated"+ /** Shizuku 13 passes the service a Context, which [ShizukuShell] needs to know who may call it. */+ private const val MIN_SERVER_VERSION = 13+ private const val PERMISSION_REQUEST = 0x5A71+ private const val BIND_MS = 15_000L+ private const val PERMISSION_MS = 120_000L++ /** Why starting through Shizuku didn't work. */+ enum class Problem { NotRunning, Denied, Root }++ /** Whether Shizuku's app is on the phone (so Elevated may offer it). */+ fun installed(context: Context): Boolean = runCatching {+ context.packageManager.getPackageInfo(PACKAGE, 0)+ true+ }.getOrDefault(false)++ /** Whether Shizuku's service is running and answering. */+ fun running(): Boolean = runCatching { Shizuku.pingBinder() }.getOrDefault(false)++ /** Whether Shizuku is running, new enough, and lets NectarLink use it. */+ fun allowed(): Boolean = running() && runCatching {+ !Shizuku.isPreV11() && Shizuku.getVersion() >= MIN_SERVER_VERSION &&+ Shizuku.checkSelfPermission() == PackageManager.PERMISSION_GRANTED+ }.getOrDefault(false)++ /** Calls [onRunning] whenever Shizuku's service (re)appears. */+ fun watch(onRunning: () -> Unit) {+ Shizuku.addBinderReceivedListenerSticky { onRunning() }+ }++ /**+ * Asks Shizuku to let NectarLink use it, if it hasn't yet; Shizuku shows+ * its own dialog. Null when Shizuku isn't usable at all.+ */+ suspend fun requestPermission(): Problem? {+ if (!running()) return Problem.NotRunning+ if (runCatching { Shizuku.isPreV11() || Shizuku.getVersion() < MIN_SERVER_VERSION }.getOrDefault(true)) {+ return Problem.Denied+ }+ if (allowed()) return null+ val answer = CompletableDeferred<Boolean>()+ val listener = Shizuku.OnRequestPermissionResultListener { code, result ->+ if (code == PERMISSION_REQUEST) answer.complete(result == PackageManager.PERMISSION_GRANTED)+ }+ Shizuku.addRequestPermissionResultListener(listener)+ return try {+ Shizuku.requestPermission(PERMISSION_REQUEST)+ if (withTimeoutOrNull(PERMISSION_MS) { answer.await() } == true) null else Problem.Denied+ } catch (e: RuntimeException) {+ Log.i(TAG, "Shizuku's permission request failed", e)+ Problem.Denied+ } finally {+ Shizuku.removeRequestPermissionResultListener(listener)+ }+ }++ private var args: Shizuku.UserServiceArgs? = null+ private var connection: ServiceConnection? = null+ @Volatile private var service: IBinder? = null++ /** The service's Binder, binding it first if needed. Null if Shizuku won't. */+ private suspend fun bind(context: Context): IBinder? {+ service?.takeIf { it.pingBinder() }?.let { return it }+ stop()+ val bound = CompletableDeferred<IBinder?>()+ val serviceArgs = Shizuku.UserServiceArgs(ComponentName(context.packageName, ShizukuShell::class.java.name))+ .processNameSuffix("elevated")+ .tag("elevated")+ .version(app.nectarlink.android.BuildConfig.VERSION_CODE)+ .debuggable(app.nectarlink.android.BuildConfig.DEBUG)+ // Ends with NectarLink, so the helper never outlives the app that controls it.+ .daemon(false)+ val conn = object : ServiceConnection {+ override fun onServiceConnected(name: ComponentName?, service: IBinder?) {+ bound.complete(service?.takeIf { it.pingBinder() })+ }++ override fun onServiceDisconnected(name: ComponentName?) {+ service = null+ bound.complete(null)+ }+ }+ withContext(Dispatchers.Main) {+ runCatching { Shizuku.bindUserService(serviceArgs, conn) }+ .onFailure { Log.i(TAG, "Shizuku didn't bind the helper's service", it) }+ }+ args = serviceArgs+ connection = conn+ return withTimeoutOrNull(BIND_MS) { bound.await() }.also { service = it }+ }++ /**+ * Runs the grants and starts [InputServer] with [token] through Shizuku.+ * Returns the port it listens on, or why it couldn't.+ */+ suspend fun startHelper(context: Context, grants: List<String>, token: String): Result<Int> {+ if (!running()) return Result.failure(ShizukuProblem(Problem.NotRunning))+ if (!allowed()) return Result.failure(ShizukuProblem(Problem.Denied))+ val binder = bind(context) ?: return Result.failure(ShizukuProblem(Problem.Denied))+ return withContext(Dispatchers.IO) {+ runCatching {+ val uid = transact(binder, ShizukuShell.UID) { reply -> reply.readInt() }+ if (uid != ShizukuShell.SHELL_UID) {+ Log.i(TAG, "Shizuku runs as $uid, not the shell; not using it")+ throw ShizukuProblem(Problem.Root)+ }+ grants.forEach { grant ->+ transact(binder, ShizukuShell.RUN, { it.writeString(grant) }) { reply -> reply.readInt() }+ }+ val (port, said) = transact(binder, ShizukuShell.START, { it.writeString(token) }) { reply ->+ reply.readInt() to reply.readString().orEmpty()+ }+ check(port > 0) { "the helper said ${said.ifEmpty { "nothing" }}" }+ port+ }+ }+ }++ /** Stops the helper and lets Shizuku end the service's process. */+ fun stop() {+ val serviceArgs = args ?: return+ val conn = connection+ args = null+ connection = null+ service = null+ runCatching { Shizuku.unbindUserService(serviceArgs, conn, true) }+ .onFailure { Log.i(TAG, "Shizuku didn't unbind the helper's service", it) }+ }++ private fun <T> transact(binder: IBinder, code: Int, write: (Parcel) -> Unit = {}, read: (Parcel) -> T): T {+ val data = Parcel.obtain()+ val reply = Parcel.obtain()+ try {+ data.writeInterfaceToken(ShizukuShell.DESCRIPTOR)+ write(data)+ check(binder.transact(code, data, reply, 0)) { "the helper's service refused call $code" }+ reply.readException()+ return read(reply)+ } finally {+ data.recycle()+ reply.recycle()+ }+ }++ class ShizukuProblem(val problem: Problem) : Exception("Shizuku: $problem")+}++/**+ * Runs in the process Shizuku starts for NectarLink (as Shizuku's user,+ * normally the shell), not in the app. Answers only NectarLink itself and+ * Shizuku, and only to: say which user it runs as, run a grant from+ * [ShizukuShellRules.isGrant], and start [InputServer] from NectarLink's own+ * APK with a token. Nothing it's given ends up in a shell command line.+ */+class ShizukuShell(context: Context) : Binder() {+ private val appUid = context.applicationInfo.uid+ private val apk = context.applicationInfo.sourceDir+ @Volatile private var helper: Process? = null++ override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {+ val caller = getCallingUid()+ if (caller != appUid && caller != android.os.Process.myUid()) return false+ if (code == DESTROY) {+ stopHelper()+ exitProcess(0)+ }+ if (code !in UID..START) return super.onTransact(code, data, reply, flags)+ data.enforceInterface(DESCRIPTOR)+ val out = reply ?: return false+ when (code) {+ UID -> {+ out.writeNoException()+ out.writeInt(android.os.Process.myUid())+ }+ RUN -> {+ val grant = data.readString().orEmpty()+ out.writeNoException()+ out.writeInt(if (ShizukuShellRules.isGrant(grant)) run(ShizukuShellRules.words(grant)) else -1)+ }+ START -> {+ val token = data.readString().orEmpty()+ val (port, said) = if (ShizukuShellRules.isToken(token)) startHelper(token) else -1 to "bad token"+ out.writeNoException()+ out.writeInt(port)+ out.writeString(said)+ }+ }+ return true+ }++ /** Runs one grant to its end (they print next to nothing); its exit code, or -1. */+ private fun run(words: List<String>): Int = runCatching {+ val process = ProcessBuilder(words).redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.to(java.io.File("/dev/null"))).start()+ if (process.waitFor(RUN_S, TimeUnit.SECONDS)) process.exitValue() else -1.also { process.destroyForcibly() }+ }.getOrDefault(-1)++ /** Starts [InputServer]; its port, or -1 and what it said. */+ private fun startHelper(token: String): Pair<Int, String> {+ stopHelper()+ val process = runCatching {+ ProcessBuilder(APP_PROCESS, "/system/bin", InputServer::class.java.name, token)+ .redirectErrorStream(true)+ .apply { environment()["CLASSPATH"] = apk }+ .start()+ }.getOrElse { return -1 to "can't start app_process: $it" }+ val output = process.inputStream.bufferedReader()+ val reader = Executors.newSingleThreadExecutor()+ val first = runCatching { reader.submit<String> { output.readLine().orEmpty() }.get(READY_S, TimeUnit.SECONDS) }+ .getOrDefault("")+ reader.shutdownNow()+ val port = ShizukuShellRules.readyPort(first)+ if (port == null) {+ process.destroyForcibly()+ return -1 to first+ }+ helper = process+ thread(name = "elevated-helper-log") {+ runCatching { output.lineSequence().forEach { Log.d("Elevated", "shizuku-helper: $it") } }+ }+ return port to ""+ }++ private fun stopHelper() {+ helper?.let { runCatching { it.destroyForcibly() } }+ helper = null+ }++ companion object {+ const val DESCRIPTOR = "app.nectarlink.android.elevated.ShizukuShell"+ const val UID = FIRST_CALL_TRANSACTION+ const val RUN = FIRST_CALL_TRANSACTION + 1+ const val START = FIRST_CALL_TRANSACTION + 2+ /** What Shizuku sends when it ends the service (`USER_SERVICE_TRANSACTION_destroy`). */+ const val DESTROY = 16777115+ const val SHELL_UID = 2000+ private const val APP_PROCESS = "/system/bin/app_process"+ private const val RUN_S = 30L+ private const val READY_S = 15L+ }+}++/** What [ShizukuShell] accepts, as plain functions so they're unit-tested. */+object ShizukuShellRules {+ private val TOKEN = Regex("[0-9a-f]{48}")+ private val PACKAGE = Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+")+ private val OP = Regex("[A-Z][A-Z0-9_]*")+ private val PERMISSION = Regex("android\\.permission\\.[A-Z][A-Z0-9_]*")+ private val COMPONENT = Regex("${PACKAGE.pattern}/${PACKAGE.pattern}")++ /** A token [Elevated] makes: 24 random bytes in hex. */+ fun isToken(token: String) = TOKEN.matches(token)++ /**+ * One of the grants [Elevated] runs before the helper starts, for+ * NectarLink's own package and nothing else: `pm grant`, `appops set …+ * allow` and `cmd notification allow_listener|allow_dnd`.+ */+ fun isGrant(command: String): Boolean {+ val w = words(command)+ val own = app.nectarlink.android.BuildConfig.APPLICATION_ID+ return when {+ w.size == 4 && w[0] == "pm" && w[1] == "grant" -> w[2] == own && PERMISSION.matches(w[3])+ w.size == 5 && w[0] == "appops" && w[1] == "set" && w[4] == "allow" -> w[2] == own && OP.matches(w[3])+ w.size == 4 && w[0] == "cmd" && w[1] == "notification" && w[2] == "allow_dnd" -> w[3] == own+ w.size == 4 && w[0] == "cmd" && w[1] == "notification" && w[2] == "allow_listener" ->+ COMPONENT.matches(w[3]) && w[3].substringBefore('/') == own+ else -> false+ }+ }++ fun words(command: String): List<String> = command.trim().split(Regex("\\s+")).filter(String::isNotEmpty)++ /** The port in the helper's first line (`ready <port>`), if that's what it said. */+ fun readyPort(line: String): Int? =+ line.takeIf { it.startsWith("ready ") }?.removePrefix("ready ")?.trim()?.toIntOrNull()?.takeIf { it in 1..65535 }+}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 dde793c..0926757 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@@ -74,6 +74,7 @@ import app.nectarlink.android.companion.PcCompanionimport app.nectarlink.android.contacts.PhoneContactsimport app.nectarlink.android.elevated.Elevatedimport app.nectarlink.android.elevated.PairingNotification+import app.nectarlink.android.elevated.ShizukuElevatedimport app.nectarlink.android.mirror.InputServiceimport app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.sms.PhoneSms@@ -1075,6 +1076,13 @@ private fun openAppInfoSettings(context: Context) {}}+/** Shizuku's app, where it's started and where NectarLink is allowed. */+private fun openShizuku(context: Context) {+ context.packageManager.getLaunchIntentForPackage(ShizukuElevated.PACKAGE)+ ?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ ?.let { runCatching { context.startActivity(it) } }+}+private fun openDeveloperOptionsSettings(context: Context) {val devIntent = Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)@@ -1306,6 +1314,12 @@ private fun ElevatedAccess() {val scope = rememberCoroutineScope()val state by Elevated.state.collectAsStateWithLifecycle()var steps by remember { mutableStateOf(false) }+ val shizukuInstalled = remember { ShizukuElevated.installed(context) }+ val failure = (state as? Elevated.State.Failed)?.reason+ val shizukuFailure = failure == Elevated.Reason.ShizukuNotRunning ||+ failure == Elevated.Reason.ShizukuDenied || failure == Elevated.Reason.ShizukuRoot+ // Through Shizuku, the way back is in Shizuku's app, not Developer options.+ val viaShizuku = Elevated.usesShizuku() || shizukuFailureColumn(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {Column(Modifier.weight(1f).padding(end = 12.dp)) {@@ -1314,13 +1328,20 @@ private fun ElevatedAccess() {stringResource(when (state) {Elevated.State.NotSetUp -> R.string.elevated_not_set_up- Elevated.State.Waiting -> R.string.elevated_waiting+ Elevated.State.Waiting ->+ if (Elevated.usesShizuku()) R.string.elevated_shizuku_waiting else R.string.elevated_waitingElevated.State.Starting -> R.string.elevated_starting- Elevated.State.Running ->- if (Elevated.rootActive) R.string.elevated_running_root else R.string.elevated_running+ Elevated.State.Running -> when {+ Elevated.rootActive -> R.string.elevated_running_root+ Elevated.shizukuActive -> R.string.elevated_running_shizuku+ else -> R.string.elevated_running+ }is Elevated.State.Failed -> when ((state as Elevated.State.Failed).reason) {Elevated.Reason.NotPaired -> R.string.elevated_not_pairedElevated.Reason.RootDenied -> R.string.elevated_root_failed+ Elevated.Reason.ShizukuNotRunning -> R.string.elevated_shizuku_not_running+ Elevated.Reason.ShizukuDenied -> R.string.elevated_shizuku_denied+ Elevated.Reason.ShizukuRoot -> R.string.elevated_shizuku_rootelse -> R.string.elevated_failed}},@@ -1335,6 +1356,10 @@ private fun ElevatedAccess() {}Elevated.State.Waiting -> Button(onClick = {scope.launch {+ if (Elevated.usesShizuku()) {+ if (!Elevated.start() && !ShizukuElevated.running()) openShizuku(context)+ return@launch+ }PairingNotification.show(context)if (!Elevated.start()) {openDeveloperOptionsSettings(context)@@ -1351,11 +1376,17 @@ private fun ElevatedAccess() {}if (state == Elevated.State.Waiting || state is Elevated.State.Failed) {Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- OutlinedButton(onClick = {- PairingNotification.show(context)- openDeveloperOptionsSettings(context)- }) {- Text(stringResource(R.string.elevated_open_developer))+ if (viaShizuku && shizukuInstalled) {+ OutlinedButton(onClick = { openShizuku(context) }) {+ Text(stringResource(R.string.elevated_open_shizuku))+ }+ } else {+ OutlinedButton(onClick = {+ PairingNotification.show(context)+ openDeveloperOptionsSettings(context)+ }) {+ Text(stringResource(R.string.elevated_open_developer))+ }}}}@@ -1372,6 +1403,23 @@ private fun ElevatedAccess() {Text(stringResource(R.string.elevated_use_root))}}+ // Shizuku too, only when the user picks it and only when its app is installed.+ val shizukuOffered = shizukuInstalled && !Elevated.usesShizuku() &&+ (state == Elevated.State.NotSetUp || state is Elevated.State.Failed)+ if (shizukuOffered) {+ Text(+ stringResource(R.string.elevated_shizuku_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ OutlinedButton(onClick = {+ scope.launch {+ if (!Elevated.setUpWithShizuku() && !ShizukuElevated.running()) openShizuku(context)+ }+ }) {+ Text(stringResource(R.string.elevated_use_shizuku))+ }+ }}if (steps) {AlertDialog(diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xmlindex d66895e..d6568cb 100644--- a/android/app/src/main/res/values-de/strings.xml+++ b/android/app/src/main/res/values-de/strings.xml@@ -103,6 +103,14 @@<string name="elevated_root_hint">Dieses Gerät ist gerootet, daher kann der erweiterte Modus stattdessen über Root starten: ohne Kopplung, und er ist nach einem Neustart oder ohne WLAN von selbst wieder da. Er erhält dieselben Berechtigungen wie beim Kabellosen Debugging.</string><string name="elevated_running_root">Ein (über Root): Maus und Tastatur deines PCs funktionieren wie ein echter Touchscreen und eine echte Tastatur.</string><string name="elevated_root_failed">Root-Zugriff wurde nicht gewährt oder dein Root-Manager kann den NectarLink-Helfer nicht als Shell-Benutzer starten. Du kannst ihn stattdessen über Kabelloses Debugging einrichten.</string>+ <string name="elevated_use_shizuku">Shizuku verwenden</string>+ <string name="elevated_shizuku_hint">Shizuku ist installiert, daher kann der erweiterte Modus stattdessen darüber starten: ohne eigene Kopplung, und er funktioniert auch ohne WLAN, solange Shizuku läuft. Er erhält dieselben Berechtigungen wie beim Kabellosen Debugging.</string>+ <string name="elevated_running_shizuku">An, über Shizuku: Maus und Tastatur deines PCs funktionieren wie ein echter Touchscreen und eine echte Tastatur.</string>+ <string name="elevated_shizuku_waiting">Warte auf Shizuku. Starte es in der Shizuku-App und öffne dann NectarLink.</string>+ <string name="elevated_shizuku_not_running">Shizuku läuft nicht. Starte es in der Shizuku-App und versuche es dann erneut.</string>+ <string name="elevated_shizuku_denied">Shizuku hat NectarLink nicht zugelassen. Erlaube es in Shizuku (und aktualisiere Shizuku, falls es alt ist) und versuche es dann erneut.</string>+ <string name="elevated_shizuku_root">Shizuku läuft mit Root, und der erweiterte Modus startet seinen Helfer nur als Shell-Benutzer. Starte Shizuku stattdessen über das Kabellose Debugging oder verwende Root.</string>+ <string name="elevated_open_shizuku">Shizuku öffnen</string><string name="elevated_turn_off">Ausschalten</string><string name="elevated_try_again">Erneut versuchen</string><string name="elevated_steps_title">Kabelloses Debugging einrichten</string>diff --git a/android/app/src/main/res/values-tr/strings.xml b/android/app/src/main/res/values-tr/strings.xmlindex 049734c..6b4f39d 100644--- a/android/app/src/main/res/values-tr/strings.xml+++ b/android/app/src/main/res/values-tr/strings.xml@@ -103,6 +103,14 @@<string name="elevated_root_hint">Bu telefon root\'lu, bu yüzden Yükseltilmiş mod bunun yerine root üzerinden başlayabilir: eşleştirme gerekmez ve yeniden başlatmadan sonra veya Wi-Fi dışındayken kendiliğinden geri gelir. Kablosuz hata ayıklamadakiyle aynı izinleri alır.</string><string name="elevated_running_root">Açık, root üzerinden: bilgisayarınızın faresi ve klavyesi gerçek bir dokunmatik ekran ve klavye gibi çalışır.</string><string name="elevated_root_failed">Root izni verilmedi veya root yöneticiniz NectarLink\'in yardımcısını shell kullanıcısı olarak başlatamıyor. Bunun yerine Kablosuz hata ayıklama ile kurabilirsiniz.</string>+ <string name="elevated_use_shizuku">Shizuku kullan</string>+ <string name="elevated_shizuku_hint">Shizuku yüklü, bu yüzden Yükseltilmiş mod onun üzerinden başlayabilir: ayrıca eşleştirme gerekmez ve Shizuku çalıştığı sürece Wi-Fi dışındayken de çalışır. Kablosuz hata ayıklamadakiyle aynı izinleri alır.</string>+ <string name="elevated_running_shizuku">Açık, Shizuku üzerinden: bilgisayarınızın faresi ve klavyesi gerçek bir dokunmatik ekran ve klavye gibi çalışır.</string>+ <string name="elevated_shizuku_waiting">Shizuku bekleniyor. Shizuku uygulamasından başlatın, sonra NectarLink\'i açın.</string>+ <string name="elevated_shizuku_not_running">Shizuku çalışmıyor. Shizuku uygulamasından başlatın, sonra tekrar deneyin.</string>+ <string name="elevated_shizuku_denied">Shizuku, NectarLink\'e izin vermedi. Shizuku\'da izin verin (Shizuku eskiyse güncelleyin), sonra tekrar deneyin.</string>+ <string name="elevated_shizuku_root">Shizuku root ile çalışıyor ve Yükseltilmiş mod yardımcısını yalnızca shell kullanıcısı olarak başlatır. Shizuku\'yu bunun yerine Kablosuz hata ayıklama ile başlatın ya da root kullanın.</string>+ <string name="elevated_open_shizuku">Shizuku\'yu aç</string><string name="elevated_turn_off">Kapat</string><string name="elevated_try_again">Tekrar dene</string><string name="elevated_steps_title">Kablosuz hata ayıklamayı ayarlayın</string>diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xmlindex ffee11d..b13eca9 100644--- a/android/app/src/main/res/values-zh-rCN/strings.xml+++ b/android/app/src/main/res/values-zh-rCN/strings.xml@@ -97,6 +97,14 @@<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_use_shizuku">使用 Shizuku</string>+ <string name="elevated_shizuku_hint">已安装 Shizuku,因此 Elevated 可以改为通过它启动:无需单独配对,只要 Shizuku 在运行,离开 Wi-Fi 也能继续使用。它获得的权限与无线调试相同。</string>+ <string name="elevated_running_shizuku">已开启(通过 Shizuku):电脑的鼠标和键盘就像真正的触摸屏和键盘一样工作。</string>+ <string name="elevated_shizuku_waiting">正在等待 Shizuku。请在 Shizuku 应用中启动它,然后打开 NectarLink。</string>+ <string name="elevated_shizuku_not_running">Shizuku 未运行。请在 Shizuku 应用中启动它,然后重试。</string>+ <string name="elevated_shizuku_denied">Shizuku 未授权 NectarLink。请在 Shizuku 中允许(如果 Shizuku 版本较旧,请更新),然后重试。</string>+ <string name="elevated_shizuku_root">Shizuku 正以 Root 身份运行,而 Elevated 只会以 shell 用户身份启动其辅助程序。请改用无线调试启动 Shizuku,或使用 Root。</string>+ <string name="elevated_open_shizuku">打开 Shizuku</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 3973d3d..29b156b 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -103,6 +103,14 @@<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_use_shizuku">Use Shizuku</string>+ <string name="elevated_shizuku_hint">Shizuku is installed, so Elevated can start through it instead: no pairing of its own, and it keeps working away from Wi-Fi while Shizuku runs. It gets the same permissions as with Wireless debugging.</string>+ <string name="elevated_running_shizuku">On, through Shizuku: your PC\'s mouse and keyboard work like a real touchscreen and keyboard.</string>+ <string name="elevated_shizuku_waiting">Waiting for Shizuku. Start it in the Shizuku app, then open NectarLink.</string>+ <string name="elevated_shizuku_not_running">Shizuku isn\'t running. Start it in the Shizuku app, then try again.</string>+ <string name="elevated_shizuku_denied">Shizuku didn\'t let NectarLink in. Allow it in Shizuku (and update Shizuku if it\'s old), then try again.</string>+ <string name="elevated_shizuku_root">Shizuku is running with root, and Elevated only starts its helper as the shell user. Start Shizuku with Wireless debugging instead, or use root.</string>+ <string name="elevated_open_shizuku">Open Shizuku</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/android/app/src/test/kotlin/app/nectarlink/android/elevated/ShizukuShellRulesTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/elevated/ShizukuShellRulesTest.ktnew file mode 100644index 0000000..faa506f--- /dev/null+++ b/android/app/src/test/kotlin/app/nectarlink/android/elevated/ShizukuShellRulesTest.kt@@ -0,0 +1,56 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.elevated++import app.nectarlink.android.BuildConfig+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class ShizukuShellRulesTest {+ private val own = BuildConfig.APPLICATION_ID++ @Test+ fun takesOnlyTheTokensElevatedMakes() {+ assertTrue(ShizukuShellRules.isToken("0123456789abcdef".repeat(3)))+ assertFalse(ShizukuShellRules.isToken("0123456789ABCDEF".repeat(3)))+ assertFalse(ShizukuShellRules.isToken("abc"))+ assertFalse(ShizukuShellRules.isToken("0123456789abcdef".repeat(3) + " ; reboot"))+ }++ @Test+ fun runsTheGrantsElevatedAsksForItsOwnPackage() {+ listOf(+ "pm grant $own android.permission.WRITE_SECURE_SETTINGS",+ "appops set $own GET_USAGE_STATS allow",+ "appops set $own WRITE_SETTINGS allow",+ "cmd notification allow_dnd $own",+ "cmd notification allow_listener $own/app.nectarlink.android.notifications.NotificationListener",+ ).forEach { assertTrue(it, ShizukuShellRules.isGrant(it)) }+ }++ @Test+ fun refusesAnythingElse() {+ listOf(+ "pm grant com.example.other android.permission.WRITE_SECURE_SETTINGS",+ "pm grant $own android.permission.WRITE_SECURE_SETTINGS; reboot",+ "appops set $own GET_USAGE_STATS deny",+ "appops set com.example.other GET_USAGE_STATS allow",+ "cmd notification allow_listener com.example.other/$own.Listener",+ "cmd notification allow_dnd com.example.other",+ "pm uninstall $own",+ "reboot",+ "",+ ).forEach { assertFalse(it, ShizukuShellRules.isGrant(it)) }+ }++ @Test+ fun readsThePortTheHelperListensOn() {+ assertEquals(43567, ShizukuShellRules.readyPort("ready 43567"))+ assertNull(ShizukuShellRules.readyPort("can't inject input: java.lang.SecurityException"))+ assertNull(ShizukuShellRules.readyPort("ready 0"))+ assertNull(ShizukuShellRules.readyPort("ready 70000"))+ assertNull(ShizukuShellRules.readyPort(""))+ }+}diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.tomlindex 0deac21..af5d3e6 100644--- a/android/gradle/libs.versions.toml+++ b/android/gradle/libs.versions.toml@@ -10,11 +10,15 @@ coroutines = "1.11.0"camerax = "1.6.2"zxing = "3.5.4"jna = "5.19.1"+shizuku = "13.1.5"junit = "4.13.2"[libraries]libadb-android = { module = "com.github.MuntashirAkon:libadb-android", version = "3.1.1" }conscrypt-android = { module = "org.conscrypt:conscrypt-android", version = "2.8.0" }+# Shizuku (MIT), an optional way to start Elevated (#110).+shizuku-api = { module = "dev.rikka.shizuku:api", version.ref = "shizuku" }+shizuku-provider = { module = "dev.rikka.shizuku:provider", version.ref = "shizuku" }androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "core-ktx" }androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activity-compose" }androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }diff --git a/docs/guide/faq.md b/docs/guide/faq.mdindex 0d9e30a..cb5b121 100644--- a/docs/guide/faq.md+++ b/docs/guide/faq.md@@ -44,6 +44,8 @@ No. Every everyday feature works at the default `Standard` power level using norIf 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.+If you already use [Shizuku](https://shizuku.rikka.app/), you can choose **Use Shizuku** instead (it shows when Shizuku's app is installed). Shizuku asks once whether NectarLink may use it; after that Elevated starts through Shizuku whenever it runs, with no pairing of its own, and keeps working away from Wi-Fi. The helper is the same and runs as the shell user. If Shizuku runs with root, NectarLink doesn't use it: start Shizuku through Wireless debugging, or choose **Use root**. After a restart, start Shizuku again, then open NectarLink once: Shizuku only tells apps it's running when they come to the front, and Elevated starts as soon as it hears.+### Why does Android 13+ gray out the Notification access or Accessibility switch ("Restricted settings")?Android 13 and newer block sideloaded APKs (apps installed outside an app store) from turning on Notification Listener or Accessibility services until you confirm in **App info**. Open **Android Settings › Apps › NectarLink**, tap the three-dot menu in the top-right corner, tap **Allow restricted settings**, verify with your fingerprint or PIN, and then return to NectarLink to turn the switch on.diff --git a/docs/technical/security-model.md b/docs/technical/security-model.mdindex 38ab45f..08fcd58 100644--- a/docs/technical/security-model.md+++ b/docs/technical/security-model.md@@ -12,6 +12,7 @@ For the full audit record and vulnerability remediation history, see [`docs/SECU| Compromised Relay Server (**Connect over mobile data** / `away_mode`) | Can observe outer UDP packet sizes/timing and drop traffic | End-to-end TLS 1.3 termination between peer `DeviceId` keys; relay never possesses session keys; high-risk capabilities (`storage` without `remote_files`) are blocked on `ConnectionPath::Relay` || Malicious Web Page on Local PC | Can send cross-origin `fetch` / `XMLHttpRequest` / `WebSocket` requests to `127.0.0.1:53320` | Local HTTP API is disabled by default; requires a 256-bit Bearer token in `Authorization` header (constant-time verified) and rejects any request carrying an `Origin` header or `Sec-Fetch-Mode: cors` / `no-cors` || Unprivileged Local App on Android | Can attempt to connect to local ports or read app storage | Elevated helper (`InputServer`) binds `127.0.0.1:<ephemeral_port>` and requires a 192-bit (24-byte / 48-hex-char) per-session `SecureRandom` token on the first line, verified in constant time (`MessageDigest.isEqual`) before accepting any commands |+| Another App Reaching NectarLink's Shizuku Service (Elevated through Shizuku, `elevated/ShizukuShell.kt`) | Gets hold of the Binder of the process Shizuku runs for NectarLink, as the shell user, and asks it to run commands | Shizuku hands that Binder only to NectarLink, and `ShizukuShell` answers only NectarLink's own UID and Shizuku's. It runs nothing it's given as a command line: only the grants Elevated needs for NectarLink's own package (`pm grant`, `appops set … allow`, `cmd notification allow_listener|allow_dnd`, checked word by word) as argument lists, and `InputServer` from NectarLink's own APK with a 48-hex token. It isn't used when Shizuku runs as root, and its process ends with NectarLink's || Offline Disk Inspection | Read access to `%LOCALAPPDATA%\Nectarlink` or Android app data directory | Private identity key (`identity.key`) and clipboard vault (`clipboard_history.enc`, `clipboard_images/*.enc`) are sealed using Windows DPAPI (`CryptProtectData`, tied to the Windows user logon credential) or Android Keystore AES-256-GCM (hardware-backed when supported by the device) || Paired Device Exceeding Intended Access | Attempts to invoke disabled capabilities, traverse outside shared paths, or start silent screen/input capture | Inbound dispatch enforces `CapabilityMatrix::is_allowed` per peer, canonicalizes file paths, and gates sensitive sessions (`pc_mirror`, `remote_input`, first-time `storage`, `webcam`) behind explicit user confirmation |