Files
Kelx/utils/atomic-file.js
T
2026-11-30 16:32:37 +00:00

99 lines
4.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
// Atomic file replacement primitive shared by every writer of security-relevant
// panel state (database-config.json, mongodb-config.json, pgadmin-config.json,
// install-job records). In-place writeFileSync leaves a torn, truncated file
// behind when the process dies (or the host loses power) mid-write; a fail-open
// loader then reads that wreckage as "nothing configured" and the next save
// persists the empty state, erasing bookkeeping while live accounts remain on
// the server. The temp-file-then-rename sequence below is the standard remedy:
// rename(2) is atomic on the same filesystem, so readers observe either the
// complete previous content or the complete new content — never a partial one.
//
// The temp file is created with O_EXCL ('wx') in the DESTINATION directory so
// the final rename never crosses a filesystem boundary, is fsynced before the
// rename so the payload hits the disk before the file becomes visible under
// its real name, and the directory entry is fsynced after the rename so the
// replacement itself survives a power cut. By default fsync is best-effort: on a
// filesystem that rejects directory fsyncs (or a sandbox without fsync) the
// write still completes — only the power-loss guarantee degrades, never the
// crash-safety of the rename itself.
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
function fsyncPath(targetPath, required) {
let fd = null;
try {
// O_RDONLY on a directory is legal on Linux/FreeBSD/macOS; on platforms
// where it is not (or the sandbox denies it) the errno is swallowed.
fd = fs.openSync(targetPath, "r");
fs.fsyncSync(fd);
} catch (err) {
if (required) throw err;
} finally {
if (fd !== null) {
try { fs.closeSync(fd); } catch (_) { }
}
}
}
function createAtomicWriteTempPath(filePath) {
return path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
}
/**
* Atomically replace filePath with content.
*
* @param {string} filePath destination path (file is replaced atomically)
* @param {string|Buffer} content full payload to write
* @param {{mode?: number, encoding?: string, durable?: boolean, beforeOpen?: function(string): void, temporaryPath?: string}} [options]
* mode – permissions applied to the destination (default 0o644). The temp
* file is created with the same mode and explicitly chmodded so a
* restrictive umask can never widen the final file's permissions.
* encoding– text encoding when content is a string (default "utf8").
* durable – require both fsyncs. A directory fsync error can be reported
* after the replacement; callers opting in must handle that.
* beforeOpen – record the temporary path before it can appear on disk.
* temporaryPath – same-directory name selected in advance for durable recovery.
* @returns {void} throws on failure; the destination is never written partially.
*/
function atomicWriteFileSync(filePath, content, options = {}) {
const mode = options.mode != null ? options.mode : 0o644;
const encoding = options.encoding || "utf8";
const durable = options.durable === true;
const dir = path.dirname(filePath);
const tmpPath = options.temporaryPath ?? createAtomicWriteTempPath(filePath);
if (path.dirname(path.resolve(tmpPath)) !== path.resolve(dir) || path.resolve(tmpPath) === path.resolve(filePath)) {
throw new Error("Atomic write needs a distinct temporary path in the destination directory");
}
options.beforeOpen?.(tmpPath);
let fd = null;
let created = false;
try {
fd = fs.openSync(tmpPath, "wx", mode);
created = true;
try {
fs.writeFileSync(fd, content, encoding);
// openSync mode is filtered by the process umask; enforce exactly.
fs.fchmodSync(fd, mode);
try { fs.fsyncSync(fd); } catch (err) { if (durable) throw err; }
} finally {
fs.closeSync(fd);
fd = null;
}
fs.renameSync(tmpPath, filePath);
} catch (err) {
if (fd !== null) {
try { fs.closeSync(fd); } catch (_) { /* already closed */ }
}
if (created) try { fs.unlinkSync(tmpPath); } catch (_) { /* nothing to clean */ }
throw err;
}
fsyncPath(dir, durable);
}
module.exports = { atomicWriteFileSync, createAtomicWriteTempPath };