Skip to content

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

fix: address review (claude) — narrow autofixer env, scan diffs for secrets, roll back on restart-fail (#2371)

Adam Eivy1cdaad02fd4f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e5c2386ea9..e48b0b9178 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,7 @@
## Security
-- **[issue-2371] The autonomous Autofixer now repairs crashed apps in an isolated sandbox behind an explicit promotion gate — untrusted crash logs can no longer drive a credentialed agent against your live checkout.** The autofixer built a file-editing CLI prompt straight from raw PM2 stderr/stdout and ran it every 15 minutes in the managed repo with the full host environment inherited, so a payload reflected into a crashing process's log could become instructions to an agent with shell + file access and every ambient credential. It now: cuts a disposable, detached git worktree at HEAD and runs the agent there (a hard rollback boundary — no git checkout means no autonomous repair at all); hands the agent an allowlisted environment stripped of unrelated secrets (DB passwords, cloud keys, GitHub tokens — only system + AI-provider auth survive); fences the logs as clearly-labelled UNTRUSTED evidence with a per-session, forge-resistant delimiter and "data, not instructions" framing; denies the shell/network toolset for Claude so the agent can only read/edit files; validates the resulting diff (size cap + rejects absolute/traversal paths and edits to `.env`/`.git`/`.github`/secrets); optionally runs a user-configured `verifyCommand` in the worktree; and only promotes the change to the live checkout + restarts the process when the user has explicitly enabled `settings.autofixer.autoPromote` (default **off** — otherwise the validated patch is staged beside the session for manual review). Adversarial tests cover fenced prompt-injection payloads and credential-access attempts.
+- **[issue-2371] The autonomous Autofixer now repairs crashed apps in an isolated sandbox behind an explicit promotion gate — untrusted crash logs can no longer drive a credentialed agent against your live checkout.** The autofixer built a file-editing CLI prompt straight from raw PM2 stderr/stdout and ran it every 15 minutes in the managed repo with the full host environment inherited, so a payload reflected into a crashing process's log could become instructions to an agent with shell + file access and every ambient credential. It now: cuts a disposable, detached git worktree at HEAD and runs the agent there (a hard rollback boundary — no git checkout means no autonomous repair at all); hands the agent an allowlisted environment stripped of unrelated secrets (DB passwords, cloud keys, GitHub tokens, filesystem-backed service-account creds — only the direct AI-provider API-key vars the CLI reads survive); fences the logs as clearly-labelled UNTRUSTED evidence with a per-session, forge-resistant delimiter and "data, not instructions" framing; for the default Claude provider denies the shell/network toolset so the agent can only read/edit files; validates the resulting diff (size cap, rejects absolute/traversal paths and edits to `.env`/`.git`/`.github`/secrets, and blocks any diff that writes a credential — matched by pattern or by a live env secret value — into the repo, closing the read-then-promote exfil path); optionally runs a user-configured `verifyCommand` in the worktree; and only promotes the change to the live checkout + restarts the process when the user has explicitly enabled `settings.autofixer.autoPromote` (default **off** — otherwise the validated patch is staged beside the session for manual review), rolling the patch back if the post-apply restart fails. Adversarial tests cover fenced prompt-injection payloads and credential-access attempts. (Non-Claude CLI providers retain their own provider key in-env with network access, since PortOS can't portably constrain their toolset — the worktree + promotion gate + diff secret-scan still contain file changes; hardening that residual — e.g. hard-gating to constrainable providers or a network namespace — is a documented known limitation.)
- **The reference-audio waveform is now keyboard-operable and two hand-rolled modals gained real dialog semantics.** The Songs "reference analysis" waveform scrubber was a mouse-only `<div onClick>` (`role="presentation"`) — keyboard and screen-reader users could not seek at all. It is now a proper `role="slider"` with `aria-valuemin/max/now/valuetext`, focusable, and scrubbable with the arrow keys (±1s, ±5s with Shift) plus Home/End (WCAG 2.1.1). Separately, the CyberCity photo-mode "postcard preview" overlay and the Catalog "pick from media gallery" picker were hand-rolled `fixed inset-0` backdrops with no `role="dialog"`, no `aria-modal`, no Escape-to-close, and no focus trap; both now render through the shared `Modal` (focus trap + Esc stack + labelled dialog), with the postcard preview portaled so it escapes the WebGL HUD's stacking/pointer-events context.
diff --git a/autofixer/sandbox.js b/autofixer/sandbox.js
index d8166a2786..9394154ebc 100644
--- a/autofixer/sandbox.js
+++ b/autofixer/sandbox.js
@@ -50,15 +50,22 @@ const SAFE_ENV_PREFIXES = ['LC_'];
// AI-provider auth the agent's CLI needs to authenticate. These are the ONLY
// credentials it should carry — everything else (DB passwords, cloud keys,
// GitHub tokens, other apps' secrets) is unrelated and stripped.
+// NOTE: intentionally excludes filesystem-backed cloud creds
+// (GOOGLE_APPLICATION_CREDENTIALS keyfile path, AWS_PROFILE, GOOGLE_CLOUD_PROJECT).
+// Even with Bash denied, a Read-capable agent could read the pointed-to keyfile
+// (or /proc/self/environ) and write it into an allowed source file — so we keep
+// only the API-key vars the CLI reads directly, and the diff secret-scan
+// (scanDiffForSecrets) is the backstop that blocks any surviving value from
+// being written into the repo. Bedrock/Vertex users set these via
+// provider.envVars, which still overlays inside the runner.
const PROVIDER_AUTH_ALLOW = new Set([
'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',
'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX',
'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_API_BASE',
'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_GENAI_API_KEY',
- 'GOOGLE_APPLICATION_CREDENTIALS', 'GOOGLE_CLOUD_PROJECT', 'VERTEX_PROJECT',
'XAI_API_KEY', 'GROK_API_KEY', 'OPENROUTER_API_KEY',
'OLLAMA_HOST', 'OLLAMA_API_BASE', 'AWS_REGION', 'AWS_DEFAULT_REGION',
- 'AWS_PROFILE', 'OPENCODE_CONFIG_CONTENT',
+ 'OPENCODE_CONFIG_CONTENT',
]);
// Prefix families for provider auth (CLAUDE_CODE_*, e.g. the OAuth token).
@@ -215,13 +222,56 @@ export function extractDiffPaths(diff) {
return Array.from(paths);
}
+// Secret markers that must never be introduced INTO a source file by the agent.
+// This is the backstop against "Read a credential file / /proc/self/environ,
+// then write it into an allowed source file and promote it." Applied to added
+// (`+`) lines only.
+const SECRET_LINE_PATTERNS = [
+ /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
+ /\bAKIA[0-9A-Z]{16}\b/, // AWS access key id
+ /\baws_secret_access_key\b/i,
+ /\bsk-ant-[A-Za-z0-9_-]{12,}/, // Anthropic
+ /\bsk-[A-Za-z0-9]{20,}/, // OpenAI-style
+ /\bghp_[A-Za-z0-9]{20,}/, // GitHub PAT
+ /\bxai-[A-Za-z0-9]{16,}/, // xAI
+ /\bAIza[0-9A-Za-z_-]{20,}/, // Google API key
+];
+
+/**
+ * Scan the ADDED lines of a diff for secrets. Rejects on either a known secret
+ * pattern or a literal occurrence of one of the caller-supplied `secretValues`
+ * (the live env's provider-auth values), so an agent can't smuggle a credential
+ * it read at runtime into the promoted repository.
+ *
+ * @param {string} diff
+ * @param {string[]} [secretValues] live secret values to reject verbatim
+ * @returns {string|null} a short marker of what matched, or null when clean
+ */
+export function scanDiffForSecrets(diff, secretValues = []) {
+ if (typeof diff !== 'string' || !diff) return null;
+ const values = (Array.isArray(secretValues) ? secretValues : [])
+ .filter((v) => typeof v === 'string' && v.length >= 8);
+ for (const raw of diff.split('\n')) {
+ if (!raw.startsWith('+') || raw.startsWith('+++')) continue;
+ const line = raw.slice(1);
+ for (const re of SECRET_LINE_PATTERNS) {
+ if (re.test(line)) return `secret pattern ${re}`;
+ }
+ for (const v of values) {
+ if (line.includes(v)) return 'live credential value';
+ }
+ }
+ return null;
+}
+
/**
* Validate an agent-proposed diff before it can be promoted to the live
* checkout. Rejects: empty diffs, oversized diffs, absolute paths, `..`
- * traversal, and edits to forbidden files (secrets, .git, CI config).
+ * traversal, edits to forbidden files (secrets, .git, CI config), and diffs
+ * that introduce credentials (pattern or a live env secret value).
*
* @param {string} diff unified diff (git diff output)
- * @param {{ maxBytes?: number }} [opts]
+ * @param {{ maxBytes?: number, secretValues?: string[] }} [opts]
* @returns {{ ok: boolean, reason?: string, files: string[] }}
*/
export function validateProposedDiff(diff, opts = {}) {
@@ -236,6 +286,10 @@ export function validateProposedDiff(diff, opts = {}) {
if (files.length === 0) {
return { ok: false, reason: 'diff touches no files', files: [] };
}
+ const secret = scanDiffForSecrets(diff, opts.secretValues);
+ if (secret) {
+ return { ok: false, reason: `diff introduces a credential (${secret})`, files };
+ }
for (const file of files) {
if (isAbsolute(file) || file.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(file)) {
return { ok: false, reason: `absolute path not allowed: ${file}`, files };
@@ -357,3 +411,18 @@ export async function applyDiffToLive(repoPath, diff, tmpDir) {
if (applied.code !== 0) return { error: `git apply failed: ${applied.stderr.trim()}` };
return { ok: true };
}
+
+/**
+ * Reverse-apply a previously-applied diff, restoring the live checkout. Used
+ * when a promoted fix applied cleanly but the process restart then failed — so
+ * we don't leave the live tree mutated (which would make the next cycle either
+ * double-apply or fail `git apply --check` forever). Best-effort.
+ */
+export async function revertDiffFromLive(repoPath, diff, tmpDir) {
+ const patchFile = join(tmpDir, `autofix-revert-${randomBytes(6).toString('hex')}.patch`);
+ await writeFile(patchFile, diff.endsWith('\n') ? diff : `${diff}\n`);
+ const reverted = await execGit(['apply', '--reverse', '--whitespace=nowarn', patchFile], repoPath);
+ await rm(patchFile, { force: true }).catch(() => {});
+ if (reverted.code !== 0) return { error: `git apply --reverse failed: ${reverted.stderr.trim()}` };
+ return { ok: true };
+}
diff --git a/autofixer/sandbox.test.js b/autofixer/sandbox.test.js
index 3a919ea33a..e48074907a 100644
--- a/autofixer/sandbox.test.js
+++ b/autofixer/sandbox.test.js
@@ -5,6 +5,7 @@ import {
defuseSentinel,
restrictedToolArgs,
validateProposedDiff,
+ scanDiffForSecrets,
extractDiffPaths,
} from './sandbox.js';
@@ -182,6 +183,31 @@ index 111..222 100644
expect(validateProposedDiff(diff).ok).toBe(false);
});
+ it('rejects a diff that writes a live credential value into a source file (read-then-promote exfil)', () => {
+ const stolen = 'sk-ant-supersecretkeyvalue1234567890';
+ const diff = `diff --git a/src/config.js b/src/config.js
+--- a/src/config.js
++++ b/src/config.js
+@@ -1 +1,2 @@
+ const x = 1
++const leak = "${stolen}"
+`;
+ const r = validateProposedDiff(diff, { secretValues: [stolen] });
+ expect(r.ok).toBe(false);
+ expect(r.reason).toMatch(/credential/);
+ });
+
+ it('rejects a diff introducing a private key / AWS key by pattern', () => {
+ const diff = `diff --git a/src/a.js b/src/a.js
+--- a/src/a.js
++++ b/src/a.js
+@@ -1 +1,2 @@
+ x
++const k = "AKIAABCDEFGHIJKLMNOP"
+`;
+ expect(validateProposedDiff(diff).ok).toBe(false);
+ });
+
it('rejects an absolute path', () => {
const diff = `diff --git a//etc/passwd b//etc/passwd
--- a//etc/passwd
@@ -194,6 +220,26 @@ index 111..222 100644
});
});
+describe('scanDiffForSecrets', () => {
+ it('only inspects added lines, ignoring context/removed', () => {
+ const diff = `--- a/x
++++ b/x
+@@ -1,2 +1,1 @@
+-const old = "AKIAOLDKEY0000000000"
+ context AKIACONTEXT000000000
+`;
+ // The secret only appears on a removed/context line — not an addition.
+ expect(scanDiffForSecrets(diff)).toBeNull();
+ });
+ it('flags an added AWS key and a verbatim live value', () => {
+ expect(scanDiffForSecrets('+AKIAABCDEFGHIJKLMNOP')).toMatch(/pattern/);
+ expect(scanDiffForSecrets('+token=abcd1234efgh', ['abcd1234efgh'])).toMatch(/live credential/);
+ });
+ it('ignores short secretValues to avoid false positives', () => {
+ expect(scanDiffForSecrets('+const x = 1', ['1'])).toBeNull();
+ });
+});
+
describe('extractDiffPaths', () => {
it('collects paths from git and unified headers, excluding /dev/null', () => {
const diff = `diff --git a/new.js b/new.js
diff --git a/autofixer/server.js b/autofixer/server.js
index fa5b8ab7e2..a278f56d54 100644
--- a/autofixer/server.js
+++ b/autofixer/server.js
@@ -19,6 +19,7 @@ import {
collectWorktreeDiff,
removeWorktree,
applyDiffToLive,
+ revertDiffFromLive,
runVerifyCommand,
} from './sandbox.js';
@@ -254,7 +255,7 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {
const verifyCommand = typeof autofixerCfg.verifyCommand === 'string' ? autofixerCfg.verifyCommand.trim() : '';
// Single completion path — write the session record + return the result.
- const finalize = async ({ success, exitCode, error, extra = {}, patch }) => {
+ const finalize = async ({ success, exitCode, error, extra = {}, patch, cooldown }) => {
const endTime = new Date().toISOString();
const duration = new Date(endTime).getTime() - new Date(startTime).getTime();
const output = outputBuffer.join('') + (error ? `\n[ERROR] ${error}` : '');
@@ -284,9 +285,10 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {
await saveSession(sessionId, prompt, output, metadata, patch);
console.log(`💾 [Autofixer] Saved session: ${sessionId}`);
- // Cool down on any usable outcome (promoted OR staged) so we don't
- // regenerate a fix for the same crash every cycle.
- if (success) markAsFixed(processName);
+ // Cool down whenever a usable fix was produced (promoted, staged, OR
+ // applied-but-restart-failed) — not just on full success — so a crash the
+ // agent already addressed doesn't re-trigger the LLM every 15-min cycle.
+ if (cooldown ?? success) markAsFixed(processName);
return { success, sessionId, output, ...(error ? { error } : {}) };
};
@@ -340,8 +342,13 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {
// work from an agent that didn't finish cleanly.
const diff = await collectWorktreeDiff(worktreePath);
const agentOk = !result.error;
+ // The live env's provider-auth values — reject any diff that tries to write
+ // one into the repo (agent read-then-promote exfil backstop).
+ const secretValues = Object.entries(childEnv)
+ .filter(([k]) => /API_KEY|TOKEN|SECRET|CREDENTIAL/i.test(k))
+ .map(([, v]) => v);
const validation = agentOk
- ? validateProposedDiff(diff, { maxBytes: MAX_DIFF_BYTES })
+ ? validateProposedDiff(diff, { maxBytes: MAX_DIFF_BYTES, secretValues })
: { ok: false, reason: `agent did not complete: ${result.error}`, files: [] };
// Optional verification against the user-configured test command, run in the
@@ -366,8 +373,15 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {
const restart = await execPm2(['restart', processName]).catch((e) => ({ error: e.message }));
promoted = !restart.error;
promotionError = restart.error || null;
- if (promoted) console.log(`🚀 [Autofixer] Promoted + restarted ${processName}`);
- else console.error(`❌ [Autofixer] Applied fix but restart failed: ${restart.error}`);
+ if (promoted) {
+ console.log(`🚀 [Autofixer] Promoted + restarted ${processName}`);
+ } else {
+ // Applied cleanly but the restart failed — roll the patch back so the
+ // live tree isn't left mutated (which would make the next cycle
+ // double-apply or fail `git apply --check` forever).
+ const reverted = await revertDiffFromLive(app.repoPath, diff, AUTOFIXER_DIR);
+ console.error(`❌ [Autofixer] Restart failed, rolled back applied fix for ${processName}: ${restart.error}${reverted.error ? ` (rollback also failed: ${reverted.error})` : ''}`);
+ }
} else {
promotionError = applied.error;
console.error(`❌ [Autofixer] Promotion blocked: ${applied.error}`);
@@ -383,9 +397,11 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {
// Always discard the disposable worktree.
await removeWorktree(app.repoPath, worktreePath);
- const success = validation.ok && verifyOk && (autoPromote ? promoted : true);
+ const producedFix = validation.ok && verifyOk; // usable fix, regardless of restart outcome
+ const success = producedFix && (autoPromote ? promoted : true);
return finalize({
success,
+ cooldown: producedFix,
exitCode: result.exitCode ?? -1,
error: result.error || promotionError || (!validation.ok ? validation.reason : null) || null,
patch: validation.ok ? diff : undefined,