Files
claude-code/src/utils/fsOperations.ts
Dosion c2ac9a74c1 fix: resolve dependency audit findings precisely (#361)
* fix: harden ACP communication boundaries

Harden ACP communication boundaries

Remote ACP sessions now cannot widen permission mode through untrusted
metadata or client payloads. WebSocket ACP ingress measures payloads by bytes
before binary decode, and prompt queue handoff keeps exactly one prompt active
while queued prompts are drained FIFO.

Constraint: ACP remote clients must not be able to open bypassPermissions without local launch intent
Constraint: WebSocket payload limits must be byte-based and checked before binary decode
Rejected: Keep promptToQueryContent wrapper | no production consumers remained after prompt conversion single-sourcing
Confidence: high
Scope-risk: moderate
Directive: Do not re-enable remote bypassPermissions from _meta unless a local launch gate is verified in both acp-link and agent
Tested: targeted ACP/RCS/acp-link prompt queue, bridge, permission, payload, and prompt conversion tests; bun run typecheck; bun run build
Not-tested: Manual live ACP/RCS session against an external client

* fix: restore repository verification gates

Keep the full repository test, typecheck, build, and Biome lint gates usable
after the ACP fix pass. This commit is intentionally separate from the ACP
behavior change: it fixes Windows-safe Langfuse home redaction, removes stale
lint suppressions, resolves Biome warning/info diagnostics, and keeps env
expansion tests explicit without template-placeholder lint noise.

Constraint: The project completion contract requires full typecheck, lint, test, and build evidence
Rejected: Leave warning/info diagnostics as historical noise | they obscure future gate regressions and weaken flow-impact claims
Confidence: high
Scope-risk: narrow
Directive: Keep repository gate cleanup separate from feature fixes when it is not part of the same runtime path
Tested: bunx biome lint src/; bunx tsc --noEmit; bun test src/services/mcp/__tests__/envExpansion.test.ts src/utils/__tests__/sliceAnsi.test.ts src/utils/__tests__/stringUtils.test.ts; bun test; bun run build
Not-tested: Manual Langfuse export against a real external Langfuse service

* fix: harden ACP failure boundaries after review

Deep review found several paths that made ACP communication failures look normal: prompt errors could finish as end_turn, permission pipeline exceptions could fall through to client approval, tool rawInput was deep-copied with JSON, and acp-link accepted unbounded or unvalidated WebSocket payloads. This keeps the behavior fail-closed, validates WS payloads before dispatch, caps payload size before JSON parse, and preserves cancellation intent with a generation counter.

Constraint: User explicitly rejected pseudo-fixes, fallback behavior, and unbounded payload handling

Rejected: Keep JSON stringify/parse rawInput copy | duplicates large payloads and silently drops non-JSON inputs

Rejected: Delegate permission pipeline errors to client approval | allows a broken local permission check to be bypassed

Confidence: high

Scope-risk: moderate

Directive: Do not convert ACP errors into normal end_turn responses without a protocol-level reason and regression tests

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test packages/acp-link/src/__tests__/server.test.ts

Tested: bunx tsc --noEmit

Tested: bunx biome lint src/ packages/acp-link/src/

Tested: bun run test:all

Tested: bun run build

Not-tested: Manual end-to-end ACP client session over a real editor WebSocket

* fix: prevent ACP coverage runs from seeing partial mocks

GitHub Actions failed under bun test --coverage because permissions.test.ts replaced ../bridge.js with a partial mock that omitted forwardSessionUpdates. Coverage worker ordering on Linux let sibling tests observe that incomplete module.

This isolates ACP test mocks by snapshotting real exports, overriding only requested symbols, and restoring mocks in LIFO order. The shared helper also keeps the same behavior in agent.test.ts without duplicating mock infrastructure.

Constraint: bun:test mock.module is process-global inside a worker.

Rejected: Add fallback exports or production guards | the bridge export exists; the failure was test mock pollution.

Rejected: Keep per-file helper copies | duplication would let restore semantics drift again.

Confidence: high

Scope-risk: narrow

Directive: Prefer safeMockModule for partial mocks of real modules in ACP tests; plain mock.module is only appropriate for fully synthetic modules or isolated tests.

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test --coverage --coverage-reporter=lcov

Tested: bunx tsc --noEmit

Tested: bun run lint

Tested: git diff --check

Not-tested: Linux runner directly before push

* fix: normalize ACP bypass requests without warning noise

The previous CI repair removed the failing partial bridge mock, but it also added a shared safeMockModule helper and left the acp-link bypass normalization warning in the real new_session path.

This tightens the fix: acp-link now treats an unauthorized client bypass request as normal permission-mode normalization without emitting a warning, and the ACP permission test explicitly preserves the real bridge and permission exports instead of using a shared helper. The agent test keeps its local mock preservation but names it by behavior and restores mocks in LIFO order.

Constraint: CI output should not contain expected warning noise for covered policy branches.

Rejected: Silence the test only | the normal new_session path would still warn for an expected normalization branch.

Rejected: Keep the shared safeMockModule helper | the failing module was specific and should be fixed by preserving real exports at the mocking site.

Confidence: high

Scope-risk: narrow

Directive: Treat client-requested bypassPermissions as data to normalize unless the local default explicitly enables bypass.

Tested: bun test packages/acp-link/src/__tests__/server.test.ts

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test --coverage --coverage-reporter=lcov with UPPER_WARN_COUNT=0

Tested: bun run test:all

Tested: bun run lint

Tested: bunx tsc --noEmit

Tested: git diff --check

* fix: harden ACP bypass and CI warning gates

ACP clients must not be able to enter bypassPermissions unless the local ACP gate and process environment both allow it. The same gate now controls session creation, explicit mode changes, and the ExitPlanMode option list, while session setup restores process.cwd so coverage and later work do not inherit ACP session state.

Constraint: CI must stay warning-clean without hiding real ACP permission failures

Rejected: Logging rejected bypass requests on the normal new_session path | it preserves audit text but reintroduces warning noise the runtime should not emit

Rejected: Broad CI=true postinstall skip | it hides explicit Chrome MCP setup checks outside the install path

Confidence: high

Scope-risk: moderate

Directive: Keep bypassPermissions gated through one ACP availability decision before exposing it to clients

Tested: bun test src/services/acp/__tests__/permissions.test.ts src/services/acp/__tests__/agent.test.ts packages/acp-link/src/__tests__/server.test.ts

Tested: bun run test:all

Tested: bun run lint

Tested: bun run build:vite with zero warning matches

Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage produced non-empty lcov with SF records and zero filtered warning matches

Not-tested: GitHub Actions result after this push

* fix: remove remaining CI warning noise

The CI log still had three non-failing warnings after the ACP hardening commit: git init default-branch advice from checkout, a Node 20 action-runtime deprecation, and one additional known Vite dynamic-import diagnostic that only surfaced on Linux. The workflow now provides explicit git config and opts actions into Node 24, while Vite keeps a narrow allowlist for acknowledged optimizer diagnostics.

Constraint: Do not use shell log filtering to hide warnings after they happen

Rejected: Grep warning lines out of CI output | it would make future diagnostics harder to find

Confidence: high

Scope-risk: narrow

Directive: Add new Vite warning allowlist entries only after checking that they are existing optimizer diagnostics, not new application defects

Tested: bunx tsc --noEmit --pretty false

Tested: bunx biome lint .github/workflows/ci.yml vite.config.ts

Tested: bun run build:vite with zero warning matches

Not-tested: GitHub Actions result after this push

* fix: reject unauthorized ACP bypass and harden CI actions

ACP clients now fail closed when permissionMode is malformed, unknown, or requests bypass without a local bypass opt-in. acp-link validates new_session input before forwarding to the agent and returns client error frames for expected unauthorized requests without logging create-failed noise. The direct AcpAgent path independently rejects invalid _meta.permissionMode and unauthorized bypass instead of falling back to settings.

CI workflows and generated GitHub App templates now use Node 24-compatible actions pinned to immutable commit SHAs, and acp-link startup output no longer prints the auth token.

Constraint: Must not hide warnings with test isolation or log filtering

Rejected: Silent fallback to local permission mode | accepts invalid client intent and masks boundary behavior

Rejected: Broad dependency churn from bun update | audit remained failing while package and lockfile churn expanded scope

Confidence: high

Scope-risk: moderate

Directive: Client-provided permissionMode must stay fail-closed before reaching AcpAgent; only local settings.defaultMode may fall back to default on invalid local config

Tested: bun test packages/acp-link/src/__tests__/server.test.ts src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/permissions.test.ts src/services/skillLearning/__tests__/skillLifecycle.test.ts src/utils/settings/__tests__/config.test.ts

Tested: bunx tsc -p packages/acp-link/tsconfig.json --noEmit --pretty false

Tested: bunx tsc --noEmit --pretty false

Tested: bun run lint

Tested: bun run test:all

Tested: local CI equivalent install/typecheck/coverage/build with warning_scan=0

Not-tested: Pre-existing bun audit vulnerabilities require a separate dependency-hardening PR

* fix: resolve dependency audit findings precisely

Use dependency-native upgrades and lockfile resolution to close the audit findings without suppressions. Keep the chrome MCP setup aligned with the new dependency graph and add real integration coverage so the override behavior stays verified.

Constraint: no audit ignores or warning suppression
Rejected: broad google-auth/protobuf overrides | replaced with upstream-compatible resolution
Confidence: high
Scope-risk: moderate
Directive: keep dependency fixes upstream-compatible; do not reintroduce blanket overrides unless the audit surface changes materially
Tested: bun audit; bun audit --json; bun install --frozen-lockfile with CLAUDE_CODE_SKIP_CHROME_MCP_SETUP=1; bunx tsc --noEmit --pretty false; bun run lint; targeted tests; bun run test:all; bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run build:vite
Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks

* fix: keep ACP auth tokens out of URLs

Replace the ad hoc URL-token flow with crypto UUID-backed transport identifiers so the bearer token stays in structured request data instead of query strings. Keep the server, web client, and transport helpers aligned so the ACP/RCS handshake remains compatible after the API shape change.

Constraint: token must not be embedded in the URL
Rejected: token-as-uuid query fallback | leaked bearer tokens in URLs
Confidence: high
Scope-risk: moderate
Directive: preserve the structured auth path; do not reintroduce query-token fallback when adjusting ACP transport code
Tested: targeted ACP/RCS transport tests
Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks

* fix: normalize WebFetch request headers

Normalize WebFetch headers before dispatch so canonicalization preserves auth semantics and duplicate forms do not slip through. Keep the behavior locked with a focused header test instead of broadening the request pipeline.

Constraint: preserve header semantics without widening the fetch surface
Rejected: ad hoc caller-side normalization | too easy to bypass in future call sites
Confidence: high
Scope-risk: narrow
Directive: keep header normalization close to the WebFetch utility so future callers inherit the same behavior automatically
Tested: targeted WebFetch header tests
Not-tested: unrelated fetch backend behavior beyond header normalization

* fix: harden ACP remote auth surfaces

Tighten the remaining Claude security artifact items by requiring API keys on ACP global reads and relay upgrades, moving WebSocket tokens out of URLs, and replacing open web CORS with an explicit allowlist.

Constraint: Browser WebSocket clients cannot set arbitrary Authorization headers, so the token is carried in a selected subprotocol instead of a query string.
Rejected: Keep UUID auth for ACP channel groups | any caller can mint a UUID and read global ACP data.
Rejected: Preserve ?token= compatibility | secrets leak into logs, history, referrers, and intermediaries.
Confidence: high
Scope-risk: moderate
Directive: Do not reintroduce query-string bearer tokens; use Authorization or rcs.auth.<base64url-token>.
Tested: bunx tsc --noEmit --pretty false
Tested: bun run typecheck in packages/remote-control-server
Tested: bun run build in packages/acp-link
Tested: bun run lint
Tested: bun audit
Tested: focused RCS/acp-link/web tests, 160 pass
Tested: Edge headless browser WebSocket subprotocol handshake
Tested: bun run test:all, 3669 pass
Tested: bun run build:vite
Tested: bun run build
Not-tested: Manual end-to-end relay with a live external ACP agent

* fix: resolve CI dependency override lookup

The CI runner does not expose @grpc/proto-loader as a root-resolvable package, and the test was relying on local hoisting rather than the real dependency owner. Resolve proto-loader through @opentelemetry/exporter-trace-otlp-grpc and @grpc/grpc-js so the smoke test follows the package graph it is validating.

Constraint: Do not add a new root dependency for a transitive smoke test.

Rejected: Skip or weaken the test | the test protects the protobuf 7 override path and should keep exercising loadSync.

Rejected: Add @grpc/proto-loader directly to root package.json | that hides the owning-package resolution issue and broadens dependency surface.

Confidence: high

Scope-risk: narrow

Directive: Dependency override smoke tests should resolve from the package that actually owns the dependency, not from incidental root hoisting.

Tested: bun test tests/integration/dependency-overrides.test.ts; bunx tsc --noEmit --pretty false; bun run lint; bun audit; bun run test:all; git diff --check

---------

Co-authored-by: unraid <local@unraid.local>
2026-04-26 19:49:54 +08:00

771 lines
24 KiB
TypeScript

import * as fs from 'fs'
import {
mkdir as mkdirPromise,
open,
readdir as readdirPromise,
readFile as readFilePromise,
rename as renamePromise,
rmdir as rmdirPromise,
rm as rmPromise,
stat as statPromise,
unlink as unlinkPromise,
} from 'fs/promises'
import { homedir } from 'os'
import * as nodePath from 'path'
import { getErrnoCode } from './errors.js'
import { slowLogging } from './slowOperations.js'
/**
* Simplified filesystem operations interface based on Node.js fs module.
* Provides a subset of commonly used sync operations with type safety.
* Allows abstraction for alternative implementations (e.g., mock, virtual).
*/
export type FsOperations = {
// File access and information operations
/** Gets the current working directory */
cwd(): string
/** Checks if a file or directory exists */
existsSync(path: string): boolean
/** Gets file stats asynchronously */
stat(path: string): Promise<fs.Stats>
/** Lists directory contents with file type information asynchronously */
readdir(path: string): Promise<fs.Dirent[]>
/** Deletes file asynchronously */
unlink(path: string): Promise<void>
/** Removes an empty directory asynchronously */
rmdir(path: string): Promise<void>
/** Removes files and directories asynchronously (with recursive option) */
rm(
path: string,
options?: { recursive?: boolean; force?: boolean },
): Promise<void>
/** Creates directory recursively asynchronously. */
mkdir(path: string, options?: { mode?: number }): Promise<void>
/** Reads file content as string asynchronously */
readFile(path: string, options: { encoding: BufferEncoding }): Promise<string>
/** Renames/moves file asynchronously */
rename(oldPath: string, newPath: string): Promise<void>
/** Gets file stats */
statSync(path: string): fs.Stats
/** Gets file stats without following symlinks */
lstatSync(path: string): fs.Stats
// File content operations
/** Reads file content as string with specified encoding */
readFileSync(
path: string,
options: {
encoding: BufferEncoding
},
): string
/** Reads raw file bytes as Buffer */
readFileBytesSync(path: string): Buffer
/** Reads specified number of bytes from file start */
readSync(
path: string,
options: {
length: number
},
): {
buffer: Buffer
bytesRead: number
}
/** Appends string to file */
appendFileSync(path: string, data: string, options?: { mode?: number }): void
/** Copies file from source to destination */
copyFileSync(src: string, dest: string): void
/** Deletes file */
unlinkSync(path: string): void
/** Renames/moves file */
renameSync(oldPath: string, newPath: string): void
/** Creates hard link */
linkSync(target: string, path: string): void
/** Creates symbolic link */
symlinkSync(
target: string,
path: string,
type?: 'dir' | 'file' | 'junction',
): void
/** Reads symbolic link */
readlinkSync(path: string): string
/** Resolves symbolic links and returns the canonical pathname */
realpathSync(path: string): string
// Directory operations
/** Creates directory recursively. Mode defaults to 0o777 & ~umask if not specified. */
mkdirSync(
path: string,
options?: {
mode?: number
},
): void
/** Lists directory contents with file type information */
readdirSync(path: string): fs.Dirent[]
/** Lists directory contents as strings */
readdirStringSync(path: string): string[]
/** Checks if the directory is empty */
isDirEmptySync(path: string): boolean
/** Removes an empty directory */
rmdirSync(path: string): void
/** Removes files and directories (with recursive option) */
rmSync(
path: string,
options?: {
recursive?: boolean
force?: boolean
},
): void
/** Create a writable stream for writing data to a file. */
createWriteStream(path: string): fs.WriteStream
/** Reads raw file bytes as Buffer asynchronously.
* When maxBytes is set, only reads up to that many bytes. */
readFileBytes(path: string, maxBytes?: number): Promise<Buffer>
}
/**
* Safely resolves a file path, handling symlinks and errors gracefully.
*
* Error handling strategy:
* - If the file doesn't exist, returns the original path (allows for file creation)
* - If symlink resolution fails (broken symlink, permission denied, circular links),
* returns the original path and marks it as not a symlink
* - This ensures operations can continue with the original path rather than failing
*
* @param fs The filesystem implementation to use
* @param filePath The path to resolve
* @returns Object containing the resolved path and whether it was a symlink
*/
export function safeResolvePath(
fs: FsOperations,
filePath: string,
): { resolvedPath: string; isSymlink: boolean; isCanonical: boolean } {
// Block UNC paths before any filesystem access to prevent network
// requests (DNS/SMB) during validation on Windows
if (filePath.startsWith('//') || filePath.startsWith('\\\\')) {
return { resolvedPath: filePath, isSymlink: false, isCanonical: false }
}
try {
// Check for special file types (FIFOs, sockets, devices) before calling realpathSync.
// realpathSync can block on FIFOs waiting for a writer, causing hangs.
// If the file doesn't exist, lstatSync throws ENOENT which the catch
// below handles by returning the original path (allows file creation).
const stats = fs.lstatSync(filePath)
if (
stats.isFIFO() ||
stats.isSocket() ||
stats.isCharacterDevice() ||
stats.isBlockDevice()
) {
return { resolvedPath: filePath, isSymlink: false, isCanonical: false }
}
const resolvedPath = fs.realpathSync(filePath)
return {
resolvedPath,
isSymlink: resolvedPath !== filePath,
// realpathSync returned: resolvedPath is canonical (all symlinks in
// all path components resolved). Callers can skip further symlink
// resolution on this path.
isCanonical: true,
}
} catch (_error) {
// If lstat/realpath fails for any reason (ENOENT, broken symlink,
// EACCES, ELOOP, etc.), return the original path to allow operations
// to proceed
return { resolvedPath: filePath, isSymlink: false, isCanonical: false }
}
}
/**
* Check if a file path is a duplicate and should be skipped.
* Resolves symlinks to detect duplicates pointing to the same file.
* If not a duplicate, adds the resolved path to loadedPaths.
*
* @returns true if the file should be skipped (is duplicate)
*/
export function isDuplicatePath(
fs: FsOperations,
filePath: string,
loadedPaths: Set<string>,
): boolean {
const { resolvedPath } = safeResolvePath(fs, filePath)
if (loadedPaths.has(resolvedPath)) {
return true
}
loadedPaths.add(resolvedPath)
return false
}
/**
* Resolve the deepest existing ancestor of a path via realpathSync, walking
* up until it succeeds. Detects dangling symlinks (link entry exists, target
* doesn't) via lstat and resolves them via readlink.
*
* Use when the input path may not exist (new file writes) and you need to
* know where the write would ACTUALLY land after the OS follows symlinks.
*
* Returns the resolved absolute path with non-existent tail segments
* rejoined, or undefined if no symlink was found in any existing ancestor
* (the path's existing ancestors all resolve to themselves).
*
* Handles: live parent symlinks, dangling file symlinks, dangling parent
* symlinks. Same core algorithm as teamMemPaths.ts:realpathDeepestExisting.
*/
export function resolveDeepestExistingAncestorSync(
fs: FsOperations,
absolutePath: string,
): string | undefined {
let dir = absolutePath
const segments: string[] = []
// Walk up using lstat (cheap, O(1)) to find the first existing component.
// lstat does not follow symlinks, so dangling symlinks are detected here.
// Only call realpathSync (expensive, O(depth)) once at the end.
while (dir !== nodePath.dirname(dir)) {
let st: fs.Stats
try {
st = fs.lstatSync(dir)
} catch {
// lstat failed: truly non-existent. Walk up.
segments.unshift(nodePath.basename(dir))
dir = nodePath.dirname(dir)
continue
}
if (st.isSymbolicLink()) {
// Found a symlink (live or dangling). Try realpath first (resolves
// chained symlinks); fall back to readlink for dangling symlinks.
try {
const resolved = fs.realpathSync(dir)
return segments.length === 0
? resolved
: nodePath.join(resolved, ...segments)
} catch {
// Dangling: realpath failed but lstat saw the link entry.
const target = fs.readlinkSync(dir)
const absTarget = nodePath.isAbsolute(target)
? target
: nodePath.resolve(nodePath.dirname(dir), target)
return segments.length === 0
? absTarget
: nodePath.join(absTarget, ...segments)
}
}
// Existing non-symlink component. One realpath call resolves any
// symlinks in its ancestors. If none, return undefined (no symlink).
try {
const resolved = fs.realpathSync(dir)
if (resolved !== dir) {
return segments.length === 0
? resolved
: nodePath.join(resolved, ...segments)
}
} catch {
// realpath can still fail (e.g. EACCES in ancestors). Return
// undefined — we can't resolve, and the logical path is already
// in pathSet for the caller.
}
return undefined
}
return undefined
}
/**
* Gets all paths that should be checked for permissions.
* This includes the original path, all intermediate symlink targets in the chain,
* and the final resolved path.
*
* For example, if test.txt -> /etc/passwd -> /private/etc/passwd:
* - test.txt (original path)
* - /etc/passwd (intermediate symlink target)
* - /private/etc/passwd (final resolved path)
*
* This is important for security: a deny rule for /etc/passwd should block
* access even if the file is actually at /private/etc/passwd (as on macOS).
*
* @param path - The path to check (will be converted to absolute)
* @returns An array of absolute paths to check permissions for
*/
export function getPathsForPermissionCheck(inputPath: string): string[] {
// Expand tilde notation defensively - tools should do this in getPath(),
// but we normalize here as defense in depth for permission checking
let path = inputPath
if (path === '~') {
path = homedir().normalize('NFC')
} else if (path.startsWith('~/')) {
path = nodePath.join(homedir().normalize('NFC'), path.slice(2))
}
const pathSet = new Set<string>()
const fsImpl = getFsImplementation()
// Always check the original path
pathSet.add(path)
// Block UNC paths before any filesystem access to prevent network
// requests (DNS/SMB) during validation on Windows
if (path.startsWith('//') || path.startsWith('\\\\')) {
return Array.from(pathSet)
}
// Follow the symlink chain, collecting ALL intermediate targets
// This handles cases like: test.txt -> /etc/passwd -> /private/etc/passwd
// We want to check all three paths, not just test.txt and /private/etc/passwd
try {
let currentPath = path
const visited = new Set<string>()
const maxDepth = 40 // Prevent runaway loops, matches typical SYMLOOP_MAX
for (let depth = 0; depth < maxDepth; depth++) {
// Prevent infinite loops from circular symlinks
if (visited.has(currentPath)) {
break
}
visited.add(currentPath)
if (!fsImpl.existsSync(currentPath)) {
// Path doesn't exist (new file case). existsSync follows symlinks,
// so this is also reached for DANGLING symlinks (link entry exists,
// target doesn't). Resolve symlinks in the path and its ancestors
// so permission checks see the real destination. Without this,
// `./data -> /etc/cron.d/` (live parent symlink) or
// `./evil.txt -> ~/.ssh/authorized_keys2` (dangling file symlink)
// would allow writes that escape the working directory.
if (currentPath === path) {
const resolved = resolveDeepestExistingAncestorSync(fsImpl, path)
if (resolved !== undefined) {
pathSet.add(resolved)
}
}
break
}
const stats = fsImpl.lstatSync(currentPath)
// Skip special file types that can cause issues
if (
stats.isFIFO() ||
stats.isSocket() ||
stats.isCharacterDevice() ||
stats.isBlockDevice()
) {
break
}
if (!stats.isSymbolicLink()) {
break
}
// Get the immediate symlink target
const target = fsImpl.readlinkSync(currentPath)
// If target is relative, resolve it relative to the symlink's directory
const absoluteTarget = nodePath.isAbsolute(target)
? target
: nodePath.resolve(nodePath.dirname(currentPath), target)
// Add this intermediate target to the set
pathSet.add(absoluteTarget)
currentPath = absoluteTarget
}
} catch {
// If anything fails during chain traversal, continue with what we have
}
// Also add the final resolved path using realpathSync for completeness
// This handles any remaining symlinks in directory components
const { resolvedPath, isSymlink } = safeResolvePath(fsImpl, path)
if (isSymlink && resolvedPath !== path) {
pathSet.add(resolvedPath)
}
return Array.from(pathSet)
}
export const NodeFsOperations: FsOperations = {
cwd() {
return process.cwd()
},
existsSync(fsPath) {
using _ = slowLogging`fs.existsSync(${fsPath})`
return fs.existsSync(fsPath)
},
async stat(fsPath) {
return statPromise(fsPath)
},
async readdir(fsPath) {
return readdirPromise(fsPath, { withFileTypes: true })
},
async unlink(fsPath) {
return unlinkPromise(fsPath)
},
async rmdir(fsPath) {
return rmdirPromise(fsPath)
},
async rm(fsPath, options) {
return rmPromise(fsPath, options)
},
async mkdir(dirPath, options) {
try {
await mkdirPromise(dirPath, { recursive: true, ...options })
} catch (e) {
// Bun/Windows: recursive:true throws EEXIST on directories with the
// FILE_ATTRIBUTE_READONLY bit set (Group Policy, OneDrive, desktop.ini).
// Bun's directoryExistsAt misclassifies DIRECTORY+READONLY as not-a-dir
// (bun-internal src/sys.zig existsAtType). The dir exists; ignore.
// https://github.com/anthropics/claude-code/issues/30924
if (getErrnoCode(e) !== 'EEXIST') throw e
}
},
async readFile(fsPath, options) {
return readFilePromise(fsPath, { encoding: options.encoding })
},
async rename(oldPath, newPath) {
return renamePromise(oldPath, newPath)
},
statSync(fsPath) {
using _ = slowLogging`fs.statSync(${fsPath})`
return fs.statSync(fsPath)
},
lstatSync(fsPath) {
using _ = slowLogging`fs.lstatSync(${fsPath})`
return fs.lstatSync(fsPath)
},
readFileSync(fsPath, options) {
using _ = slowLogging`fs.readFileSync(${fsPath})`
return fs.readFileSync(fsPath, { encoding: options.encoding })
},
readFileBytesSync(fsPath) {
using _ = slowLogging`fs.readFileBytesSync(${fsPath})`
return fs.readFileSync(fsPath)
},
readSync(fsPath, options) {
using _ = slowLogging`fs.readSync(${fsPath}, ${options.length} bytes)`
let fd: number | undefined
try {
fd = fs.openSync(fsPath, 'r')
const buffer = Buffer.alloc(options.length)
const bytesRead = fs.readSync(fd, buffer, 0, options.length, 0)
return { buffer, bytesRead }
} finally {
if (fd) fs.closeSync(fd)
}
},
appendFileSync(path, data, options) {
using _ = slowLogging`fs.appendFileSync(${path}, ${data.length} chars)`
// For new files with explicit mode, use 'ax' (atomic create-with-mode) to avoid
// TOCTOU race between existence check and open. Fall back to normal append if exists.
if (options?.mode !== undefined) {
try {
const fd = fs.openSync(path, 'ax', options.mode)
try {
fs.appendFileSync(fd, data)
} finally {
fs.closeSync(fd)
}
return
} catch (e) {
if (getErrnoCode(e) !== 'EEXIST') throw e
// File exists — fall through to normal append
}
}
fs.appendFileSync(path, data)
},
copyFileSync(src, dest) {
using _ = slowLogging`fs.copyFileSync(${src}${dest})`
fs.copyFileSync(src, dest)
},
unlinkSync(path: string) {
using _ = slowLogging`fs.unlinkSync(${path})`
fs.unlinkSync(path)
},
renameSync(oldPath: string, newPath: string) {
using _ = slowLogging`fs.renameSync(${oldPath}${newPath})`
fs.renameSync(oldPath, newPath)
},
linkSync(target: string, path: string) {
using _ = slowLogging`fs.linkSync(${target}${path})`
fs.linkSync(target, path)
},
symlinkSync(
target: string,
path: string,
type?: 'dir' | 'file' | 'junction',
) {
using _ = slowLogging`fs.symlinkSync(${target}${path})`
fs.symlinkSync(target, path, type)
},
readlinkSync(path: string) {
using _ = slowLogging`fs.readlinkSync(${path})`
return fs.readlinkSync(path)
},
realpathSync(path: string) {
using _ = slowLogging`fs.realpathSync(${path})`
return fs.realpathSync(path).normalize('NFC')
},
mkdirSync(dirPath, options) {
using _ = slowLogging`fs.mkdirSync(${dirPath})`
const mkdirOptions: { recursive: boolean; mode?: number } = {
recursive: true,
}
if (options?.mode !== undefined) {
mkdirOptions.mode = options.mode
}
try {
fs.mkdirSync(dirPath, mkdirOptions)
} catch (e) {
// Bun/Windows: recursive:true throws EEXIST on directories with the
// FILE_ATTRIBUTE_READONLY bit set (Group Policy, OneDrive, desktop.ini).
// Bun's directoryExistsAt misclassifies DIRECTORY+READONLY as not-a-dir
// (bun-internal src/sys.zig existsAtType). The dir exists; ignore.
// https://github.com/anthropics/claude-code/issues/30924
if (getErrnoCode(e) !== 'EEXIST') throw e
}
},
readdirSync(dirPath) {
using _ = slowLogging`fs.readdirSync(${dirPath})`
return fs.readdirSync(dirPath, { withFileTypes: true })
},
readdirStringSync(dirPath) {
using _ = slowLogging`fs.readdirStringSync(${dirPath})`
return fs.readdirSync(dirPath)
},
isDirEmptySync(dirPath) {
using _ = slowLogging`fs.isDirEmptySync(${dirPath})`
const files = this.readdirSync(dirPath)
return files.length === 0
},
rmdirSync(dirPath) {
using _ = slowLogging`fs.rmdirSync(${dirPath})`
fs.rmdirSync(dirPath)
},
rmSync(path, options) {
using _ = slowLogging`fs.rmSync(${path})`
fs.rmSync(path, options)
},
createWriteStream(path: string) {
return fs.createWriteStream(path)
},
async readFileBytes(fsPath: string, maxBytes?: number) {
if (maxBytes === undefined) {
return readFilePromise(fsPath)
}
const handle = await open(fsPath, 'r')
try {
const { size } = await handle.stat()
const readSize = Math.min(size, maxBytes)
const buffer = Buffer.allocUnsafe(readSize)
let offset = 0
while (offset < readSize) {
const { bytesRead } = await handle.read(
buffer,
offset,
readSize - offset,
offset,
)
if (bytesRead === 0) break
offset += bytesRead
}
return offset < readSize ? buffer.subarray(0, offset) : buffer
} finally {
await handle.close()
}
},
}
// The currently active filesystem implementation
let activeFs: FsOperations = NodeFsOperations
/**
* Overrides the filesystem implementation. Note: This function does not
* automatically update cwd.
* @param implementation The filesystem implementation to use
*/
export function setFsImplementation(implementation: FsOperations): void {
activeFs = implementation
}
/**
* Gets the currently active filesystem implementation
* @returns The currently active filesystem implementation
*/
export function getFsImplementation(): FsOperations {
return activeFs
}
/**
* Resets the filesystem implementation to the default Node.js implementation.
* Note: This function does not automatically update cwd.
*/
export function setOriginalFsImplementation(): void {
activeFs = NodeFsOperations
}
export type ReadFileRangeResult = {
content: string
bytesRead: number
bytesTotal: number
}
/**
* Read up to `maxBytes` from a file starting at `offset`.
* Returns a flat string from Buffer — no sliced string references to a
* larger parent. Returns null if the file is smaller than the offset.
*/
export async function readFileRange(
path: string,
offset: number,
maxBytes: number,
): Promise<ReadFileRangeResult | null> {
await using fh = await open(path, 'r')
const size = (await fh.stat()).size
if (size <= offset) {
return null
}
const bytesToRead = Math.min(size - offset, maxBytes)
const buffer = Buffer.allocUnsafe(bytesToRead)
let totalRead = 0
while (totalRead < bytesToRead) {
const { bytesRead } = await fh.read(
buffer,
totalRead,
bytesToRead - totalRead,
offset + totalRead,
)
if (bytesRead === 0) {
break
}
totalRead += bytesRead
}
return {
content: buffer.toString('utf8', 0, totalRead),
bytesRead: totalRead,
bytesTotal: size,
}
}
/**
* Read the last `maxBytes` of a file.
* Returns the whole file if it's smaller than maxBytes.
*/
export async function tailFile(
path: string,
maxBytes: number,
): Promise<ReadFileRangeResult> {
await using fh = await open(path, 'r')
const size = (await fh.stat()).size
if (size === 0) {
return { content: '', bytesRead: 0, bytesTotal: 0 }
}
const offset = Math.max(0, size - maxBytes)
const bytesToRead = size - offset
const buffer = Buffer.allocUnsafe(bytesToRead)
let totalRead = 0
while (totalRead < bytesToRead) {
const { bytesRead } = await fh.read(
buffer,
totalRead,
bytesToRead - totalRead,
offset + totalRead,
)
if (bytesRead === 0) {
break
}
totalRead += bytesRead
}
return {
content: buffer.toString('utf8', 0, totalRead),
bytesRead: totalRead,
bytesTotal: size,
}
}
/**
* Async generator that yields lines from a file in reverse order.
* Reads the file backwards in chunks to avoid loading the entire file into memory.
* @param path - The path to the file to read
* @returns An async generator that yields lines in reverse order
*/
export async function* readLinesReverse(
path: string,
): AsyncGenerator<string, void, undefined> {
const CHUNK_SIZE = 1024 * 4
const fileHandle = await open(path, 'r')
try {
const stats = await fileHandle.stat()
let position = stats.size
// Carry raw bytes (not a decoded string) across chunk boundaries so that
// multi-byte UTF-8 sequences split by the 4KB boundary are not corrupted.
// Decoding per-chunk would turn a split sequence into U+FFFD on both sides,
// which for history.jsonl means JSON.parse throws and the entry is dropped.
let remainder = Buffer.alloc(0)
const buffer = Buffer.alloc(CHUNK_SIZE)
while (position > 0) {
const currentChunkSize = Math.min(CHUNK_SIZE, position)
position -= currentChunkSize
await fileHandle.read(buffer, 0, currentChunkSize, position)
const combined = Buffer.concat([
buffer.subarray(0, currentChunkSize),
remainder,
])
const firstNewline = combined.indexOf(0x0a)
if (firstNewline === -1) {
remainder = combined
continue
}
remainder = Buffer.from(combined.subarray(0, firstNewline))
const lines = combined.toString('utf8', firstNewline + 1).split('\n')
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i]!
if (line) {
yield line
}
}
}
if (remainder.length > 0) {
yield remainder.toString('utf8')
}
} finally {
await fileHandle.close()
}
}