A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.
Rust
feat: add opt-in read-only root scanning (#25)
Vishnu Srivatsava8b177e57e9d1
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 017860e..aa8ddd8 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -74,6 +74,10 @@ jobs:if: runner.os != 'Windows'run: python3 -m unittest discover -s tests -v+ - name: Test root scans in a disposable Linux filesystem+ if: runner.os == 'Linux'+ run: sudo -n env CXX=g++ python3 -m unittest discover -s tests -p test_root_scan.py -v+# ── Cross-compile C++ daemon for Android aarch64 ──────────────────────# The daemon always targets Android ARM64, regardless of host OS.# Uses the pre-installed Android NDK on GitHub Actions runners.diff --git a/README.md b/README.mdindex 63439f3..55b0fda 100644--- a/README.md+++ b/README.md@@ -99,6 +99,35 @@ Go to **Settings → About Phone → tap "Build Number" 7 times** to unlock DeveThat's it. No apps to install on your phone, no Wi-Fi setup, no root required.+### Optional: scan with root access++This option is included in source builds and the next release; v1.1.1 does not+expose it.++On an already-rooted device, enable **Scan with root access (read-only)** before+connecting. Choose **App and user data (`/data`)** to include private app files,+**Internal data and system (`/`)** for a broader internal scan, or **Shared storage+(`/sdcard`)**. Rescan keeps the current scan location.++SocketSweep uses an already-root ADB shell when available; otherwise it requests+access through `su`. Approve shell access in your phone's root manager when+prompted. On supported debug builds, you can run `adb root` yourself before+connecting. SocketSweep does not restart ADB or root your device, and refuses a+root session unless the daemon confirms UID 0 and read-only mode.++Root scans disable deletion in the UI, bridge, and daemon. A daemon running as+root is always read-only, even if the root option was left off. Disconnect and+use an ordinary non-root ADB shell to restore the normal shared-storage workflow.++The internal `/` scan excludes `/proc`, `/sys`, `/dev`, `/mnt`, `/storage`,+`/data_mirror`, and `/apex` to avoid virtual files and duplicate views of storage.+It includes internal shared media through `/data/media`; removable storage is+outside this scan's scope. Virtual filesystems are skipped elsewhere too, and+files or directories with the same device/inode identity are counted once per+root scan. Symlinks are not followed below the scan root. Totals use logical file+sizes, rather than allocated blocks, so they need not match `du` or Android's+storage screen exactly. Access errors and excluded entries are shown in results.+---## 🧠 How It Works (The Short Version)@@ -205,7 +234,7 @@ bash ./build.sh```*This generates the stripped `daemon` binary in the `engine/` directory andcopies it into `src-tauri/bin/daemon`, which Tauri bundles. Rebuild after changing-the daemon so local development uses the current protocol.*+the daemon so local development uses the current protocol (v3).*### 2. Install Frontend Dependencies```bashdiff --git a/engine/daemon.cpp b/engine/daemon.cppindex 5537625..888c287 100644--- a/engine/daemon.cpp+++ b/engine/daemon.cpp@@ -11,6 +11,11 @@#include <cerrno>#include <string>#include <vector>+#include <set>+#if defined(__linux__)+#include <linux/magic.h>+#include <sys/vfs.h>+#endif#include <arpa/inet.h>#include <dirent.h>@@ -41,6 +46,7 @@ static volatile sig_atomic_t g_running = 1;static void on_signal(int) { g_running = 0; }static safe_delete::Root g_scan_root; // pins the successful scan root for deletionstatic std::string g_session_token;+static bool g_read_only = false;// Per-phase scan timing (see SCAN in handle_client). Counters reset per scan.static int64_t g_sort_ns = 0; // cumulative time sorting directory children@@ -142,6 +148,8 @@ struct ScanStats {int64_t dirs = 0;int64_t total_size = 0;int64_t errors = 0;+ int64_t skipped = 0;+ std::set<std::pair<dev_t, ino_t>> seen;};// ── JSON helpers ────────────────────────────────────────────────────────────@@ -190,6 +198,35 @@ static void serialize_node(JsonStream& out, const FileNode& node) {}// ── Recursive Scanner ───────────────────────────────────────────────────────+static bool virtual_filesystem(const std::string& path) {+#if defined(__linux__)+ struct statfs fs{};+ if (::statfs(path.c_str(), &fs) != 0) return false; // traversal reports access errors+ switch (static_cast<unsigned long>(fs.f_type)) {+ case PROC_SUPER_MAGIC: case SYSFS_MAGIC: case DEVPTS_SUPER_MAGIC:+ case CGROUP_SUPER_MAGIC: case CGROUP2_SUPER_MAGIC: case DEBUGFS_MAGIC:+ case TRACEFS_MAGIC: case SECURITYFS_MAGIC: case SELINUX_MAGIC:+ case BPF_FS_MAGIC: case NSFS_MAGIC:+ return true;+ default: return false;+ }+#else+ (void)path;+ return false;+#endif+}++static bool root_mount_alias(const char* name) {+ // /data/media is the canonical internal media tree. FUSE views can have+ // different device/inode identities, so inode deduplication alone cannot+ // prevent them being counted again through /mnt or /storage. APEX images+ // are already represented by their package files on /system or /data.+ return std::strcmp(name, "mnt") == 0 || std::strcmp(name, "storage") == 0 ||+ std::strcmp(name, "data_mirror") == 0 || std::strcmp(name, "apex") == 0 ||+ std::strcmp(name, "proc") == 0 || std::strcmp(name, "sys") == 0 ||+ std::strcmp(name, "dev") == 0;+}+static FileNode scan(const std::string& path, const std::string& name,ScanStats& st, int depth){@@ -205,6 +242,15 @@ static FileNode scan(const std::string& path, const std::string& name,}if (depth > 0 && S_ISLNK(info.st_mode)) return node;+ node.is_dir = S_ISDIR(info.st_mode);++ if (g_read_only && (S_ISREG(info.st_mode) || S_ISDIR(info.st_mode))) {+ if ((S_ISDIR(info.st_mode) && virtual_filesystem(path)) ||+ !st.seen.emplace(info.st_dev, info.st_ino).second) {+ ++st.skipped;+ return node;+ }+ }if (S_ISREG(info.st_mode)) {node.size = info.st_size;@@ -234,7 +280,11 @@ static FileNode scan(const std::string& path, const std::string& name,if (ent->d_type == DT_LNK) continue;#endif- std::string child_path = path + '/' + ent->d_name;+ if (g_read_only && path == "/" && root_mount_alias(ent->d_name)) {+ ++st.skipped;+ continue;+ }+ std::string child_path = (path == "/" ? path : path + '/') + ent->d_name;FileNode child = scan(child_path, ent->d_name, st, depth + 1);node.size += child.size;@@ -272,7 +322,11 @@ static void handle_client(int fd) {}if (cmd == "PING") {- out.write("{\"status\":\"ok\",\"message\":\"pong\",\"protocol_version\":2}\n");+ out.write("{\"status\":\"ok\",\"message\":\"pong\",\"protocol_version\":3,\"uid\":");+ out.write(std::to_string(::geteuid()));+ out.write(",\"read_only\":");+ out.write(g_read_only ? "true" : "false");+ out.write("}\n");}else if (cmd == "SHUTDOWN") {out.write("{\"status\":\"ok\",\"message\":\"shutting down\"}\n");@@ -281,6 +335,10 @@ static void handle_client(int fd) {return;}else if (cmd.rfind("DELETE ", 0) == 0) {+ if (g_read_only) {+ out.write("{\"status\":\"error\",\"message\":\"Root scans are read-only; deletion is disabled\"}\n");+ return;+ }std::string target = cmd.substr(7);const auto result = safe_delete::remove(g_scan_root, target, cfg::MAX_DEPTH);@@ -305,6 +363,22 @@ static void handle_client(int fd) {}while (root.size() > 1 && root.back() == '/') root.pop_back();+ if (g_read_only) {+ // Resolve aliases once so /./ or a symlink to / cannot bypass the+ // whole-device exclusions. Read-only scans never enable deletion.+ char* canonical = ::realpath(root.c_str(), nullptr);+ if (!canonical) {+ out.write("{\"status\":\"error\",\"message\":\"Scan root is not an accessible directory\"}\n");+ return;+ }+ root = canonical;+ std::free(canonical);+ if (virtual_filesystem(root)) {+ out.write("{\"status\":\"error\",\"message\":\"Virtual filesystems are excluded from root scans\"}\n");+ return;+ }+ }+std::string root_name = root;auto pos = root.rfind('/');if (pos != std::string::npos && pos + 1 < root.size())@@ -353,6 +427,10 @@ static void handle_client(int fd) {out.write(std::to_string(stats.total_size));out.write(",\"errors\":");out.write(std::to_string(stats.errors));+ out.write(",\"skipped\":");+ out.write(std::to_string(stats.skipped));+ out.write(",\"read_only\":");+ out.write(g_read_only ? "true" : "false");out.write(",\"tree\":");serialize_node(out, tree);@@ -393,10 +471,12 @@ int main(int argc, char* argv[]) {// A shell-owned 0600 file supplies the secret, keeping it out of process// arguments. Consume and unlink it before accepting any connections.- if (argc != 3) {- std::fprintf(stderr, "[engine] Usage: daemon PORT TOKEN_FILE\n");+ if (argc != 3 && !(argc == 4 && std::strcmp(argv[3], "--read-only") == 0)) {+ std::fprintf(stderr, "[engine] Usage: daemon PORT TOKEN_FILE [--read-only]\n");return 1;}+ // Even an already-root ADB shell using the default launch cannot delete.+ g_read_only = argc == 4 || ::geteuid() == 0;{std::ifstream token_file(argv[2]);std::getline(token_file, g_session_token);diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 988706f..aca30b9 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -7,7 +7,7 @@//// Wire protocol (matches Phase 1 daemon):// Each connection starts with "AUTH <session token>\n", then one command.-// → "PING\n" ← {"status":"ok","message":"pong","protocol_version":2}+// → "PING\n" ← {"status":"ok","protocol_version":3,"uid":…,"read_only":…}// → "SCAN [path]\n" ← {"status":"ok","scan_time_ms":…,"tree":{…}}// → "SHUTDOWN\n" ← {"status":"ok","message":"shutting down"}// ============================================================================@@ -33,9 +33,45 @@ static SCAN_ROOT: Mutex<Option<String>> = Mutex::new(None);/// Tracks the serial of the connected device so all ADB calls target the right device.static DEVICE_SERIAL: Mutex<Option<String>> = Mutex::new(None);static SESSION_TOKEN: Mutex<Option<String>> = Mutex::new(None);+static READ_ONLY: Mutex<bool> = Mutex::new(false);+static DEVICE_PRIVILEGE: Mutex<Privilege> = Mutex::new(Privilege::Shell);// Keep connection changes, scans, and deletes in order across async commands.static DAEMON_OPERATION: Mutex<()> = Mutex::new(());+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Privilege {+ Shell,+ Su,+}++fn select_privilege(+ root_mode: bool,+ mut execute: impl FnMut(&[&str]) -> Result<String, String>,+) -> Result<Privilege, String> {+ if !root_mode {+ return Ok(Privilege::Shell);+ }+ if execute(&["shell", "id -u"])?.trim() == "0" {+ return Ok(Privilege::Shell); // adbd was already started as root+ }+ if execute(&["shell", "su -c 'id -u'"]).is_ok_and(|uid| uid.trim() == "0") {+ return Ok(Privilege::Su);+ }+ Err("Root access was not granted. Approve shell access in your phone's root manager and retry, or use adb root on a supported debug build before connecting.".into())+}++fn device_shell_command(privilege: Privilege, command: &str) -> String {+ match privilege {+ Privilege::Shell => command.to_string(),+ Privilege::Su => format!("su -c '{}'", command.replace('\'', "'\\''")),+ }+}++fn device_shell(adb_path: &std::path::Path, command: &str) -> Result<String, String> {+ let privilege = *DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")?;+ adb_s(adb_path, &["shell", &device_shell_command(privilege, command)])+}+// ── Resource Resolution ─────────────────────────────────────────────────────use tauri::Manager;@@ -215,6 +251,22 @@ struct DaemonStatus {status: String,message: Option<String>,protocol_version: Option<u32>,+ uid: Option<u32>,+ read_only: Option<bool>,+}++fn require_handshake(response: &str, root_mode: bool) -> Result<DaemonStatus, String> {+ let parsed = require_ok(response)?;+ if parsed.protocol_version != Some(3) || parsed.uid.is_none() || parsed.read_only.is_none() {+ return Err("Bundled daemon is outdated. Rebuild it before connecting.".into());+ }+ if (root_mode && parsed.uid != Some(0)) || (parsed.uid == Some(0) && parsed.read_only != Some(true)) {+ return Err("Daemon did not start with read-only root access.".into());+ }+ if root_mode && parsed.read_only != Some(true) {+ return Err("Root scans must be read-only.".into());+ }+ Ok(parsed)}fn require_ok(response: &str) -> Result<DaemonStatus, String> {@@ -244,29 +296,36 @@ fn check_adb(app: tauri::AppHandle) -> Result<String, String> {}#[tauri::command(async)]-fn init_daemon(app: tauri::AppHandle) -> Result<String, String> {+fn init_daemon(app: tauri::AppHandle, root_mode: Option<bool>) -> Result<String, String> {let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;+ let has_session = DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")?.is_some();+ if has_session {+ stop_daemon_inner(&app)?;+ }*SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")? = None;*SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;*DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")? = None;- let result = init_daemon_inner(app.clone());+ *READ_ONLY.lock().map_err(|_| "Session state is unavailable")? = false;+ *DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")? = Privilege::Shell;+ let result = init_daemon_inner(app.clone(), root_mode.unwrap_or(false));if result.is_err() {// A failed push/start/handshake must not leave a live daemon or a// startup secret behind. Only target the device selected by this init.let has_device = DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")?.is_some();if has_device {if let Ok(adb_path) = get_bundled_binary(&app, "adb") {- let _ = adb_s(&adb_path, &["shell", "pkill -f '[s]ocketsweep_daemon' || true"]);+ let _ = device_shell(&adb_path, "pkill -f '[s]ocketsweep_daemon' || true");let _ = adb_s(&adb_path, &["forward", "--remove", &format!("tcp:{DAEMON_PORT}")]);let _ = adb_s(&adb_path, &["shell", "rm", "-f", DEVICE_TOKEN_PATH]);}}*DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")? = None;+ *DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")? = Privilege::Shell;}result}-fn init_daemon_inner(app: tauri::AppHandle) -> Result<String, String> {+fn init_daemon_inner(app: tauri::AppHandle, root_mode: bool) -> Result<String, String> {let adb_path = get_bundled_binary(&app, "adb")?;let daemon_src = get_bundled_binary(&app, "daemon")?;@@ -295,8 +354,12 @@ fn init_daemon_inner(app: tauri::AppHandle) -> Result<String, String> {*guard = Some(serial);}+ let privilege = select_privilege(root_mode, |args| adb_s(&adb_path, args))?;+ *DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")? = privilege;+// 2 — Kill any zombie daemon before we push/start.- let _ = adb_s(&adb_path, &["shell", "pkill -f '[s]ocketsweep_daemon' || true"]);+ device_shell(&adb_path, "pkill -f '[s]ocketsweep_daemon' || true")?;+ std::thread::sleep(Duration::from_millis(300));// Transfer the fresh secret over stdin into a shell-owned file. Neither// the startup arguments nor the frontend response contain the secret.@@ -315,14 +378,11 @@ fn init_daemon_inner(app: tauri::AppHandle) -> Result<String, String> {// 5 — Make it executable.adb_s(&adb_path, &["shell", "chmod", "+x", DEVICE_BIN_PATH])?;- // 5 — Kill any previously running instance (ignore errors).- let _ = adb_s(&adb_path, &["shell", "pkill", "-f", "'[s]ocketsweep_daemon'"]);- std::thread::sleep(Duration::from_millis(300));-// 6 — Start the daemon in the background on the device.- let start_cmd = format!("nohup {DEVICE_BIN_PATH} {DAEMON_PORT} {DEVICE_TOKEN_PATH} > /dev/null 2>&1 & echo $!; exit");- let pid_output = adb_s(&adb_path, &["shell", &start_cmd])?;- let pid = pid_output.trim().to_string();+ let mode_arg = if root_mode { " --read-only" } else { "" };+ let start_cmd = format!("nohup {DEVICE_BIN_PATH} {DAEMON_PORT} {DEVICE_TOKEN_PATH}{mode_arg} > /dev/null 2>&1 & echo $!; exit");+ let pid_output = device_shell(&adb_path, &start_cmd)?;+ let pid: u32 = pid_output.trim().parse().map_err(|_| "Daemon launch did not return a process ID")?;// 7 — Set up the USB TCP tunnel.adb_s(&adb_path, &["forward", &format!("tcp:{DAEMON_PORT}"), &format!("tcp:{DAEMON_PORT}")])?;@@ -330,13 +390,11 @@ fn init_daemon_inner(app: tauri::AppHandle) -> Result<String, String> {// 8 — Ping-Retry loop.let mut pong = String::new();let mut connected_daemon = false;+ let mut handshake_error = String::new();for _ in 0..15 {std::thread::sleep(Duration::from_millis(150));match daemon_command_with_token("PING", &token).and_then(|res| {- let parsed = require_ok(&res)?;- if parsed.protocol_version != Some(2) {- return Err("Bundled daemon is outdated. Rebuild it before connecting.".into());- }+ require_handshake(&res, root_mode)?;Ok(res)}) {Ok(res) => {@@ -344,15 +402,19 @@ fn init_daemon_inner(app: tauri::AppHandle) -> Result<String, String> {connected_daemon = true;break;}- Err(_) => continue,+ Err(error) => {+ handshake_error = error;+ continue;+ }}}if !connected_daemon {- return Err("Daemon did not complete the authenticated handshake. Rebuild the bundled daemon and reconnect.".into());+ return Err(format!("Daemon did not complete the authenticated handshake: {handshake_error}"));}*SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")? = Some(token);+ *READ_ONLY.lock().map_err(|_| "Session state is unavailable")? = require_handshake(&pong, root_mode)?.read_only.unwrap();Ok(format!("{{\"daemon_pid\":\"{pid}\",\"ping_response\":{pong}}}"@@ -388,19 +450,34 @@ fn ping_daemon() -> Result<String, String> {#[tauri::command(async)]fn stop_daemon(app: tauri::AppHandle) -> Result<String, String> {let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;- let adb_path = get_bundled_binary(&app, "adb")?;- let response = daemon_command("SHUTDOWN").unwrap_or_else(|_| "daemon already stopped".into());- let _ = adb_s(&adb_path, &["forward", "--remove", &format!("tcp:{DAEMON_PORT}")]);- let _ = adb_s(&adb_path, &["shell", "rm", "-f", DEVICE_BIN_PATH, DEVICE_TOKEN_PATH]);+ stop_daemon_inner(&app)+}++fn stop_daemon_inner(app: &tauri::AppHandle) -> Result<String, String> {+ let adb_path = get_bundled_binary(app, "adb")?;+ let response = daemon_command("SHUTDOWN");+ let has_device = DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")?.is_some();+ if has_device {+ if response.is_err() {+ let _ = device_shell(&adb_path, "pkill -f '[s]ocketsweep_daemon' || true");+ }+ let _ = adb_s(&adb_path, &["forward", "--remove", &format!("tcp:{DAEMON_PORT}")]);+ let _ = adb_s(&adb_path, &["shell", "rm", "-f", DEVICE_BIN_PATH, DEVICE_TOKEN_PATH]);+ }*SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")? = None;*SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;*DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")? = None;- Ok(response)+ *DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")? = Privilege::Shell;+ *READ_ONLY.lock().map_err(|_| "Session state is unavailable")? = false;+ Ok(response.unwrap_or_else(|_| "daemon already stopped".into()))}#[tauri::command(async)]fn delete_item(path: String) -> Result<String, String> {let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;+ if *READ_ONLY.lock().map_err(|_| "Session state is unavailable")? {+ return Err("Root scans are read-only; deletion is disabled.".into());+ }// Prevent deletion of the scan root directory.let root = SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")?;match root.as_ref() {@@ -436,6 +513,44 @@ pub fn run() {mod tests {use super::*;+ #[test]+ fn root_access_is_explicit_and_verified_without_restarting_adbd() {+ assert_eq!(select_privilege(false, |_| panic!("Normal mode must not request root")).unwrap(), Privilege::Shell);+ assert_eq!(select_privilege(true, |args| {+ assert_eq!(args, ["shell", "id -u"]);+ Ok("0\n".into())+ }).unwrap(), Privilege::Shell);+ let mut calls = Vec::new();+ assert_eq!(select_privilege(true, |args| {+ calls.push(args.join(" "));+ Ok(if calls.len() == 1 { "2000\n" } else { "0\n" }.into())+ }).unwrap(), Privilege::Su);+ assert_eq!(calls, ["shell id -u", "shell su -c 'id -u'"]);+ assert!(select_privilege(true, |_| Ok("2000\n".into())).is_err());+ assert!(select_privilege(true, |_| Err("permission denied".into())).is_err());+ }++ #[test]+ fn root_handshake_rejects_wrong_uid_writable_daemon_and_old_protocol() {+ let response = |version, uid, read_only| format!("{{\"status\":\"ok\",\"protocol_version\":{version},\"uid\":{uid},\"read_only\":{read_only}}}");+ assert!(require_handshake(&response(3, 0, true), true).is_ok());+ assert!(require_handshake(&response(3, 2000, false), false).is_ok());+ assert!(require_handshake(&response(3, 0, true), false).is_ok());+ assert!(require_handshake(&response(3, 2000, true), true).is_err());+ assert!(require_handshake(&response(3, 0, false), true).is_err());+ assert!(require_handshake(&response(3, 0, false), false).is_err());+ assert!(require_handshake(&response(2, 0, true), true).is_err());+ assert!(require_handshake("{\"status\":\"ok\",\"protocol_version\":3}", true).is_err());+ }++ #[test]+ fn su_wraps_the_complete_shell_command_without_exposing_its_quotes() {+ let command = "pkill -f '[s]ocketsweep_daemon' || true";+ assert_eq!(device_shell_command(Privilege::Shell, command), command);+ let wrapped = device_shell_command(Privilege::Su, command);+ assert_eq!(wrapped, "su -c 'pkill -f '\\''[s]ocketsweep_daemon'\\'' || true'");+ }+#[test]fn paths_keep_their_exact_spaces() {assert_eq!(command_payload("DELETE /sdcard/ report ", "token").unwrap(),diff --git a/src/App.tsx b/src/App.tsxindex b9e2070..ab47839 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -20,6 +20,8 @@ interface ScanResponse {total_dirs: number;total_size: number;errors: number;+ read_only: boolean;+ skipped: number;/** Per-phase timings from daemon v1.2+ (issue #3); absent in older daemons. */traverse_ms?: number;sort_ms?: number;@@ -252,7 +254,14 @@ function TerminalLog({ logs }: { logs: string[] }) {// ── Setup Screen ────────────────────────────────────────────────────────────-function SetupScreen({ onConnect, loading }: { onConnect: () => void; loading: boolean }) {+function SetupScreen({ onConnect, loading, rootMode, onRootModeChange, rootPath, onRootPathChange }: {+ onConnect: () => void;+ loading: boolean;+ rootMode: boolean;+ onRootModeChange: (enabled: boolean) => void;+ rootPath: string;+ onRootPathChange: (path: string) => void;+}) {return (<div className="flex flex-col items-center justify-center flex-1 gap-8 animate-fade-in-up">{/* Hero */}@@ -279,6 +288,41 @@ function SetupScreen({ onConnect, loading }: { onConnect: () => void; loading: b</div></div>+ <div className="w-full max-w-sm px-6 space-y-3 text-sm">+ <label className="flex items-center gap-3 text-zinc-300">+ <input+ id="scan-as-root"+ type="checkbox"+ checked={rootMode}+ disabled={loading}+ onChange={(event) => onRootModeChange(event.target.checked)}+ className="accent-teal-500"+ />+ Scan with root access (read-only)+ </label>+ {rootMode && (+ <>+ <label className="block text-xs text-zinc-400" htmlFor="root-scan-path">Scan location</label>+ <select+ id="root-scan-path"+ value={rootPath}+ disabled={loading}+ onChange={(event) => onRootPathChange(event.target.value)}+ className="w-full rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 text-zinc-200"+ >+ <option value="/data">App and user data (/data)</option>+ <option value="/">Internal data and system (/)</option>+ <option value="/sdcard">Shared storage (/sdcard)</option>+ </select>+ <p className="text-xs leading-relaxed text-zinc-400">+ Requires a rooted device. Approve shell access on your phone if prompted.+ Internal scans exclude virtual filesystems and duplicate storage views;+ removable storage is excluded from the whole-device scan.+ </p>+ </>+ )}+ </div>+{/* Connect Button */}<buttonid="btn-connect"@@ -378,7 +422,7 @@ function FileTreeNode({node: FileNode;parentSize: number;depth: number;- onNuke: (path: string, name: string) => void;+ onNuke?: (path: string, name: string) => void;onZoom: (path: string) => void;}) {const [open, setOpen] = useState(depth < 1);@@ -429,7 +473,7 @@ function FileTreeNode({{formatBytes(node.size)}</span>- {depth > 0 && (+ {depth > 0 && onNuke && (<buttonclassName="btn-nuke opacity-0 group-hover:opacity-100 ml-1 px-2 py-1 rounded-mdbg-danger-600/20 border border-danger-500/30 text-danger-400@@ -437,7 +481,7 @@ function FileTreeNode({cursor-pointer"onClick={(e) => {e.stopPropagation();- onNuke(node.path, node.name);+ onNuke?.(node.path, node.name);}}title={`Delete ${node.name}`}>@@ -597,6 +641,12 @@ function ResultScreen({</div></header>+ {data.read_only && (+ <div className="px-6 pt-3 text-xs text-accent-300">+ Root access · Read-only · Deletion disabled+ </div>+ )}+{/* Stats row */}<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 px-6 py-4 shrink-0"><StatCard label="Total Size" value={formatBytes(data.total_size)} accent />@@ -644,13 +694,15 @@ function ResultScreen({<div className="flex-1 overflow-y-auto px-3 pb-4 min-h-0"><div className="flex items-center gap-2 px-3 py-2 mb-1"><span className="text-xs font-semibold text-zinc-500 uppercase tracking-wider flex-1">Storage Map</span>- <span className="text-xs text-zinc-600">{data.errors > 0 ? `${data.errors} access errors skipped` : ""}</span>+ <span className="text-xs text-zinc-500">+ {[data.errors > 0 ? `${data.errors} access errors` : "", data.skipped > 0 ? `${data.skipped} excluded or duplicate entries` : ""].filter(Boolean).join(" · ")}+ </span></div><FileTreeNodenode={renderNode}parentSize={renderNode.size}depth={0}- onNuke={onNuke}+ onNuke={data.read_only ? undefined : onNuke}onZoom={setZoomPath}/></div>@@ -662,6 +714,8 @@ function ResultScreen({function App() {const [phase, setPhase] = useState<AppPhase>("setup");+ const [rootMode, setRootMode] = useState(false);+ const [rootPath, setRootPath] = useState("/data");const [scanData, setScanData] = useState<ScanResponse | null>(null);const [statusText, setStatusText] = useState("Initializing…");const [toasts, setToasts] = useState<Toast[]>([]);@@ -700,21 +754,24 @@ function App() {// ── Connect flow ────────────────────────────────────────────────────────const handleConnect = useCallback(async () => {setPhase("connecting");+ const scanPath = rootMode ? rootPath : "/sdcard";+ let initialized = false;try {setStatusText("Checking ADB…");addLog("[ADB] Checking version...");const adbVersion = await invoke<string>("check_adb");addLog(`[ADB] Found: ${adbVersion}`);- setStatusText("Pushing daemon to device…");+ setStatusText(rootMode ? "Requesting root access…" : "Pushing daemon to device…");addLog("[ADB] Killing old daemon, pushing new binary...");- await invoke<string>("init_daemon");+ await invoke<string>("init_daemon", { rootMode });+ initialized = true;addLog("[SOCKET] Daemon started and connected via TCP tunnel!");setPhase("scanning");- setStatusText("Scanning /sdcard …");- addLog("[SCAN] Requesting /sdcard (Fast POSIX traversal)...");- const raw = await invoke<string>("run_scan", { path: "/sdcard" });+ setStatusText(`Scanning ${scanPath} …`);+ addLog(`[SCAN] Requesting ${scanPath}${rootMode ? " with read-only root access" : ""}...`);+ const raw = await invoke<string>("run_scan", { path: scanPath });const parsed: ScanResponse = JSON.parse(raw);if (parsed.status !== "ok") throw new Error("Scan returned non-ok status");@@ -725,20 +782,25 @@ function App() {const phases = scanPhaseLog(parsed);if (phases) addLog(phases);} catch (err: unknown) {+ if (initialized) {+ try { await invoke<string>("stop_daemon"); } catch { /* show the original connection error */ }+ }const message = err instanceof Error ? err.message : String(err);pushToast(message, "error");addLog(`[ERROR] ${message}`);setPhase("setup");}- }, [pushToast, addLog]);+ }, [pushToast, addLog, rootMode, rootPath]);// ── Rescan ──────────────────────────────────────────────────────────────const handleRescan = useCallback(async () => {+ if (!scanData) return;+ const scanPath = scanData.tree.path;setPhase("scanning");- setStatusText("Re-scanning /sdcard …");- addLog("[SCAN] Re-scanning /sdcard...");+ setStatusText(`Re-scanning ${scanPath} …`);+ addLog(`[SCAN] Re-scanning ${scanPath}...`);try {- const raw = await invoke<string>("run_scan", { path: "/sdcard" });+ const raw = await invoke<string>("run_scan", { path: scanPath });const parsed: ScanResponse = JSON.parse(raw);setScanData(parsed);setPhase("result");@@ -751,7 +813,7 @@ function App() {addLog(`[ERROR] ${message}`);setPhase("result");}- }, [pushToast, addLog]);+ }, [pushToast, addLog, scanData]);// ── Disconnect ──────────────────────────────────────────────────────────const handleDisconnect = useCallback(async () => {@@ -771,13 +833,15 @@ function App() {// ── Nuke (Delete) ───────────────────────────────────────────────────────const handleNuke = useCallback((path: string, name: string) => {+ if (scanData?.read_only) return;setConfirmDelete({ path, name });- }, []);+ }, [scanData]);const executeDelete = useCallback(async () => {if (!confirmDelete) return;const { path, name } = confirmDelete;setConfirmDelete(null);+ if (scanData?.read_only) return;// Guard: never delete the scan rootif (scanData && path === scanData.tree.path) {@@ -826,8 +890,16 @@ function App() {<ToastContainer toasts={toasts} onDismiss={dismissToast} /><div className="flex-1 flex flex-col min-h-0">- {phase === "setup" && <SetupScreen onConnect={handleConnect} loading={false} />}- {phase === "connecting" && <SetupScreen onConnect={handleConnect} loading={true} />}+ {(phase === "setup" || phase === "connecting") && (+ <SetupScreen+ onConnect={handleConnect}+ loading={phase === "connecting"}+ rootMode={rootMode}+ onRootModeChange={setRootMode}+ rootPath={rootPath}+ onRootPathChange={setRootPath}+ />+ )}{phase === "scanning" && <ScanningScreen statusText={statusText} />}{phase === "result" && scanData && (<ResultScreendiff --git a/tests/test_daemon.py b/tests/test_daemon.pyindex ab6d70f..279842c 100644--- a/tests/test_daemon.py+++ b/tests/test_daemon.py@@ -10,12 +10,14 @@ import secretsimport shutilimport socketimport subprocess+import sysimport tempfileimport timeimport unittest-class DaemonTests(unittest.TestCase):+class DaemonHarness(unittest.TestCase):+ read_only = False@classmethoddef setUpClass(cls):cls.build_dir = tempfile.TemporaryDirectory(prefix="socketsweep-test-build-")@@ -42,7 +44,10 @@ class DaemonTests(unittest.TestCase):with socket.socket() as reservation:reservation.bind(("127.0.0.1", 0))self.port = reservation.getsockname()[1]- self.process = subprocess.Popen([self.binary, str(self.port), str(token_file)],+ args = [self.binary, str(self.port), str(token_file)]+ if self.read_only:+ args.append("--read-only")+ self.process = subprocess.Popen(args,stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)self.addCleanup(self.stop)for _ in range(100):@@ -87,9 +92,12 @@ class DaemonTests(unittest.TestCase):self.assertEqual(result["status"], "ok")return result+[email protected](os.geteuid() == 0, "Writable daemon tests require an unprivileged user")+class DaemonTests(DaemonHarness):def test_authenticated_ping_and_scan(self):(self.root / "photo").write_bytes(b"1234567")- self.assertEqual(self.request("PING")["protocol_version"], 2)+ self.assertEqual(self.request("PING")["protocol_version"], 3)result = self.scan()self.assertEqual(result["total_files"], 1)self.assertEqual(result["total_size"], 7)@@ -192,6 +200,55 @@ class DaemonTests(unittest.TestCase):self.assertTrue((outside / "keep").exists())+class ReadOnlyDaemonTests(DaemonHarness):+ read_only = True++ def test_read_only_handshake_and_delete_block_before_and_after_scan(self):+ status = self.request("PING")+ self.assertEqual(status["protocol_version"], 3)+ self.assertEqual(status["uid"], os.geteuid())+ self.assertTrue(status["read_only"])+ target = self.root / "keep"+ target.write_text("private app data")+ for scanned in [False, True]:+ if scanned:+ self.assertTrue(self.scan()["read_only"])+ result = self.request(f"DELETE {target}")+ self.assertEqual(result["status"], "error")+ self.assertIn("read-only", result["message"])+ self.assertEqual(target.read_text(), "private app data")++ def test_hard_links_are_counted_once_and_rescan_resets_seen_entries(self):+ (self.root / "original").write_bytes(b"1234567")+ os.link(self.root / "original", self.root / "alias")+ for _ in range(2):+ result = self.scan()+ self.assertEqual(result["total_files"], 1)+ self.assertEqual(result["total_size"], 7)+ self.assertEqual(result["skipped"], 1)+ self.assertEqual(sum(node["size"] for node in result["tree"]["children"]), 7)++ def test_alias_root_is_canonicalized_and_nested_directory_names_are_preserved(self):+ (self.root / "mnt").mkdir()+ (self.root / "mnt" / "private-file").write_bytes(b"1234567")+ alias = Path(self.files.name) / "alias"+ alias.symlink_to(self.root, target_is_directory=True)+ result = self.request(f"SCAN {alias}/.")+ self.assertEqual(result["status"], "ok")+ self.assertEqual(result["tree"]["path"], str(self.root.resolve()))+ self.assertEqual(result["total_size"], 7)+ self.assertEqual(result["tree"]["children"][0]["name"], "mnt")++ @unittest.skipUnless(sys.platform.startswith("linux"), "Linux virtual filesystem types")+ def test_virtual_filesystem_roots_and_aliases_are_rejected(self):+ alias = Path(self.files.name) / "proc-alias"+ alias.symlink_to("/proc", target_is_directory=True)+ for path in ["/proc", "/sys", str(alias)]:+ result = self.request(f"SCAN {path}")+ self.assertEqual(result["status"], "error")+ self.assertIn("Virtual filesystems", result["message"])++class DeletionRaceTests(unittest.TestCase):@classmethoddef setUpClass(cls):diff --git a/tests/test_root_scan.py b/tests/test_root_scan.pynew file mode 100644index 0000000..6e88848--- /dev/null+++ b/tests/test_root_scan.py@@ -0,0 +1,127 @@+"""Run the real UID-0 daemon in an isolated, disposable Linux chroot.++CI runs this file with sudo; ordinary test discovery skips it. The daemon is+statically linked and placed under /dev so full scans only count fixture data.+No Android device, real device storage, or filesystem mounts are involved.+"""++import json+import os+from pathlib import Path+import secrets+import shutil+import socket+import subprocess+import sys+import tempfile+import time+import unittest++[email protected](sys.platform.startswith("linux") and os.geteuid() == 0,+ "Requires Linux root for the disposable chroot")+class RootScanSandboxTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.build = tempfile.TemporaryDirectory(prefix="socketsweep-root-build-")+ cls.binary = Path(cls.build.name) / "daemon"+ source = Path(__file__).resolve().parents[1] / "engine" / "daemon.cpp"+ subprocess.run([os.environ.get("CXX", "g++"), "-std=c++17", "-O2", "-static",+ "-Wall", "-Wextra", "-Wpedantic", "-fno-exceptions",+ "-fno-rtti", str(source), "-o", str(cls.binary)], check=True)++ @classmethod+ def tearDownClass(cls):+ cls.build.cleanup()++ def setUp(self):+ self.files = tempfile.TemporaryDirectory(prefix="socketsweep-root-fs-")+ self.addCleanup(self.files.cleanup)+ self.root = Path(self.files.name)+ for name in ["data", "system", "mnt", "storage", "data_mirror", "apex", "proc", "sys", "dev"]:+ (self.root / name).mkdir()+ if name not in ["data", "system"]:+ (self.root / name / "excluded").write_bytes(b"must not be counted")+ (self.root / "data" / "private").write_bytes(b"private app data")+ (self.root / "system" / "system-file").write_bytes(b"system files")+ shutil.copy2(self.binary, self.root / "dev" / "daemon")+ self.token = secrets.token_hex(32)+ token_file = self.root / "dev" / "token"+ token_file.write_text(self.token + "\n")+ token_file.chmod(0o600)+ with socket.socket() as reservation:+ reservation.bind(("127.0.0.1", 0))+ self.port = reservation.getsockname()[1]+ # Deliberately omit --read-only: UID 0 must enforce it on its own.+ self.process = subprocess.Popen(["chroot", str(self.root), "/dev/daemon",+ str(self.port), "/dev/token"],+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)+ self.addCleanup(self.stop)+ for _ in range(100):+ try:+ self.request("PING")+ break+ except OSError:+ if self.process.poll() is not None:+ self.fail(self.process.stderr.read().decode())+ time.sleep(0.01)+ else:+ self.fail("Sandbox daemon did not start")+ self.assertFalse(token_file.exists())++ def request(self, command):+ with socket.create_connection(("127.0.0.1", self.port), timeout=2) as client:+ client.sendall(f"AUTH {self.token}\n{command}\n".encode())+ client.shutdown(socket.SHUT_WR)+ data = b""+ while not data.endswith(b"\n"):+ chunk = client.recv(65536)+ if not chunk:+ break+ data += chunk+ return json.loads(data)++ def stop(self):+ if self.process.poll() is None:+ try:+ self.request("SHUTDOWN")+ self.process.wait(timeout=2)+ except (OSError, subprocess.TimeoutExpired):+ self.process.kill()+ self.process.wait()+ self.process.stderr.close()++ def test_whole_internal_scan_excludes_aliases_and_uses_single_slash_paths(self):+ status = self.request("PING")+ self.assertEqual(status["uid"], 0)+ self.assertTrue(status["read_only"])+ result = self.request("SCAN /")+ self.assertEqual(result["status"], "ok")+ self.assertEqual(result["tree"]["path"], "/")+ self.assertEqual(result["total_files"], 2)+ self.assertEqual(result["total_size"], len(b"private app data") + len(b"system files"))+ self.assertEqual(result["skipped"], 7)+ self.assertEqual({node["path"] for node in result["tree"]["children"]}, {"/data", "/system"})++ def test_root_alias_cannot_bypass_exclusions_and_rescans_reset_deduplication(self):+ (self.root / "alias").symlink_to("/", target_is_directory=True)+ os.link(self.root / "data" / "private", self.root / "data" / "hard-link")+ for path in ["/alias/.", "/./", "/"]:+ result = self.request(f"SCAN {path}")+ self.assertEqual(result["status"], "ok")+ self.assertEqual(result["tree"]["path"], "/")+ self.assertEqual(result["total_files"], 2)+ self.assertEqual(result["skipped"], 8)++ def test_uid_zero_cannot_delete_even_without_read_only_launch_flag(self):+ for scanned in [False, True]:+ if scanned:+ self.assertEqual(self.request("SCAN /data")["status"], "ok")+ result = self.request("DELETE /data/private")+ self.assertEqual(result["status"], "error")+ self.assertIn("read-only", result["message"])+ self.assertEqual((self.root / "data" / "private").read_bytes(), b"private app data")+++if __name__ == "__main__":+ unittest.main()