Skip to content

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 node details before deletion confirmation (#102)

Vishnu Srivatsavacd6dccae0481
diff --git a/docs/scan-store.md b/docs/scan-store.md
index 1605900..5f42443 100644
--- a/docs/scan-store.md
+++ b/docs/scan-store.md
@@ -24,6 +24,11 @@ rows and broader navigation work.
- Every query, detail request, cursor and delete requires the current generation
and revision. IDs never renumber within a generation. Deleted nodes and their
descendants become unavailable; revision changes invalidate older cursors.
+- Before showing deletion confirmation, the UI validates node details against
+ the requested snapshot and ID, including node shape, exact root-relative path,
+ UTF-8 limits and deletion eligibility flags. Invalid details show an error
+ without opening the dialog or issuing a delete. The largest-files query shares
+ the same node/path validation. Rust remains the final deletion authority.
- `delete_item` accepts IDs, never a frontend path. Rust reconstructs the exact
accepted UTF-8 path, refuses the root/read-only entries and line-protocol
delimiters/oversized commands, then uses the existing authenticated command
diff --git a/src/App.tsx b/src/App.tsx
index b5eb833..7a3ad2c 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,7 +1,7 @@
import { useState, useCallback, useRef } from "react";
import { Channel, invoke } from "@tauri-apps/api/core";
import { formatBytes } from "./formatBytes";
-import { sameScan } from "./scanView";
+import { sameScan, parseNodeDetail } from "./scanView";
import type { ScanResponse, NodeDetail, DeleteResult } from "./scanView";
import { IconNuke } from "./Icons";
import { ToastContainer } from "./ToastContainer";
@@ -280,8 +280,8 @@ function App() {
const request = ++confirmationRequest.current;
try {
const raw = await invoke<string>("get_scan_node", { generation: scope.generation, revision: scope.revision, nodeId });
- const detail: NodeDetail = JSON.parse(raw);
- if (request === confirmationRequest.current && !actionPending.current && sameScan(snapshot.current, scope) && sameScan(detail, scope) && detail.node.id === nodeId && detail.node.can_delete) {
+ const detail = parseNodeDetail(raw, scope, nodeId);
+ if (request === confirmationRequest.current && !actionPending.current && sameScan(snapshot.current, scope) && detail.node.can_delete) {
setConfirmDelete(detail);
}
} catch (err) {
diff --git a/src/largestFilesSummary.ts b/src/largestFilesSummary.ts
index 2a74b85..93516e6 100644
--- a/src/largestFilesSummary.ts
+++ b/src/largestFilesSummary.ts
@@ -1,4 +1,4 @@
-import { sameScan, isRecord, isCount } from "./scanView";
+import { sameScan, isRecord, isCount, isU32, parseNodeReference } from "./scanView";
import type { ScanScope, ScanResponse, NodeDetail } from "./scanView";
export interface LargestResponse extends ScanScope {
@@ -7,21 +7,11 @@ export interface LargestResponse extends ScanScope {
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)
+ if (!isRecord(data) || typeof data.generation !== "string" || !isU32(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
@@ -29,28 +19,17 @@ export function parseLargestFiles(raw: string, expected: Expected, limit: number
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();
+ const reference = parseNodeReference(file, expected);
+ const { node, path } = reference;
+ if (node.id === 0 || seen.has(node.id) || paths.has(path)
+ || node.type !== "file" || !node.counted) 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,
- } });
+ paths.add(path);
+ files.push(reference);
}
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/scanView.ts b/src/scanView.ts
index fe1b224..0621c57 100644
--- a/src/scanView.ts
+++ b/src/scanView.ts
@@ -57,6 +57,58 @@ 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 const isU32 = (value: unknown): value is number => isCount(value) && value <= 0xffff_ffff;
+const encoder = new TextEncoder();
+const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
+const textBytes = (value: string) => {
+ const bytes = encoder.encode(value);
+ return decoder.decode(bytes) === value ? bytes.length : Infinity;
+};
+const entryName = (value: unknown): value is string => typeof value === "string" && value !== "" && value !== "." && value !== ".."
+ && !value.includes("/") && !value.includes("\0") && textBytes(value) <= 255;
+type NodeContext = Pick<ScanResponse, "root_path" | "read_only" | "total_size">;
+const invalidNode = () => new Error("Scan node response does not match this scan");
+
+/** Shared node/path contract; contextual actions still require their own scope. */
+export function parseNodeReference(value: unknown, expected: NodeContext): Pick<NodeDetail, "node" | "path"> {
+ if (!isRecord(value) || !isRecord(value.node) || typeof value.path !== "string") throw invalidNode();
+ const node = value.node;
+ if (!isU32(node.id) || typeof node.name !== "string"
+ || (node.parent_id !== null && !isU32(node.parent_id)) || !isCount(node.size) || node.size > expected.total_size
+ || !isCount(node.child_count) || typeof node.counted !== "boolean" || typeof node.can_delete !== "boolean"
+ || (node.type !== "file" && node.type !== "directory")
+ || (node.type === "file" && node.child_count !== 0)
+ || (!node.counted && (node.size !== 0 || node.child_count !== 0))) throw invalidNode();
+ const pathBytes = textBytes(value.path);
+ if (pathBytes > 16 * 1024 || (node.can_delete && (expected.read_only || node.id === 0
+ || /[\r\n\0]/.test(value.path) || pathBytes + "DELETE ".length > 16 * 1024))) throw invalidNode();
+ if (node.id === 0) {
+ const rootName = expected.root_path === "/" ? "/" : expected.root_path.slice(expected.root_path.lastIndexOf("/") + 1);
+ if (node.parent_id !== null || node.type !== "directory" || !node.counted
+ || node.name !== rootName || value.path !== expected.root_path) throw invalidNode();
+ } else {
+ if (!isU32(node.parent_id) || node.parent_id >= node.id || !entryName(node.name)) throw invalidNode();
+ const prefix = expected.root_path === "/" ? "/" : `${expected.root_path}/`;
+ const relative = value.path.startsWith(prefix) ? value.path.slice(prefix.length) : "";
+ const parts = relative.split("/");
+ if (!parts.every(entryName) || parts[parts.length - 1] !== node.name
+ || (node.parent_id === 0) !== (parts.length === 1)) throw invalidNode();
+ }
+ return { path: value.path, node: {
+ id: node.id, parent_id: node.parent_id, name: node.name,
+ type: node.type, size: node.size, counted: node.counted, child_count: node.child_count, can_delete: node.can_delete,
+ } };
+}
+
+/** Validate the fresh detail used by confirmation without accepting UI paths. */
+export function parseNodeDetail(raw: string, expected: ScanScope & NodeContext, nodeId: number): NodeDetail {
+ const data: unknown = JSON.parse(raw);
+ if (!isRecord(data) || typeof data.generation !== "string" || !isU32(data.revision) || !isU32(nodeId)
+ || !sameScan({ generation: data.generation, revision: data.revision }, expected)) throw invalidNode();
+ const reference = parseNodeReference(data, expected);
+ if (reference.node.id !== nodeId) throw invalidNode();
+ return { generation: data.generation, revision: data.revision, ...reference };
+}
export function sameScan(a: ScanScope | null, b: ScanScope): boolean {
return a?.generation === b.generation && a.revision === b.revision;
}
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index 21ed608..88aba6f 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -9,6 +9,7 @@
let readOnly = false;
let delayedZoom = true;
let delayedDetail = true;
+ let badDetail = null;
let delayedLargest = true;
let failLargest = false;
let malformedLargest = false;
@@ -182,6 +183,11 @@
return response;
}
if (command === "get_scan_node") {
+ if (badDetail) {
+ const path = badDetail === "object" ? {} : "/outside/file-0";
+ badDetail = null;
+ return JSON.stringify({ ...detail(args.nodeId), path });
+ }
const response = JSON.stringify(detail(args.nodeId));
if (delayedDetail) { delayedDetail = false; await pause(300); }
return response;
@@ -405,6 +411,16 @@
await pause(30);
check(calls.filter(item => item.command === "get_scan_view").length === before, "Other tile zoomed");
+ for (const invalidPath of ["object", "outside"]) {
+ badDetail = invalidPath;
+ const toastsBeforeBadDetail = document.querySelectorAll("#toast-container > div").length;
+ const deletesBeforeBadDetail = calls.filter(call => call.command === "delete_item").length;
+ document.querySelector('[aria-label="Delete file-0 "]').click();
+ await waitFor(() => !document.querySelector("#btn-rescan") || button("NUKE IT") || document.querySelectorAll("#toast-container > div").length > toastsBeforeBadDetail, "Malformed confirmation was not reported");
+ check(document.querySelector("#btn-rescan") && !button("NUKE IT"), "Malformed confirmation crashed results or opened a delete dialog");
+ check(calls.filter(call => call.command === "delete_item").length === deletesBeforeBadDetail, "Malformed confirmation issued a delete");
+ }
+
document.querySelector('[aria-label="Delete file-0 "]').click();
document.querySelector("#btn-rescan").click();
await waitFor(() => rows().length === 129, "Rescan did not reload");
diff --git a/tests/scan_view.test.mjs b/tests/scan_view.test.mjs
index 1843aee..c074312 100644
--- a/tests/scan_view.test.mjs
+++ b/tests/scan_view.test.mjs
@@ -7,7 +7,7 @@ const source = await readFile(new URL("../src/scanView.ts", import.meta.url), "u
const { outputText } = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext },
});
-const { sameScan, viewKey, viewReducer } = await import(
+const { sameScan, viewKey, viewReducer, parseNodeDetail } = await import(
`data:text/javascript;base64,${Buffer.from(outputText).toString("base64")}`
);
const scope = { generation: "scan-a", revision: 0 };
@@ -81,3 +81,57 @@ test("retry clears the error and ignores the prior failure", () => {
const pending = state;
assert.equal(viewReducer(state, { type: "error", request: 1, error: "old error" }), pending);
});
+
+const detailScope = { ...scope, root_path: "/sdcard", read_only: false, total_size: 100 };
+const detail = () => ({ ...scope, path: "/sdcard/photo.jpg", node: {
+ id: 1, parent_id: 0, name: "photo.jpg", type: "file", size: 100,
+ counted: true, child_count: 0, can_delete: true,
+} });
+const parseDetail = (value, expected = detailScope, id = 1) => parseNodeDetail(JSON.stringify(value), expected, id);
+
+test("node detail accepts files, directories, exact labels and uncounted special entries", () => {
+ assert.deepEqual(parseDetail(detail()), detail());
+ for (const name of [" file ", "\ufeffphoto.jpg", "photo-😀.jpg"]) {
+ const value = detail(); value.node.name = name; value.path = `/sdcard/${name}`;
+ assert.deepEqual(parseDetail(value), value);
+ }
+ const folder = detail(); folder.node.type = "directory"; folder.node.child_count = 3;
+ assert.deepEqual(parseDetail(folder), folder);
+ const special = detail(); special.node.counted = false; special.node.size = 0;
+ assert.deepEqual(parseDetail(special), special);
+ const root = detail(); root.node = { ...root.node, id: 0, parent_id: null, name: "sdcard", type: "directory", can_delete: false }; root.path = "/sdcard";
+ assert.deepEqual(parseDetail(root, detailScope, 0), root);
+ root.node.name = "/"; root.path = "/";
+ assert.deepEqual(parseDetail(root, { ...detailScope, root_path: "/" }, 0), root);
+});
+
+test("node detail rejects stale scopes and a different requested ID", () => {
+ assert.throws(() => parseDetail({ ...detail(), generation: "scan-b" }));
+ assert.throws(() => parseDetail({ ...detail(), revision: 1 }));
+ assert.throws(() => parseDetail(detail(), detailScope, 2));
+ assert.throws(() => parseDetail(detail(), detailScope, -1));
+});
+
+test("node detail rejects malformed records, IDs, counts and node kinds", () => {
+ for (const value of [null, [], {}, { ...detail(), node: null }, { ...detail(), path: {} }]) assert.throws(() => parseDetail(value));
+ for (const [field, value] of [
+ ["id", -1], ["id", 2 ** 32], ["parent_id", null], ["parent_id", 1],
+ ["size", -1], ["size", 101], ["size", 0.5], ["child_count", 1],
+ ["counted", "true"], ["can_delete", "true"], ["name", {}], ["type", "symlink"],
+ ["counted", false],
+ ]) assert.throws(() => parseDetail({ ...detail(), node: { ...detail().node, [field]: value } }), field);
+});
+
+test("node detail rejects misleading paths and unsafe deletion flags", () => {
+ for (const path of ["/elsewhere/photo.jpg", "/sdcard2/photo.jpg", "/sdcard/other.jpg", "/sdcard/../photo.jpg", "/sdcard//photo.jpg", "/sdcard/folder/photo.jpg"]) {
+ assert.throws(() => parseDetail({ ...detail(), path }), path);
+ }
+ for (const name of [".", "..", "a/b", "a\0b", "\ud800", "x".repeat(256), "photo\n.jpg"]) {
+ assert.throws(() => parseDetail({ ...detail(), path: `/sdcard/${name}`, node: { ...detail().node, name } }));
+ }
+ const newline = detail(); newline.node.name = "photo\n.jpg"; newline.path = `/sdcard/${newline.node.name}`; newline.node.can_delete = false;
+ assert.deepEqual(parseDetail(newline), newline);
+ assert.throws(() => parseDetail(detail(), { ...detailScope, read_only: true }));
+ const readOnly = detail(); readOnly.node.can_delete = false;
+ assert.deepEqual(parseDetail(readOnly, { ...detailScope, read_only: true }), readOnly);
+});