← Back to PRs

#10729: fix: replace existsSync+readFileSync with try-catch in env-file

by Yida-Dev open 2026-02-06 22:17 View on GitHub →
stale
## Summary - The `upsertSharedEnvVar` function uses `existsSync` followed by `readFileSync`, creating a TOCTOU (time-of-check-time-of-use) race condition where the file could be deleted between the existence check and the read - Replace with a direct `readFileSync` wrapped in try-catch that only catches `ENOENT`, which is both race-free and idiomatic Node.js - Also remove the redundant `existsSync` guard before `mkdirSync({ recursive: true })`, since `recursive: true` is already a no-op when the directory exists ## Test plan - [x] Manual verification: function behavior is identical for existing file, missing file, and missing directory cases - [x] The try-catch properly re-throws non-ENOENT errors (e.g. permission denied) Generated with [Claude Code](https://claude.com/claude-code) <!-- greptile_comment --> <h2>Greptile Overview</h2> <h3>Greptile Summary</h3> - Updates `upsertSharedEnvVar` to avoid a TOCTOU race by removing `existsSync` and reading the `.env` file directly inside a try/catch that only swallows `ENOENT`. - Simplifies directory creation by calling `mkdirSync(dir, { recursive: true })` unconditionally instead of guarding with `existsSync`. - Keeps existing behavior for updating/adding the requested key and writing the `.env` file with locked-down permissions. <h3>Confidence Score: 5/5</h3> - This PR is safe to merge with minimal risk. - The change is small, localized to `src/infra/env-file.ts`, and replaces an `existsSync` + `readFileSync` sequence with an idiomatic ENOENT-only try/catch that preserves semantics while removing a TOCTOU window. The unconditional `mkdirSync(..., { recursive: true })` is also standard and aligns with Node’s documented behavior. - No files require special attention <!-- greptile_other_comments_section --> **Context used:** - Context from `dashboard` - CLAUDE.md ([source](https://app.greptile.com/review/custom-context?memory=fd949e91-5c3a-4ab5-90a1-cbe184fd6ce8)) - Context from `dashboard` - AGENTS.md ([source](https://app.greptile.com/review/custom-context?memory=0d0c8278-ef8e-4d6c-ab21-f5527e322f13)) <!-- /greptile_comment -->

Most Similar PRs