Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

feat: Elevated over USB

Beebd3c9b12abd7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cdb57d0..17c00b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,11 @@ change things that need a step from you, and its notes say so.
### New
+- **Elevated over USB.** Plug the phone into the PC with USB debugging
+ allowed and Elevated starts by itself, without setting up Wireless
+ debugging. It runs while the cable is in. The PC only starts NectarLink's
+ own helper, on the phone that asked
+ ([#70](https://github.com/thtbee/nectarlink/issues/70)).
- **The PC app on Linux**, for Ubuntu 24.04 or newer, Debian 13, Fedora 40
or newer and other distributions from 2024 on, as a `.deb`, an `.rpm`,
an AppImage or a tarball. It does what the Windows app does: notifications with
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index 10c7184..0ef13dd 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
@@ -859,6 +859,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
} else if (event.link is Link.Online) {
wakeTimers.remove(event.id)?.cancel()
retryWaitingRecordings(event.id)
+ // Plugged into a PC with USB debugging allowed: it can start Elevated.
+ if (!Elevated.running) scope.launch(Dispatchers.IO) { Elevated.startOverUsb() }
scope.launch(Dispatchers.Default) {
accent.syncNow()
}
@@ -1066,6 +1068,21 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
return node.mirrorOpenAudio(pcId)
}
+ /**
+ * Elevated over USB (`docs/protocol/elevated-usb.md`): asks each connected
+ * PC to start this phone's helper; only one it's plugged into with USB
+ * debugging allowed can. Returns the helper's port, or `null`.
+ */
+ suspend fun elevatedUsbStart(apk: String, token: String, grants: List<String>): Int? {
+ startJob?.join()
+ val node = node ?: return null
+ for (pc in _state.value.devices.filter { it.online }) {
+ val port = runCatching { node.elevatedUsbStart(pc.id, apk, token, grants) }.getOrNull()
+ if (port != null) return port.toInt()
+ }
+ return null
+ }
+
/** Accepted codecs from the connected PC; an unknown receiver gets H.264. */
suspend fun webcamCodecs(pcId: String): List<String> {
startJob?.join()
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
index 9c3ee32..a730e4e 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
@@ -348,7 +348,6 @@ object Elevated {
/** Connects and starts the input helper (when set up; again after it stopped). */
suspend fun start(): Boolean = withContext(Dispatchers.IO) {
held = 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)) {
@@ -362,6 +361,8 @@ object Elevated {
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
return@withLock false
}
@@ -383,6 +384,7 @@ object Elevated {
}
if (!connected) {
discardConnection()
+ if (startOverUsbLocked()) return@withLock true
_state.value = State.Waiting
return@withLock false
}
@@ -637,6 +639,36 @@ object Elevated {
return out.toString(Charsets.UTF_8.name())
}
+ /**
+ * Starts through a PC this phone is plugged into with USB debugging allowed
+ * (`docs/protocol/elevated-usb.md`), when Elevated isn't running. Called when
+ * a PC connects, so plugging in is enough.
+ */
+ suspend fun startOverUsb(): Boolean = withContext(Dispatchers.IO) {
+ if (held || running || BankingPause.isPaused(context)) return@withContext running
+ lock.withLock { running || startOverUsbLocked() }
+ }
+
+ /**
+ * Asks the PC this phone is plugged into to run the grants and start the
+ * helper over USB, then connects to it. The helper runs until the cable
+ * comes out (its socket then closes, see [connectSocketLocked]).
+ */
+ private suspend fun startOverUsbLocked(): Boolean {
+ val app = context.applicationContext as? app.nectarlink.android.NectarlinkApplication ?: return false
+ val token = ByteArray(24).also(SecureRandom()::nextBytes).joinToString("") { "%02x".format(it) }
+ val port = app.core.elevatedUsbStart(context.applicationInfo.sourceDir, token, grants()) ?: return false
+ return runCatching {
+ connectSocketLocked(port, token)
+ Log.i(TAG, "started over USB")
+ cancelRetry()
+ true
+ }.getOrElse {
+ Log.w(TAG, "the helper started over USB didn't answer", it)
+ false
+ }
+ }
+
/** Stops the helper and disconnects, and keeps it stopped until [start]. */
suspend fun stop() = withContext(Dispatchers.IO) {
held = true
diff --git a/core/nectarlink-adb/src/lib.rs b/core/nectarlink-adb/src/lib.rs
index 1ef820c..16f8999 100644
--- a/core/nectarlink-adb/src/lib.rs
+++ b/core/nectarlink-adb/src/lib.rs
@@ -188,6 +188,19 @@ fn is_bind_failure(reason: &str) -> bool {
reason.contains("cannot bind") || reason.contains("already in use")
}
+/// Runs `command` in a shell on `serial` (`adb -s <serial> shell <command>`)
+/// and returns the connection carrying its output. The command runs as long
+/// as the connection stays open; dropping it ends the command.
+pub async fn shell(server: SocketAddr, serial: &str, command: &str) -> Result<TcpStream, AdbError> {
+ if !is_serial_allowed(serial) {
+ return Err(AdbError::BlockedSerial(serial.to_owned()));
+ }
+ let mut stream = TcpStream::connect(server).await?;
+ send_command(&mut stream, &format!("host:transport:{serial}")).await?;
+ send_command(&mut stream, &format!("shell:{command}")).await?;
+ Ok(stream)
+}
+
/// Removes a TCP port forward (`adb -s <serial> forward --remove tcp:<local>`).
pub async fn kill_forward_tcp(server: SocketAddr, serial: &str, local_port: u16) -> Result<(), AdbError> {
if !is_serial_allowed(serial) {
@@ -342,6 +355,30 @@ emulator-5554 device product:sdk_gphone64_x86_64 model:Pixel_9 device:e
assert_eq!(commands.lock().unwrap().len(), 1, "a port the caller chose is not swapped");
}
+ #[tokio::test]
+ async fn shell_picks_the_device_then_streams_the_commands_output() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let transport = read_payload(&mut socket).await.unwrap();
+ socket.write_all(b"OKAY").await.unwrap();
+ let shell = read_payload(&mut socket).await.unwrap();
+ socket.write_all(b"OKAY").await.unwrap();
+ socket.write_all(b"ready 41234\n").await.unwrap();
+ (transport, shell)
+ });
+ let mut stream = shell(addr, "R5CT1234", "echo hi").await.unwrap();
+ let mut line = String::new();
+ tokio::io::AsyncBufReadExt::read_line(&mut tokio::io::BufReader::new(&mut stream), &mut line)
+ .await
+ .unwrap();
+ assert_eq!(line, "ready 41234\n");
+ let (transport, shell_cmd) = server.await.unwrap();
+ assert_eq!(transport, "host:transport:R5CT1234");
+ assert_eq!(shell_cmd, "shell:echo hi");
+ }
+
#[tokio::test]
async fn mock_adb_server_forward_killforward_and_track_devices() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
diff --git a/core/nectarlink-core/src/elevated_usb.rs b/core/nectarlink-core/src/elevated_usb.rs
new file mode 100644
index 0000000..9844460
--- /dev/null
+++ b/core/nectarlink-core/src/elevated_usb.rs
@@ -0,0 +1,158 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Elevated over USB (`docs/protocol/elevated-usb.md`).
+//!
+//! Elevated runs a small helper on the phone as Android's shell user. The
+//! phone normally starts it through its own wireless debugging; a phone
+//! plugged into a PC with USB debugging allowed can instead ask the PC to
+//! start it, the way scrcpy starts its server. The PC only runs the app's own
+//! helper and the app's own grants (checked in [`ElevatedUsbStart::is_valid`]),
+//! and only on the phone that asked, over that phone's own USB connection.
+//! The helper runs as long as the PC holds its adb shell: until the phone
+//! asks again, the cable comes out, or the node stops.
+
+use std::{net::SocketAddr, sync::Arc, time::Duration};
+
+use nectarlink_protocol::{
+ DeviceId, Envelope, ErrorCode,
+ messages::{ElevatedUsbReady, ElevatedUsbStart, elevated, types},
+};
+use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
+
+use crate::{
+ error::{Error, Result},
+ node::Shared,
+ session::Session,
+};
+
+/// How long one grant may take.
+const GRANT_TIMEOUT: Duration = Duration::from_secs(10);
+/// How long the helper may take to say it's listening.
+const READY_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// The phone's side: asks `session`'s PC to start this phone's helper and
+/// returns the port it listens on.
+pub(crate) async fn start(session: &Session, request: ElevatedUsbStart) -> Result<u16> {
+ if !request.is_valid() {
+ return Err(Error::Protocol("invalid Elevated over USB request".into()));
+ }
+ let env = Envelope::new(types::ELEVATED_USB_START, &request)?;
+ let reply = session.request(env, READY_TIMEOUT + GRANT_TIMEOUT * elevated::MAX_GRANTS as u32).await?;
+ let ready: ElevatedUsbReady = reply.expect_body(types::ELEVATED_USB_READY)?;
+ Ok(ready.port)
+}
+
+/// The PC's side of `elevated.usb.start`.
+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {
+ if env.t != types::ELEVATED_USB_START {
+ return Ok(false);
+ }
+ let peer = session.peer;
+ let request: ElevatedUsbStart = env.body()?;
+ let usb = shared.usb_serials.lock().unwrap_or_else(|e| e.into_inner()).get(&peer).cloned();
+ let refusal = if !request.is_valid() {
+ Some(Envelope::error(ErrorCode::BadMessage, "invalid Elevated over USB request"))
+ } else if !shared.we_offer(elevated::USB) {
+ Some(Envelope::error(ErrorCode::Unsupported, "this PC doesn't start Elevated over USB"))
+ } else if usb.is_none() {
+ Some(Envelope::error(ErrorCode::Unsupported, "this phone isn't connected to this PC over USB"))
+ } else {
+ None
+ };
+ if let Some(refusal) = refusal {
+ session.send(refusal.reply_to(env.id)).await?;
+ return Ok(true);
+ }
+ let Some((serial, adb_addr)) = usb else { return Ok(true) };
+ // Grants and the helper take seconds: answer from a task of its own.
+ let (shared, session, id) = (shared.clone(), session.clone(), env.id);
+ tokio::spawn(async move {
+ let reply = match launch(&shared, peer, adb_addr, &serial, &request).await {
+ Ok(port) => Envelope::new(types::ELEVATED_USB_READY, &ElevatedUsbReady { port })
+ .unwrap_or_else(|_| Envelope::error(ErrorCode::Internal, "can't answer")),
+ Err(reason) => {
+ tracing::info!(peer = %peer.short(), reason, "couldn't start Elevated over USB");
+ Envelope::error(ErrorCode::Internal, reason)
+ }
+ };
+ let _ = session.send(reply.reply_to(id)).await;
+ });
+ Ok(true)
+}
+
+/// Runs the grants, then starts the helper and keeps its shell open in a task
+/// stored for `peer`. Returns the helper's port.
+async fn launch(
+ shared: &Arc<Shared>,
+ peer: DeviceId,
+ adb_addr: SocketAddr,
+ serial: &str,
+ request: &ElevatedUsbStart,
+) -> std::result::Result<u16, String> {
+ for grant in &request.grants {
+ run_to_end(adb_addr, serial, grant).await?;
+ }
+ let command = helper_command(&request.apk, &request.token);
+ let stream = nectarlink_adb::shell(adb_addr, serial, &command).await.map_err(|e| e.to_string())?;
+ let mut output = BufReader::new(stream);
+ let mut first = String::new();
+ tokio::time::timeout(READY_TIMEOUT, output.read_line(&mut first))
+ .await
+ .map_err(|_| "the helper didn't start in time".to_owned())?
+ .map_err(|e| e.to_string())?;
+ let port = parse_ready(&first).ok_or_else(|| format!("the helper said {:?}", first.trim()))?;
+ // Holding the shell keeps the helper running; its output is only drained.
+ let keep = tokio::spawn(async move {
+ let mut sink = [0u8; 1024];
+ while matches!(output.read(&mut sink).await, Ok(n) if n > 0) {}
+ });
+ if let Some(old) = shared.usb_helpers.lock().unwrap_or_else(|e| e.into_inner()).insert(peer, keep) {
+ old.abort();
+ }
+ Ok(port)
+}
+
+/// Runs a short command and waits for it to finish.
+async fn run_to_end(adb_addr: SocketAddr, serial: &str, command: &str) -> std::result::Result<(), String> {
+ let mut stream = nectarlink_adb::shell(adb_addr, serial, command).await.map_err(|e| e.to_string())?;
+ let mut ignored = Vec::new();
+ tokio::time::timeout(GRANT_TIMEOUT, stream.read_to_end(&mut ignored))
+ .await
+ .map_err(|_| format!("{command:?} didn't finish"))?
+ .map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+/// The shell command that starts the helper (both parts already checked).
+fn helper_command(apk: &str, token: &str) -> String {
+ format!("CLASSPATH={apk} app_process /system/bin {} {token}", elevated::HELPER_CLASS)
+}
+
+/// The port from the helper's first line, `ready <port>`.
+fn parse_ready(line: &str) -> Option<u16> {
+ line.trim().strip_prefix("ready ")?.parse().ok().filter(|p| *p > 0)
+}
+
+/// Stops every helper started over USB (the node is stopping).
+pub(crate) fn stop_all(shared: &Shared) {
+ for (_, helper) in shared.usb_helpers.lock().unwrap_or_else(|e| e.into_inner()).drain() {
+ helper.abort();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_helper_command_and_its_answer() {
+ assert_eq!(
+ helper_command("/data/app/~~a==/app.nectarlink-b==/base.apk", "00ff"),
+ "CLASSPATH=/data/app/~~a==/app.nectarlink-b==/base.apk app_process /system/bin \
+ app.nectarlink.android.elevated.InputServer 00ff"
+ );
+ assert_eq!(parse_ready("ready 41234\n"), Some(41234));
+ assert_eq!(parse_ready("ready 0"), None);
+ assert_eq!(parse_ready("can't listen: denied"), None);
+ assert_eq!(parse_ready(""), None);
+ }
+}
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 2ba1c97..20e53c1 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -15,6 +15,7 @@ mod config;
mod contacts;
pub mod continuity_camera;
pub mod deck;
+pub(crate) mod elevated_usb;
mod error;
mod events;
pub mod features;
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index 458a0db..891e791 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -85,6 +85,8 @@ pub(crate) struct LocalState {
pub power: PowerLevel,
pub extra_capabilities: Vec<String>,
pub battery: Option<Battery>,
+ /// Watching adb for USB phones: can start a phone's Elevated helper over USB.
+ pub adb: bool,
}
impl LocalState {
@@ -98,6 +100,9 @@ impl LocalState {
caps.push(cap.clone());
}
}
+ if self.adb {
+ caps.push(nectarlink_protocol::messages::elevated::USB.to_owned());
+ }
caps
}
@@ -107,6 +112,7 @@ impl LocalState {
|| (cap == nectarlink_protocol::messages::continuity_camera::RECEIVE
&& !matches!(self.device.kind, DeviceKind::Phone | DeviceKind::Tablet))
|| self.extra_capabilities.iter().any(|c| c == cap)
+ || (self.adb && cap == nectarlink_protocol::messages::elevated::USB)
}
}
@@ -187,6 +193,10 @@ pub(crate) struct Shared {
pub(crate) usb_bridge_ports: Arc<Mutex<std::collections::HashSet<u16>>>,
/// Active USB tunnel peers mapped to their local UDP bridge address and cancellation token.
pub(crate) usb_peers: Arc<Mutex<HashMap<DeviceId, (SocketAddr, CancellationToken)>>>,
+ /// The adb serial (and adb server) each USB-tunnelled phone is on.
+ pub(crate) usb_serials: Mutex<HashMap<DeviceId, (String, SocketAddr)>>,
+ /// Elevated helpers started over USB, by phone: they run until dropped.
+ pub(crate) usb_helpers: Mutex<HashMap<DeviceId, tokio::task::JoinHandle<()>>>,
/// Peers whose USB tunnel this device accepted (a phone plugged into that PC).
pub(crate) usb_inbound: Mutex<std::collections::HashSet<DeviceId>>,
/// USB peers that are only paired by hand (Android emulators).
@@ -1529,6 +1539,7 @@ impl Node {
power: config.power,
extra_capabilities: config.capabilities.clone(),
battery: None,
+ adb: config.adb_server.is_some(),
}),
pairing: PairingState::default(),
cancel: CancellationToken::new(),
@@ -1563,6 +1574,8 @@ impl Node {
usb_listener_port: std::sync::atomic::AtomicU16::new(0),
usb_bridge_ports: Arc::new(Mutex::new(std::collections::HashSet::new())),
usb_peers: Arc::new(Mutex::new(HashMap::new())),
+ usb_serials: Mutex::new(HashMap::new()),
+ usb_helpers: Mutex::new(HashMap::new()),
usb_inbound: Mutex::new(std::collections::HashSet::new()),
usb_manual_pair: Mutex::new(std::collections::HashSet::new()),
usb_poke: Notify::new(),
@@ -1666,6 +1679,7 @@ impl Node {
/// Stops all sessions and networking.
pub async fn shutdown(&self) {
self.shared.cancel.cancel();
+ crate::elevated_usb::stop_all(&self.shared);
self.shared.localsend.stop(&self.shared);
let sessions: Vec<_> = lock(&self.shared.sessions).drain().map(|(_, s)| s).collect();
for session in sessions {
@@ -2700,6 +2714,24 @@ impl Node {
/// Asks a paired phone to stream its microphone; the phone asks its
/// user. Sound then arrives through [`Platform::mic_sink`](crate::Platform::mic_sink).
+ /// Asks `pc`, which this phone is plugged into over USB, to start this
+ /// phone's Elevated helper from `apk` with `token` after running `grants`
+ /// (`docs/protocol/elevated-usb.md`). Returns the helper's loopback port.
+ pub async fn elevated_usb_start(
+ &self,
+ pc: DeviceId,
+ apk: String,
+ token: String,
+ grants: Vec<String>,
+ ) -> Result<u16> {
+ let session = self.connected(&pc)?;
+ crate::elevated_usb::start(
+ &session,
+ nectarlink_protocol::messages::ElevatedUsbStart { apk, token, grants },
+ )
+ .await
+ }
+
pub async fn mic_start(&self, peer: DeviceId) -> Result<()> {
let session = self.connected(&peer)?;
crate::mic::start(&self.shared, &session).await
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index 3d1e0d0..33c748b 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -517,6 +517,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
t if t.starts_with("mirror.") && crate::mirror::handle(shared, session, &env).await? => {}
t if t.starts_with("webcam.") && crate::webcam::handle(shared, session, &env).await? => {}
t if t.starts_with("mic.") && crate::mic::handle(shared, session, &env).await? => {}
+ t if t.starts_with("elevated.usb") && crate::elevated_usb::handle(shared, session, &env).await? => {}
t if t.starts_with("camera.capture.")
&& crate::continuity_camera::handle(shared, session, &env).await? => {}
t if t.starts_with("remote.") && crate::remote::handle(shared, session, &env).await? => {}
diff --git a/core/nectarlink-core/src/usb.rs b/core/nectarlink-core/src/usb.rs
index 172efdf..582fcdf 100644
--- a/core/nectarlink-core/src/usb.rs
+++ b/core/nectarlink-core/src/usb.rs
@@ -375,7 +375,13 @@ async fn run_port_worker(
let mut answered = false;
if let Ok(host_port) = nectarlink_adb::forward_tcp(adb_addr, &serial, 0, phone_port).await {
let forwarded = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), host_port);
- let target = UsbTarget { phone_port, auto_pair: auto_pairs(&serial), profiles: profiles.clone() };
+ let target = UsbTarget {
+ phone_port,
+ auto_pair: auto_pairs(&serial),
+ profiles: profiles.clone(),
+ serial: serial.clone(),
+ adb_addr,
+ };
answered = run_forwarded_session(&shared, forwarded, &cancel, target).await;
let _ = nectarlink_adb::kill_forward_tcp(adb_addr, &serial, host_port).await;
}
@@ -399,6 +405,9 @@ struct UsbTarget {
phone_port: u16,
auto_pair: bool,
profiles: Arc<Mutex<SerialProfiles>>,
+ /// The phone's adb serial, so its Elevated helper can be started over USB.
+ serial: String,
+ adb_addr: SocketAddr,
}
/// Whether plugging in this device should start pairing on its own. Android
@@ -444,12 +453,22 @@ async fn run_forwarded_session(
let tunnel_cancel = cancel.child_token();
shared.register_usb_bridge_port(bridge_port);
+ shared
+ .usb_serials
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .insert(phone_id, (target.serial.clone(), target.adb_addr));
shared.on_usb_tunnel_connected(phone_id, phone_name, bridge_addr, tunnel_cancel.clone(), auto_pair);
let default_target = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), iroh_port);
relay_tcp_udp(stream, udp, default_target, tunnel_cancel).await;
target.profiles.lock().unwrap_or_else(|e| e.into_inner()).paired.remove(&target.phone_port);
+ shared.usb_serials.lock().unwrap_or_else(|e| e.into_inner()).remove(&phone_id);
+ // The cable is out: a helper started over it has stopped with it.
+ if let Some(helper) = shared.usb_helpers.lock().unwrap_or_else(|e| e.into_inner()).remove(&phone_id) {
+ helper.abort();
+ }
shared.unregister_usb_bridge_port(bridge_port);
shared.on_usb_tunnel_disconnected(phone_id, bridge_addr).await;
true
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 2806a0c..0a37a79 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -6442,3 +6442,23 @@ async fn notification_history_keeps_the_newest_thousand() {
assert!(history.iter().all(|n| n.key.as_str() >= "app|0005"), "the oldest five are gone");
phone.node.shutdown().await;
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn elevated_over_usb_is_refused_without_a_usb_connection() {
+ let mut pc = device("pc", DeviceKind::Desktop).await;
+ let mut phone = device("phone", DeviceKind::Phone).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let pc_id = pc.node.device_id();
+ let apk = "/data/app/~~a==/app.nectarlink-b==/base.apk".to_owned();
+ let token = "0123456789abcdef0123456789abcdef".to_owned();
+
+ // This PC doesn't watch adb, so it can't start anything over USB.
+ let refused = phone.node.elevated_usb_start(pc_id, apk.clone(), token.clone(), Vec::new()).await;
+ assert!(matches!(refused, Err(Error::Unsupported)), "{refused:?}");
+ // A request for anything but the app's own helper never leaves the phone.
+ let bad = phone.node.elevated_usb_start(pc_id, apk, token, vec!["reboot".into()]).await;
+ assert!(matches!(bad, Err(Error::Protocol(_))), "{bad:?}");
+
+ pc.node.shutdown().await;
+ phone.node.shutdown().await;
+}
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index 4fadcae..c4c6d5c 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -3375,6 +3375,20 @@ impl NectarlinkNode {
self.run(async move { Ok(node.unpair(id).await?) }).await
}
+ /// Asks a PC this phone is plugged into over USB to start this phone's
+ /// Elevated helper (`docs/protocol/elevated-usb.md`); returns its port.
+ pub async fn elevated_usb_start(
+ &self,
+ pc_id: String,
+ apk: String,
+ token: String,
+ grants: Vec<String>,
+ ) -> Result<u16> {
+ let id = parse_id(&pc_id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.elevated_usb_start(id, apk, token, grants).await?) }).await
+ }
+
pub async fn ring(&self, id: String, on: bool) -> Result<()> {
let id = parse_id(&id)?;
let node = self.node.clone();
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index 6a81925..39207a8 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -93,6 +93,8 @@ pub mod types {
pub const STORAGE_RENAME: &str = "storage.rename";
pub const STORAGE_DELETE: &str = "storage.delete";
pub const STORAGE_CHANGED: &str = "storage.changed";
+ pub const ELEVATED_USB_START: &str = "elevated.usb.start";
+ pub const ELEVATED_USB_READY: &str = "elevated.usb.ready";
pub const MIC_START: &str = "mic.start";
pub const MIC_STOP: &str = "mic.stop";
pub const WEBCAM_START: &str = "webcam.start";
@@ -1640,6 +1642,83 @@ impl MirrorAudioConfig {
// ---- Phone as webcam (docs/protocol/webcam.md) ----
/// Phone as microphone (`docs/protocol/mic.md`).
+/// Elevated over USB (`docs/protocol/elevated-usb.md`): a phone without
+/// wireless debugging asks the PC it's plugged into to start its Elevated
+/// helper over USB debugging.
+pub mod elevated {
+ /// Offered by PCs that can start a USB-connected phone's helper.
+ pub const USB: &str = "elevated.usb";
+ /// The only package the PC runs anything for.
+ pub const PACKAGE: &str = "app.nectarlink";
+ /// The helper the PC starts, with `app_process`.
+ pub const HELPER_CLASS: &str = "app.nectarlink.android.elevated.InputServer";
+ /// Grants a request may carry, at most.
+ pub const MAX_GRANTS: usize = 8;
+}
+
+/// Body of `elevated.usb.start`: start the helper from `apk` with `token`,
+/// after running `grants` (each one of the phone's own, see [`is_valid_grant`]).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ElevatedUsbStart {
+ pub apk: String,
+ pub token: String,
+ #[serde(default)]
+ pub grants: Vec<String>,
+}
+
+impl ElevatedUsbStart {
+ pub fn is_valid(&self) -> bool {
+ is_valid_app_apk(&self.apk)
+ && (32..=64).contains(&self.token.len())
+ && self.token.bytes().all(|b| b.is_ascii_hexdigit())
+ && self.grants.len() <= elevated::MAX_GRANTS
+ && self.grants.iter().all(|g| is_valid_grant(g))
+ }
+}
+
+/// Body of `elevated.usb.ready`: the helper listens on this loopback port.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ElevatedUsbReady {
+ pub port: u16,
+}
+
+/// Characters a path or command the PC passes to the phone's shell may use:
+/// nothing the shell would read as more than a word.
+fn is_shell_word(s: &str) -> bool {
+ !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"._/=~+-:".contains(&b))
+}
+
+/// The app's own installed APK (`pm path` gives `/data/app/<...>/base.apk`).
+pub fn is_valid_app_apk(apk: &str) -> bool {
+ apk.len() <= 512
+ && apk.starts_with("/data/app/")
+ && apk.ends_with("/base.apk")
+ && !apk.contains("..")
+ && apk.contains(elevated::PACKAGE)
+ && is_shell_word(apk)
+}
+
+/// A grant the phone may ask for itself, and nothing else: a permission or
+/// app op for NectarLink's own package, or its own notification listener.
+pub fn is_valid_grant(grant: &str) -> bool {
+ let words: Vec<&str> = grant.split(' ').collect();
+ if !words.iter().all(|w| is_shell_word(w)) {
+ return false;
+ }
+ let pkg = elevated::PACKAGE;
+ match words.as_slice() {
+ ["pm", "grant", p, perm] => *p == pkg && perm.starts_with("android.permission."),
+ ["appops", "set", p, op, "allow"] => {
+ *p == pkg && op.bytes().all(|b| b.is_ascii_uppercase() || b == b'_')
+ }
+ ["cmd", "notification", "allow_dnd", p] => *p == pkg,
+ ["cmd", "notification", "allow_listener", component] => {
+ component.strip_prefix(pkg).is_some_and(|rest| rest.starts_with('/'))
+ }
+ _ => false,
+ }
+}
+
pub mod mic {
/// Offered by phones that stream their microphone.
pub const STREAM: &str = "mic.stream";
@@ -4181,6 +4260,50 @@ mod tests {
}
}
+ #[test]
+ fn elevated_usb_only_runs_the_apps_own_helper_and_grants() {
+ let apk = "/data/app/~~kG3x_Q==/app.nectarlink-Ab1-cD2==/base.apk";
+ let start = ElevatedUsbStart {
+ apk: apk.into(),
+ token: "0123456789abcdef0123456789abcdef0123456789abcdef".into(),
+ grants: vec![
+ "pm grant app.nectarlink android.permission.WRITE_SECURE_SETTINGS".into(),
+ "appops set app.nectarlink RECEIVE_SENSITIVE_NOTIFICATIONS allow".into(),
+ "cmd notification allow_dnd app.nectarlink".into(),
+ "cmd notification allow_listener app.nectarlink/app.nectarlink.android.notifications.NotificationListener"
+ .into(),
+ ],
+ };
+ assert!(start.is_valid());
+
+ for apk in [
+ "/data/app/other.app-1/base.apk",
+ "/sdcard/app.nectarlink/base.apk",
+ "/data/app/app.nectarlink-1/../../evil/base.apk",
+ "/data/app/app.nectarlink-1/base.apk; reboot",
+ "/data/app/app.nectarlink-1/base.apk$(id)",
+ ] {
+ assert!(!ElevatedUsbStart { apk: apk.into(), ..start.clone() }.is_valid(), "{apk}");
+ }
+ for grant in [
+ "pm grant com.other android.permission.WRITE_SECURE_SETTINGS",
+ "pm grant app.nectarlink android.permission.X; rm -rf /sdcard",
+ "pm grant app.nectarlink android.permission.X && reboot",
+ "appops set app.nectarlink.evil SYSTEM_ALERT_WINDOW allow",
+ "cmd notification allow_listener com.other/x.Listener",
+ "cmd notification allow_dnd com.other",
+ "settings put global adb_enabled 1",
+ "reboot",
+ ] {
+ assert!(!ElevatedUsbStart { grants: vec![grant.into()], ..start.clone() }.is_valid(), "{grant}");
+ }
+ assert!(
+ !ElevatedUsbStart { token: "not-hex-token-not-hex-token-not-hex".into(), ..start.clone() }
+ .is_valid()
+ );
+ assert!(!ElevatedUsbStart { grants: vec![start.grants[0].clone(); 9], ..start }.is_valid());
+ }
+
#[test]
fn device_names_are_cleaned_and_capped() {
assert_eq!(info().sanitized(), info(), "ordinary info is unchanged");
diff --git a/desktop/app/qml/components/LockChip.qml b/desktop/app/qml/components/LockChip.qml
index 584a41e..bd092ee 100644
--- a/desktop/app/qml/components/LockChip.qml
+++ b/desktop/app/qml/components/LockChip.qml
@@ -45,7 +45,7 @@ Rectangle {
case "assist":
return qsTr("On your phone, open NectarLink › Settings › Control from your PC and turn on the Accessibility service.")
case "elevated":
- return qsTr("Needs Elevated: on your phone, open NectarLink › Settings › Control from your PC and set up Wireless debugging.")
+ return qsTr("Needs Elevated: set up Wireless debugging in NectarLink › Settings › Control from your PC, or connect the phone over USB with USB debugging allowed.")
case "role":
return qsTr("On your phone, set NectarLink as the default SMS/Caller ID app when prompted.")
case "permission":
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index 3199487..e4b9287 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -55,6 +55,7 @@ capability is missing.
| `clip.share` | Sends the clipboard when the user taps "Send" | app update |
| `clip.read.auto` | Sends clipboard changes automatically, in the background | Elevated |
| `photos.read` | Announces new photos and screenshots, lists albums and items, serves thumbnails, and sends files on request ([photos](photos.md)) | photos permission |
+| `elevated.usb` | Starts a USB-connected phone's Elevated helper over adb ([Elevated over USB](elevated-usb.md)) | adb on the PC |
| `mirror.capture` | Streams its screen (with the system's capture prompt at Basic; [mirroring](mirror.md)) | app update |
| `mirror.input` | Accepts touch, key and scroll input while mirrored | Assist |
| `mirror.virtual_display` | Runs apps on displays of their own, shown in windows on the PC ([mirroring](mirror.md)) | Elevated, Android 11+ |
diff --git a/docs/protocol/elevated-usb.md b/docs/protocol/elevated-usb.md
new file mode 100644
index 0000000..24ae981
--- /dev/null
+++ b/docs/protocol/elevated-usb.md
@@ -0,0 +1,52 @@
+# Elevated over USB
+
+> Status: draft (v0). Part of [the protocol](v0.md). Breaking changes are
+> allowed until v1. License: CC BY 4.0.
+
+Elevated runs a small helper on the phone as Android's shell user
+(`app_process`, from the app's own APK). The phone normally starts it through
+its own wireless debugging. A phone plugged into a PC with USB debugging
+allowed can instead ask that PC to start it, the way scrcpy starts its server.
+
+## 1. Capability
+
+| Capability | Offered by | Meaning |
+|---|---|---|
+| `elevated.usb` | PC | Can start a USB-connected phone's helper over adb |
+
+A PC offers it while it watches adb for USB phones.
+
+## 2. Messages
+
+```
+t = "elevated.usb.start" id = n b = { apk: text, token: text, grants: [text] }
+t = "elevated.usb.ready" id = n b = { port: uint }
+```
+
+The phone sends `elevated.usb.start`. The PC:
+
+1. Refuses unless the request is valid (§3) and the phone is connected to it
+ over USB, through that phone's own adb serial.
+2. Runs each grant in the phone's shell, waiting up to 10 seconds for each.
+3. Runs `CLASSPATH=<apk> app_process /system/bin
+ app.nectarlink.android.elevated.InputServer <token>` and waits up to 15
+ seconds for its first line, `ready <port>`.
+4. Answers `elevated.usb.ready` with that port, or an error.
+
+The phone connects to the helper on `127.0.0.1:<port>` with the token, as when
+it starts the helper itself. The helper runs while the PC holds its adb shell:
+until the phone asks again, the USB tunnel ends, or the PC's node stops.
+
+## 3. What the PC accepts
+
+The PC runs nothing but the app's own helper and grants, and only words the
+shell reads as single words (letters, digits and `._/=~+-:`):
+
+- `apk`: a path under `/data/app/` ending in `/base.apk`, containing
+ `app.nectarlink`, without `..`, at most 512 bytes.
+- `token`: 32 to 64 hexadecimal characters.
+- `grants`: at most 8, each one of:
+ - `pm grant app.nectarlink android.permission.<NAME>`
+ - `appops set app.nectarlink <OP> allow` (`OP` in capitals and `_`)
+ - `cmd notification allow_dnd app.nectarlink`
+ - `cmd notification allow_listener app.nectarlink/<component>`