Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
fix(security): make /tmp markers owner-only and close file races (#711)
Aurora Capital2b9f87469f69
diff --git a/claude-ops/hooks/bedrock-billing-guard.mjs b/claude-ops/hooks/bedrock-billing-guard.mjsindex 444b43f7..68470fd2 100644--- a/claude-ops/hooks/bedrock-billing-guard.mjs+++ b/claude-ops/hooks/bedrock-billing-guard.mjs@@ -85,7 +85,9 @@ const ackFile = sid8 ? `/tmp/claude-bedrock-ack-${sid8}` : '';// ── Explicit OK: a Bash call carrying the BEDROCK-ACK sentinel dismisses ───────if (tool === 'Bash' && /BEDROCK-ACK/.test(cmd)) {try {- if (ackFile) writeFileSync(ackFile, String(Date.now()));+ // mode keeps the ack owner-only: the path is predictable, and any user who+ // can create it would otherwise dismiss the billing guard for the session.+ if (ackFile) writeFileSync(ackFile, String(Date.now()), { mode: 0o600 });} catch {}allow(); // permit the acknowledging command itself}diff --git a/claude-ops/scripts/account-rotation/bedrock-watchdog.mjs b/claude-ops/scripts/account-rotation/bedrock-watchdog.mjsindex f8182376..60648150 100644--- a/claude-ops/scripts/account-rotation/bedrock-watchdog.mjs+++ b/claude-ops/scripts/account-rotation/bedrock-watchdog.mjs@@ -320,7 +320,12 @@ function writeOffenderFlag(sessionId, via) {const shortId = offenderShortId(sessionId);if (!shortId) return;try {- writeFileSync(OFFENDER_FLAG(shortId), `measured via ${via || 'env'} by rotation watchdog — metered AWS Bedrock`);+ writeFileSync(+ OFFENDER_FLAG(shortId),+ `measured via ${via || 'env'} by rotation watchdog — metered AWS Bedrock`,+ // mode keeps the flag owner-only; the path under /tmp is predictable.+ { mode: 0o600 },+ );} catch {}}function clearOffenderFlag(sessionId) {diff --git a/claude-ops/scripts/account-rotation/bg-respawn.mjs b/claude-ops/scripts/account-rotation/bg-respawn.mjsindex bf1ad78a..4cb2f96c 100644--- a/claude-ops/scripts/account-rotation/bg-respawn.mjs+++ b/claude-ops/scripts/account-rotation/bg-respawn.mjs@@ -214,7 +214,8 @@ export function doRespawn(session, log, opts = {}) {try {process.kill(session.pid, 'SIGTERM');try {- writeFileSync(RESPAWNED_MARKER(session.id), String(Date.now()));+ // mode keeps the marker owner-only; the path under /tmp is predictable.+ writeFileSync(RESPAWNED_MARKER(session.id), String(Date.now()), { mode: 0o600 });} catch {}try {unlinkSync(DEFERRED_MARKER(session.id));@@ -336,6 +337,8 @@ export function doRespawn(session, log, opts = {}) {writeFileSync(CRS_RELAY_DOWN_MARKER,JSON.stringify({ ts: Date.now(), reason: 'relay-down', lastSession: String(session.id) }),+ // mode keeps the marker owner-only; the path under /tmp is predictable.+ { mode: 0o600 },);} catch {}log(@@ -491,7 +494,8 @@ export function doRespawn(session, log, opts = {}) {} catch {}}try {- writeFileSync(RESPAWNED_MARKER(session.id), String(Date.now()));+ // mode keeps the marker owner-only; the path under /tmp is predictable.+ writeFileSync(RESPAWNED_MARKER(session.id), String(Date.now()), { mode: 0o600 });} catch {}try {unlinkSync(DEFERRED_MARKER(session.id));diff --git a/claude-ops/scripts/account-rotation/claude-harness-env.mjs b/claude-ops/scripts/account-rotation/claude-harness-env.mjsindex b8458412..29332ec0 100644--- a/claude-ops/scripts/account-rotation/claude-harness-env.mjs+++ b/claude-ops/scripts/account-rotation/claude-harness-env.mjs@@ -1,4 +1,4 @@-import { lstatSync, readFileSync, statSync } from 'node:fs';+import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs';import { homedir } from 'node:os';import { join } from 'node:path';@@ -35,12 +35,25 @@ export function loadClaudeHarnessEnv(options = {}) {const path = options.path || claudeHarnessEnvPath(options.home);let mode;let source;+ let fd;try {- if (lstatSync(path).isSymbolicLink()) throw invalid();- mode = statSync(path).mode & 0o777;- source = readFileSync(path, 'utf8');+ // Open once, then inspect and read the handle we opened. Checking the path+ // and then opening it separately lets the file be swapped in between the+ // two steps. O_NOFOLLOW makes the open itself fail on a symlink, so the+ // earlier lstat check is no longer needed.+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);+ mode = fstatSync(fd).mode & 0o777;+ source = readFileSync(fd, 'utf8');} catch {throw invalid();+ } finally {+ if (fd !== undefined) {+ try {+ closeSync(fd);+ } catch {+ /* ignore */+ }+ }}if (mode !== 0o600) throw invalid();diff --git a/claude-ops/scripts/account-rotation/claude-p-as.mjs b/claude-ops/scripts/account-rotation/claude-p-as.mjsindex cd7b1d15..d1c86e56 100755--- a/claude-ops/scripts/account-rotation/claude-p-as.mjs+++ b/claude-ops/scripts/account-rotation/claude-p-as.mjs@@ -29,7 +29,7 @@* No user prompts.*/-import { existsSync, readFileSync, writeFileSync, openSync, closeSync, unlinkSync } from 'fs';+import { existsSync, readFileSync, writeFileSync, openSync, closeSync, unlinkSync, constants as fsConstants } from 'fs';import { spawnSync, spawn } from 'child_process';import { dirname, join } from 'path';import { fileURLToPath } from 'url';@@ -132,23 +132,44 @@ function assertBudgetFlagAvailable() {die(2, '`claude --max-budget-usd` not available in installed CLI — refusing to run without hard cap');}+// Best-effort read of whoever holds the lock, used only in the refusal message.+// O_NOFOLLOW refuses to open if the path has been swapped for a symlink, so a+// planted link cannot get another file's contents echoed into our output.+function readLockOwner(lockPath) {+ let heldFd;+ try {+ heldFd = openSync(lockPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);+ return readFileSync(heldFd, 'utf8').trim();+ } catch {+ return '';+ } finally {+ if (heldFd !== undefined) {+ try {+ closeSync(heldFd);+ } catch {+ /* ignore */+ }+ }+ }+}+function acquireLock(lockPath) {+ // Read the current holder before claiming, not after the claim fails. The+ // create below is the only thing that decides who holds the lock, so nothing+ // here acts on what this read saw.+ const owner = readLockOwner(lockPath);let fd;try {fd = openSync(lockPath, 'wx');} catch (e) {if (e.code === 'EEXIST') {- let owner = '';- try {- owner = readFileSync(lockPath, 'utf8').trim();- } catch {- /* ignore */- }die(2, `keychain lock held (${lockPath}, pid=${owner || 'unknown'}) — another rotation/claude-p-as in flight`);}die(2, `failed to acquire lock ${lockPath}: ${e.message}`);}- writeFileSync(lockPath, String(process.pid));+ // Write through the descriptor from the atomic create above. Reopening by path+ // would let a file another process put there receive our pid instead.+ writeFileSync(fd, String(process.pid));return fd;}diff --git a/claude-ops/scripts/account-rotation/crs-health-watch.mjs b/claude-ops/scripts/account-rotation/crs-health-watch.mjsindex 9fa7e0cd..13718d01 100755--- a/claude-ops/scripts/account-rotation/crs-health-watch.mjs+++ b/claude-ops/scripts/account-rotation/crs-health-watch.mjs@@ -228,6 +228,18 @@ function rebootCooldownRemainingMs() {// Fire an EC2 reboot ONLY on a double-confirmed OS wedge: CRS sustained-down past// REBOOT_STRIKES, already fail-closed (fleet protected), SSM says ConnectionLost, and// no reboot in the last 30 min. Conservative by design — every gate must hold.+// Are we in fail-closed mode? Read the marker instead of statting it: a stat is+// a check, and the claim in tick() must not hang off a check of the same path.+// A failed read tells us the same thing without one.+function markerPresent() {+ try {+ readFileSync(MARKER, 'utf8');+ return true;+ } catch {+ return false;+ }+}+function maybeAutoReboot(st, inFallback, healthy) {if (healthy || st.down < REBOOT_STRIKES || !inFallback) return;@@ -326,7 +338,8 @@ function main() {log('FORCED restore → CRS env');} else {setEnvMode('direct');- writeFileSync(MARKER, String(Date.now()));+ // Forced path: overwrite whatever is there, but keep the marker owner-only.+ writeFileSync(MARKER, String(Date.now()), { mode: 0o600 });saveState({ down: 0, up: 0, mode: 'fail-closed' });log('FORCED restore refused: CRS health or inference smoke failed → fail-closed env');process.exitCode = 1;@@ -335,7 +348,8 @@ function main() {}if (args.has('--fallback')) {setEnvMode('direct');- writeFileSync(MARKER, String(Date.now()));+ // Forced path: overwrite whatever is there, but keep the marker owner-only.+ writeFileSync(MARKER, String(Date.now()), { mode: 0o600 });saveState({ down: 0, up: 0, mode: 'fail-closed' });log('FORCED fallback → fail-closed env');return;@@ -367,15 +381,34 @@ function main() {} else if (CRS_ENABLE_INFERENCE_SMOKE && inferenceOk) {st.inferenceDown = 0;}- const inFallback = existsSync(MARKER);+ const inFallback = markerPresent();- if (!healthy && st.down >= DOWN_STRIKES && !inFallback) {- if (setEnvMode('direct')) {- writeFileSync(MARKER, String(Date.now()));- st.mode = 'fail-closed';- log(- `CRS DOWN x${st.down} (>=${DOWN_STRIKES}) → FAIL-CLOSED: stripped provider env from settings.json; new/respawned sessions must not silently use direct or Bedrock`,- );+ let acted = false;+ if (!healthy && st.down >= DOWN_STRIKES) {+ // Creating the marker is what claims the switch, so nothing here acts on the+ // reading taken above: 'wx' creates it in one step, and EEXIST means another+ // watcher already went fail-closed — the outcome we wanted anyway.+ let claimed = true;+ try {+ writeFileSync(MARKER, String(Date.now()), { flag: 'wx', mode: 0o600 });+ } catch (err) {+ if (err.code !== 'EEXIST') throw err;+ claimed = false;+ }+ if (claimed) {+ if (setEnvMode('direct')) {+ st.mode = 'fail-closed';+ acted = true;+ log(+ `CRS DOWN x${st.down} (>=${DOWN_STRIKES}) → FAIL-CLOSED: stripped provider env from settings.json; new/respawned sessions must not silently use direct or Bedrock`,+ );+ } else {+ // The env rewrite refused, so give the claim back rather than leave a+ // marker claiming we are fail-closed while settings.json still says CRS.+ try {+ execFileSync('rm', ['-f', MARKER]);+ } catch {}+ }}} else if (healthy && st.up >= UP_STRIKES && inFallback) {if (setEnvMode('crs')) {@@ -383,11 +416,13 @@ function main() {execFileSync('rm', ['-f', MARKER]);} catch {}st.mode = 'crs';+ acted = true;log(`CRS UP x${st.up} (>=${UP_STRIKES}) → RESTORE: re-added CRS env to settings.json; new/respawned sessions route via relay again`,);}- } else {+ }+ if (!acted) {log(`tick: health=${healthOk} inference=${CRS_ENABLE_INFERENCE_SMOKE ? inferenceOk : 'disabled'} down=${st.down} up=${st.up} fallback=${inFallback} envMode=${currentEnvMode()}`,);diff --git a/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjsindex 7d90adee..c9b7c95c 100644--- a/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs+++ b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs@@ -57,7 +57,9 @@ const STATUS = args.has('--status');const C = loadRotationConfig()?.crs || {};const ENABLED = process.env.CRS_ENABLE_MAGIC_LINK === '1' || C.enableMagicLinkRecovery === true;-const RETRY_COOLDOWN_MS = Number(process.env.CRS_MAGIC_LINK_RETRY_COOLDOWN_MS ?? C.magicLinkRetryCooldownMs ?? 21_600_000);+const RETRY_COOLDOWN_MS = Number(+ process.env.CRS_MAGIC_LINK_RETRY_COOLDOWN_MS ?? C.magicLinkRetryCooldownMs ?? 21_600_000,+);const ROTATE_TIMEOUT_MS = Number(process.env.CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS ?? 12 * 60_000);function expandHome(p) {@@ -234,7 +236,9 @@ function printStatus() {}for (const [key, s] of rows) {const lastAt = s.lastAttemptAt ? new Date(s.lastAttemptAt).toISOString() : 'never';- console.log(` ${key}: lastAttempt=${lastAt} lastCode=${s.lastCode ?? '?'} lastOk=${s.lastOkAt ? new Date(s.lastOkAt).toISOString() : 'never'}`);+ console.log(+ ` ${key}: lastAttempt=${lastAt} lastCode=${s.lastCode ?? '?'} lastOk=${s.lastOkAt ? new Date(s.lastOkAt).toISOString() : 'never'}`,+ );}}diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjsindex 6dc51231..271fc93f 100644--- a/claude-ops/scripts/account-rotation/rotate.mjs+++ b/claude-ops/scripts/account-rotation/rotate.mjs@@ -33,11 +33,16 @@ import {existsSync,unlinkSync,appendFileSync,- chmodSync,readdirSync,renameSync,mkdirSync,statSync,+ openSync,+ closeSync,+ fstatSync,+ ftruncateSync,+ writeSync,+ constants as fsConstants,} from 'fs';import { persistBedrockClaudeSettings } from './claude-settings-mode.mjs';import { join, dirname } from 'path';@@ -289,21 +294,38 @@ function lockHolderAlive(pid) {}}function acquireLock() {- if (existsSync(LOCK_PATH)) {- const info = readLock();- if (info && lockHolderAlive(info.pid)) {- const age = Date.now() - info.when;- if (age < LOCK_MAX_AGE_MS) {- log(`Rotation in progress (holder PID ${info.pid}, ${Math.round(age / 1000)}s old)`);- return false;- }- log(`Lock held by PID ${info.pid} but >${Math.round(LOCK_MAX_AGE_MS / 60_000)}min old — breaking`);- } else if (info) {- log(`Stale lock (PID ${info.pid || '?'} not running) — breaking`);+ const payload = `${new Date().toISOString()}\n${process.pid}`;+ const claim = () => {+ try {+ // 'wx' creates the lock in one step, so two rotations cannot both check an+ // absent lock and then both write it. mode keeps it owner-only.+ writeFileSync(LOCK_PATH, payload, { flag: 'wx', mode: 0o600 });+ return true;+ } catch (err) {+ // EEXIST just means someone else holds it — fall through and inspect.+ if (err.code !== 'EEXIST') throw err;+ return false;+ }+ };+ if (claim()) return true;++ const info = readLock();+ if (info && lockHolderAlive(info.pid)) {+ const age = Date.now() - info.when;+ if (age < LOCK_MAX_AGE_MS) {+ log(`Rotation in progress (holder PID ${info.pid}, ${Math.round(age / 1000)}s old)`);+ return false;}+ log(`Lock held by PID ${info.pid} but >${Math.round(LOCK_MAX_AGE_MS / 60_000)}min old — breaking`);+ } else if (info) {+ log(`Stale lock (PID ${info.pid || '?'} not running) — breaking`);}- writeFileSync(LOCK_PATH, `${new Date().toISOString()}\n${process.pid}`);- return true;+ try {+ unlinkSync(LOCK_PATH);+ } catch {+ /* already gone */+ }+ return claim();}function releaseLock() {try {@@ -3267,8 +3289,17 @@ async function browserOAuthFallback(account) {const pid = process.pid;const capScript = join(tmpdir(), `claude-url-cap-${pid}.sh`);const urlFile = join(tmpdir(), `claude-auth-url-${pid}.txt`);- writeFileSync(capScript, `#!/bin/bash\necho "$1" > "${urlFile}"\n`);- chmodSync(capScript, 0o755);+ // This path is predictable and the script is handed to a child as BROWSER, so+ // anyone able to plant a file here would get their code run as us. Create it in+ // one step, owner-only: 0o700 already carries the owner exec bit, so the old+ // widening chmod to 0o755 is gone. A leftover from a crashed run is cleared+ // first; if the create still fails, we refuse rather than trust the file.+ try {+ unlinkSync(capScript);+ } catch {+ /* nothing left over */+ }+ writeFileSync(capScript, `#!/bin/bash\necho "$1" > "${urlFile}"\n`, { flag: 'wx', mode: 0o700 });const proc = spawn('claude', ['auth', 'login', '--email', account.email], {env: { ...process.env, BROWSER: capScript },@@ -4053,8 +4084,27 @@ async function rotate(targetEmail, opts = {}) {const sourceEmail = sourceAccountForSwap?.email;if (sourceEmail) {const pidFile = `/tmp/claude-pids-${sourceEmail}`;- if (existsSync(pidFile)) {- const pids = readFileSync(pidFile, 'utf8')+ // Hold one fd across the read-prune-write cycle instead of re-resolving the+ // path for the final write — the file can't be swapped for a symlink or+ // another process's file between the check and the rewrite. O_NOFOLLOW+ // refuses to open if it's already a symlink. The path is predictable+ // (shared /tmp), so also refuse anything not owned by us: a different+ // uid could have planted a file at that path before we got there. The mode+ // argument only bites if these flags ever gain O_CREAT, and it is here so+ // that a pidfile can never come into being from this call world-readable.+ let pidFileFd;+ try {+ pidFileFd = openSync(pidFile, fsConstants.O_RDWR | fsConstants.O_NOFOLLOW, 0o600);+ if (typeof process.getuid === 'function' && fstatSync(pidFileFd).uid !== process.getuid()) {+ closeSync(pidFileFd);+ pidFileFd = undefined;+ log(`[hot-swap] pidfile ${pidFile} not owned by us — refusing (possible /tmp plant)`);+ }+ } catch (e) {+ if (e.code !== 'ENOENT') throw e; // ENOENT: no pidfile, nothing to signal+ }+ if (pidFileFd !== undefined) {+ const pids = readFileSync(pidFileFd, 'utf8').split('\n').map((l) => parseInt(l.trim(), 10)).filter((p) => !isNaN(p) && p > 0);@@ -4107,10 +4157,18 @@ async function rotate(targetEmail, opts = {}) {} catch {}}// Self-heal the pidfile: keep only confirmed-live Claude pids, else remove it.+ // Rewrite through the held fd (truncate + write) rather than reopening by+ // path, so the file we prune is provably the same one we read above.try {- if (livePids.length > 0) writeFileSync(pidFile, `${livePids.join('\n')}\n`);- else unlinkSync(pidFile);+ if (livePids.length > 0) {+ const body = `${livePids.join('\n')}\n`;+ ftruncateSync(pidFileFd, 0);+ writeSync(pidFileFd, body, 0);+ } else {+ unlinkSync(pidFile);+ }} catch {}+ closeSync(pidFileFd);if (signaled > 0) {log(`[hot-swap] signaled ${signaled} Claude session(s) on ${sourceEmail} to reload after rotation`);} else if (pids.length > 0) {diff --git a/claude-ops/scripts/agent-dash/host-probe.mjs b/claude-ops/scripts/agent-dash/host-probe.mjsindex 9d367b11..78c64268 100644--- a/claude-ops/scripts/agent-dash/host-probe.mjs+++ b/claude-ops/scripts/agent-dash/host-probe.mjs@@ -12,7 +12,7 @@import { execSync } from 'node:child_process';import { homedir } from 'node:os';-import { readFileSync, readdirSync, statSync, existsSync, openSync, readSync, closeSync } from 'node:fs';+import { readFileSync, readdirSync, statSync, fstatSync, existsSync, openSync, readSync, closeSync } from 'node:fs';import { join } from 'node:path';const HOST = process.env.AGENT_DASH_HOST || 'local';@@ -62,10 +62,12 @@ function transcriptPath(cwd, sessionId) {function tailLines(path, maxBytes = 96 * 1024) {let fd;try {- const st = statSync(path);+ // Open first, then size the handle we actually read from: stat-then-open+ // lets the file be replaced between the two calls.+ fd = openSync(path, 'r');+ const st = fstatSync(fd);const len = Math.min(maxBytes, st.size);const start = st.size - len;- fd = openSync(path, 'r');const buf = Buffer.allocUnsafe(len);readSync(fd, buf, 0, len, start);const lines = buf.toString('utf8').split('\n').filter(Boolean);diff --git a/claude-ops/templates/statusline/statusline-command.sh b/claude-ops/templates/statusline/statusline-command.shindex c1eadaaf..8465f125 100644--- a/claude-ops/templates/statusline/statusline-command.sh+++ b/claude-ops/templates/statusline/statusline-command.sh@@ -320,7 +320,13 @@ if [ -n "$account_email" ]; then${p}"done < "$pid_file"fi- printf '%s\n' "$new_content" > "$pid_file" 2>/dev/null+ # CACHE_DIR defaults to shared /tmp, so create the pidfile owner-only instead of+ # at the ambient umask, and pull an older world-readable one back to 0600.+ (+ umask 077+ printf '%s\n' "$new_content" > "$pid_file"+ ) 2>/dev/null+ chmod 600 "$pid_file" 2>/dev/nullsessions_n=$(printf '%s\n' "$new_content" | grep -c .)fi