Skip to content

Commit f748844

Browse files
authored
fix(temp): use exact identities for cleanup (#133)
* fix(temp): use exact identities for cleanup * test(temp): assert exact cleanup identities * fix(temp): keep cleanup receipts exact
1 parent e1e17e1 commit f748844

13 files changed

Lines changed: 93 additions & 37 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
### Security and Correctness
66

7-
- Preserve replaced temporary paths during Windows cleanup when libuv reports a zero device or inode, treating unknown identity as fail-closed instead of authorizing recursive deletion.
7+
- Preserve replaced temporary paths during Windows cleanup when libuv reports a zero device or inode or a file index exceeds JavaScript's safe integer range, treating unknown or rounded identity as fail-closed instead of authorizing deletion.
88

99
## 0.5.5 - 2026-08-12
1010

‎src/move-path.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ export async function movePathWithCopyFallback(
399399
sourceHardlinks: options.sourceHardlinks ?? "allow",
400400
...(rejectHardlinks ? { budget: { discovered: 1 } } : {}),
401401
});
402-
unregisterStaged.setIdentity(await fs.lstat(staged));
402+
unregisterStaged.setIdentity(await fs.lstat(staged, { bigint: true }));
403403
await assertCopyDestinationOutsideSource(sourcePath, targetPath);
404404
await guardedRename({ from: staged, to: targetPath });
405405
stagedCommitted = true;
@@ -411,7 +411,7 @@ export async function movePathWithCopyFallback(
411411
} finally {
412412
if (!stagedCommitted) {
413413
try {
414-
const stagedIdentity = await fs.lstat(staged);
414+
const stagedIdentity = await fs.lstat(staged, { bigint: true });
415415
if (!stagedIdentity.isSymbolicLink()) unregisterStaged.setIdentity(stagedIdentity);
416416
} catch (error) {
417417
if ((error as NodeJS.ErrnoException).code === "ENOENT") {

‎src/output-sibling.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ export async function writeExternalFileViaSibling<T>(params: {
112112
const result = await params.write(tempPath);
113113
const pinned = await openPinnedStagedFile(tempPath, params.maxBytes);
114114
stagedIdentity = pinned.identity;
115-
unregisterTempPath.setIdentity(stagedIdentity);
115+
unregisterTempPath.setIdentity(await pinned.handle.stat({ bigint: true }));
116116
try {
117117
if (params.mode !== undefined) {
118118
await pinned.handle.chmod(params.mode);

‎src/private-temp-workspace.ts‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ async function cleanupWorkspace(
145145
): Promise<TempWorkspaceCleanupResult> {
146146
let current;
147147
try {
148-
current = await fs.lstat(dir);
148+
current = await fs.lstat(dir, { bigint: true });
149149
} catch (error) {
150150
return (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "identity-mismatch";
151151
}
@@ -162,7 +162,7 @@ function cleanupWorkspaceSync(
162162
): TempWorkspaceCleanupResult {
163163
let current;
164164
try {
165-
current = fsSync.lstatSync(dir);
165+
current = fsSync.lstatSync(dir, { bigint: true });
166166
} catch (error) {
167167
return (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "identity-mismatch";
168168
}
@@ -183,12 +183,16 @@ async function createTempWorkspace(
183183
await ensurePrivateDirectory(root, dirMode);
184184
const dir = await fs.mkdtemp(path.join(root, sanitizeTempPrefix(options.prefix)));
185185
await fs.chmod(dir, dirMode).catch(() => undefined);
186-
const stat = await fs.lstat(dir);
186+
const stat = await fs.lstat(dir, { bigint: true });
187187
if (stat.isSymbolicLink() || !stat.isDirectory()) {
188188
throw new Error(`Temp workspace must be a directory: ${dir}`);
189189
}
190-
const identity = { dev: stat.dev, ino: stat.ino };
191-
const unregisterTempDir = registerTempPathForExit(dir, { recursive: true, identity });
190+
const identity = { dev: Number(stat.dev), ino: Number(stat.ino) };
191+
const cleanupIdentity = { dev: stat.dev, ino: stat.ino };
192+
const unregisterTempDir = registerTempPathForExit(dir, {
193+
recursive: true,
194+
identity: cleanupIdentity,
195+
});
192196
const store = fileStore({ rootDir: dir, private: true, dirMode, mode });
193197

194198
return {
@@ -216,14 +220,14 @@ async function createTempWorkspace(
216220
},
217221
cleanup: async () => {
218222
try {
219-
return await cleanupWorkspace(dir, identity);
223+
return await cleanupWorkspace(dir, cleanupIdentity);
220224
} finally {
221225
unregisterTempDir();
222226
}
223227
},
224228
[Symbol.asyncDispose]: async () => {
225229
try {
226-
await cleanupWorkspace(dir, identity);
230+
await cleanupWorkspace(dir, cleanupIdentity);
227231
} finally {
228232
unregisterTempDir();
229233
}
@@ -271,12 +275,16 @@ export function tempWorkspaceSync(
271275
} catch {
272276
// Best-effort on platforms that do not enforce POSIX modes.
273277
}
274-
const stat = fsSync.lstatSync(dir);
278+
const stat = fsSync.lstatSync(dir, { bigint: true });
275279
if (stat.isSymbolicLink() || !stat.isDirectory()) {
276280
throw new Error(`Temp workspace must be a directory: ${dir}`);
277281
}
278-
const identity = { dev: stat.dev, ino: stat.ino };
279-
const unregisterTempDir = registerTempPathForExit(dir, { recursive: true, identity });
282+
const identity = { dev: Number(stat.dev), ino: Number(stat.ino) };
283+
const cleanupIdentity = { dev: stat.dev, ino: stat.ino };
284+
const unregisterTempDir = registerTempPathForExit(dir, {
285+
recursive: true,
286+
identity: cleanupIdentity,
287+
});
280288
const store = fileStoreSync({ rootDir: dir, private: true, dirMode, mode });
281289

282290
return {
@@ -315,14 +323,14 @@ export function tempWorkspaceSync(
315323
},
316324
cleanup: () => {
317325
try {
318-
return cleanupWorkspaceSync(dir, identity);
326+
return cleanupWorkspaceSync(dir, cleanupIdentity);
319327
} finally {
320328
unregisterTempDir();
321329
}
322330
},
323331
[Symbol.dispose]: () => {
324332
try {
325-
cleanupWorkspaceSync(dir, identity);
333+
cleanupWorkspaceSync(dir, cleanupIdentity);
326334
} finally {
327335
unregisterTempDir();
328336
}

‎src/replace-file-descriptor.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import syncFs, { type Stats } from "node:fs";
1+
import syncFs, { type BigIntStats, type Stats } from "node:fs";
22
import fs, { type FileHandle } from "node:fs/promises";
33
import { FsSafeError } from "./errors.js";
44
import { sameFileIdentity } from "./file-identity.js";
@@ -86,7 +86,7 @@ export async function writeTempFile(params: {
8686
content: string | Uint8Array;
8787
mode: number;
8888
sync: boolean;
89-
}): Promise<Stats> {
89+
}): Promise<BigIntStats> {
9090
const handle = await params.fsModule.open(params.tempPath, "wx", params.mode);
9191
try {
9292
await params.fsModule.writeFile(handle, params.content);
@@ -100,7 +100,7 @@ export async function writeTempFile(params: {
100100
}
101101
}
102102
}
103-
return await handle.stat();
103+
return await handle.stat({ bigint: true });
104104
} finally {
105105
await handle.close();
106106
}
@@ -113,7 +113,7 @@ export function writeTempFileSync(params: {
113113
mode: number;
114114
fchmodSync?: SyncFchmod;
115115
sync: boolean;
116-
}): Stats {
116+
}): BigIntStats {
117117
const fd = params.fsModule.openSync(params.tempPath, "wx", params.mode);
118118
try {
119119
params.fsModule.writeFileSync(fd, params.content);
@@ -127,7 +127,7 @@ export function writeTempFileSync(params: {
127127
}
128128
}
129129
}
130-
return params.fsModule.fstatSync(fd);
130+
return params.fsModule.fstatSync(fd, { bigint: true });
131131
} finally {
132132
params.fsModule.closeSync(fd);
133133
}

‎src/root-impl.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { randomUUID } from "node:crypto";
2-
import type { Stats } from "node:fs";
2+
import type { BigIntStats, Stats } from "node:fs";
33
import { constants as fsConstants } from "node:fs";
44
import type { FileHandle } from "node:fs/promises";
55
import fs from "node:fs/promises";
@@ -800,15 +800,18 @@ async function writeTempFileForAtomicReplace(params: {
800800
data: string | Buffer;
801801
encoding?: BufferEncoding;
802802
mode: number;
803-
}): Promise<Stats> {
803+
}): Promise<{ identity: Stats; cleanupIdentity: BigIntStats }> {
804804
const tempHandle = await fs.open(params.tempPath, OPEN_WRITE_CREATE_FLAGS, params.mode);
805805
try {
806806
if (typeof params.data === "string") {
807807
await tempHandle.writeFile(params.data, params.encoding ?? "utf8");
808808
} else {
809809
await tempHandle.writeFile(params.data);
810810
}
811-
return await tempHandle.stat();
811+
return {
812+
identity: await tempHandle.stat(),
813+
cleanupIdentity: await tempHandle.stat({ bigint: true }),
814+
};
812815
} finally {
813816
await tempHandle.close().catch(() => {});
814817
}
@@ -1612,13 +1615,13 @@ async function writeFileFallback(
16121615
try {
16131616
tempPath = buildAtomicWriteTempPath(destinationPath);
16141617
unregisterTempPath = registerTempPathForExit(tempPath);
1615-
const writtenStat = await writeTempFileForAtomicReplace({
1618+
const written = await writeTempFileForAtomicReplace({
16161619
tempPath,
16171620
data: params.data,
16181621
encoding: params.encoding,
16191622
mode: mode || 0o600,
16201623
});
1621-
unregisterTempPath.setIdentity(writtenStat);
1624+
unregisterTempPath.setIdentity(written.cleanupIdentity);
16221625
const commitTempPath = tempPath;
16231626
await withAsyncDirectoryGuards([destinationGuard], async () => {
16241627
await fs.rename(commitTempPath, destinationPath);
@@ -1630,7 +1633,7 @@ async function writeFileFallback(
16301633
await verifyAtomicWriteResult({
16311634
root,
16321635
targetPath: destinationPath,
1633-
expectedIdentity: writtenStat,
1636+
expectedIdentity: written.identity,
16341637
});
16351638
} catch (err) {
16361639
emitWriteBoundaryWarning(`post-write verification failed: ${String(err)}`);

‎src/sibling-temp.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ export async function writeSiblingTempFile<T>(
7272
try {
7373
tempExists = true;
7474
const result = await options.writeTemp(tempPath);
75-
unregisterTempPath.setIdentity(await fs.lstat(tempPath));
75+
unregisterTempPath.setIdentity(await fs.lstat(tempPath, { bigint: true }));
7676
if (options.mode !== undefined) {
7777
await fs.chmod(tempPath, options.mode).catch(() => undefined);
7878
}

‎src/temp-cleanup.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ function pathStillMatchesReceipt(entry: TempCleanupEntry): boolean {
2121
return false;
2222
}
2323
try {
24-
return sameFileIdentityForCleanup(fsSync.lstatSync(entry.path), entry.identity);
24+
return sameFileIdentityForCleanup(
25+
fsSync.lstatSync(entry.path, { bigint: true }),
26+
entry.identity,
27+
);
2528
} catch (error) {
2629
return (error as NodeJS.ErrnoException).code === "ENOENT";
2730
}
@@ -55,7 +58,7 @@ export function registerTempPathForExit(
5558
};
5659
if (!entry.identity) {
5760
try {
58-
entry.identity = fsSync.lstatSync(tempPath);
61+
entry.identity = fsSync.lstatSync(tempPath, { bigint: true });
5962
} catch {
6063
// Callers that register before creation set the identity after opening.
6164
}

‎src/temp-target.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import crypto from "node:crypto";
2-
import { lstat, mkdtemp, rm } from "node:fs/promises";
2+
import fs from "node:fs/promises";
33
import path from "node:path";
44
import { sameFileIdentityForCleanup, type FileIdentityStat } from "./file-identity.js";
55
import { assertSafePathSegment, sanitizeSafePathSegment } from "./safe-path-segment.js";
@@ -128,7 +128,7 @@ async function cleanupTempDir(
128128
onCleanupError?: (error: unknown) => void,
129129
) {
130130
try {
131-
const current = await lstat(dir).catch((error: unknown) => {
131+
const current = await fs.lstat(dir, { bigint: true }).catch((error: unknown) => {
132132
if (isNodeErrorWithCode(error, "ENOENT")) {
133133
return undefined;
134134
}
@@ -137,7 +137,7 @@ async function cleanupTempDir(
137137
if (!current || !sameFileIdentityForCleanup(current, identity)) {
138138
return;
139139
}
140-
await rm(dir, { recursive: true, force: true });
140+
await fs.rm(dir, { recursive: true, force: true });
141141
} catch (err) {
142142
if (!isNodeErrorWithCode(err, "ENOENT")) {
143143
onCleanupError?.(err);
@@ -157,8 +157,10 @@ export async function tempFile(params: {
157157
}): Promise<TempFile> {
158158
const rootDir = resolveTempRoot(params.rootDir);
159159
const prefix = `${sanitizePrefix(params.prefix)}-`;
160-
const dir = await mkdtemp(path.join(rootDir, prefix));
161-
const identity = await lstat(dir);
160+
const dir = await fs.mkdtemp(path.join(rootDir, prefix));
161+
// Windows file indexes can exceed Number.MAX_SAFE_INTEGER. Cleanup receipts
162+
// must retain the exact identity or adjacent directories can compare equal.
163+
const identity = await fs.lstat(dir, { bigint: true });
162164
const unregisterTempDir = registerTempPathForExit(dir, { recursive: true, identity });
163165
const file = (fileName?: string) =>
164166
path.join(dir, sanitizeTempFileName(fileName ?? params.fileName ?? "download.bin"));

‎test/additional-boundary-bypass.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,17 @@ describe("additional helper boundary bypass attempts", () => {
9090
.resolves.toBe("keep");
9191
});
9292

93+
it("captures exact directory identities for temp file cleanup", async () => {
94+
const layout = await makeTempLayout("fs-safe-temp-exact-identity", tempDirs);
95+
const lstat = vi.spyOn(fsp, "lstat");
96+
const target = await tempFile({ rootDir: layout.root, prefix: "download" });
97+
expect(lstat).toHaveBeenCalledWith(target.dir, { bigint: true });
98+
99+
lstat.mockClear();
100+
await target.cleanup();
101+
expect(lstat).toHaveBeenCalledWith(target.dir, { bigint: true });
102+
});
103+
93104
it("rejects remote or encoded-separator file URLs while accepting local file URLs", () => {
94105
const local = pathToFileURL(path.join(os.tmpdir(), "safe.txt")).toString();
95106
expect(safeFileURLToPath(local)).toBe(path.join(os.tmpdir(), "safe.txt"));

0 commit comments

Comments
 (0)