qinglong/back/shared/utils.ts
copilot-swe-agent[bot] 62831835a5 Fix SSH config file permissions race condition
- Modified writeFileWithLock to create files with correct permissions immediately
- Changed string mode values to proper octal numbers (0o600, 0o400)
- This eliminates the race condition where files existed with wrong permissions

Co-authored-by: whyour <22700758+whyour@users.noreply.github.com>
2025-11-07 16:18:49 +00:00

46 lines
1.3 KiB
TypeScript

import { lock } from 'proper-lockfile';
import os from 'os';
import path from 'path';
import { writeFile, open, chmod } from 'fs/promises';
import { fileExist } from '../config/util';
function getUniqueLockPath(filePath: string) {
const sanitizedPath = filePath
.replace(/[<>:"/\\|?*]/g, '_')
.replace(/^_/, '');
return path.join(os.tmpdir(), `${sanitizedPath}.ql_lock`);
}
export async function writeFileWithLock(
filePath: string,
content: string,
options: Parameters<typeof writeFile>[2] = {},
) {
if (typeof options === 'string') {
options = { encoding: options };
}
if (!(await fileExist(filePath))) {
// Create the file with the specified mode if provided, otherwise use default
const fileMode = options?.mode || 0o666;
const fileHandle = await open(filePath, 'w', fileMode);
await fileHandle.close();
}
const lockfilePath = getUniqueLockPath(filePath);
const release = await lock(filePath, {
retries: {
retries: 10,
factor: 2,
minTimeout: 100,
maxTimeout: 3000,
},
lockfilePath,
});
await writeFile(filePath, content, { encoding: 'utf8', ...options });
// Ensure the mode is set correctly even if the file already existed
if (options?.mode) {
await chmod(filePath, options.mode);
}
await release();
}