Skip to content

Commit 261ca3c

Browse files
committed
fix(fs): preserve prune and trash fallback behavior
1 parent feb21f0 commit 261ca3c

6 files changed

Lines changed: 69 additions & 14 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
- Centralize safe path segment validation, directory identity guards, and guarded mutation wrappers so future filesystem helpers reuse the same race-resistant checks.
1010
- Route archive ZIP staging, temp workspace sync reads, secret-file commits, and atomic move/replace fallbacks through shared pinned-read or guarded-write primitives without applying private-directory modes to public paths.
1111
- Close guarded fallback write handles without following path names if post-write directory verification fails, avoiding descriptor leaks and unsafe cleanup in symlink-swap races.
12+
- Preserve empty-directory pruning and broken-symlink trash moves across guarded fallback paths.
1213

1314
### Tests
1415

‎src/file-store-prune.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ export async function pruneExpiredStoreEntries(params: {
8484
}
8585
if (shouldDescend && (await pruneDir(fullPath, relativePath, depth + 1))) {
8686
await assertRootGuard();
87+
// Keep empty-dir pruning on the same root-bounded remove path as files;
88+
// the Root fallback handles empty directories without recursive delete.
8789
await scopedRoot.remove(relativePath).catch(() => undefined);
8890
}
8991
continue;

‎src/root-impl.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1379,7 +1379,7 @@ async function removePathFallback(resolved: { resolved: string }): Promise<void>
13791379
const guard = await createAsyncDirectoryGuard(path.dirname(resolved.resolved));
13801380
await getFsSafeTestHooks()?.beforeRootFallbackMutation?.("remove", resolved.resolved);
13811381
await assertAsyncDirectoryGuard(guard);
1382-
await fs.rm(resolved.resolved);
1382+
await ((await fs.lstat(resolved.resolved)).isDirectory() ? fs.rmdir(resolved.resolved) : fs.rm(resolved.resolved));
13831383
await assertAsyncDirectoryGuard(guard).catch(() => undefined);
13841384
}
13851385

‎src/trash.ts‎

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,14 @@ function isSameOrChildPath(candidate: string, parent: string): boolean {
3030
}
3131

