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(crsproxy): fix 5 scrutiny round 1 blocking issues
auroracapital0f6cb3b7b485
diff --git a/claude-ops/scripts/crsproxy-reauth/auto_reauth.py b/claude-ops/scripts/crsproxy-reauth/auto_reauth.pyindex f5806b6b..0297f31f 100644--- a/claude-ops/scripts/crsproxy-reauth/auto_reauth.py+++ b/claude-ops/scripts/crsproxy-reauth/auto_reauth.py@@ -286,8 +286,8 @@ def find_auth_file(provider: str, email: str) -> Path | None:return f# Fallback: read files and check the email field inside (handles- # filename mismatches, e.g. [email protected]- # containing email "[email protected]").+ # filename mismatches, e.g. [email protected]+ # containing email "[email protected]").for f in AUTH_DIR.glob(f"{provider}-*.json"):if any(ext in f.name for ext in (".bak", ".stale", ".lock", ".tmp")):continue@@ -390,10 +390,16 @@ def parse_expiry(expired: str):return None-def scan_auth_files():+def scan_auth_files(policy_disabled=None):"""Scan all auth files and return a list of dicts describing each accountthat needs a reauth (token expired/expiring-soon or disabled) and is- supported by the reauth pipeline."""+ supported by the reauth pipeline.++ If policy_disabled is provided (a set of (provider, email) tuples),+ accounts matching those tuples are excluded — they were intentionally+ disabled by policy and should not be reauthed. This prevents the+ reconciliation step from disabling a policy-disabled account and then+ the scan step immediately re-queueing it for reauth in the same cycle."""now = datetime.now(timezone.utc)needs_reauth = []all_files = sorted(AUTH_DIR.glob("*.json"))@@ -406,6 +412,10 @@ def scan_auth_files():provider = data.get("type", "")email = data.get("email", "")+ # Skip accounts that are intentionally disabled by policy — they+ # should not be re-queued for reauth by the generic scan.+ if policy_disabled and (provider, email) in policy_disabled:+ continuedisabled = bool(data.get("disabled", False))exp = parse_expiry(data.get("expired", ""))@@ -680,8 +690,19 @@ def main() -> int:# 3. Run account policy reconciliation.reconcile_summary = reconcile_accounts(env, seats, state)+ # Build set of policy-disabled accounts to exclude from the generic scan.+ # This prevents the scan from re-queueing accounts that were just disabled+ # by reconcile_accounts() in the same cycle (reconciliation bug fix).+ policy = load_account_policy()+ policy_disabled = set()+ if policy:+ for entry in policy.get("accounts", []):+ if not entry.get("enabled", True):+ policy_disabled.add(+ (entry.get("provider", ""), entry.get("email", "")))+# 4. Scan auth files for expired/disabled accounts.- needs = scan_auth_files()+ needs = scan_auth_files(policy_disabled=policy_disabled)log(f"[scan] {len(needs)} account(s) need reauth (token expiry/disabled)")if not needs:diff --git a/claude-ops/scripts/crsproxy-reauth/bu_profile_reauth.py b/claude-ops/scripts/crsproxy-reauth/bu_profile_reauth.pyindex b15241a5..ac523b6d 100644--- a/claude-ops/scripts/crsproxy-reauth/bu_profile_reauth.py+++ b/claude-ops/scripts/crsproxy-reauth/bu_profile_reauth.py@@ -25,9 +25,10 @@ import timefrom datetime import datetime, timedelta, timezonefrom pathlib import Path-# Import infrastructure from bu_reauth.py+# Import infrastructure from bu_reauth_lib.py (the stable copy that avoids+# the quarantine issue affecting bu_reauth.py on the hub).sys.path.insert(0, "/opt/crsproxy")-from bu_reauth import (+from bu_reauth_lib import (BrowserUseClient,PROVIDERS,INTERCEPT_JS_TEMPLATE,@@ -58,7 +59,7 @@ from bu_reauth import ()# Also import _complete_reauth for the final step-from bu_reauth import _complete_reauth+from bu_reauth_lib import _complete_reauthdef run_profile_reauth(provider: str, email: str, profile_id: str,@@ -239,7 +240,7 @@ def _fallback_email_entry(proc, client, session_id, provider, email,This reuses the session to enter the email and proceed with thestandard OAuth flow (code/magic link via Gmail)."""- from bu_reauth import (+ from bu_reauth_lib import (poll_gmail_for_code,record_email_send,_code_entry_failed,diff --git a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py b/claude-ops/scripts/crsproxy-reauth/bu_reauth.pyindex bf0a8ea0..b279f9e4 100644--- a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py+++ b/claude-ops/scripts/crsproxy-reauth/bu_reauth.py@@ -20,7 +20,7 @@ Features:keeps browser session alive, waits for a file-based trigger, thenresumes with a follow-up run in the same session to click Authorizeand capture the callback URL.- - Serialization lease: checks /tmp/crsproxy-claude-oauth-lease.json+ - Serialization lease: checks /opt/crsproxy/state/crsproxy-claude-oauth-lease.jsonbefore starting a login, waits if held, cleans up after completion.- Email cooldown: tracks verification code send timestamps, enforcesa 5-minute cooldown if >3 codes are sent in 5 minutes, logs@@ -61,7 +61,7 @@ Usage:# When hCaptcha is detected, the script emits the live_view_url and waits.# After solving the captcha in the browser, create the trigger file:- # touch /tmp/bu_reauth_checkpoint_trigger+ # sudo -u crsproxy touch /opt/crsproxy/state/bu_reauth_checkpoint_trigger# The script will then create a follow-up run and complete the flow."""@@ -900,7 +900,14 @@ def _code_entry_failed(result_text: str) -> bool:def detect_captcha(run_result: dict, client: BrowserUseClient) -> bool:"""Check if the run result or events indicate a real captcha challenge."""- result_text = str(run_result.get("result", "") or "").lower()+ result_raw = str(run_result.get("result", "") or "")+ result_text = result_raw.lower()+ # Browser Use tasks report exact 'CAPTCHA' (uppercase) as a sentinel+ # when they encounter a real captcha challenge. Use a word-boundary+ # regex on the original (non-lowercased) text so that 'captcha' in+ # sentences like "No captcha needed" does NOT trigger a false positive.+ if re.search(r'\bCAPTCHA\b', result_raw):+ return True# "captcha" in a sentence is not enough — look for specific indicatorscaptcha_indicators = [# These indicators are checked ONLY against the agent's result@@ -965,7 +972,7 @@ def wait_for_checkpoint_signal(timeout: int = CHECKPOINT_TIMEOUT) -> bool:Polls for the existence of CHECKPOINT_TRIGGER every CHECKPOINT_POLL_INTERVALseconds. Returns True if the trigger appears, False on timeout.- The trigger file can be created by: touch /tmp/bu_reauth_checkpoint_trigger+ The trigger file can be created by: sudo -u crsproxy touch /opt/crsproxy/state/bu_reauth_checkpoint_trigger"""log(f"[CAPTCHA_CHECKPOINT] Waiting up to {timeout}s for trigger: {CHECKPOINT_TRIGGER}")t0 = time.time()@@ -999,7 +1006,7 @@ def handle_captcha_checkpoint(client: BrowserUseClient, run_id: str,2. Emit the URL to stdout (full URL for Sam, sanitized for logs).3. Keep the browser session alive (do NOT stop it).4. Write a checkpoint file with session state.- 5. Wait for a file-based trigger (touch /tmp/bu_reauth_checkpoint_trigger).+ 5. Wait for a file-based trigger (sudo -u crsproxy touch /opt/crsproxy/state/bu_reauth_checkpoint_trigger).6. After trigger, create a follow-up run in the same session to clickAuthorize with JS interception and capture the callback URL.7. Return (callback_url, session_id) or (None, session_id) on failure.@@ -1515,7 +1522,7 @@ def _timeout_handler(signum, frame):def _checkpoint_resume(args) -> int:"""Resume from a hCaptcha checkpoint file.- Reads /tmp/bu_reauth_checkpoint.json for the session_id, provider,+ Reads /opt/crsproxy/state/bu_reauth_checkpoint.json for the session_id, provider,email, and callback_port. Starts a new cli-proxy-api login process(the original one is likely dead), creates a follow-up run in thesame Browser Use session to click Authorize, extracts the callback@@ -1688,7 +1695,7 @@ def main():parser.add_argument("-checkpoint-resume", action="store_true",help="Resume from a checkpoint file written by a ""previous run that detected hCaptcha. Reads "- "/tmp/bu_reauth_checkpoint.json for the "+ "/opt/crsproxy/state/bu_reauth_checkpoint.json for the ""session_id, then creates a follow-up run to ""click Authorize and complete the flow.")parser.add_argument("-log-file", default="",diff --git a/claude-ops/scripts/crsproxy-reauth/crsproxy_auto_router.py b/claude-ops/scripts/crsproxy-reauth/crsproxy_auto_router.pyindex 4ab35a74..c05294de 100644--- a/claude-ops/scripts/crsproxy-reauth/crsproxy_auto_router.py+++ b/claude-ops/scripts/crsproxy-reauth/crsproxy_auto_router.py@@ -60,7 +60,7 @@ logger = logging.getLogger("crsproxy-auto-router")def mask_email(email):"""Mask an email address for safe logging.- Returns 'ad**@healify.ai' for '[email protected]'.+ Returns 'us**@example.com' for '[email protected]'.Returns '[no-email]' for empty/invalid input."""if not email or "@" not in email:diff --git a/claude-ops/scripts/crsproxy-reauth/test_auto_reauth.py b/claude-ops/scripts/crsproxy-reauth/test_auto_reauth.pynew file mode 100644index 00000000..d30a5e09--- /dev/null+++ b/claude-ops/scripts/crsproxy-reauth/test_auto_reauth.py@@ -0,0 +1,207 @@+#!/usr/bin/env python3+"""test_auto_reauth.py — Unit tests for auto_reauth.py.++Tests the reconciliation bug fix: after reconcile_accounts() disables a+policy-disabled account, the generic scan_auth_files() call in the same+cycle must NOT pick up that account and queue it for reauth.++Run: python3 test_auto_reauth.py+"""++import json+import os+import shutil+import sys+import tempfile+import unittest+from datetime import datetime, timezone, timedelta+from pathlib import Path+from unittest.mock import patch++# Add parent directory to path so we can import the module+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))++import auto_reauth+++class TestScanAuthFilesPolicyFilter(unittest.TestCase):+ """Test that scan_auth_files excludes policy-disabled accounts."""++ def setUp(self):+ self.tmpdir = tempfile.mkdtemp()+ now = datetime.now(timezone.utc)+ future = (now + timedelta(hours=8)).isoformat().replace("+00:00", "Z")+ past = (now - timedelta(hours=1)).isoformat().replace("+00:00", "Z")++ # Create auth files:+ # - [email protected]: disabled, fresh token (would be queued by scan)+ # - [email protected]: enabled, expired token (would be queued by scan)+ # - [email protected]: enabled, fresh token (not queued)+ self._create_auth("[email protected]", "claude", True, future)+ self._create_auth("[email protected]", "claude", False, past)+ self._create_auth("[email protected]", "claude", False, future)++ def _create_auth(self, email, auth_type, disabled, expired):+ data = {+ "email": email,+ "type": auth_type,+ "disabled": disabled,+ "expired": expired,+ }+ Path(self.tmpdir, f"{auth_type}-{email}.json").write_text(json.dumps(data))++ def tearDown(self):+ shutil.rmtree(self.tmpdir)++ @patch("auto_reauth.AUTH_DIR")+ def test_scan_without_policy_disabled(self, mock_auth_dir):+ """Without policy_disabled, all disabled/expired accounts are queued."""+ mock_auth_dir.glob = lambda pattern: sorted(Path(self.tmpdir).glob(pattern))++ needs = auto_reauth.scan_auth_files()+ emails = [a["email"] for a in needs]+ self.assertIn("[email protected]", emails)+ self.assertIn("[email protected]", emails)+ self.assertNotIn("[email protected]", emails)++ @patch("auto_reauth.AUTH_DIR")+ def test_scan_excludes_policy_disabled(self, mock_auth_dir):+ """With policy_disabled, the policy-disabled account is excluded."""+ mock_auth_dir.glob = lambda pattern: sorted(Path(self.tmpdir).glob(pattern))++ # [email protected] is policy-disabled+ policy_disabled = {("claude", "[email protected]")}+ needs = auto_reauth.scan_auth_files(policy_disabled=policy_disabled)+ emails = [a["email"] for a in needs]++ # [email protected] should NOT be in the scan results+ self.assertNotIn("[email protected]", emails)+ # [email protected] should still be in the results (not policy-disabled)+ self.assertIn("[email protected]", emails)+ # [email protected] should not be in results (healthy)+ self.assertNotIn("[email protected]", emails)++ @patch("auto_reauth.AUTH_DIR")+ def test_scan_excludes_multiple_policy_disabled(self, mock_auth_dir):+ """Multiple policy-disabled accounts are all excluded."""+ mock_auth_dir.glob = lambda pattern: sorted(Path(self.tmpdir).glob(pattern))++ policy_disabled = {+ ("claude", "[email protected]"),+ ("claude", "[email protected]"),+ }+ needs = auto_reauth.scan_auth_files(policy_disabled=policy_disabled)+ emails = [a["email"] for a in needs]++ self.assertNotIn("[email protected]", emails)+ self.assertNotIn("[email protected]", emails)+ self.assertNotIn("[email protected]", emails)++ @patch("auto_reauth.AUTH_DIR")+ def test_scan_empty_policy_disabled(self, mock_auth_dir):+ """Empty policy_disabled set behaves like no filter (all queued)."""+ mock_auth_dir.glob = lambda pattern: sorted(Path(self.tmpdir).glob(pattern))++ needs = auto_reauth.scan_auth_files(policy_disabled=set())+ emails = [a["email"] for a in needs]+ self.assertIn("[email protected]", emails)+ self.assertIn("[email protected]", emails)++ @patch("auto_reauth.AUTH_DIR")+ def test_scan_none_policy_disabled(self, mock_auth_dir):+ """None policy_disabled behaves like no filter (all queued)."""+ mock_auth_dir.glob = lambda pattern: sorted(Path(self.tmpdir).glob(pattern))++ needs = auto_reauth.scan_auth_files(policy_disabled=None)+ emails = [a["email"] for a in needs]+ self.assertIn("[email protected]", emails)+ self.assertIn("[email protected]", emails)+++class TestReconciliationBugScenario(unittest.TestCase):+ """End-to-end test for the reconciliation bug scenario.++ Verifies that after a policy-disabled account is disabled by+ reconcile_accounts(), the subsequent scan_auth_files() call with+ the policy_disabled filter does NOT re-queue it.+ """++ def setUp(self):+ self.tmpdir = tempfile.mkdtemp()+ now = datetime.now(timezone.utc)+ future = (now + timedelta(hours=8)).isoformat().replace("+00:00", "Z")++ # Create an enabled account that policy says should be disabled+ self._create_auth("[email protected]", "claude", False, future)++ def _create_auth(self, email, auth_type, disabled, expired):+ data = {+ "email": email,+ "type": auth_type,+ "disabled": disabled,+ "expired": expired,+ }+ Path(self.tmpdir, f"{auth_type}-{email}.json").write_text(json.dumps(data))++ def tearDown(self):+ shutil.rmtree(self.tmpdir)++ @patch("auto_reauth.AUTH_DIR")+ def test_policy_disabled_account_not_requeued(self, mock_auth_dir):+ """After policy disables an account, scan should not re-queue it.++ This simulates the full cycle:+ 1. Policy says [email protected] should be disabled+ 2. reconcile_accounts() disables it (sets disabled=true)+ 3. scan_auth_files() with policy_disabled filter should NOT+ include it in the reauth queue+ """+ mock_auth_dir.glob = lambda pattern: sorted(Path(self.tmpdir).glob(pattern))++ # Simulate step 2: reconcile_accounts disables the account+ auth_file = Path(self.tmpdir, "[email protected]")+ data = json.loads(auth_file.read_text())+ data["disabled"] = True+ auth_file.write_text(json.dumps(data))++ # Step 3: build policy_disabled set (as main() does)+ policy_disabled = {("claude", "[email protected]")}++ # Scan with the filter+ needs = auto_reauth.scan_auth_files(policy_disabled=policy_disabled)+ emails = [a["email"] for a in needs]++ # The just-disabled account should NOT be re-queued+ self.assertNotIn(+ "[email protected]", emails,+ "Policy-disabled account should NOT be re-queued for reauth"+ )++ @patch("auto_reauth.AUTH_DIR")+ def test_without_filter_account_would_be_requeued(self, mock_auth_dir):+ """Without the filter, the disabled account WOULD be re-queued.++ This demonstrates the bug: without the policy_disabled filter,+ the scan picks up the just-disabled account.+ """+ mock_auth_dir.glob = lambda pattern: sorted(Path(self.tmpdir).glob(pattern))++ # Simulate reconcile_accounts disabling the account+ auth_file = Path(self.tmpdir, "[email protected]")+ data = json.loads(auth_file.read_text())+ data["disabled"] = True+ auth_file.write_text(json.dumps(data))++ # Scan WITHOUT the filter (old behavior)+ needs = auto_reauth.scan_auth_files()+ emails = [a["email"] for a in needs]++ # The disabled account WOULD be re-queued (this is the bug)+ self.assertIn(+ "[email protected]", emails,+ "Without filter, disabled account IS re-queued (demonstrates the bug)"+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/claude-ops/scripts/crsproxy-reauth/test_auto_router.py b/claude-ops/scripts/crsproxy-reauth/test_auto_router.pyindex a540d18c..478b4ccb 100644--- a/claude-ops/scripts/crsproxy-reauth/test_auto_router.py+++ b/claude-ops/scripts/crsproxy-reauth/test_auto_router.py@@ -77,9 +77,9 @@ class TestMaskEmail(unittest.TestCase):"""Test email masking for logs."""def test_normal_email(self):- self.assertEqual(router.mask_email("[email protected]"), "ad**@healify.ai")+ self.assertEqual(router.mask_email("[email protected]"), "us**@example.com")self.assertEqual(- router.mask_email("[email protected]"), "in**@auroracapital.nl"+ router.mask_email("[email protected]"), "us***@example.com")def test_short_email(self):diff --git a/claude-ops/scripts/crsproxy-reauth/test_checkpoint.py b/claude-ops/scripts/crsproxy-reauth/test_checkpoint.pyindex c5f0f7fa..7062aca6 100644--- a/claude-ops/scripts/crsproxy-reauth/test_checkpoint.py+++ b/claude-ops/scripts/crsproxy-reauth/test_checkpoint.py@@ -76,6 +76,34 @@ def test_detect_captcha_negative():print("PASS: detect_captcha returns False for non-captcha text")+def test_detect_captcha_exact_sentinel():+ """detect_captcha returns True for exact 'CAPTCHA' sentinel (uppercase).++ Browser Use tasks report 'CAPTCHA' (uppercase) as a sentinel when they+ encounter a real captcha challenge. This must be detected via word-boundary+ matching on the original (non-lowercased) text, while lowercase 'captcha'+ in a sentence must NOT trigger a false positive.+ """+ client = MagicMock()+ client.get_run_events.return_value = []++ # Exact 'CAPTCHA' sentinel — must be detected+ result = bu_reauth.detect_captcha({"result": "CAPTCHA"}, client)+ assert result is True, "Expected True for exact 'CAPTCHA' sentinel"++ # 'CAPTCHA' within a sentence — still detected (word boundary match)+ result = bu_reauth.detect_captcha(+ {"result": "I encountered a CAPTCHA challenge on the page"}, client)+ assert result is True, "Expected True for 'CAPTCHA' in text"++ # Negative: lowercase 'captcha' in a sentence must NOT match+ result = bu_reauth.detect_captcha(+ {"result": "The page loaded successfully. No captcha needed."},+ client)+ assert result is False, "Expected False for lowercase 'captcha' in sentence"+ print("PASS: detect_captcha exact 'CAPTCHA' sentinel works with word boundary")++def test_checkpoint_file_write_read():"""write_checkpoint writes a valid JSON file."""with tempfile.TemporaryDirectory() as tmpdir:@@ -220,6 +248,7 @@ def main():test_safe_email,test_detect_captcha_positive,test_detect_captcha_negative,+ test_detect_captcha_exact_sentinel,test_checkpoint_file_write_read,test_checkpoint_trigger,test_checkpoint_timeout,