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): close 10 high-severity CodeQL alerts (logging, TOCTOU, perms, sanitization) (#796)
Aurora Capital85b8b308e80a
diff --git a/.gitignore b/.gitignoreindex 19351263..9ad9c290 100644--- a/.gitignore+++ b/.gitignore@@ -14,3 +14,12 @@ node_modules/ops.local.json*.local.json.ops-prefs.json++# Runtime message/session stores written by local bridges (WhatsApp whatsmeow,+# etc). These hold real conversation content and pairing state and must never+# reach this public repo.+store/+*.db+*.db-journal+*.db-wal+*.db-shmdiff --git a/claude-ops/bin/ops-slack-autolink.mjs b/claude-ops/bin/ops-slack-autolink.mjsindex 87d4e755..07c10f64 100755--- a/claude-ops/bin/ops-slack-autolink.mjs+++ b/claude-ops/bin/ops-slack-autolink.mjs@@ -938,9 +938,18 @@ try {}if (!xoxcToken) die('Could not find XOXC token — ensure the workspace is fully loaded');- // Extract XOXD ('d' cookie) from the context cookie jar+ // Extract XOXD ('d' cookie) from the context cookie jar.+ // Match the cookie domain exactly (or as a true subdomain). An unanchored+ // /slack\.com/ test would also accept a look-alike like+ // "notslack.com.example.net", handing the session cookie to the wrong host.+ const isSlackDomain = (domain) => {+ const host = String(domain || '')+ .replace(/^\./, '')+ .toLowerCase();+ return host === 'slack.com' || host.endsWith('.slack.com');+ };const cookies = await context.cookies();- const dCookie = cookies.find((c) => c.name === 'd' && /slack\.com/.test(c.domain));+ const dCookie = cookies.find((c) => c.name === 'd' && isSlackDomain(c.domain));if (!dCookie) die("Could not find 'd' cookie (XOXD token)");const xoxdToken = dCookie.value.startsWith('xoxd-') ? dCookie.value : `xoxd-${dCookie.value}`;diff --git a/claude-ops/bin/ops-telegram-autolink.mjs b/claude-ops/bin/ops-telegram-autolink.mjsindex 7c748e6e..ece088dc 100755--- a/claude-ops/bin/ops-telegram-autolink.mjs+++ b/claude-ops/bin/ops-telegram-autolink.mjs@@ -319,15 +319,102 @@ if (!apiId || !apiHash) {({ apiId, apiHash } = extract(appsHtml));}+/**+ * Extract human-readable text from an HTML document for diagnostics.+ *+ * Deliberately NOT a chain of `.replace(/<script.*?<\/script>/gi, '')`-style+ * regexes: those miss valid-but-unusual end tags (`</script >`, `</script\n>`)+ * and, because each pass can re-create a tag the previous pass removed, they can+ * leave live `<script`/`<style` markup behind. This is a single left-to-right+ * pass over the input that can never resurrect markup, and it HTML-escapes the+ * text it keeps so the result is inert wherever it is later rendered.+ */+function htmlToDiagnosticText(html) {+ const RAW_TEXT = new Set(['script', 'style', 'textarea', 'title', 'noscript']);+ const out = [];+ let i = 0;+ const n = html.length;++ while (i < n) {+ const lt = html.indexOf('<', i);+ if (lt === -1) {+ out.push(html.slice(i));+ break;+ }+ out.push(html.slice(i, lt));++ // Comment / CDATA / doctype+ if (html.startsWith('<!--', lt)) {+ const end = html.indexOf('-->', lt + 4);+ i = end === -1 ? n : end + 3;+ continue;+ }+ if (html[lt + 1] === '!' || html[lt + 1] === '?') {+ const end = html.indexOf('>', lt);+ i = end === -1 ? n : end + 1;+ continue;+ }++ // A '<' that does not open a tag is literal text, not markup.+ const nameMatch = /^<\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(html.slice(lt, lt + 64));+ if (!nameMatch) {+ out.push('<');+ i = lt + 1;+ continue;+ }+ const tagName = nameMatch[1].toLowerCase();+ const isClosing = html[lt + 1] === '/';++ // Walk to the tag's '>' while respecting quoted attribute values, so a '>'+ // inside an attribute does not terminate the tag early.+ let j = lt + nameMatch[0].length;+ let quote = null;+ while (j < n) {+ const c = html[j];+ if (quote) {+ if (c === quote) quote = null;+ } else if (c === '"' || c === "'") {+ quote = c;+ } else if (c === '>') {+ break;+ }+ j++;+ }+ i = j < n ? j + 1 : n;++ // Raw-text elements: skip their entire content, matching the end tag the way+ // an HTML parser does — '</name' followed by whitespace, '/' or '>'.+ if (!isClosing && RAW_TEXT.has(tagName) && html[j - 1] !== '/') {+ const endRe = new RegExp(`</${tagName}(?=[\\s/>])`, 'i');+ const rest = html.slice(i);+ const m = endRe.exec(rest);+ if (!m) {+ i = n;+ } else {+ const close = html.indexOf('>', i + m.index);+ i = close === -1 ? n : close + 1;+ }+ continue;+ }++ out.push(' ');+ }++ // Escape what survived: the snippet is inert wherever it is later rendered.+ return out+ .join('')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''')+ .replace(/\s+/g, ' ')+ .trim();+}+if (!apiId || !apiHash) {// Dump a snippet of the HTML so the caller can diagnose what changed- const snippet = appsHtml- .replace(/<script[\s\S]*?<\/script>/gi, '')- .replace(/<style[\s\S]*?<\/style>/gi, '')- .replace(/<[^>]+>/g, ' ')- .replace(/\s+/g, ' ')- .trim()- .slice(0, 500);+ const snippet = htmlToDiagnosticText(appsHtml).slice(0, 500);die(`could not extract ${!apiId ? 'api_id' : ''}${!apiId && !apiHash ? ' or ' : ''}${!apiHash ? 'api_hash' : ''} from /apps HTML after 6 extraction strategies`,{ html_snippet: snippet },diff --git a/claude-ops/lib/credential-store.mjs b/claude-ops/lib/credential-store.mjsindex 1712725b..3ec14fb2 100644--- a/claude-ops/lib/credential-store.mjs+++ b/claude-ops/lib/credential-store.mjs@@ -33,7 +33,44 @@ const MASTERKEY_FILE = path.join(DATA_DIR, '.masterkey');let __plaintextWarned = false;-const log = (...args) => console.error('credential-store:', ...args);+// ─── Redacted logging ────────────────────────────────────────────────────────++/** Fixed label. A constant, never derived from any runtime value. */+const REDACTED_TOKEN = '<redacted:token>';++/**+ * Redact credential-shaped strings before anything reaches stderr.+ *+ * Scope note, deliberately narrow: this does NOT read `process.env`. Earlier+ * revisions hashed every sensitive env value and redacted matches, as+ * defence-in-depth against a secret being interpolated into a child-process+ * error message. That was dropped for three reasons:+ *+ * 1. No call site in this module logs a secret. Every `log()` argument is a+ * literal status string, plus one `Error.message`.+ * 2. Reading process.env inside the function that feeds console.error is a+ * genuine source→sink flow (CodeQL js/clear-text-logging #294). Keeping+ * code a scanner cannot distinguish from "logs secrets" makes the next+ * real finding in this file easier to wave through.+ * 3. Token-shape matching still covers the realistic leak — an API key or+ * bearer token embedded in an error string — without touching the+ * environment at all.+ *+ * If a future call site logs child-process or attacker-influenced text that may+ * embed an env secret, redact at that call site rather than widening this one.+ */+function scrub(text) {+ return String(text).replace(+ /\b(?:sk|pk|xoxc|xoxd|xoxb|xoxp|ghp|gho|github_pat)[-_][A-Za-z0-9_-]{8,}/g,+ REDACTED_TOKEN,+ );+}++const log = (...args) =>+ console.error(+ 'credential-store:',+ ...args.map((a) => scrub(a instanceof Error ? a.message : typeof a === 'string' ? a : JSON.stringify(a))),+ );function assertPublicWriteAllowed(service) {const name = String(service || '').toLowerCase();@@ -293,7 +330,7 @@ async function encJsonGet(service, account) {if (!store[key]) return null;const k = await masterKey();const pt = decrypt(store[key], k);- if (pt === null) log('decrypt failed for enc-json/' + key);+ if (pt === null) log('decrypt failed for enc-json/' + service);return pt;}async function encJsonDelete(service, account) {@@ -355,7 +392,6 @@ export async function backendsAvailable() {*/export async function setCredential(service, account, secret) {assertPublicWriteAllowed(service);- const forced = process.env.CLAUDE_OPS_CRED_BACKEND;const tryBackend = async (name) => {let ok = false;switch (name) {@@ -377,15 +413,58 @@ export async function setCredential(service, account, secret) {case 'plaintext-json':ok = await plainSet(service, account, secret);break;+ default:+ return false;}+ // `name` is always a case-arm literal here (the switch above is exhaustive+ // for every value we call with). Concatenating it into the log line is+ // therefore not an env-derived flow.if (ok) log('stored via=' + name);return ok;};- if (forced) {- const ok = await tryBackend(forced);- if (!ok) log('forced backend=' + forced + ' failed');- return { backend: forced, ok };+ // Force path: one case arm per known backend, each calling tryBackend with a+ // string LITERAL. A Set/allowlist membership check is not recognised as a+ // sanitizer by CodeQL (documented on the spawnSync path further down this+ // file); a switch of string literals is, so the env value never reaches a+ // log line or a backend call as a data flow.+ switch (process.env.CLAUDE_OPS_CRED_BACKEND) {+ case 'security': {+ const ok = await tryBackend('security');+ if (!ok) log('forced backend failed');+ return { backend: 'security', ok };+ }+ case 'secret-tool': {+ const ok = await tryBackend('secret-tool');+ if (!ok) log('forced backend failed');+ return { backend: 'secret-tool', ok };+ }+ case 'wincred': {+ const ok = await tryBackend('wincred');+ if (!ok) log('forced backend failed');+ return { backend: 'wincred', ok };+ }+ case 'keytar': {+ const ok = await tryBackend('keytar');+ if (!ok) log('forced backend failed');+ return { backend: 'keytar', ok };+ }+ case 'enc-json': {+ const ok = await tryBackend('enc-json');+ if (!ok) log('forced backend failed');+ return { backend: 'enc-json', ok };+ }+ case 'plaintext-json': {+ const ok = await tryBackend('plaintext-json');+ if (!ok) log('forced backend failed');+ return { backend: 'plaintext-json', ok };+ }+ case undefined:+ case '':+ break;+ default:+ log('forced backend rejected (unknown name)');+ return { backend: null, ok: false };}const cascade = [];diff --git a/claude-ops/scripts/account-rotation/__tests__/daily-credit-digest.test.mjs b/claude-ops/scripts/account-rotation/__tests__/daily-credit-digest.test.mjsindex fc8c0dcb..47f85f17 100644--- a/claude-ops/scripts/account-rotation/__tests__/daily-credit-digest.test.mjs+++ b/claude-ops/scripts/account-rotation/__tests__/daily-credit-digest.test.mjs@@ -22,6 +22,34 @@ import {} from '../daily-credit-digest.mjs';import { SCHEMA_VERSION, MAX_PLAN_MONTHLY_USD } from '../ledger.mjs';+/**+ * Assert a rendered message body leaks no Slack webhook.+ *+ * Written as "parse every URL, check its hostname" rather than a substring or+ * regex test on the raw text. A substring check for a host literal is exactly+ * the js/incomplete-url-substring-sanitization pattern: the host can appear+ * anywhere in a URL (https://evil.example/?x=hooks.slack.com) so matching it+ * proves nothing about where the URL actually points. Parsing gives the real+ * host, and the assertion catches ANY Slack URL rather than one known literal.+ */+function assertNoSlackWebhook(body) {+ // Case-insensitive scheme match + strip trailing DNS root dots so+ // `HTTPS://hooks.slack.com./...` still fails the host check.+ const urls = String(body).match(/https?:\/\/[^\s<>"')\]]+/gi) || [];+ for (const raw of urls) {+ let host;+ try {+ host = new URL(raw).hostname.toLowerCase().replace(/\.+$/, '');+ } catch {+ continue; // not a parseable URL, so not a live webhook+ }+ assert.ok(+ host !== 'slack.com' && !host.endsWith('.slack.com'),+ `body must not leak a Slack webhook URL (found host ${host})`,+ );+ }+}+function makeLedger(month, accounts) {return { schema_version: SCHEMA_VERSION, month, accounts };}@@ -281,8 +309,7 @@ test('formatSlackBody: includes pool, severity, projection, fallback section', (assert.match(body, /Fallback 24h:/);assert.match(body, /a@x/);assert.match(body, /b@x/);- // No webhook leaks- assert.doesNotMatch(body, /hooks\.slack\.com/);+ assertNoSlackWebhook(body);});test('formatSlackBody: graceful fallback when CloudWatch unavailable', () => {diff --git a/claude-ops/scripts/account-rotation/__tests__/monthly-credit-reclaim.test.mjs b/claude-ops/scripts/account-rotation/__tests__/monthly-credit-reclaim.test.mjsindex 2edf759f..01ba0cb5 100644--- a/claude-ops/scripts/account-rotation/__tests__/monthly-credit-reclaim.test.mjs+++ b/claude-ops/scripts/account-rotation/__tests__/monthly-credit-reclaim.test.mjs@@ -16,6 +16,34 @@ import {} from '../monthly-credit-reclaim.mjs';import { SCHEMA_VERSION, MAX_PLAN_MONTHLY_USD } from '../ledger.mjs';+/**+ * Assert a rendered message body leaks no Slack webhook.+ *+ * Written as "parse every URL, check its hostname" rather than a substring or+ * regex test on the raw text. A substring check for a host literal is exactly+ * the js/incomplete-url-substring-sanitization pattern: the host can appear+ * anywhere in a URL (https://evil.example/?x=hooks.slack.com) so matching it+ * proves nothing about where the URL actually points. Parsing gives the real+ * host, and the assertion catches ANY Slack URL rather than one known literal.+ */+function assertNoSlackWebhook(body) {+ // Case-insensitive scheme match + strip trailing DNS root dots so+ // `HTTPS://hooks.slack.com./...` still fails the host check.+ const urls = String(body).match(/https?:\/\/[^\s<>"')\]]+/gi) || [];+ for (const raw of urls) {+ let host;+ try {+ host = new URL(raw).hostname.toLowerCase().replace(/\.+$/, '');+ } catch {+ continue; // not a parseable URL, so not a live webhook+ }+ assert.ok(+ host !== 'slack.com' && !host.endsWith('.slack.com'),+ `body must not leak a Slack webhook URL (found host ${host})`,+ );+ }+}+function makeLedger(month, accounts) {return { schema_version: SCHEMA_VERSION, month, accounts };}@@ -105,8 +133,7 @@ test('formatSlackBody: includes pool, waste %, prior cycle, no secrets', () => {assert.match(body, /50% waste/);assert.match(body, /2026-05/);assert.match(body, /2\/2 accounts re-claimed/);- // Ensure no API token / webhook leaks- assert.doesNotMatch(body, /hooks\.slack\.com/);+ assertNoSlackWebhook(body);});test('formatSlackBody: reports failed accounts', () => {diff --git a/claude-ops/scripts/account-rotation/bg-spawn.mjs b/claude-ops/scripts/account-rotation/bg-spawn.mjsindex ba12beaf..8ad27a67 100644--- a/claude-ops/scripts/account-rotation/bg-spawn.mjs+++ b/claude-ops/scripts/account-rotation/bg-spawn.mjs@@ -30,6 +30,7 @@ import { readFileSync, existsSync } from 'fs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { spawnSync } from 'child_process';+import { randomBytes } from 'node:crypto';import { applyAccountLeases } from './account-leases.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -91,8 +92,10 @@ try {// accountKey helper (mirrors session-router.mjs)const accountKey = (a) => a.label || a.email;-// Generate a stable session ID for this dispatch-const sessionId = `bg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+// Generate a stable session ID for this dispatch. The session id keys the+// account lease (which account's credentials this dispatch gets), so it must be+// unguessable and collision-free — a CSPRNG, not Math.random().+const sessionId = `bg-${Date.now()}-${randomBytes(9).toString('base64url')}`;// Pick accountconst key = pickAccountForSession(sessionId, config, state);diff --git a/claude-ops/scripts/account-rotation/ensure-rotate-captcha-hooks.mjs b/claude-ops/scripts/account-rotation/ensure-rotate-captcha-hooks.mjsindex 4a531cde..f83df152 100644--- a/claude-ops/scripts/account-rotation/ensure-rotate-captcha-hooks.mjs+++ b/claude-ops/scripts/account-rotation/ensure-rotate-captcha-hooks.mjs@@ -4,7 +4,7 @@** Mutates sibling rotate.mjs once when markers are missing.*/-import { readFileSync, writeFileSync, existsSync } from 'fs';+import { readFileSync, writeFileSync, renameSync, statSync, unlinkSync, chmodSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';@@ -15,7 +15,17 @@ const MARKER = 'auth-step-${step}'; // template marker after patchconst MARKER_PLAIN = 'auth-step-'; // simpler detectexport function rotateCaptchaHooksPresent(src = null) {- const text = src ?? (existsSync(ROTATE) ? readFileSync(ROTATE, 'utf8') : '');+ let text = src;+ if (text == null) {+ // Read directly and treat ENOENT as "absent" rather than testing existence+ // first: the existsSync/readFileSync pair is a TOCTOU race, and the read+ // already tells us everything the check would have.+ try {+ text = readFileSync(ROTATE, 'utf8');+ } catch {+ text = '';+ }+ }return (text.includes("from './rotate-captcha-soft.mjs'") ||(text.includes('trySolveCaptchaWall') && text.includes('oauth-authorize') && text.includes(MARKER_PLAIN))@@ -23,10 +33,13 @@ export function rotateCaptchaHooksPresent(src = null) {}export function ensureRotateCaptchaHooks({ dryRun = false } = {}) {- if (!existsSync(ROTATE)) {+ // Read first; ENOENT is the "missing" signal. No existsSync pre-check.+ let text;+ try {+ text = readFileSync(ROTATE, 'utf8');+ } catch {return { ok: false, reason: 'rotate-missing' };}- let text = readFileSync(ROTATE, 'utf8');if (rotateCaptchaHooksPresent(text)) {return { ok: true, changed: false, reason: 'already-present' };}@@ -186,7 +199,32 @@ const __dirname`,if (dryRun) {return { ok: true, changed: true, dryRun: true, presentAfter: rotateCaptchaHooksPresent(text) };}- writeFileSync(ROTATE, text);+ // Write atomically: temp file in the same directory + rename(2). A direct+ // writeFileSync over the path we read leaves a window in which rotate.mjs can+ // be replaced between read and write, and a crash mid-write would truncate the+ // live script. rename(2) is atomic within a filesystem, so readers see either+ // the old file or the complete new one.+ const tmp = `${ROTATE}.tmp-${process.pid}`;+ try {+ let mode = 0o644;+ try {+ mode = statSync(ROTATE).mode & 0o777;+ } catch {}+ // writeFileSync only applies `mode` on create. A leftover tmp from a crashed+ // run with a reused pid would be opened/truncated and keep its old bits —+ // unlink first, write exclusively, then reassert mode before rename.+ try {+ unlinkSync(tmp);+ } catch {}+ writeFileSync(tmp, text, { flag: 'wx', mode });+ chmodSync(tmp, mode);+ renameSync(tmp, ROTATE);+ } catch (e) {+ try {+ unlinkSync(tmp);+ } catch {}+ throw e;+ }return { ok: true, changed: true, presentAfter: rotateCaptchaHooksPresent(text) };}diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjsindex 26e821c5..a20d720b 100644--- a/claude-ops/scripts/account-rotation/rotate.mjs+++ b/claude-ops/scripts/account-rotation/rotate.mjs@@ -1956,7 +1956,7 @@ async function makeKaptureDriver() {.replace(/button:has-text\("?([^"]+)"?\)/g, '$1').replace(/"/g, '').trim();- const escaped = clean.replace(/'/g, "\\'");+ const escaped = clean.replace(/\\/g, '\\\\').replace(/'/g, "\\'");const xpaths = [`//button[.//*[contains(normalize-space(.),'${escaped}')] or contains(normalize-space(.),'${escaped}')]`,`//a[.//*[contains(normalize-space(.),'${escaped}')] or contains(normalize-space(.),'${escaped}')]`,@@ -2400,7 +2400,7 @@ async function makeChromeJXADriver() {if (!val) return false;try {jxaJs(- `(function(){var e=document.querySelector('${sel}');if(e){e.value='${val.replace(/'/g, "\\'")}';e.dispatchEvent(new Event('input',{bubbles:true}));e.dispatchEvent(new Event('change',{bubbles:true}));}})()`,+ `(function(){var e=document.querySelector('${sel}');if(e){e.value='${val.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}';e.dispatchEvent(new Event('input',{bubbles:true}));e.dispatchEvent(new Event('change',{bubbles:true}));}})()`,);return true;} catch {@@ -2861,7 +2861,7 @@ async function runAuthFlow(driver, account, hooks = {}) {log(`Step ${step} [${driver.name}]: ${url.substring(0, 100)}`);// Browser wall: CF / hCaptcha / interactive tile challenge- if (driver._page && url.includes('claude.ai')) {+ if (driver._page && hostIs(url, 'claude.ai')) {const wallish = await pageLooksLikeCaptchaWall(driver._page);if (wallish || step === 0) {const solved = await trySolveCaptchaWallSafe(driver._page, (m) => log(m), {@@ -2881,7 +2881,7 @@ async function runAuthFlow(driver, account, hooks = {}) {// /oauth/authorize URL. Handle known Claude auth prompts before the generic// stall detector, otherwise AI-brain burns multiple decisions waiting for a// verification code that the deterministic Gmail poller can resolve or fail.- if (account.useMagicLink && url.includes('claude.ai')) {+ if (account.useMagicLink && hostIs(url, 'claude.ai')) {if (await handleClaudeMagicLinkEmailPrompt(url.includes('/oauth/authorize') ? 'OAuth page rendered login prompt' : 'Login prompt',@@ -2974,8 +2974,22 @@ async function runAuthFlow(driver, account, hooks = {}) {continue;}+ /** Exact hostname match (and optional subdomains). Avoids url.includes host checks. */+ function hostIs(url, host) {+ try {+ const h = new URL(url).hostname.toLowerCase();+ const target = String(host).toLowerCase();+ return h === target || h.endsWith('.' + target);+ } catch {+ return false;+ }+ }+ function hostIsAny(url, hosts) {+ return hosts.some((h) => hostIs(url, h));+ }+// Google 2FA: push notification to phone (/challenge/dp) — can't automate, must switch- if (url.includes('accounts.google.com') && url.includes('challenge/dp')) {+ if (hostIs(url, 'accounts.google.com') && url.includes('challenge/dp')) {log(`Push-notification 2FA detected — clicking "Try another way"`);const clicked = await driver.findAndClick(['Try another way', 'Probeer een andere manier']);if (!clicked) {@@ -2988,7 +3002,7 @@ async function runAuthFlow(driver, account, hooks = {}) {// Google passkey challenge (/challenge/pk/presend, /challenge/pk/verify).// No hardware key available — bail out via "Try another way".- if (url.includes('accounts.google.com') && url.includes('/challenge/pk')) {+ if (hostIs(url, 'accounts.google.com') && url.includes('/challenge/pk')) {log(`Passkey challenge detected — clicking "Try another way"`);const clicked = await driver.findAndClick(['Try another way',@@ -3018,7 +3032,7 @@ async function runAuthFlow(driver, account, hooks = {}) {// - data-challengetype="6" → TOTP authenticator app// Preference: password (we have it via dcli) > TOTP (we have the secret)// > SMS (requires a phone) > passkey (no hardware).- if (url.includes('accounts.google.com') && url.includes('challenge/selection')) {+ if (hostIs(url, 'accounts.google.com') && url.includes('challenge/selection')) {log(`On 2FA selection page — prefer password, then TOTP, then SMS`);const selectors = [];if (googlePassword)@@ -3051,7 +3065,7 @@ async function runAuthFlow(driver, account, hooks = {}) {}// Google 2FA: TOTP code entry- if (url.includes('accounts.google.com') && url.includes('challenge/totp')) {+ if (hostIs(url, 'accounts.google.com') && url.includes('challenge/totp')) {if (googleOtpSecret) {const code = generateTOTP(googleOtpSecret);log(`Entering TOTP code from dcli secret`);@@ -3068,7 +3082,7 @@ async function runAuthFlow(driver, account, hooks = {}) {}// Google 2FA: SMS phone collect (/challenge/ipp/collect) — enter phone, click Send- if (url.includes('accounts.google.com') && url.includes('challenge/ipp/collect')) {+ if (hostIs(url, 'accounts.google.com') && url.includes('challenge/ipp/collect')) {if (!googleSmsPhone) {log(`SMS phone collect page — no phone (set CLAUDE_ROTATION_GOOGLE_SMS_PHONE, account.googleSmsPhone, or dcli phone on google.com cred)`,@@ -3084,10 +3098,7 @@ async function runAuthFlow(driver, account, hooks = {}) {}// Google 2FA: SMS code verify (/challenge/ipp/verify or /challenge/sms)- if (- url.includes('accounts.google.com') &&- (url.includes('challenge/ipp/verify') || url.includes('challenge/sms'))- ) {+ if (hostIs(url, 'accounts.google.com') && (url.includes('challenge/ipp/verify') || url.includes('challenge/sms'))) {log(`Waiting for SMS code from Messages.app (up to 60s)...`);let smsCode = null;for (let waitI = 0; waitI < 12; waitI++) {@@ -3109,7 +3120,7 @@ async function runAuthFlow(driver, account, hooks = {}) {// Google consent page (/signin/oauth/id or /signin/oauth/consent) — click Continueif (- url.includes('accounts.google.com') &&+ hostIs(url, 'accounts.google.com') &&(url.includes('/signin/oauth/id') ||url.includes('/signin/oauth/consent') ||url.includes('/signin/oauth/legacy'))@@ -3146,7 +3157,7 @@ async function runAuthFlow(driver, account, hooks = {}) {// Google password prompt (standalone /challenge/pwd — must run BEFORE the// broad accounts.google.com account-chooser branch below).- if (url.includes('accounts.google.com') && url.includes('challenge/pwd')) {+ if (hostIs(url, 'accounts.google.com') && url.includes('challenge/pwd')) {if (googlePassword) {await driver.fillInput('input[type="password"]', googlePassword);await sleep(500);@@ -3156,7 +3167,7 @@ async function runAuthFlow(driver, account, hooks = {}) {}// Google account chooser — click the target account- if (url.includes('accounts.google.com')) {+ if (hostIs(url, 'accounts.google.com')) {// Detect "Signed out" next to the target account (needs re-login)let targetSignedOut = false;if (driver.readPageText) {@@ -3199,7 +3210,7 @@ async function runAuthFlow(driver, account, hooks = {}) {// several times (select-organization, onboarding/organization, workspaces,// choose-workspace). Also triggers on page-text heuristic for routes we miss.const isOrgChooserUrl =- url.includes('claude.ai') &&+ hostIs(url, 'claude.ai') &&(url.includes('select-organization') ||url.includes('/onboarding/organization') ||url.includes('choose-organization') ||@@ -3209,7 +3220,7 @@ async function runAuthFlow(driver, account, hooks = {}) {url.includes('select-account') ||url.includes('switch-org'));let isOrgChooserByText = false;- if (!isOrgChooserUrl && url.includes('claude.ai') && driver.readPageText) {+ if (!isOrgChooserUrl && hostIs(url, 'claude.ai') && driver.readPageText) {try {const t = (await driver.readPageText()).toLowerCase();isOrgChooserByText =@@ -3382,7 +3393,7 @@ async function runAuthFlow(driver, account, hooks = {}) {const currentUrl = await driver.currentUrl().catch(() => '');if (currentUrl.includes('/oauth/code/success') ||- (currentUrl && !currentUrl.includes('claude.ai') && !currentUrl.includes('claude.com'))+ (currentUrl && !hostIsAny(currentUrl, ['claude.ai', 'claude.com']))) {log(`Auth already succeeded — URL moved to ${currentUrl.substring(0, 80)}`);authorized = true;@@ -3436,7 +3447,7 @@ async function runAuthFlow(driver, account, hooks = {}) {}// Dismiss cookie consent banner if present (blocks clicks on everything else)- if (url.includes('claude.ai')) {+ if (hostIs(url, 'claude.ai')) {await driver.findAndClick(['[data-testid="consent-reject"]','[data-testid="consent-accept"]',@@ -3711,12 +3722,18 @@ async function browserOAuthFallback(account) {try {unlinkSync(urlFile);} catch {}- if (!existsSync(capScript)) {- writeFileSync(capScript, `#!/bin/bash\numask 077\necho "$1" > "${urlFile}"\n`, {- flag: 'wx',- mode: 0o700,- });+ // Same exclusive-create sequence as the initial BROWSER helper above: clear+ // any leftover, then refuse if the exclusive create still fails. EEXIST+ // after the unlink means another writer planted the file, not a no-op.+ try {+ unlinkSync(capScript);+ } catch {+ /* nothing left over */}+ writeFileSync(capScript, `#!/bin/bash\numask 077\necho "$1" > "${urlFile}"\n`, {+ flag: 'wx',+ mode: 0o700,+ });proc = spawnOAuthWriter();let freshUrl = null;const scanFreshUrl = (chunk) => {diff --git a/claude-ops/scripts/account-rotation/secrets-bootstrap.mjs b/claude-ops/scripts/account-rotation/secrets-bootstrap.mjsindex 6ba722e5..007d9e5a 100644--- a/claude-ops/scripts/account-rotation/secrets-bootstrap.mjs+++ b/claude-ops/scripts/account-rotation/secrets-bootstrap.mjs@@ -6,7 +6,7 @@// Never throws. Never prints secret values. Runs the Doppler CLI at most once// per process, and only if at least one required key is missing.import { execFileSync } from 'child_process';-import { existsSync, readFileSync, statSync } from 'fs';+import { closeSync, fstatSync, openSync, readFileSync } from 'fs';import { homedir } from 'os';import { join } from 'path';@@ -86,14 +86,24 @@ const SECRET_FILES = [function hydrateFromSecretFiles(keys, log) {const loaded = [];for (const path of SECRET_FILES) {+ let fd = null;try {- if (!existsSync(path)) continue;- if ((statSync(path).mode & 0o077) !== 0) {+ // Open first, then fstat and read *the same descriptor*. Checking+ // existence/mode by path and re-resolving the path to read it leaves a+ // TOCTOU window in which the file we vetted can be swapped for a+ // world-readable one (or a symlink to another file) before we read it.+ try {+ fd = openSync(path, 'r');+ } catch {+ continue; // missing or unreadable — nothing to hydrate from+ }+ const st = fstatSync(fd);+ if (!st.isFile() || (st.mode & 0o077) !== 0) {if (log) log(`secrets-bootstrap: refusing permissive secret file ${path}`);continue;}const allowed = new Set(keys);- for (const line of readFileSync(path, 'utf8').split(/\r?\n/)) {+ for (const line of readFileSync(fd, 'utf8').split(/\r?\n/)) {const match = line.match(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)=(.*)\s*$/);if (!match || !allowed.has(match[1]) || process.env[match[1]]) continue;let value = match[2].trim();@@ -104,7 +114,14 @@ function hydrateFromSecretFiles(keys, log) {process.env[match[1]] = value;loaded.push(match[1]);}- } catch {}+ } catch {+ } finally {+ if (fd !== null) {+ try {+ closeSync(fd);+ } catch {}+ }+ }}return loaded;}diff --git a/claude-ops/scripts/pocket-env-broker.py b/claude-ops/scripts/pocket-env-broker.pyindex 04f1483f..678fea7b 100755--- a/claude-ops/scripts/pocket-env-broker.py+++ b/claude-ops/scripts/pocket-env-broker.py@@ -39,6 +39,7 @@ import jsonimport osimport pwdimport shlex+import shutilimport signalimport socketimport struct@@ -209,8 +210,16 @@ def load_policy() -> set[str]:def audit(record: dict) -> None:record = {"ts": now_iso(), **record}try:- AUDIT_PATH.parent.mkdir(parents=True, exist_ok=True)- with AUDIT_PATH.open("a") as f:+ AUDIT_PATH.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ # mkdir(mode=...) only applies when the directory is created; force the+ # mode on pre-existing parents so a prior permissive dir does not stick.+ os.chmod(AUDIT_PATH.parent, 0o700)+ # Open with an explicit 0600 mode so the audit trail is never readable by+ # group/other even if the process umask is permissive.+ fd = os.open(+ str(AUDIT_PATH), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600+ )+ with os.fdopen(fd, "a") as f:f.write(json.dumps(record) + "\n")except OSError as e:log(f"audit write failed: {e}")@@ -301,6 +310,47 @@ def handle(conn: socket.socket, want_uid: int | None) -> None:pass+def _harden_socket_perms(want_uid: int | None) -> None:+ """Restrict the broker socket to the owner, plus the worker uid via ACL.++ The socket is the door to every allowlisted secret, so it must never be+ group- or world-accessible: a 0660 socket grants connect to every member of+ the owning group, which on a default `useradd` layout is wider than the one+ worker account we mean to authorize. We set 0600 (owner only) and then grant+ the single worker uid explicitly with a filesystem ACL where one is+ available. SO_PEERCRED remains the authoritative check either way.+ """+ os.chmod(SOCK_PATH, 0o600)+ if want_uid is None:+ return+ setfacl = shutil.which("setfacl")+ if setfacl: # Linux / any POSIX.1e ACL filesystem+ rc = subprocess.run(+ [setfacl, "-m", f"u:{want_uid}:rw", str(SOCK_PATH)],+ capture_output=True,+ ).returncode+ if rc == 0:+ return+ chmod_bin = shutil.which("chmod")+ if sys.platform == "darwin" and chmod_bin: # macOS NFSv4-style ACLs+ rc = subprocess.run(+ [+ chmod_bin,+ "+a",+ f"user:{WORKER_USER} allow read,write",+ str(SOCK_PATH),+ ],+ capture_output=True,+ ).returncode+ if rc == 0:+ return+ log(+ f"socket is 0600 and no ACL could be set for uid {want_uid} — "+ "grant access by running the broker as a user the worker can reach, "+ "or add an ACL out of band"+ )++def serve() -> int:want_uid = allowed_uid()if want_uid is None:@@ -308,15 +358,24 @@ def serve() -> int:f"worker user {WORKER_USER!r} does not exist — every request will be denied")- SOCK_PATH.parent.mkdir(parents=True, exist_ok=True)- if SOCK_PATH.exists():+ SOCK_PATH.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ # mkdir(mode=...) only applies on create; reassert owner-only on existing dirs.+ os.chmod(SOCK_PATH.parent, 0o700)+ try:SOCK_PATH.unlink()+ except FileNotFoundError:+ # No stale socket file to remove; first start or already cleaned up.+ passsrv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- srv.bind(str(SOCK_PATH))- # 0660: connect is gated by filesystem perms (provisioning grants the worker- # user via group/ACL) AND by SO_PEERCRED at the application layer.- os.chmod(SOCK_PATH, 0o660)+ # Create the inode under a restrictive umask so it is never world-accessible+ # between bind() and the later chmod/ACL hardening step.+ old_umask = os.umask(0o177)+ try:+ srv.bind(str(SOCK_PATH))+ finally:+ os.umask(old_umask)+ _harden_socket_perms(want_uid)srv.listen(16)with _METRICS_LOCK:_METRICS["started_at"] = now_iso()