3232
function resolveAllowedTrashRoots(allowedRoots?: Iterable<string>): string[] {
33-
const roots = [...(allowedRoots ?? [os.homedir(), os.tmpdir()])].map((root) => {
33+
const roots = [...(allowedRoots ?? [os.homedir(), os.tmpdir()])].flatMap((root) => {
34+
const lexicalRoot = path.resolve(root);
3435
try {
35-
return path.resolve(fs.realpathSync.native(root));
36+
// Keep both spellings: broken symlink targets cannot be realpathed and
37+
// may only compare equal to the caller's lexical allowed root.
38+
return [path.resolve(fs.realpathSync.native(root)), lexicalRoot];
3639
} catch {
37-
return path.resolve(root);
40+
return [lexicalRoot];
3841
}
3942
});
4043
return [...new Set(roots)];
@@ -43,36 +46,51 @@ function resolveAllowedTrashRoots(allowedRoots?: Iterable<string>): string[] {
4346
type TrashTargetGuard = {
4447
path: string;
4548
realPath: string;
49+
realPathResolved: boolean;
4650
stat: fs.Stats;
4751
};
4852

53+
function resolveTrashTargetPath(targetPath: string): { path: string; resolved: boolean } {
54+
try {
55+
return { path: path.resolve(fs.realpathSync.native(targetPath)), resolved: true };
56+
} catch {
57+
// Broken symlinks are valid trash targets. Fall back to the lexical path,
58+
// then rely on lstat identity so the move renames the symlink itself.
59+
return { path: path.resolve(targetPath), resolved: false };
60+
}
61+
}
62+
4963
function assertAllowedTrashTarget(
5064
targetPath: string,
5165
allowedRoots?: Iterable<string>,
5266
): TrashTargetGuard {
53-
let resolvedTargetPath = path.resolve(targetPath);
54-
const stat = fs.lstatSync(resolvedTargetPath);
55-
try {
56-
resolvedTargetPath = path.resolve(fs.realpathSync.native(targetPath));
57-
} catch {
58-
// The subsequent move will surface missing or inaccessible targets.
59-
}
67+
const stat = fs.lstatSync(path.resolve(targetPath));
68+
const resolvedTarget = resolveTrashTargetPath(targetPath);
69+
const resolvedTargetPath = resolvedTarget.path;
6070
const isAllowed = resolveAllowedTrashRoots(allowedRoots).some(
6171
(root) => resolvedTargetPath !== root && isSameOrChildPath(resolvedTargetPath, root),
6272
);
6373
if (!isAllowed) {
6474
throw new Error(`Refusing to trash path outside allowed roots: ${targetPath}`);
6575
}
66-
return { path: path.resolve(targetPath), realPath: resolvedTargetPath, stat };
76+
return {
77+
path: path.resolve(targetPath),
78+
realPath: resolvedTargetPath,
79+
realPathResolved: resolvedTarget.resolved,
80+
stat,
81+
};
6782
}
6883

6984
function assertTrashTargetGuard(guard: TrashTargetGuard): void {
7085
const stat = fs.lstatSync(guard.path);
7186
if (!sameFileIdentity(stat, guard.stat)) {
7287
throw new Error(`Refusing to trash path after it changed: ${guard.path}`);
7388
}
74-
const realPath = path.resolve(fs.realpathSync.native(guard.path));
75-
if (realPath !== guard.realPath) {
89+
const current = resolveTrashTargetPath(guard.path);
90+
if (guard.realPathResolved && (!current.resolved || current.path !== guard.realPath)) {
91+
throw new Error(`Refusing to trash path after it changed: ${guard.path}`);
92+
}
93+
if (!guard.realPathResolved && current.resolved) {
7694
throw new Error(`Refusing to trash path after it changed: ${guard.path}`);
7795
}
7896
}

‎test/edge-coverage.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,4 +229,21 @@ describe("trash edge paths", () => {
229229
await fs.rm(path.dirname(copiedDest), { recursive: true, force: true });
230230
}
231231
});
232+
233+
it.runIf(process.platform !== "win32")("moves broken symlinks to trash", async () => {
234+
const root = await tempRoot("fs-safe-trash-broken-link-");
235+
const linkPath = path.join(root, "broken-link");
236+
const missingTarget = path.join(root, "missing-target");
237+
await fs.symlink(missingTarget, linkPath);
238+
239+
const dest = await movePathToTrash(linkPath, { allowedRoots: [root] });
240+
try {
241+
// Broken links cannot be realpathed; the guard keeps lstat identity and
242+
// renames the link itself instead of requiring the target to exist.
243+
await expect(fs.readlink(dest)).resolves.toBe(missingTarget);
244+
await expect(fs.lstat(linkPath)).rejects.toMatchObject({ code: "ENOENT" });
245+
} finally {
246+
await fs.rm(path.dirname(dest), { recursive: true, force: true });
247+
}
248+
});
232249
});

‎test/platform-fallback-coverage.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,21 @@ describe("platform fallback coverage", () => {
7272
code: "ENOENT",
7373
});
7474
});
75+
76+
it("prunes empty directories through the Windows remove fallback", async () => {
77+
await importRootForPlatform("win32");
78+
const { fileStore } = await import("../src/file-store.js");
79+
const rootDir = await tempRoot("fs-safe-win-prune-");
80+
const store = fileStore({ rootDir });
81+
const stalePath = path.join(rootDir, "old", "stale.txt");
82+
await fs.mkdir(path.dirname(stalePath), { recursive: true });
83+
await fs.writeFile(stalePath, "stale", "utf8");
84+
await fs.utimes(stalePath, new Date(0), new Date(0));
85+
86+
await store.pruneExpired({ ttlMs: 1, recursive: true, pruneEmptyDirs: true });
87+
88+
// Root.remove's Node fallback must use rmdir for empty directories; fs.rm
89+
// without recursive rejects dirs and would silently leave pruneEmptyDirs work.
90+
await expect(fs.stat(path.join(rootDir, "old"))).rejects.toMatchObject({ code: "ENOENT" });
91+
});
7592
});

0 commit comments

Comments
 (0)