Skip to content

Commit 8587c77

Browse files
fix(credentials): use wx exclusive create for lock acquisition
renameSync atomically replaces an existing lock file on POSIX, so two contending processes can overwrite lockPath and both enter the critical section. writeFileSync with flag 'wx' creates the lock with full PID and timestamp content in one syscall, preserving mutual exclusion without the open-then-write TOCTOU window.
1 parent a92720a commit 8587c77

1 file changed

Lines changed: 1 addition & 8 deletions

File tree

src/lib/credentials.ts

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -220,17 +220,10 @@ function acquireCredentialsLock(credentialsPath: string): void {
220220
mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
221221
const deadline = Date.now() + CREDENTIALS_LOCK_MAX_WAIT_MS;
222222
while (Date.now() < deadline) {
223-
const tmp = `${lockPath}.tmp.${process.pid}.${Date.now()}`;
224-
writeFileSync(tmp, `${process.pid}\n${Date.now()}\n`, 'utf8');
225223
try {
226-
renameSync(tmp, lockPath);
224+
writeFileSync(lockPath, `${process.pid}\n${Date.now()}\n`, { flag: 'wx', encoding: 'utf8' });
227225
return;
228226
} catch (err) {
229-
try {
230-
unlinkSync(tmp);
231-
} catch {
232-
// Best-effort cleanup of the unclaimed temp file.
233-
}
234227
const code = (err as NodeJS.ErrnoException).code;
235228
if (code !== 'EEXIST') throw err;
236229
if (isStaleCredentialsLock(lockPath)) {

0 commit comments

Comments
 (0)