A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.
Rust
Validate largest-files replies before rendering rows and actions (#100)
Vishnu Srivatsavaf9f0dfeaba3e
diff --git a/docs/largest-files.md b/docs/largest-files.mdindex e190b3b..12c1f3d 100644--- a/docs/largest-files.md+++ b/docs/largest-files.md@@ -32,6 +32,17 @@ The limit selector remains available after an error. Frontend queries hide oldrows immediately when their scan revision or limit changes and ignore lateresponses after replacement or unmount.+The frontend also validates the response before rendering rows or actions:+matching scope/workload/limit, exactly the bounded number of rows, unique+unsigned IDs and paths, counted regular-file metadata, safe sizes, descending+size order, exact root/name/path relationships and deletion eligibility.+Selected bytes cannot exceed scan totals; a complete list must reconcile with+the scan's bytes. Valid UTF-8 labels, including whitespace, BOM and CR/LF names,+remain exact. Delimiter-containing or oversized command paths cannot offer+deletion. Invalid data uses the existing error/retry view instead of crashing+the results screen. Rust remains the final authority for IDs, paths and deletes.++This is an adaptation of the largest-files idea in Shanmukh's fork at[`d677b530`](https://github.com/ksaishanmukh/SocketSweep/tree/d677b530e00dec75c305fc56318720aa8c161692)(commits `670736d`, `5e442e2`), implemented on SocketSweep's existing host catalog.diff --git a/package.json b/package.jsonindex 671ee4f..8f95824 100644--- a/package.json+++ b/package.json@@ -8,7 +8,7 @@"dev": "vite","build": "tsc && vite build","lint": "eslint src tests vite.config.ts eslint.config.js --max-warnings 0",- "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs tests/devices.test.mjs tests/file_types.test.mjs tests/scan_history.test.mjs",+ "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs tests/devices.test.mjs tests/file_types.test.mjs tests/scan_history.test.mjs tests/largest_files.test.mjs","preview": "vite preview","tauri": "tauri"},diff --git a/src/LargestFiles.tsx b/src/LargestFiles.tsxindex 0b78f6f..7eb0899 100644--- a/src/LargestFiles.tsx+++ b/src/LargestFiles.tsx@@ -1,37 +1,31 @@import { useEffect, useState } from "react";import { invoke } from "@tauri-apps/api/core";-import { sameScan } from "./scanView";-import type { ScanScope, NodeDetail } from "./scanView";+import { parseLargestFiles } from "./largestFilesSummary";+import type { LargestResponse } from "./largestFilesSummary";+import type { ScanResponse } from "./scanView";import { formatBytes } from "./formatBytes";-interface LargestResponse extends ScanScope {- limit: number;- total_files: number;- files: Pick<NodeDetail, "node" | "path">[];-}-export function LargestFiles({ scope, busy, onZoom, onNuke }: {- scope: ScanScope;+ scope: ScanResponse;busy: boolean;onZoom: (id: number) => void;onNuke: (id: number) => void;}) {- const { generation, revision } = scope;+ const { generation, revision, root_path, read_only, total_files, total_size } = scope;const [limit, setLimit] = useState(25);const [retry, setRetry] = useState(0);- const key = JSON.stringify([generation, revision, limit, retry]);+ const key = JSON.stringify([generation, revision, root_path, read_only, total_files, total_size, limit, retry]);const [state, setState] = useState<{ key: string; data?: LargestResponse; error?: string }>({ key: "" });useEffect(() => {let current = true;void invoke<string>("get_largest_files", { generation, revision, limit }).then(raw => {- const data: LargestResponse = JSON.parse(raw);- if (!sameScan(data, { generation, revision }) || data.limit !== limit) throw new Error("Scan query returned unexpected largest files");+ const data = parseLargestFiles(raw, { generation, revision, root_path, read_only, total_files, total_size }, limit);if (current) setState({ key, data });}).catch(error => {if (current) setState({ key, error: String(error) });});return () => { current = false; };- }, [generation, revision, limit, key]);+ }, [generation, revision, root_path, read_only, total_files, total_size, limit, key]);// Hide the previous revision/limit synchronously, before its effect cleans up.const data = state.key === key ? state.data : undefined;const error = state.key === key ? state.error : undefined;diff --git a/src/fileTypeSummary.ts b/src/fileTypeSummary.tsindex bae5c5a..bb076ca 100644--- a/src/fileTypeSummary.ts+++ b/src/fileTypeSummary.ts@@ -1,4 +1,4 @@-import { sameScan } from "./scanView";+import { sameScan, isRecord as object, isCount as count } from "./scanView";import type { ScanScope } from "./scanView";export const FILE_TYPE_LABELS = {@@ -20,8 +20,6 @@ export interface FileTypesResponse extends ScanScope {categories: FileTypeCount[];}type Expected = ScanScope & { total_files: number; total_size: number };-const object = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);-const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;/** Reject stale, malformed or non-reconciling summaries before showing totals. */export function parseFileTypes(raw: string, expected: Expected): FileTypesResponse {diff --git a/src/largestFilesSummary.ts b/src/largestFilesSummary.tsnew file mode 100644index 0000000..2a74b85--- /dev/null+++ b/src/largestFilesSummary.ts@@ -0,0 +1,57 @@+import { sameScan, isRecord, isCount } from "./scanView";+import type { ScanScope, ScanResponse, NodeDetail } from "./scanView";++export interface LargestResponse extends ScanScope {+ limit: number;+ total_files: number;+ files: Pick<NodeDetail, "node" | "path">[];+}+type Expected = Pick<ScanResponse, "generation" | "revision" | "root_path" | "read_only" | "total_files" | "total_size">;+const encoder = new TextEncoder();+const decoder = new TextDecoder("utf-8", { ignoreBOM: true });+const id = (value: unknown): value is number => isCount(value) && value <= 0xffff_ffff;+const textBytes = (value: string) => {+ const bytes = encoder.encode(value);+ return decoder.decode(bytes) === value ? bytes.length : Infinity;+};+const name = (value: unknown): value is string => typeof value === "string" && value !== "" && value !== "." && value !== ".."+ && !value.includes("/") && !value.includes("\0") && textBytes(value) <= 255;++/** Validate bounded, scoped regular-file rows before rendering action controls. */+export function parseLargestFiles(raw: string, expected: Expected, limit: number): LargestResponse {+ const data: unknown = JSON.parse(raw);+ const invalid = () => new Error("Largest-files response does not match this scan");+ if (!isRecord(data) || typeof data.generation !== "string" || !id(data.revision)+ || !sameScan({ generation: data.generation, revision: data.revision }, expected)+ || !isCount(limit) || limit < 1 || limit > 100 || data.limit !== limit+ || !isCount(data.total_files) || data.total_files !== expected.total_files+ || !Array.isArray(data.files) || data.files.length !== Math.min(limit, data.total_files)) throw invalid();+ const files: LargestResponse["files"] = [];+ const seen = new Set<number>();+ const paths = new Set<string>();+ const prefix = expected.root_path === "/" ? "/" : `${expected.root_path}/`;+ let bytes = 0;+ for (const file of data.files) {+ if (!isRecord(file) || !isRecord(file.node) || typeof file.path !== "string" || paths.has(file.path)) throw invalid();+ const node = file.node;+ if (!id(node.id) || node.id === 0 || seen.has(node.id) || !id(node.parent_id) || node.parent_id >= node.id+ || !name(node.name) || node.type !== "file" || node.counted !== true || node.child_count !== 0+ || !isCount(node.size) || typeof node.can_delete !== "boolean") throw invalid();+ const pathBytes = textBytes(file.path);+ const relative = file.path.startsWith(prefix) ? file.path.slice(prefix.length) : "";+ const parts = relative.split("/");+ if (pathBytes > 16 * 1024 || !parts.every(name) || parts[parts.length - 1] !== node.name+ || (node.parent_id === 0) !== (parts.length === 1)+ || (node.can_delete && (expected.read_only || /[\r\n\0]/.test(file.path) || pathBytes + "DELETE ".length > 16 * 1024))) throw invalid();+ bytes += node.size;+ if (!isCount(bytes) || bytes > expected.total_size || (files.length > 0 && node.size > files[files.length - 1].node.size)) throw invalid();+ seen.add(node.id);+ paths.add(file.path);+ files.push({ path: file.path, node: {+ id: node.id, parent_id: node.parent_id, name: node.name, type: "file", size: node.size,+ counted: true, child_count: 0, can_delete: node.can_delete,+ } });+ }+ if (files.length === data.total_files && bytes !== expected.total_size) throw invalid();+ return { generation: data.generation, revision: data.revision, limit, total_files: data.total_files, files };+}diff --git a/src/scanComparison.ts b/src/scanComparison.tsindex ee173f7..670009f 100644--- a/src/scanComparison.ts+++ b/src/scanComparison.ts@@ -1,4 +1,4 @@-import { sameScan } from "./scanView";+import { sameScan, isRecord as object, isCount as count } from "./scanView";import type { ScanScope } from "./scanView";export interface PreviousScan {@@ -13,8 +13,6 @@ export interface ScanComparison extends ScanScope {delta?: { files: number; dirs: number; size: number };}type Expected = ScanScope & { total_files: number; total_dirs: number; total_size: number };-const object = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);-const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;const change = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value);/** Reject stale, malformed or non-reconciling comparisons before display. */diff --git a/src/scanView.ts b/src/scanView.tsindex aabab12..fe1b224 100644--- a/src/scanView.ts+++ b/src/scanView.ts@@ -54,6 +54,9 @@ export interface DeleteResult {removed: { files: number; dirs: number; size: number };}export interface ScanScope { generation: string; revision: number }+/** Shared guards for scan IPC values before feature-specific validation. */+export const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);+export const isCount = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;export function sameScan(a: ScanScope | null, b: ScanScope): boolean {return a?.generation === b.generation && a.revision === b.revision;}diff --git a/tests/largest_files.test.mjs b/tests/largest_files.test.mjsnew file mode 100644index 0000000..7048227--- /dev/null+++ b/tests/largest_files.test.mjs@@ -0,0 +1,117 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";+import ts from "typescript";++const transpile = source => ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext } }).outputText;+const url = source => `data:text/javascript;base64,${Buffer.from(source).toString("base64")}`;+const scanView = url(transpile(await readFile(new URL("../src/scanView.ts", import.meta.url), "utf8")));+const source = transpile(await readFile(new URL("../src/largestFilesSummary.ts", import.meta.url), "utf8")).replace('"./scanView"', JSON.stringify(scanView));+const { parseLargestFiles } = await import(url(source));+const expected = { generation: "scan-a", revision: 2, root_path: "/fixture", read_only: false, total_files: 2, total_size: 10 };+const row = (id, name, size) => ({ path: `/fixture/${name}`, node: {+ id, parent_id: 0, name, type: "file", size, counted: true, child_count: 0, can_delete: true,+} });+const report = () => ({ generation: "scan-a", revision: 2, limit: 25, total_files: 2,+ files: [row(2, "large.txt", 7), row(3, "empty-ish", 3)] });+const parse = (data, scope = expected, limit = 25) => parseLargestFiles(JSON.stringify(data), scope, limit);++test("valid complete and top-K responses retain exact labels and IDs", () => {+ assert.deepEqual(parse(report()).files, report().files);+ const data = { ...report(), limit: 1, files: report().files.slice(0, 1) };+ assert.equal(parse(data, expected, 1).files.length, 1);+ data.files[0].ignored = "not part of the contract";+ assert.equal(parse(data, expected, 1).files[0].ignored, undefined);+});++test("empty scans and zero-byte counted files are accepted", () => {+ assert.equal(parse({ ...report(), total_files: 0, files: [] }, { ...expected, total_files: 0, total_size: 0 }).files.length, 0);+ const data = { ...report(), total_files: 1, files: [row(1, "zero", 0)] };+ assert.equal(parse(data, { ...expected, total_files: 1, total_size: 0 }).files[0].node.size, 0);+});++test("malformed payloads, row collections and unexpected workload totals are rejected", () => {+ for (const raw of ["{", "null", "[]", "5"]) assert.throws(() => parseLargestFiles(raw, expected, 25));+ for (const files of [null, {}, [], [null], [report().files[0]], [null, report().files[1]], [{ node: null, path: "/fixture/large.txt" }, report().files[1]]]) assert.throws(() => parse({ ...report(), files }));+ assert.throws(() => parse({ ...report(), files: Array(101).fill(report().files[0]) }));+ for (const changes of [{ generation: "old" }, { revision: 1 }, { revision: -1 }, { limit: 50 }, { total_files: 3 }]) {+ assert.throws(() => parse({ ...report(), ...changes }));+ }+ for (const limit of [0, 101, 1.5, NaN]) assert.throws(() => parse({ ...report(), limit }, expected, limit));+});++test("invalid or duplicate node IDs, parents and regular-file metadata are rejected", () => {+ for (const change of [+ node => { node.id = 0; }, node => { node.id = 0x1_0000_0000; }, node => { node.parent_id = null; },+ node => { node.parent_id = node.id; }, node => { node.id = 3; }, node => { node.type = "directory"; },+ node => { node.counted = false; }, node => { node.child_count = 1; }, node => { node.can_delete = "true"; },+ node => { node.size = -1; }, node => { node.size = 0.5; }, node => { node.size = Number.MAX_SAFE_INTEGER + 1; },+ node => { node.size = "7"; }, node => { node.name = null; },+ ]) {+ const data = report(); change(data.files[0].node); assert.throws(() => parse(data));+ }+});++test("sizes must be ranked, bounded and reconcile when all files are returned", () => {+ const data = report();+ data.files.reverse(); assert.throws(() => parse(data));+ assert.throws(() => parse(report(), { ...expected, total_size: 9 }));+ assert.throws(() => parse(report(), { ...expected, total_size: 11 }));+ assert.throws(() => parse({ ...report(), limit: 1, files: [row(2, "huge", 11)] }, expected, 1));+});++test("paths must match the scan root, exact name and parent shape", () => {+ for (const path of ["/another/large.txt", "/fixture-other/large.txt", "/fixture/../large.txt", "/fixture//large.txt", "/fixture/wrong.txt", "/fixture/folder/large.txt", "/fixture/large.txt\0"]) {+ const data = report(); data.files[0].path = path; assert.throws(() => parse(data));+ }+ for (const name of ["", ".", "..", "a/b", "bad\0name", "x".repeat(256), "\ud800"]) {+ const data = report(); data.files[0] = row(2, name, 7); assert.throws(() => parse(data));+ }+ const nested = report(); nested.files[0].path = "/fixture/folder/large.txt"; nested.files[0].node.parent_id = 1;+ assert.equal(parse(nested).files[0].node.parent_id, 1);+ const root = report(); root.files.forEach(file => { file.path = `/${file.node.name}`; });+ assert.equal(parse(root, { ...expected, root_path: "/" }).files.length, 2);+});++test("Unicode, BOM and whitespace labels stay exact; delimiter paths cannot offer deletion", () => {+ for (const name of [" leading trailing ", "\ufeffname", "photo-🙂", "line\nname", "line\rname"]) {+ const data = report(); data.files[0] = row(2, name, 7);+ if (/[\r\n]/.test(name)) {+ assert.throws(() => parse(data));+ data.files[0].node.can_delete = false;+ }+ assert.equal(parse(data).files[0].node.name, name);+ }+ const data = report();+ assert.throws(() => parse(data, { ...expected, read_only: true }));+ data.files.forEach(file => { file.node.can_delete = false; });+ assert.equal(parse(data, { ...expected, read_only: true }).files.length, 2);+});++test("UTF-8 path and deletion-command budgets remain distinct", () => {+ const name = "x".repeat(247);+ const file = row(2, name, 10);+ file.node.parent_id = 1;+ file.node.can_delete = false;+ file.path = `/fixture/${(`${"d".repeat(255)}/`).repeat(63)}${name}`;+ assert.equal(new TextEncoder().encode(file.path).length, 16 * 1024);+ const data = { ...report(), total_files: 1, files: [file] };+ assert.equal(parse(data, { ...expected, total_files: 1 }).files.length, 1);+ file.node.can_delete = true; assert.throws(() => parse(data, { ...expected, total_files: 1 }));+ file.node.can_delete = false; file.path += "x"; file.node.name += "x";+ assert.throws(() => parse(data, { ...expected, total_files: 1 }));+});+++test("the maximum page is bounded and paths cannot be duplicated under different IDs", () => {+ const data = { ...report(), limit: 100, total_files: 100,+ files: Array.from({ length: 100 }, (_, index) => row(index + 1, `file-${index}`, 1)) };+ const scope = { ...expected, total_files: 100, total_size: 100 };+ assert.equal(parse(data, scope, 100).files.length, 100);+ data.files.push(row(101, "extra", 0));+ assert.throws(() => parse(data, scope, 100));+ const duplicate = report();+ duplicate.files[0].node.name = duplicate.files[1].node.name;+ duplicate.files[0].path = duplicate.files[1].path;+ assert.throws(() => parse(duplicate));+});diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.jsindex 77fc5a4..21ed608 100644--- a/tests/scan_ui_fixture.js+++ b/tests/scan_ui_fixture.js@@ -11,6 +11,7 @@let delayedDetail = true;let delayedLargest = true;let failLargest = false;+ let malformedLargest = false;let holdTypes = false;let resolveTypes;let failTypes = false;@@ -145,6 +146,10 @@if (command === "get_largest_files") {check(Number.isInteger(args.limit) && args.limit > 0 && args.limit <= 100, "Unbounded largest-files query");if (failLargest) { failLargest = false; throw "Mock largest-files failure"; }+ if (malformedLargest) {+ malformedLargest = false;+ return JSON.stringify({ ...scope(), limit: args.limit, total_files: summary().total_files, files: null });+ }const files = [...rootChildren, ...folderChildren].filter(item => item.type === "file").sort((a, b) => b.size - a.size || (a.name < b.name ? -1 : a.name > b.name ? 1 : a.id - b.id));const response = JSON.stringify({ ...scope(), limit: args.limit, total_files: files.length,@@ -204,7 +209,7 @@const report = (passed, error) => {const output = document.createElement("pre");output.id = "scan-test-report";- output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "complete paging", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "bounded largest files", "late largest response", "largest query retry", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "duplicate rescan guard", "rescan failure recovery", "rescan cancellation recovery", "toast dismissal integration", "bounded diagnostic integration"] : undefined });+ output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "complete paging", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "bounded largest files", "late largest response", "largest query retry", "malformed largest response recovery", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "duplicate rescan guard", "rescan failure recovery", "rescan cancellation recovery", "toast dismissal integration", "bounded diagnostic integration"] : undefined });document.body.append(output);void fetch("/report", { method: "POST", body: output.textContent }).then(() => {if (passed) location.replace("/tests/toast_lifecycle_fixture.html");@@ -363,6 +368,12 @@await waitFor(() => largestRows().length === 50, "Largest-files retry failed");chooseLimit(100);await waitFor(() => largestRows().length === 100, "Maximum largest-files page missing");+ malformedLargest = true;+ chooseLimit(25);+ await waitFor(() => button("Retry") || !document.querySelector("#btn-rescan"), "Malformed largest-files response did not offer retry");+ check(button("Retry") && largestRows().length === 0 && document.querySelector("#btn-rescan"), "Malformed largest-files response retained rows or crashed results");+ button("Retry").click();+ await waitFor(() => largestRows().length === 25, "Malformed largest-files response did not recover");button("Show folder").click();await waitFor(() => rows().length === 129, "Show folder did not restore map");check(calls.filter(item => item.command === "run_scan").length === scanCount + 1, "Largest-files browsing rescanned the phone");