|
| 1 | +import { randomUUID } from "node:crypto"; |
| 2 | +import fsSync from "node:fs"; |
| 3 | +import fs, { type FileHandle } from "node:fs/promises"; |
| 4 | +import path from "node:path"; |
| 5 | +import { createAsyncDirectoryGuard } from "./directory-guard.js"; |
| 6 | +import { syncDirectoryBestEffort } from "./directory-durability.js"; |
| 7 | +import { FsSafeError } from "./errors.js"; |
| 8 | +import { sameFileIdentity } from "./file-identity.js"; |
| 9 | +import { withAsyncDirectoryGuards } from "./guarded-mutation.js"; |
| 10 | +import { sanitizeUntrustedFileName } from "./filename.js"; |
| 11 | +import { registerTempPathForExit } from "./temp-cleanup.js"; |
| 12 | +import { serializePathWrite } from "./write-queue.js"; |
| 13 | + |
| 14 | +const OPEN_READ_WRITE_NOFOLLOW = |
| 15 | + fsSync.constants.O_RDWR | |
| 16 | + (process.platform !== "win32" && typeof fsSync.constants.O_NOFOLLOW === "number" |
| 17 | + ? fsSync.constants.O_NOFOLLOW |
| 18 | + : 0); |
| 19 | + |
| 20 | +function safeFallbackFileName(fallbackFileName?: string): string { |
| 21 | + return sanitizeUntrustedFileName(fallbackFileName ?? "output.bin", "output.bin"); |
| 22 | +} |
| 23 | + |
| 24 | +function buildSiblingTempPath(targetPath: string, fallbackFileName?: string): string { |
| 25 | + const safeTail = sanitizeUntrustedFileName( |
| 26 | + path.basename(targetPath), |
| 27 | + safeFallbackFileName(fallbackFileName), |
| 28 | + ); |
| 29 | + return path.join( |
| 30 | + path.dirname(targetPath), |
| 31 | + `.fs-safe-output-${process.pid}-${randomUUID()}-${safeTail}.part`, |
| 32 | + ); |
| 33 | +} |
| 34 | + |
| 35 | +function assertStagedFile( |
| 36 | + pathname: Awaited<ReturnType<typeof fs.lstat>>, |
| 37 | + opened: Awaited<ReturnType<FileHandle["stat"]>>, |
| 38 | + maxBytes?: number, |
| 39 | +): void { |
| 40 | + if (pathname.isSymbolicLink() || !pathname.isFile() || !opened.isFile()) { |
| 41 | + throw new FsSafeError("not-file", "sibling-staged output must be a regular file"); |
| 42 | + } |
| 43 | + if (!sameFileIdentity(pathname, opened)) { |
| 44 | + throw new FsSafeError("path-mismatch", "sibling-staged output changed while opening"); |
| 45 | + } |
| 46 | + if (opened.nlink > 1) { |
| 47 | + throw new FsSafeError("hardlink", "hardlinked sibling-staged output not allowed"); |
| 48 | + } |
| 49 | + if (maxBytes !== undefined && opened.size > maxBytes) { |
| 50 | + throw new FsSafeError("too-large", `sibling-staged output exceeds maxBytes (${maxBytes})`); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +async function openPinnedStagedFile( |
| 55 | + tempPath: string, |
| 56 | + maxBytes?: number, |
| 57 | +): Promise<{ handle: FileHandle; identity: Awaited<ReturnType<FileHandle["stat"]>> }> { |
| 58 | + const preview = await fs.lstat(tempPath); |
| 59 | + if (preview.isSymbolicLink()) { |
| 60 | + throw new FsSafeError("symlink", "symlink sibling-staged output not allowed"); |
| 61 | + } |
| 62 | + const handle = await fs.open(tempPath, OPEN_READ_WRITE_NOFOLLOW); |
| 63 | + try { |
| 64 | + const identity = await handle.stat(); |
| 65 | + assertStagedFile(await fs.lstat(tempPath), identity, maxBytes); |
| 66 | + return { handle, identity }; |
| 67 | + } catch (error) { |
| 68 | + await handle.close().catch(() => undefined); |
| 69 | + throw error; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +async function syncFile(handle: FileHandle): Promise<void> { |
| 74 | + try { |
| 75 | + await handle.sync(); |
| 76 | + } catch (error) { |
| 77 | + if ((error as NodeJS.ErrnoException).code !== "EPERM") throw error; |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +async function cleanupTempPath( |
| 82 | + tempPath: string, |
| 83 | + identity?: Awaited<ReturnType<FileHandle["stat"]>>, |
| 84 | +): Promise<void> { |
| 85 | + try { |
| 86 | + const current = await fs.lstat(tempPath); |
| 87 | + if (!identity || (!current.isSymbolicLink() && sameFileIdentity(current, identity))) { |
| 88 | + await fs.rm(tempPath, { force: true }); |
| 89 | + } |
| 90 | + } catch (error) { |
| 91 | + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { |
| 92 | + // Cleanup is best-effort; the randomized path remains inside the writable boundary. |
| 93 | + } |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +export async function writeExternalFileViaSibling<T>(params: { |
| 98 | + finalPath: string; |
| 99 | + write: (filePath: string) => Promise<T>; |
| 100 | + fallbackFileName?: string; |
| 101 | + maxBytes?: number; |
| 102 | + mode?: number; |
| 103 | +}): Promise<T> { |
| 104 | + const finalPath = path.resolve(params.finalPath); |
| 105 | + const parentPath = path.dirname(finalPath); |
| 106 | + const parentGuard = await createAsyncDirectoryGuard(parentPath); |
| 107 | + const tempPath = buildSiblingTempPath(finalPath, params.fallbackFileName); |
| 108 | + const unregisterTempPath = registerTempPathForExit(tempPath); |
| 109 | + let stagedIdentity: Awaited<ReturnType<FileHandle["stat"]>> | undefined; |
| 110 | + let renamed = false; |
| 111 | + |
| 112 | + try { |
| 113 | + const result = await params.write(tempPath); |
| 114 | + const pinned = await openPinnedStagedFile(tempPath, params.maxBytes); |
| 115 | + stagedIdentity = pinned.identity; |
| 116 | + unregisterTempPath.setIdentity(stagedIdentity); |
| 117 | + try { |
| 118 | + if (params.mode !== undefined) { |
| 119 | + await pinned.handle.chmod(params.mode); |
| 120 | + } |
| 121 | + await syncFile(pinned.handle); |
| 122 | + await serializePathWrite(finalPath, async () => { |
| 123 | + await withAsyncDirectoryGuards([parentGuard], async () => { |
| 124 | + const currentIdentity = await pinned.handle.stat(); |
| 125 | + assertStagedFile(await fs.lstat(tempPath), currentIdentity, params.maxBytes); |
| 126 | + if (!sameFileIdentity(currentIdentity, stagedIdentity!)) { |
| 127 | + throw new FsSafeError("path-mismatch", "sibling-staged output changed before rename"); |
| 128 | + } |
| 129 | + await fs.rename(tempPath, finalPath); |
| 130 | + renamed = true; |
| 131 | + const published = await fs.lstat(finalPath); |
| 132 | + if (published.isSymbolicLink() || !sameFileIdentity(published, currentIdentity)) { |
| 133 | + throw new FsSafeError("path-mismatch", "sibling-staged output changed during rename"); |
| 134 | + } |
| 135 | + }); |
| 136 | + await syncDirectoryBestEffort(parentPath); |
| 137 | + }); |
| 138 | + } finally { |
| 139 | + await pinned.handle.close().catch(() => undefined); |
| 140 | + } |
| 141 | + return result; |
| 142 | + } finally { |
| 143 | + if (!renamed) { |
| 144 | + await cleanupTempPath(tempPath, stagedIdentity); |
| 145 | + } |
| 146 | + unregisterTempPath(); |
| 147 | + } |
| 148 | +} |
0 commit comments