Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): preserve destination file mode in atomicWrite
[._.]/ Adam Eivya0c14019fbc9
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex cff61a5ba1..2683796380 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -4,7 +4,7 @@* Shared utilities for file operations used across services.*/-import { access, appendFile, mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';+import { access, appendFile, chmod, mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';import { existsSync, statSync, createReadStream } from 'fs';import { execFile } from 'child_process';import { promisify } from 'util';@@ -184,6 +184,18 @@ export async function atomicWrite(filePath, data) {await ensureDir(dirname(filePath));const tmp = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;await writeFile(tmp, payload);+ // Preserve the destination's existing permission bits. A plain+ // writeFile(existing) truncated the inode in place and kept its mode, but+ // atomicWrite creates a fresh temp inode at the umask default (typically+ // 0644) and renames it over the target — which would silently widen a+ // hand-restricted file (e.g. a `chmod 600` OAuth tokens.json) on every+ // rewrite. Mirror the destination's mode onto the temp file before the+ // rename so atomicWrite is a true drop-in for the truncate pattern. New+ // files (stat fails with ENOENT) keep the umask default, exactly as before.+ const existingMode = await stat(filePath).then((s) => s.mode & 0o777, () => null);+ if (existingMode !== null) {+ await chmod(tmp, existingMode).catch(() => {});+ }// Node's fs.rename uses MoveFileExW with MOVEFILE_REPLACE_EXISTING on Windows (atomic// overwrite), but still fails with EPERM/EACCES if the destination is locked (AV scan,// concurrent reader). Fall back to a backup-swap so the original file is never lost.diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 0609a99468..748ec20043 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -15,6 +15,7 @@ vi.mock('fs/promises', async (importOriginal) => {});import {assertSafeFilename,+ atomicWrite,ensureDir,pathExists,expandHome,@@ -860,6 +861,54 @@ describe('fileUtils', () => {await expect(ensureDir(target)).rejects.toThrow(/EACCES/);});});++ describe('atomicWrite', () => {+ let tmpRoot;++ beforeEach(() => {+ tmpRoot = mkdtempSync(join(tmpdir(), 'fileutils-atomicwrite-'));+ });++ afterEach(() => {+ rmSync(tmpRoot, { recursive: true, force: true });+ });++ it('serializes a plain object with 2-space indentation', async () => {+ const target = join(tmpRoot, 'obj.json');+ await atomicWrite(target, { b: 2, a: 1 });+ expect(await readFile(target, 'utf8')).toBe('{\n "b": 2,\n "a": 1\n}');+ });++ it('writes a string payload verbatim (preserving a trailing newline)', async () => {+ const target = join(tmpRoot, 'raw.json');+ await atomicWrite(target, '{"x":1}\n');+ expect(await readFile(target, 'utf8')).toBe('{"x":1}\n');+ });++ it.skipIf(process.platform === 'win32')(+ 'preserves the destination file\'s restrictive mode on rewrite (regression: #1837)',+ async () => {+ const target = join(tmpRoot, 'secret.json');+ // Seed a hand-restricted secret file (e.g. an OAuth tokens.json the user+ // chmod 600'd). The temp-write + rename must NOT widen it to the umask+ // default — a plain writeFile(existing) kept the inode's mode, and+ // atomicWrite mirrors that.+ writeFileSync(target, '{"token":"old"}', { mode: 0o600 });+ const { chmodSync } = await import('fs');+ chmodSync(target, 0o600); // ensure 600 regardless of umask at creation+ await atomicWrite(target, { token: 'new' });+ const { statSync } = await import('fs');+ expect(statSync(target).mode & 0o777).toBe(0o600);+ expect(JSON.parse(await readFile(target, 'utf8'))).toEqual({ token: 'new' });+ }+ );++ it('creates a new file at the default mode when the destination does not exist', async () => {+ const target = join(tmpRoot, 'fresh.json');+ await atomicWrite(target, { created: true });+ expect(JSON.parse(await readFile(target, 'utf8'))).toEqual({ created: true });+ });+ });});// =============================================================================diff --git a/server/services/identity.test.js b/server/services/identity.test.jsindex 6d278f4db7..1bd778b830 100644--- a/server/services/identity.test.js+++ b/server/services/identity.test.js@@ -21,6 +21,15 @@ function makeFsPromisesStore() {}),unlink: vi.fn(async (path) => { delete store[path]; }),mkdir: vi.fn(async () => {}),+ // atomicWrite stats the destination to mirror its mode onto the temp file+ // before renaming (#1837). The in-memory store doesn't track modes, so+ // report a default for existing paths and ENOENT for absent ones; chmod is+ // a no-op here.+ stat: vi.fn(async (path) => {+ if (!(path in store)) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });+ return { mode: 0o644 };+ }),+ chmod: vi.fn(async () => {}),};}