Skip to content

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.

feat(crsproxy): add serialization lease and email cooldown to bu_reauth.py

auroracapital7084192f8d3e
diff --git a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py b/claude-ops/scripts/crsproxy-reauth/bu_reauth.py
index a00519f1..1b5cbd5a 100644
--- a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py
+++ b/claude-ops/scripts/crsproxy-reauth/bu_reauth.py
@@ -20,6 +20,11 @@ Features:
keeps browser session alive, waits for a file-based trigger, then
resumes with a follow-up run in the same session to click Authorize
and capture the callback URL.
+ - Serialization lease: checks /tmp/crsproxy-claude-oauth-lease.json
+ before starting a login, waits if held, cleans up after completion.
+ - Email cooldown: tracks verification code send timestamps, enforces
+ a 5-minute cooldown if >3 codes are sent in 5 minutes, logs
+ cooldown events without exposing the email address or code values.
Usage:
# Full reauth for a Claude account
@@ -109,6 +114,12 @@ CHECKPOINT_TRIGGER = Path("/tmp/bu_reauth_checkpoint_trigger")
CHECKPOINT_POLL_INTERVAL = 5 # seconds between trigger polls
CHECKPOINT_TIMEOUT = 600 # 10 minutes for human to solve captcha
+# Email cooldown configuration
+EMAIL_COOLDOWN_FILE = Path("/tmp/crsproxy-email-cooldown.json")
+EMAIL_COOLDOWN_WINDOW = 300 # 5 min sliding window for counting code sends
+EMAIL_COOLDOWN_THRESHOLD = 3 # max 3 code sends before cooldown triggers
+EMAIL_COOLDOWN_DURATION = 300 # 5 min cooldown when threshold exceeded
+
# Provider configuration: callback ports, login flags, auth URL patterns.
PROVIDERS = {
"claude": {
@@ -356,23 +367,44 @@ def disable_auth_file(auth_path: Path) -> bool:
# ---------------------------------------------------------------------------
# Serialization lease
# ---------------------------------------------------------------------------
-def acquire_lease(provider: str) -> bool:
- """Check/create the serialization lease file. Returns True if acquired."""
- if LEASE_FILE.exists():
- try:
- data = json.loads(LEASE_FILE.read_text())
- age = time.time() - data.get("timestamp", 0)
- if age < LEASE_STALE_SECONDS:
- log(f"Lease held by {data.get('provider','?')} "
- f"({int(age)}s old) — waiting")
- return False
- log(f"Stale lease ({int(age)}s old) — removing")
- LEASE_FILE.unlink()
- except (json.JSONDecodeError, OSError):
+def acquire_lease(provider: str, max_wait: int = 120) -> bool:
+ """Acquire the serialization lease, waiting up to max_wait seconds.
+
+ If the lease file exists and is recent (younger than
+ LEASE_STALE_SECONDS), polls every 5 seconds until it is released
+ or max_wait is reached. If the lease is stale, it is removed and a
+ new lease is acquired. Returns True if the lease was acquired,
+ False on timeout.
+ """
+ t0 = time.time()
+ first_check = True
+ while True:
+ if LEASE_FILE.exists():
try:
+ data = json.loads(LEASE_FILE.read_text())
+ age = time.time() - data.get("timestamp", 0)
+ if age < LEASE_STALE_SECONDS:
+ if first_check:
+ log(f"Lease held by {data.get('provider','?')} "
+ f"({int(age)}s old) — waiting up to {max_wait}s")
+ first_check = False
+ if time.time() - t0 >= max_wait:
+ log(f"Lease wait timed out after {max_wait}s — "
+ f"another login may still be in progress")
+ return False
+ time.sleep(5)
+ continue
+ # Stale lease — remove it
+ log(f"Stale lease ({int(age)}s old) — removing")
LEASE_FILE.unlink()
- except OSError:
- pass
+ except (json.JSONDecodeError, OSError):
+ try:
+ LEASE_FILE.unlink()
+ except OSError:
+ pass
+ # Lease file doesn't exist or was removed — acquire
+ break
+
LEASE_FILE.write_text(json.dumps({
"provider": provider,
"timestamp": time.time(),
@@ -391,6 +423,121 @@ def release_lease():
log(f"Lease release error: {e}")
+# ---------------------------------------------------------------------------
+# Email cooldown tracking
+# ---------------------------------------------------------------------------
+def _load_cooldown_state() -> dict:
+ """Load email cooldown state from file."""
+ try:
+ if EMAIL_COOLDOWN_FILE.exists():
+ return json.loads(EMAIL_COOLDOWN_FILE.read_text())
+ except Exception:
+ pass
+ return {"send_timestamps": [], "cooldown_until": 0}
+
+
+def _save_cooldown_state(state: dict):
+ """Save email cooldown state to file."""
+ try:
+ EMAIL_COOLDOWN_FILE.write_text(json.dumps(state))
+ except Exception as e:
+ log(f"Cooldown state save error: {e}")
+
+
+def record_email_send():
+ """Record a verification code send timestamp.
+
+ Called when a new verification code is found in Gmail. Prunes
+ timestamps older than the cooldown window. Never logs the email
+ address or code value.
+ """
+ state = _load_cooldown_state()
+ now = time.time()
+ state["send_timestamps"] = [
+ ts for ts in state.get("send_timestamps", [])
+ if now - ts < EMAIL_COOLDOWN_WINDOW
+ ]
+ state["send_timestamps"].append(now)
+ _save_cooldown_state(state)
+ count = len(state["send_timestamps"])
+ log(f"Email send recorded (count in window: {count})")
+
+
+def check_email_cooldown() -> tuple[bool, int]:
+ """Check if we're in an email cooldown period.
+
+ Returns (is_in_cooldown, seconds_remaining).
+ """
+ state = _load_cooldown_state()
+ now = time.time()
+ cooldown_until = state.get("cooldown_until", 0)
+ if cooldown_until > now:
+ return True, int(cooldown_until - now)
+ return False, 0
+
+
+def enforce_email_cooldown() -> bool:
+ """Check and enforce email cooldown after a code entry failure.
+
+ If more than EMAIL_COOLDOWN_THRESHOLD codes have been sent in the
+ last EMAIL_COOLDOWN_WINDOW seconds, sets a cooldown of
+ EMAIL_COOLDOWN_DURATION and blocks until it expires.
+
+ Returns True if a cooldown was enforced (waited), False if no
+ cooldown was needed. Logs cooldown events without exposing the
+ email address or code values.
+ """
+ state = _load_cooldown_state()
+ now = time.time()
+
+ # Prune old timestamps
+ state["send_timestamps"] = [
+ ts for ts in state.get("send_timestamps", [])
+ if now - ts < EMAIL_COOLDOWN_WINDOW
+ ]
+
+ # Check if we're already in a cooldown
+ cooldown_until = state.get("cooldown_until", 0)
+ if cooldown_until > now:
+ remaining = int(cooldown_until - now)
+ log(f"Email cooldown active — {remaining}s remaining "
+ f"(threshold: {EMAIL_COOLDOWN_THRESHOLD} sends per "
+ f"{EMAIL_COOLDOWN_WINDOW}s)")
+ log("Waiting for cooldown to expire before retrying...")
+ time.sleep(remaining + 1)
+ log("Email cooldown expired — proceeding with retry")
+ state["cooldown_until"] = 0
+ _save_cooldown_state(state)
+ return True
+
+ # Check if threshold is exceeded
+ count = len(state["send_timestamps"])
+ if count > EMAIL_COOLDOWN_THRESHOLD:
+ state["cooldown_until"] = now + EMAIL_COOLDOWN_DURATION
+ _save_cooldown_state(state)
+ log(f"Email cooldown triggered: {count} sends in "
+ f"{EMAIL_COOLDOWN_WINDOW}s window — waiting "
+ f"{EMAIL_COOLDOWN_DURATION}s")
+ log("Cooldown event logged (email and code values redacted)")
+ time.sleep(EMAIL_COOLDOWN_DURATION)
+ log("Email cooldown expired — proceeding with retry")
+ state["cooldown_until"] = 0
+ _save_cooldown_state(state)
+ return True
+
+ log(f"No cooldown needed ({count} sends in window)")
+ return False
+
+
+def clear_email_cooldown():
+ """Clear email cooldown state. Called on successful completion."""
+ try:
+ EMAIL_COOLDOWN_FILE.unlink(missing_ok=True)
+ log("Email cooldown state cleared")
+ except Exception as e:
+ log(f"Email cooldown clear error: {e}")
+
+
# ---------------------------------------------------------------------------
# Browser Use Cloud API client
# ---------------------------------------------------------------------------
@@ -700,6 +847,24 @@ def extract_callback_url(run_result: dict, client: BrowserUseClient,
return None
+def _code_entry_failed(result_text: str) -> bool:
+ """Check if a verification code entry run failed.
+
+ Looks for indicators that the code was rejected, expired, or
+ could not be entered. Never logs the code value itself.
+ """
+ text_lower = result_text.lower()
+ failure_indicators = [
+ "invalid code", "code is invalid", "expired",
+ "incorrect", "wrong code", "code is not valid",
+ "didn't work", "please try again", "try again",
+ "code is wrong", "enter the code again",
+ "unable to verify", "verification failed",
+ "code didn't match", "that code isn't",
+ ]
+ return any(ind in text_lower for ind in failure_indicators)
+
+
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()
@@ -990,6 +1155,9 @@ def _complete_reauth(proc: subprocess.Popen, callback_url: str,
except Exception:
pass
+ # Clear email cooldown state on successful completion
+ clear_email_cooldown()
+
log(f"[OK] Auth file activated: {auth_file.name}")
return EXIT_SUCCESS
@@ -1106,29 +1274,63 @@ def _run_reauth_inner(provider: str, email: str, gog_account: str,
# Try code first, then magic link
code = poll_gmail_for_code(provider, email, gog_account, kind="code")
if code:
+ record_email_send()
log("[4] Verification code received (value redacted)")
- task2 = (
- f"Enter the verification code in the verification field. "
- f"Click Continue. Report what you see."
- )
- run2 = client.create_run(task2, session_id=session_id)
- run2_id = run2.get("id", "")
- log(f"[4] Code entry run: {run2_id[:12]}...")
- result2 = client.wait_for_run(run2_id, timeout=RUN_POLL_TIMEOUT)
- text2 = str(result2.get("result", "") or "")
- log(f"[4] Code entry complete: {text2[:200]}")
- session_id = run2.get("sessionId", session_id)
-
- # Check for captcha after code entry
- if detect_captcha(result2, client):
- log("[CAPTCHA] Captcha detected after code entry")
- callback_url, session_id = handle_captcha_checkpoint(
- client, run2_id, session_id, provider, email, port)
- if callback_url:
- return _complete_reauth(proc, callback_url,
- auth_file, stale_backup,
- email, provider, meta)
- return EXIT_FAILURE
+
+ # Code entry with retry and email cooldown enforcement.
+ # If the code is rejected, check the email send history.
+ # If >3 codes have been sent in 5 minutes, enforce a
+ # 5-minute cooldown before retrying with a fresh code.
+ max_code_retries = 3
+ text2 = ""
+ for attempt in range(max_code_retries):
+ task2 = (
+ f"Enter the verification code in the verification field. "
+ f"Click Continue. Report what you see."
+ )
+ run2 = client.create_run(task2, session_id=session_id)
+ run2_id = run2.get("id", "")
+ log(f"[4] Code entry run (attempt {attempt+1}/"
+ f"{max_code_retries}): {run2_id[:12]}...")
+ result2 = client.wait_for_run(run2_id,
+ timeout=RUN_POLL_TIMEOUT)
+ text2 = str(result2.get("result", "") or "")
+ log(f"[4] Code entry complete: {text2[:200]}")
+ session_id = run2.get("sessionId", session_id)
+
+ # Check for captcha after code entry
+ if detect_captcha(result2, client):
+ log("[CAPTCHA] Captcha detected after code entry")
+ callback_url, session_id = handle_captcha_checkpoint(
+ client, run2_id, session_id, provider, email, port)
+ if callback_url:
+ return _complete_reauth(proc, callback_url,
+ auth_file, stale_backup,
+ email, provider, meta)
+ return EXIT_FAILURE
+
+ # Check if code entry failed
+ if _code_entry_failed(text2):
+ log(f"[4] Code entry failed on attempt {attempt+1}")
+ if attempt < max_code_retries - 1:
+ # Enforce email cooldown (waits if threshold
+ # exceeded) then poll for a fresh code
+ enforce_email_cooldown()
+ log("[4] Polling for new verification code")
+ code = poll_gmail_for_code(
+ provider, email, gog_account, kind="code")
+ if code:
+ record_email_send()
+ log("[4] New verification code received "
+ "(value redacted)")
+ else:
+ log("[FAIL] No new verification code received")
+ return EXIT_FAILURE
+ else:
+ log("[FAIL] Code entry failed after all retries")
+ return EXIT_FAILURE
+ else:
+ break # Code entry succeeded
# Check if we need a magic link (selectAccount flow)
if any(kw in text2.lower() for kw in
@@ -1147,7 +1349,8 @@ def _run_reauth_inner(provider: str, email: str, gog_account: str,
run3 = client.create_run(task3, session_id=session_id)
run3_id = run3.get("id", "")
log(f"[5] Magic link run: {run3_id[:12]}...")
- result3 = client.wait_for_run(run3_id, timeout=RUN_POLL_TIMEOUT)
+ result3 = client.wait_for_run(run3_id,
+ timeout=RUN_POLL_TIMEOUT)
text3 = str(result3.get("result", "") or "")
log(f"[5] Magic link run complete: {text3[:200]}")
session_id = run3.get("sessionId", session_id)
@@ -1309,6 +1512,11 @@ def _checkpoint_resume(args) -> int:
client = BrowserUseClient(api_key)
atexit.register(client.stop_all_browsers)
+ # Acquire serialization lease (prevents concurrent logins)
+ if not acquire_lease(provider):
+ log("[FAIL] Could not acquire lease — another login may be in progress")
+ return EXIT_FAILURE
+
# Start a new login process (the original is likely dead)
log_path = Path("/tmp/bu_reauth_hub.log")
log("[1] Starting new cli-proxy-api login for checkpoint resume")
@@ -1388,6 +1596,7 @@ def _checkpoint_resume(args) -> int:
client.stop_all_browsers()
cleanup_login_process(proc)
clear_checkpoint()
+ release_lease()
# ---------------------------------------------------------------------------
diff --git a/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py b/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py
new file mode 100644
index 00000000..f9274dd1
--- /dev/null
+++ b/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py
@@ -0,0 +1,516 @@
+#!/usr/bin/env python3
+"""Unit tests for serialization lease and email cooldown in bu_reauth.py.
+
+Tests the lease acquisition (with waiting), email cooldown tracking,
+cooldown enforcement, code entry failure detection, and cooldown
+logging (no sensitive data exposed) without requiring a real Browser
+Use Cloud session or a real hub.
+
+Run on the hub:
+ sudo -u crsproxy /opt/crsproxy/venv/bin/python \
+ /opt/crsproxy/test_lease_cooldown.py
+
+Run locally (syntax/logic only, no hub dependencies):
+ python3 test_lease_cooldown.py
+"""
+
+import json
+import os
+import sys
+import tempfile
+import time
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+# Add the script directory to the path
+sys.path.insert(0, str(Path(__file__).parent))
+
+# Import the module
+import bu_reauth
+
+
+def test_lease_file_constant():
+ """Lease file path is correct."""
+ assert bu_reauth.LEASE_FILE == Path(
+ "/tmp/crsproxy-claude-oauth-lease.json"
+ ), f"Expected /tmp/crsproxy-claude-oauth-lease.json, got {bu_reauth.LEASE_FILE}"
+ print("PASS: Lease file path is /tmp/crsproxy-claude-oauth-lease.json")
+
+
+def test_lease_stale_seconds():
+ """Lease stale threshold is defined."""
+ assert bu_reauth.LEASE_STALE_SECONDS == 600, (
+ f"Expected 600, got {bu_reauth.LEASE_STALE_SECONDS}"
+ )
+ print("PASS: Lease stale threshold is 600 seconds (10 min)")
+
+
+def test_acquire_lease_no_existing():
+ """acquire_lease acquires when no lease file exists."""
+ orig_lease = bu_reauth.LEASE_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lease_path = Path(tmpdir) / "lease.json"
+ bu_reauth.LEASE_FILE = lease_path
+
+ result = bu_reauth.acquire_lease("claude", max_wait=5)
+ assert result is True, "Expected lease acquisition to succeed"
+ assert lease_path.exists(), "Lease file should be created"
+ data = json.loads(lease_path.read_text())
+ assert data["provider"] == "claude"
+ assert "timestamp" in data
+ assert "pid" in data
+ print("PASS: acquire_lease creates lease file when none exists")
+ bu_reauth.LEASE_FILE = orig_lease
+
+
+def test_acquire_lease_stale_deleted():
+ """acquire_lease removes stale lease and acquires new one."""
+ orig_lease = bu_reauth.LEASE_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lease_path = Path(tmpdir) / "lease.json"
+ bu_reauth.LEASE_FILE = lease_path
+
+ # Write a stale lease (timestamp 20 minutes ago)
+ stale_data = {
+ "provider": "claude",
+ "timestamp": time.time() - 1200, # 20 min ago
+ "pid": 99999,
+ }
+ lease_path.write_text(json.dumps(stale_data))
+
+ result = bu_reauth.acquire_lease("claude", max_wait=5)
+ assert result is True, "Expected lease acquisition after stale removal"
+ data = json.loads(lease_path.read_text())
+ assert data["provider"] == "claude"
+ assert data["pid"] == os.getpid()
+ print("PASS: acquire_lease removes stale lease and acquires new one")
+ bu_reauth.LEASE_FILE = orig_lease
+
+
+def test_acquire_lease_waits_for_recent():
+ """acquire_lease waits when lease is recent, then acquires when released."""
+ orig_lease = bu_reauth.LEASE_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lease_path = Path(tmpdir) / "lease.json"
+ bu_reauth.LEASE_FILE = lease_path
+
+ # Write a recent lease
+ recent_data = {
+ "provider": "claude",
+ "timestamp": time.time(), # just now
+ "pid": 99999,
+ }
+ lease_path.write_text(json.dumps(recent_data))
+
+ # Start a thread that removes the lease after 2 seconds
+ import threading
+
+ def remove_lease():
+ time.sleep(2)
+ lease_path.unlink()
+
+ t = threading.Thread(target=remove_lease)
+ t.start()
+
+ result = bu_reauth.acquire_lease("claude", max_wait=10)
+ t.join()
+
+ assert result is True, (
+ "Expected lease acquisition after waiting for release"
+ )
+ assert lease_path.exists(), "New lease file should be created"
+ print("PASS: acquire_lease waits for recent lease to be released")
+ bu_reauth.LEASE_FILE = orig_lease
+
+
+def test_acquire_lease_timeout():
+ """acquire_lease returns False on timeout."""
+ orig_lease = bu_reauth.LEASE_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lease_path = Path(tmpdir) / "lease.json"
+ bu_reauth.LEASE_FILE = lease_path
+
+ # Write a recent lease that won't be removed
+ recent_data = {
+ "provider": "claude",
+ "timestamp": time.time(),
+ "pid": 99999,
+ }
+ lease_path.write_text(json.dumps(recent_data))
+
+ result = bu_reauth.acquire_lease("claude", max_wait=3)
+ assert result is False, "Expected False on timeout"
+ print("PASS: acquire_lease returns False on timeout")
+ bu_reauth.LEASE_FILE = orig_lease
+
+
+def test_release_lease():
+ """release_lease removes the lease file."""
+ orig_lease = bu_reauth.LEASE_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lease_path = Path(tmpdir) / "lease.json"
+ bu_reauth.LEASE_FILE = lease_path
+
+ # Create a lease
+ lease_path.write_text(json.dumps({"provider": "claude"}))
+ assert lease_path.exists()
+
+ bu_reauth.release_lease()
+ assert not lease_path.exists(), "Lease file should be removed"
+ print("PASS: release_lease removes the lease file")
+ bu_reauth.LEASE_FILE = orig_lease
+
+
+def test_release_lease_missing_ok():
+ """release_lease does not error if lease file doesn't exist."""
+ orig_lease = bu_reauth.LEASE_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lease_path = Path(tmpdir) / "lease.json"
+ bu_reauth.LEASE_FILE = lease_path
+
+ # No lease file exists — should not raise
+ bu_reauth.release_lease()
+ print("PASS: release_lease handles missing lease gracefully")
+
+
+def test_release_lease_always_called():
+ """release_lease is called in run_reauth's finally block."""
+ # Verify by checking the source that run_reauth has try/finally with release_lease
+ import inspect
+ source = inspect.getsource(bu_reauth.run_reauth)
+ assert "acquire_lease" in source, "run_reauth should acquire lease"
+ assert "release_lease" in source, "run_reauth should release lease"
+ assert "finally" in source, "run_reauth should have a finally block"
+ print("PASS: run_reauth acquires and releases lease in try/finally")
+
+
+# ---------------------------------------------------------------------------
+# Email cooldown tests
+# ---------------------------------------------------------------------------
+def test_email_cooldown_constants():
+ """Email cooldown constants are correct."""
+ assert bu_reauth.EMAIL_COOLDOWN_FILE == Path(
+ "/tmp/crsproxy-email-cooldown.json"
+ )
+ assert bu_reauth.EMAIL_COOLDOWN_WINDOW == 300
+ assert bu_reauth.EMAIL_COOLDOWN_THRESHOLD == 3
+ assert bu_reauth.EMAIL_COOLDOWN_DURATION == 300
+ print("PASS: Email cooldown constants are correct")
+
+
+def test_record_email_send():
+ """record_email_send records a timestamp."""
+ orig_file = bu_reauth.EMAIL_COOLDOWN_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ cd_path = Path(tmpdir) / "cooldown.json"
+ bu_reauth.EMAIL_COOLDOWN_FILE = cd_path
+
+ bu_reauth.record_email_send()
+ state = json.loads(cd_path.read_text())
+ assert len(state["send_timestamps"]) == 1
+ assert state["cooldown_until"] == 0
+
+ bu_reauth.record_email_send()
+ state = json.loads(cd_path.read_text())
+ assert len(state["send_timestamps"]) == 2
+ print("PASS: record_email_send records timestamps")
+ bu_reauth.EMAIL_COOLDOWN_FILE = orig_file
+
+
+def test_record_email_send_prunes_old():
+ """record_email_send prunes timestamps older than the window."""
+ orig_file = bu_reauth.EMAIL_COOLDOWN_FILE
+ orig_window = bu_reauth.EMAIL_COOLDOWN_WINDOW
+ with tempfile.TemporaryDirectory() as tmpdir:
+ cd_path = Path(tmpdir) / "cooldown.json"
+ bu_reauth.EMAIL_COOLDOWN_FILE = cd_path
+ bu_reauth.EMAIL_COOLDOWN_WINDOW = 2 # 2 seconds for testing
+
+ # Record an old send
+ state = {"send_timestamps": [time.time() - 10], "cooldown_until": 0}
+ cd_path.write_text(json.dumps(state))
+
+ time.sleep(0.1)
+ bu_reauth.record_email_send()
+
+ state = json.loads(cd_path.read_text())
+ assert len(state["send_timestamps"]) == 1, (
+ "Old timestamp should be pruned, only new one kept"
+ )
+ print("PASS: record_email_send prunes old timestamps")
+ bu_reauth.EMAIL_COOLDOWN_FILE = orig_file
+ bu_reauth.EMAIL_COOLDOWN_WINDOW = orig_window
+
+
+def test_check_email_cooldown_no_cooldown():
+ """check_email_cooldown returns False when no cooldown is active."""
+ orig_file = bu_reauth.EMAIL_COOLDOWN_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ cd_path = Path(tmpdir) / "cooldown.json"
+ bu_reauth.EMAIL_COOLDOWN_FILE = cd_path
+
+ # No cooldown file — should return False
+ in_cd, remaining = bu_reauth.check_email_cooldown()
+ assert in_cd is False
+ assert remaining == 0
+ print("PASS: check_email_cooldown returns False when no cooldown")
+ bu_reauth.EMAIL_COOLDOWN_FILE = orig_file
+
+
+def test_check_email_cooldown_active():
+ """check_email_cooldown returns True when cooldown is active."""
+ orig_file = bu_reauth.EMAIL_COOLDOWN_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ cd_path = Path(tmpdir) / "cooldown.json"
+ bu_reauth.EMAIL_COOLDOWN_FILE = cd_path
+
+ # Set an active cooldown
+ state = {
+ "send_timestamps": [],
+ "cooldown_until": time.time() + 100,
+ }
+ cd_path.write_text(json.dumps(state))
+
+ in_cd, remaining = bu_reauth.check_email_cooldown()
+ assert in_cd is True
+ assert 90 < remaining <= 100, f"Expected ~100s remaining, got {remaining}"
+ print("PASS: check_email_cooldown returns True when active")
+ bu_reauth.EMAIL_COOLDOWN_FILE = orig_file
+
+
+def test_enforce_email_cooldown_no_cooldown_needed():
+ """enforce_email_cooldown returns False when threshold not exceeded."""
+ orig_file = bu_reauth.EMAIL_COOLDOWN_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ cd_path = Path(tmpdir) / "cooldown.json"
+ bu_reauth.EMAIL_COOLDOWN_FILE = cd_path
+
+ # Only 2 sends (below threshold of 3)
+ state = {"send_timestamps": [time.time(), time.time()], "cooldown_until": 0}
+ cd_path.write_text(json.dumps(state))
+
+ result = bu_reauth.enforce_email_cooldown()
+ assert result is False, "Expected no cooldown when below threshold"
+ print("PASS: enforce_email_cooldown returns False below threshold")
+ bu_reauth.EMAIL_COOLDOWN_FILE = orig_file
+
+
+def test_enforce_email_cooldown_triggers():
+ """enforce_email_cooldown triggers when threshold exceeded."""
+ orig_file = bu_reauth.EMAIL_COOLDOWN_FILE
+ orig_duration = bu_reauth.EMAIL_COOLDOWN_DURATION
+ with tempfile.TemporaryDirectory() as tmpdir:
+ cd_path = Path(tmpdir) / "cooldown.json"
+ bu_reauth.EMAIL_COOLDOWN_FILE = cd_path
+ bu_reauth.EMAIL_COOLDOWN_DURATION = 1 # 1 second for testing
+
+ # 4 sends (above threshold of 3)
+ now = time.time()
+ state = {
+ "send_timestamps": [now, now, now, now],
+ "cooldown_until": 0,
+ }
+ cd_path.write_text(json.dumps(state))
+
+ start = time.time()
+ result = bu_reauth.enforce_email_cooldown()
+ elapsed = time.time() - start
+
+ assert result is True, "Expected cooldown to be enforced"
+ assert elapsed >= 1.0, (
+ f"Expected to wait at least 1s, waited {elapsed:.1f}s"
+ )
+ # Cooldown should be cleared after waiting
+ state = json.loads(cd_path.read_text())
+ assert state["cooldown_until"] == 0, "Cooldown should be cleared after wait"
+ print("PASS: enforce_email_cooldown triggers and waits when threshold exceeded")
+ bu_reauth.EMAIL_COOLDOWN_FILE = orig_file
+ bu_reauth.EMAIL_COOLDOWN_DURATION = orig_duration
+
+
+def test_clear_email_cooldown():
+ """clear_email_cooldown removes the cooldown file."""
+ orig_file = bu_reauth.EMAIL_COOLDOWN_FILE
+ with tempfile.TemporaryDirectory() as tmpdir:
+ cd_path = Path(tmpdir) / "cooldown.json"
+ bu_reauth.EMAIL_COOLDOWN_FILE = cd_path
+
+ cd_path.write_text(json.dumps({"send_timestamps": [], "cooldown_until": 0}))
+ assert cd_path.exists()
+
+ bu_reauth.clear_email_cooldown()
+ assert not cd_path.exists(), "Cooldown file should be removed"
+ print("PASS: clear_email_cooldown removes the file")
+ bu_reauth.EMAIL_COOLDOWN_FILE = orig_file
+
+
+# ---------------------------------------------------------------------------
+# Code entry failure detection tests
+# ---------------------------------------------------------------------------
+def test_code_entry_failed_positive():
+ """_code_entry_failed returns True for failure indicators."""
+ failure_texts = [
+ "The code is invalid. Please try again.",
+ "The verification code has expired.",
+ "Incorrect code, please try again.",
+ "That code isn't valid.",
+ "The code didn't match. Please enter it again.",
+ "Verification failed. Please try again.",
+ "Unable to verify the code.",
+ ]
+ for text in failure_texts:
+ result = bu_reauth._code_entry_failed(text)
+ assert result is True, f"Expected True for: {text}"
+ print("PASS: _code_entry_failed returns True for failure indicators")
+
+
+def test_code_entry_failed_negative():
+ """_code_entry_failed returns False for success indicators."""
+ success_texts = [
+ "You are now logged in. Click Authorize to continue.",
+ "The code was accepted. Proceeding to the next step.",
+ "Successfully verified. Click Continue.",
+ "Welcome back! Your account is ready.",
+ ]
+ for text in success_texts:
+ result = bu_reauth._code_entry_failed(text)
+ assert result is False, f"Expected False for: {text}"
+ print("PASS: _code_entry_failed returns False for success indicators")
+
+
+# ---------------------------------------------------------------------------
+# Sensitive data exposure tests
+# ---------------------------------------------------------------------------
+def test_cooldown_log_no_email_exposed():
+ """Cooldown logging does not expose the email address.
+
+ The log() function is used by record_email_send and
+ enforce_email_cooldown. Neither should print the email address
+ or code values. We verify by checking the log messages produced.
+ """
+ import io
+ orig_file = bu_reauth.EMAIL_COOLDOWN_FILE
+ orig_stdout = sys.stdout
+ with tempfile.TemporaryDirectory() as tmpdir:
+ cd_path = Path(tmpdir) / "cooldown.json"
+ bu_reauth.EMAIL_COOLDOWN_FILE = cd_path
+
+ # Capture stdout
+ captured = io.StringIO()
+ sys.stdout = captured
+
+ bu_reauth.record_email_send()
+ bu_reauth.enforce_email_cooldown()
+
+ sys.stdout = orig_stdout
+ output = captured.getvalue()
+
+ # Verify no email-like patterns in the output
+ # (should NOT contain @ or typical email patterns)
+ assert "@" not in output, (
+ f"Email address should not appear in cooldown logs: {output}"
+ )
+ # Verify no code-like patterns (6-digit numbers that could be codes)
+ import re
+ code_pattern = re.compile(r'\b\d{6}\b')
+ assert not code_pattern.search(output), (
+ f"Verification code values should not appear in logs: {output}"
+ )
+ print("PASS: Cooldown logs do not expose email or code values")
+ bu_reauth.EMAIL_COOLDOWN_FILE = orig_file
+
+
+def test_lease_log_no_pid_exposed_inappropriately():
+ """Lease log messages don't expose sensitive process info."""
+ import io
+ orig_lease = bu_reauth.LEASE_FILE
+ orig_stdout = sys.stdout
+ with tempfile.TemporaryDirectory() as tmpdir:
+ lease_path = Path(tmpdir) / "lease.json"
+ bu_reauth.LEASE_FILE = lease_path
+
+ captured = io.StringIO()
+ sys.stdout = captured
+
+ bu_reauth.acquire_lease("claude", max_wait=5)
+ bu_reauth.release_lease()
+
+ sys.stdout = orig_stdout
+ output = captured.getvalue()
+
+ # Should mention "Lease acquired" and "Lease released"
+ assert "Lease acquired" in output, "Should log lease acquisition"
+ assert "Lease released" in output, "Should log lease release"
+ print("PASS: Lease log messages are appropriate")
+ bu_reauth.LEASE_FILE = orig_lease
+
+
+def test_checkpoint_resume_has_lease():
+ """_checkpoint_resume acquires and releases the lease."""
+ import inspect
+ source = inspect.getsource(bu_reauth._checkpoint_resume)
+ assert "acquire_lease" in source, (
+ "_checkpoint_resume should acquire the lease"
+ )
+ assert "release_lease" in source, (
+ "_checkpoint_resume should release the lease"
+ )
+ assert "finally" in source, (
+ "_checkpoint_resume should have a finally block"
+ )
+ print("PASS: _checkpoint_resume acquires and releases lease")
+
+
+def main():
+ """Run all tests."""
+ print("=" * 60)
+ print("Testing serialization lease and email cooldown in bu_reauth.py")
+ print("=" * 60)
+
+ tests = [
+ # Lease tests
+ test_lease_file_constant,
+ test_lease_stale_seconds,
+ test_acquire_lease_no_existing,
+ test_acquire_lease_stale_deleted,
+ test_acquire_lease_waits_for_recent,
+ test_acquire_lease_timeout,
+ test_release_lease,
+ test_release_lease_missing_ok,
+ test_release_lease_always_called,
+ # Email cooldown tests
+ test_email_cooldown_constants,
+ test_record_email_send,
+ test_record_email_send_prunes_old,
+ test_check_email_cooldown_no_cooldown,
+ test_check_email_cooldown_active,
+ test_enforce_email_cooldown_no_cooldown_needed,
+ test_enforce_email_cooldown_triggers,
+ test_clear_email_cooldown,
+ # Code entry failure detection
+ test_code_entry_failed_positive,
+ test_code_entry_failed_negative,
+ # Sensitive data exposure
+ test_cooldown_log_no_email_exposed,
+ test_lease_log_no_pid_exposed_inappropriately,
+ test_checkpoint_resume_has_lease,
+ ]
+
+ passed = 0
+ failed = 0
+ for test in tests:
+ try:
+ test()
+ passed += 1
+ except Exception as e:
+ print(f"FAIL: {test.__name__}: {e}")
+ failed += 1
+
+ print("=" * 60)
+ print(f"Results: {passed} passed, {failed} failed, {len(tests)} total")
+ print("=" * 60)
+ return 0 if failed == 0 else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())