Repository navigation
credstore: atomic write to prevent torn credentials - #37
Conversation
Multiple plugin hooks (UserPromptSubmit, PreToolUse, PostToolUse, …)
run async and can write ~/.skillbench/credentials.json concurrently.
writeStore used fs.writeFileSync directly, so:
- A process killed mid-write leaves a truncated JSON file. The next
readStore catches the parse error, returns {}, and the next
writeStore silently overwrites the file with a near-empty object —
device_id, hash_salt, and license_jwt all vanish together.
- Concurrent writers partially clobber each other.
Replace writeStore with a temp-file + fsync + rename pattern:
- Write payload to a sibling tempfile (same directory → same fs, so
rename is an atomic inode swap).
- fsync before rename so a host crash can't land a renamed-but-empty
file.
- Unique tempfile name (pid + timestamp) prevents concurrent writers
from colliding on the tempfile itself.
- On error, close fd + unlink tempfile so the dir doesn't accrete
credentials.json.tmp.* garbage.
This kills the torn-write class completely and shrinks the
lost-update window from the whole I/O operation to just the
in-memory mutation. Fully eliminating lost updates still needs a
file lock (separate follow-up).
Verified:
- node -c syntax passes
- round-trip: setLicenseToken → getLicenseToken → file on disk
- concurrent-writer stress: 2 procs × 100 writes each, file stays
valid JSON, zero tempfile leftover
- mid-flight crash simulation: file remains valid JSON, zero
tempfile leftover
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
WalkthroughThe Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
skillmeter/scripts/credstore.js (1)
36-40: Use exclusive creation flag and stronger UUID for tempfile to prevent collision overwrites.The code uses
Date.now()with the"w"flag, which silently overwrites any existing tempfile at the same path. In rare concurrent-write scenarios, this could clobber writes from another process. Replace withcrypto.randomUUID()(already imported) and the"wx"flag, which atomically creates the file and fails withEEXISTif it already exists—a standard best practice for tempfile collision avoidance.Proposed hardening
- const tempPath = `${CRED_FILE}.tmp.${process.pid}.${Date.now()}`; + const tempPath = `${CRED_FILE}.tmp.${process.pid}.${crypto.randomUUID()}`; let fd; try { - fd = fs.openSync(tempPath, "w", 0o600); + fd = fs.openSync(tempPath, "wx", 0o600); fs.writeSync(fd, JSON.stringify(data, null, 2) + "\n");🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@skillmeter/scripts/credstore.js` around lines 36 - 40, The tempfile creation uses Date.now() and fs.openSync with the "w" flag which can overwrite an existing temp file; change tempPath to include crypto.randomUUID() instead of Date.now() and call fs.openSync(tempPath, "wx", 0o600) so the creation is exclusive and fails with EEXIST on collision; update the error handling around fs.openSync (in the block referencing tempPath, CRED_FILE, process.pid and fs.openSync) to retry or generate a new UUID on EEXIST instead of silently overwriting.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@skillmeter/scripts/credstore.js`:
- Line 44: After the atomic rename using fs.renameSync(tempPath, CRED_FILE) you
must fsync the parent directory to ensure the rename metadata is persisted;
modify the code after the fs.renameSync call to open the directory containing
CRED_FILE (use path.dirname(CRED_FILE)), call fs.fsyncSync on the directory file
descriptor, then close the descriptor (fs.closeSync); keep the operations
synchronous to match the existing fs.renameSync usage and surface any errors
from fs.openSync/fs.fsyncSync/fs.closeSync so failures can be handled or logged.
---
Nitpick comments:
In `@skillmeter/scripts/credstore.js`:
- Around line 36-40: The tempfile creation uses Date.now() and fs.openSync with
the "w" flag which can overwrite an existing temp file; change tempPath to
include crypto.randomUUID() instead of Date.now() and call fs.openSync(tempPath,
"wx", 0o600) so the creation is exclusive and fails with EEXIST on collision;
update the error handling around fs.openSync (in the block referencing tempPath,
CRED_FILE, process.pid and fs.openSync) to retry or generate a new UUID on
EEXIST instead of silently overwriting.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 971336a8-d19b-4de4-b5bf-26efce2f55bf
📒 Files selected for processing (1)
skillmeter/scripts/credstore.js
| fs.fsyncSync(fd); | ||
| fs.closeSync(fd); | ||
| fd = undefined; | ||
| fs.renameSync(tempPath, CRED_FILE); |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
On POSIX filesystems, after fsyncing a temp file and renaming it over the target, is fsync on the parent directory required to guarantee the rename survives power loss? Please cite Node.js and filesystem documentation.
💡 Result:
Yes, on POSIX filesystems, after fsyncing a temp file and renaming it over the target, an fsync on the parent directory is required to guarantee the rename survives power loss. POSIX requires fsync (or fdatasync) on the parent directory after rename to ensure directory modifications (like renames) are durable against crashes. Rename is atomic but not necessarily durable without it; the directory entry update may not reach disk. Linux man fsync(2) explicitly states: "Calling fsync does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync on a file descriptor for the directory is also needed." Node.js fs module exposes fs.fsync(fd) and fs.fsyncSync(fd), where fd can be from fs.open(parentDir, O_RDONLY) or fs.opendir(parentDir). After fs.fsyncSync(dirFd), the rename to target (in same parent) is durable. Node.js docs model POSIX fs functions but do not explicitly cover durability; rely on underlying syscalls. Some filesystems (ext4 with auto_da_alloc) mitigate file data issues but not directory metadata without parent fsync. For full guarantee across POSIX/Linux filesystems, parent fsync is needed.
Citations:
- 1: https://stackoverflow.com/questions/3764822/how-to-durably-rename-a-file-in-posix
- 2: https://www.reddit.com/r/kernel/comments/1mkykhz/fsync_on_file_and_parent_directory/
- 3: Question: fsync on file and/or directory google/renameio#11
- 4: https://austingroupbugs.net/view.php?id=672
- 5: https://stackoverflow.com/questions/79725268/how-to-fsync-a-directory
Persist the rename with a parent-directory fsync to guarantee crash durability of credential file writes.
Line 44 renames atomically, but without fsyncing the parent directory, a host crash can still lose the rename metadata on POSIX filesystems. According to POSIX standards, fsyncing the parent directory after rename is required to ensure directory entry modifications reach disk. Without this step, a power loss immediately after renameSync() can leave the old credential file in place.
Proposed durability fix
fs.fsyncSync(fd);
fs.closeSync(fd);
fd = undefined;
fs.renameSync(tempPath, CRED_FILE);
+ const dirFd = fs.openSync(dir, "r");
+ try {
+ fs.fsyncSync(dirFd);
+ } finally {
+ fs.closeSync(dirFd);
+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@skillmeter/scripts/credstore.js` at line 44, After the atomic rename using
fs.renameSync(tempPath, CRED_FILE) you must fsync the parent directory to ensure
the rename metadata is persisted; modify the code after the fs.renameSync call
to open the directory containing CRED_FILE (use path.dirname(CRED_FILE)), call
fs.fsyncSync on the directory file descriptor, then close the descriptor
(fs.closeSync); keep the operations synchronous to match the existing
fs.renameSync usage and surface any errors from
fs.openSync/fs.fsyncSync/fs.closeSync so failures can be handled or logged.
Summary
Multiple plugin hooks (`UserPromptSubmit`, `PreToolUse`, `PostToolUse`, …) are marked `async: true` in `hooks.json` and routinely run concurrently. `writeStore` used `fs.writeFileSync` directly, which has two concrete failure modes:
This PR replaces `writeStore` with a temp-file + fsync + rename pattern. POSIX rename within the same filesystem is atomic, so readers see either the old file or the new file — never a partial write.
Change
Single function in `skillmeter/scripts/credstore.js` (`writeStore`). No API change, no new deps, no other files touched.
Key design points:
What this does NOT fix
Lost updates across concurrent `read → mutate → write` cycles are still possible (a smaller window now, bounded by the in-memory mutation). Full fix requires a file lock (`proper-lockfile` or similar) — tracked as a separate follow-up.
Verified
🤖 Generated with Claude Code
Summary by CodeRabbit