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
Refuse sends from a send-as alias whose relay is broken (#810)
Aurora Capital907e4320bf70
diff --git a/claude-ops/scripts/outbound-guard/README.md b/claude-ops/scripts/outbound-guard/README.mdindex 401ef6b3..88c999ed 100644--- a/claude-ops/scripts/outbound-guard/README.md+++ b/claude-ops/scripts/outbound-guard/README.md@@ -66,11 +66,50 @@ then run the real thing inline. The helpers in this repo refuse to send for thatlist silently stops covering `-nl`, `-us`, or any future suffix, and the failure isinvisible: the hook still runs, still logs nothing, and allows everything.+## Broken send-as aliases++An alias whose SMTP relay credentials have gone stale fails in the worst possible way.+Gmail accepts the message, stamps it SENT, and only then drops a delivery failure into+the thread, in Trash, under CATEGORY_UPDATES. The sender sees a sent message. The+recipient gets nothing. Nobody notices until the other side chases.++Approving such a send changes nothing, so the guard refuses it outright even when an+approval token is present. The list of bad aliases lives in+`~/.claude/state/broken-send-aliases.json` and is written by `refresh_broken_aliases.py`,+which finds bounce threads and reads the failed alias off the SENT message's From header.+An absent or empty list blocks nothing, so a machine that never runs the refresh keeps+working as before.++Two ways out of a listed alias:++**Fix the relay.** Gmail Settings, Accounts, Send mail as, re-enter the app password.+Then `refresh_broken_aliases.py --clear <address>`.++**Skip the relay.** If a Workspace service account can impersonate the mailbox, sending+_as_ that mailbox over the API never touches the send-as relay and needs no app password:++```+gog -a [email protected] gmail send --to ... --subject ... --body ...+```++The guard checks for a service account file and names this command in the block message+when one exists.++`gog-sa-token` covers the case where that still fails with `unauthorized_client`. gog+requests its whole scope bundle in one token request, so a Workspace that delegated only+`gmail.send` and `gmail.readonly` refuses the entire request, and a mailbox that can in+fact send looks completely unreachable. Minting a narrow token sidesteps it:++```+gog --access-token "$(gog-sa-token [email protected] send)" -a [email protected] gmail send ...+```+## Tests```-bash claude-ops/tests/outbound-guard/test-shared-guard.sh # cross-language agreement-python3 claude-ops/tests/outbound-guard/test-hook-matrix.py # block/pass per send path+bash claude-ops/tests/outbound-guard/test-shared-guard.sh # cross-language agreement+python3 claude-ops/tests/outbound-guard/test-hook-matrix.py # block/pass per send path+python3 claude-ops/tests/outbound-guard/test-broken-alias.py # broken alias outranks approval```The matrix test checks every send path blocks without an approval (WhatsApp per account,diff --git a/claude-ops/scripts/outbound-guard/block-outbound-comms.py b/claude-ops/scripts/outbound-guard/block-outbound-comms.pyindex a1b5adfc..e430b203 100755--- a/claude-ops/scripts/outbound-guard/block-outbound-comms.py+++ b/claude-ops/scripts/outbound-guard/block-outbound-comms.py@@ -12,6 +12,7 @@ expires after 120 seconds.--dangerously-skip-permissions does NOT bypass this hook."""+import base64import jsonimport osimport re@@ -136,6 +137,31 @@ def _load_approved_recipients() -> set:return out+def _load_broken_aliases() -> set:+ """Send-as aliases whose mail bounces with a 'Send mail as' misconfiguration.++ A broken alias fails silently: Gmail stamps the message SENT, then posts the+ failure into Trash under a category the inbox does not show. Approving such a send+ does not help, so the guard refuses it outright and says why. The list is written+ by refresh_broken_aliases.py, which reads the bounces themselves.+ """+ out = set()+ try:+ with open(os.path.join(_HOME, ".claude/state/broken-send-aliases.json")) as f:+ cfg = json.load(f)+ for a in (cfg.get("aliases") or {}):+ s = str(a).strip().lower()+ if s:+ out.add(s)+ except (OSError, json.JSONDecodeError):+ # No list, or an unreadable one, means no alias is known to be broken. Blocking+ # on that would refuse every send on a machine that has never run the refresh,+ # so an empty set is the correct answer rather than a swallowed error.+ return set()+ return out+++BROKEN_ALIASES = _load_broken_aliases()SELF_EMAILS = _load_self_emails()SELF_JIDS = _load_self_jids()SELF_IMESSAGE_HANDLES = _load_self_imessage_handles()@@ -406,6 +432,52 @@ def _consume_counted() -> bool:return True+def _broken_sender(tool_name: str, tool_input: dict, cmd: str = '') -> str:+ """The broken alias this send would go out from, or '' if the sender is fine.++ Reads the explicit sender: --from on a gog command, or a from/sender field on an+ MCP call. A send with no explicit sender uses the account default, which is not an+ alias and cannot be broken this way.+ """+ if not BROKEN_ALIASES:+ return ''+ candidates = []+ if isinstance(tool_input, dict):+ for k in ('from', 'sender', 'from_address', 'fromEmail'):+ v = tool_input.get(k)+ if isinstance(v, str) and v.strip():+ candidates.append(v)+ if cmd:+ candidates += re.findall(+ r'--from[=\s]+(?:"([^"]+)"|\'([^\']+)\'|(\S+))', cmd)+ flat = []+ for c in candidates:+ if isinstance(c, tuple):+ flat += [x for x in c if x]+ else:+ flat.append(c)+ for c in flat:+ m = re.search(r'[\w.+-]+@[\w.-]+', c)+ if m and m.group(0).lower() in BROKEN_ALIASES:+ return m.group(0).lower()+ return ''+++def _native_route(addr: str) -> str:+ """The command that sends as `addr` without the send-as relay, or '' if none exists.++ A broken alias is only half the story. These mailboxes are often reachable a second+ way: when gog holds a service account that can impersonate the address, mail goes+ out as the mailbox itself and never touches the stale SMTP credential. Where that+ file exists the fix is a different command, not a trip to the Gmail settings page.+ """+ stem = base64.urlsafe_b64encode(addr.encode()).rstrip(b'=').decode()+ for root in ('~/Library/Application Support/gogcli', '~/.config/gogcli'):+ if os.path.exists(os.path.join(os.path.expanduser(root), f'sa-{stem}.json')):+ return f'gog -a {addr} gmail send --to ... --subject ... --body ...'+ return ''++def _identify(tool_name: str, tool_input: dict, cmd: str = '') -> tuple[str, str]:"""Recipient and text of this message, whatever shape it arrives in.@@ -577,6 +649,36 @@ def main():print(msg, file=sys.stderr)sys.exit(2)+ # A send from a known-broken alias is refused before every other allow path,+ # including the approved-recipient bypass below. Approving it would not help:+ # Gmail marks it SENT and the mail bounces into Trash, so the sender believes it+ # went and the recipient never gets it. Whether the recipient is trusted has no+ # bearing on that — the failure is in the sender's relay, so a pre-approved+ # address is exactly the case where the silent bounce would go unnoticed longest.+ _bad = _broken_sender(tool_name, tool_input if isinstance(tool_input, dict) else {}, cmd)+ if _bad:+ audit('BLOCKED_BROKEN_ALIAS', tool_name, _bad, cmd_snippet)+ msg = (+ f'BLOCKED: the sender alias {_bad} is misconfigured and its mail bounces.\n\n'+ "Gmail stamps the message SENT and then drops a delivery failure into Trash,\n"+ "so this send would look successful and never arrive. Approving it changes\n"+ "nothing.\n\n")+ native = _native_route(_bad)+ if native:+ msg += (+ "Send as the mailbox itself instead. That path does not use the send-as\n"+ "relay, so the stale password is irrelevant and no app password is needed:\n"+ f" {native}\n\n"+ "If gog reports unauthorized_client, this Workspace granted the service\n"+ "account only some scopes. Ask for just the one you need:\n"+ f' GOG_ACCESS_TOKEN=$(gog-sa-token {_bad} send) gog -a {_bad} gmail send ...\n\n')+ msg += (+ 'To repair the alias itself: Gmail Settings > Accounts and Import >\n'+ '"Send mail as" > edit that address > re-enter a valid app password. Then run:\n'+ " refresh_broken_aliases.py\n")+ sys.stderr.write(msg)+ sys.exit(2)+# Persistent prior-approval bypass (Sam's directive 2026-06-18): an EMAIL# whose every recipient is on the approved-recipients allowlist is a send# Sam has already signed off on — let it through without burning a token, sodiff --git a/claude-ops/scripts/outbound-guard/gog-sa-token b/claude-ops/scripts/outbound-guard/gog-sa-tokennew file mode 100755index 00000000..6cb993ac--- /dev/null+++ b/claude-ops/scripts/outbound-guard/gog-sa-token@@ -0,0 +1,102 @@+#!/usr/bin/env python3+"""Print an impersonated Google access token for one mailbox and one scope set.++gog asks for its whole scope bundle at once. A Workspace that granted the service+account only gmail.send and gmail.readonly therefore refuses the entire request with+unauthorized_client, and the mailbox looks unreachable when in fact sending is allowed.+Minting the narrow token here and handing it to `gog --access-token` sidesteps that.++ gog-sa-token [email protected] send+ gog --access-token "$(gog-sa-token [email protected] send)" -a [email protected] ...++Scope names are the short keys below, or full URLs. Tokens last about an hour.+"""+from __future__ import annotations++import base64+import json+import os+import sys+import time+import urllib.error+import urllib.parse+import urllib.request++DIR = os.path.expanduser("~/Library/Application Support/gogcli")+TOKEN_URI = "https://oauth2.googleapis.com/token"+SHORT = {+ "send": "https://www.googleapis.com/auth/gmail.send",+ "readonly": "https://www.googleapis.com/auth/gmail.readonly",+ "modify": "https://www.googleapis.com/auth/gmail.modify",+ "settings.basic": "https://www.googleapis.com/auth/gmail.settings.basic",+ "settings.sharing": "https://www.googleapis.com/auth/gmail.settings.sharing",+}+++def _b64(raw: bytes) -> bytes:+ return base64.urlsafe_b64encode(raw).rstrip(b"=")+++def sa_path(mailbox: str) -> str:+ """gog names each file after the base64 of the mailbox it impersonates."""+ stem = base64.urlsafe_b64encode(mailbox.encode()).rstrip(b"=").decode()+ return os.path.join(DIR, f"sa-{stem}.json")+++def mint(mailbox: str, scopes: list[str]) -> str:+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import padding++ path = sa_path(mailbox)+ if not os.path.exists(path):+ raise SystemExit(f"no service account on file for {mailbox}")+ with open(path) as f:+ sa = json.load(f)++ now = int(time.time())+ claim = {+ "iss": sa["client_email"],+ "sub": mailbox,+ "scope": " ".join(scopes),+ "aud": TOKEN_URI,+ "iat": now,+ "exp": now + 3600,+ }+ seg = _b64(json.dumps({"alg": "RS256", "typ": "JWT"}).encode()) + b"." + \+ _b64(json.dumps(claim).encode())+ key = serialization.load_pem_private_key(sa["private_key"].encode(), password=None)+ jwt = seg + b"." + _b64(key.sign(seg, padding.PKCS1v15(), hashes.SHA256()))++ body = urllib.parse.urlencode({+ "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",+ "assertion": jwt.decode(),+ }).encode()+ try:+ with urllib.request.urlopen(urllib.request.Request(TOKEN_URI, body), timeout=30) as r:+ return json.load(r)["access_token"]+ except urllib.error.HTTPError as e:+ # Google normally explains the refusal in a JSON body, and that explanation is+ # the whole value of this message: unauthorized_client means undelegated scopes,+ # invalid_grant means the mailbox does not exist. The body is not guaranteed to+ # be JSON though, so reading it is best effort and its absence is not an error.+ detail = ""+ try:+ d = json.load(e)+ detail = f': {d.get("error")} {d.get("error_description", "")}'.rstrip()+ except (ValueError, TypeError, AttributeError):+ detail = ""+ raise SystemExit(f"token refused for {mailbox}{detail}")+++def main() -> int:+ if len(sys.argv) < 2:+ raise SystemExit(__doc__)+ mailbox = sys.argv[1]+ names = sys.argv[2:] or ["send"]+ scopes = [SHORT.get(n, n) for n in names]+ print(mint(mailbox, scopes))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/claude-ops/scripts/outbound-guard/refresh_broken_aliases.py b/claude-ops/scripts/outbound-guard/refresh_broken_aliases.pynew file mode 100755index 00000000..23b5caf6--- /dev/null+++ b/claude-ops/scripts/outbound-guard/refresh_broken_aliases.py@@ -0,0 +1,143 @@+#!/usr/bin/env python3+"""Keep the list of broken send-as aliases current from Gmail's own bounces.++Gmail stamps a message SENT and only afterwards posts a delivery failure into the+thread, and that failure lands in Trash under CATEGORY_UPDATES rather than the inbox.+So a misconfigured alias fails invisibly: the sender sees a sent message, the+recipient never gets it, and nobody finds out until the other side chases.++This scans recent 'Send mail as' failures, extracts which alias each one was sent+from, and writes them to ~/.claude/state/broken-send-aliases.json. The outbound guard+reads that file and refuses to send from a listed alias, because approving such a send+only produces another silent bounce.++Run it on a timer, or after fixing an alias to clear it:++ python3 refresh_broken_aliases.py # rescan and rewrite the list+ python3 refresh_broken_aliases.py --clear [email protected]+"""+from __future__ import annotations++import json+import os+import re+import subprocess+import sys+import time++STATE = os.path.expanduser("~/.claude/state/broken-send-aliases.json")+WINDOW = "newer_than:90d"+# Gmail's wording when a send-as relay refuses the credentials.+SIGNATURE = "Send mail as"+++def gog(args, timeout=180):+ return subprocess.run(["gog"] + args, capture_output=True, text=True, timeout=timeout)+++def known_aliases() -> list[str]:+ p = gog(["gmail", "settings", "sendas", "list", "-j", "--no-input"])+ try:+ d = json.loads(p.stdout or "{}")+ except json.JSONDecodeError:+ return []+ rows = d if isinstance(d, list) else d.get("sendAs", [])+ return [r.get("sendAsEmail", "") for r in rows if r.get("sendAsEmail")]+++def scan() -> dict:+ aliases = known_aliases()+ p = gog(["gmail", "search", f'in:anywhere "{SIGNATURE}" misconfigured {WINDOW}',+ "--max", "40", "-j", "--results-only", "--no-input"])+ try:+ rows = json.loads(p.stdout or "[]")+ except json.JSONDecodeError:+ rows = []++ hits: dict[str, dict] = {}+ seen_threads = set()+ for r in rows:+ tid = r.get("threadId") or r.get("id")+ if not tid or tid in seen_threads:+ continue+ seen_threads.add(tid)+ t = gog(["gmail", "thread", "get", tid, "-j"], timeout=120)+ try:+ d = json.loads(t.stdout or "{}")+ except json.JSONDecodeError:+ continue+ msgs = d.get("thread", {}).get("messages", [])++ # Which alias failed is the From of the SENT message in this thread, not any+ # address that happens to appear in the bounce text. Matching alias names+ # inside the bounce body is wrong: the bounce quotes the recipient too, which+ # made the primary account look broken when it has no SMTP relay at all.+ bounced = False+ sender = ""+ for m in msgs:+ h = {x["name"]: x.get("value", "")+ for x in m.get("payload", {}).get("headers", [])}+ frm = (h.get("From") or "").lower()+ if "mailer-daemon" in frm or "postmaster" in frm:+ bounced = True+ elif "SENT" in (m.get("labelIds") or []):+ mm = re.search(r"[\w.+-]+@[\w.-]+", frm)+ if mm and mm.group(0) in [a.lower() for a in aliases]:+ sender = mm.group(0)+ if bounced and sender:+ e = hits.setdefault(sender, {"count": 0, "last_seen": ""})+ e["count"] += 1+ dt = r.get("date") or ""+ if dt > e["last_seen"]:+ e["last_seen"] = dt+ return hits+++def write(hits: dict) -> None:+ os.makedirs(os.path.dirname(STATE), exist_ok=True)+ payload = {+ "updated": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ "note": ("Aliases whose sends bounced with a 'Send mail as' misconfiguration. "+ "The outbound guard refuses to send from these. Fix the app password "+ "in Gmail Settings, Accounts, Send mail as, then rerun this script."),+ "aliases": hits,+ }+ with open(STATE, "w") as f:+ json.dump(payload, f, indent=2)+ os.chmod(STATE, 0o600)+++def load() -> dict:+ try:+ with open(STATE) as f:+ return (json.load(f) or {}).get("aliases", {}) or {}+ except (OSError, json.JSONDecodeError):+ return {}+++def main() -> int:+ if "--clear" in sys.argv:+ i = sys.argv.index("--clear")+ target = sys.argv[i + 1] if len(sys.argv) > i + 1 else ""+ hits = load()+ if target in hits:+ del hits[target]+ write(hits)+ print(f"cleared {target}; {len(hits)} still listed")+ else:+ print(f"{target} was not listed")+ return 0++ hits = scan()+ write(hits)+ if not hits:+ print("no broken aliases found")+ return 0+ print(f"{len(hits)} broken alias(es):")+ for a, e in sorted(hits.items(), key=lambda kv: -kv[1]["count"]):+ print(f" {a:38} {e['count']:3} bounces, last {e['last_seen']}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/claude-ops/tests/outbound-guard/test-broken-alias.py b/claude-ops/tests/outbound-guard/test-broken-alias.pynew file mode 100755index 00000000..4bfbb605--- /dev/null+++ b/claude-ops/tests/outbound-guard/test-broken-alias.py@@ -0,0 +1,133 @@+#!/usr/bin/env python3+"""A send from a misconfigured alias must be refused outright, not merely gated.++Approving such a send changes nothing: Gmail stamps it SENT and the mail bounces into+Trash, so the sender believes it arrived and the recipient never sees it. The guard+therefore blocks it even when an approval token is present, and says how to fix it.++The alias list normally comes from the machine's own state file. This test writes a+throwaway HOME so it runs the same way anywhere and never depends on real addresses.+"""+import contextlib+import json+import os+import shutil+import subprocess+import sys+import tempfile++HERE = os.path.dirname(os.path.abspath(__file__))+SRC = os.path.abspath(os.path.join(HERE, "..", "..", "scripts", "outbound-guard"))+HOOK = os.environ.get("OUTBOUND_HOOK", os.path.join(SRC, "block-outbound-comms.py"))+# The approval store sits at a fixed path shared by every guard, so a test that leaves+# credit in it changes the result of whichever suite runs next.+STATE_FILES = ("/tmp/.claude-outbound-guard.json", "/tmp/.claude-send-ok")+BROKEN = "[email protected]"+HEALTHY = "[email protected]"+G = "gog gmail"+++def run(cmd, home):+ env = dict(os.environ, HOME=home)+ p = subprocess.run(+ [sys.executable, "-S", HOOK],+ input=json.dumps({"tool_name": "Bash", "tool_input": {"command": cmd}}),+ capture_output=True, text=True, timeout=30, env=env)+ return p.returncode, (p.stderr or "")+++def disarm():+ """Drop any approval credit. Absent files are the state we are aiming for."""+ for p in STATE_FILES:+ with contextlib.suppress(FileNotFoundError):+ os.remove(p)+++def arm(home):+ """Mint a real approval so the test proves the block outranks the token."""+ subprocess.run([sys.executable, os.path.join(SRC, "outbound_guard.py"),+ "mint", "5", "900"],+ capture_output=True, timeout=30, env=dict(os.environ, HOME=home))+++def main() -> int:+ home = tempfile.mkdtemp(prefix="guardtest-")+ os.makedirs(os.path.join(home, ".claude", "state"), exist_ok=True)+ with open(os.path.join(home, ".claude", "state",+ "broken-send-aliases.json"), "w") as f:+ json.dump({"aliases": {BROKEN: {"count": 3}}}, f)++ fail = 0+ try:+ disarm()++ arm(home)+ rc, err = run(f"{G} send --to [email protected] --from {BROKEN} --body hi", home)+ ok = rc == 2 and "misconfigured" in err+ fail += not ok+ print(f" {'ok ' if ok else 'FAIL'} broken alias blocked despite approval (exit={rc})")++ ok = "Send mail as" in err+ fail += not ok+ print(f" {'ok ' if ok else 'FAIL'} block message names the repair")++ arm(home)+ rc, _ = run(f"{G} send --to [email protected] --from {HEALTHY} --body hi", home)+ ok = rc == 0+ fail += not ok+ print(f" {'ok ' if ok else 'FAIL'} healthy alias still allowed (exit={rc})")++ # No sender flag at all uses the account default, which cannot be broken this way.+ arm(home)+ rc, _ = run(f"{G} send --to [email protected] --body hi", home)+ ok = rc == 0+ fail += not ok+ print(f" {'ok ' if ok else 'FAIL'} default sender unaffected (exit={rc})")++ # And it must still be refused when there is no approval at all.+ disarm()+ rc, _ = run(f"{G} send --to [email protected] --from {BROKEN} --body hi", home)+ ok = rc == 2+ fail += not ok+ print(f" {'ok ' if ok else 'FAIL'} broken alias blocked without approval (exit={rc})")++ # A recipient on the approved list skips the token gate entirely. That+ # bypass must not also skip the alias check: the relay is what is broken,+ # so the mail bounces whoever it was addressed to, and a trusted recipient+ # is precisely where an unnoticed bounce does the most damage.+ with open(os.path.join(home, ".claude", "state",+ "outbound-approvals.json"), "w") as f:+ json.dump({"approved_recipients": ["[email protected]"]}, f)+ rc, err = run(f"{G} send --to [email protected] --from {BROKEN} --body hi", home)+ ok = rc == 2 and "misconfigured" in err+ fail += not ok+ print(f" {'ok ' if ok else 'FAIL'} approved recipient does not bypass the alias block (exit={rc})")++ # The same recipient on a healthy alias must still take the bypass, or the+ # check above would pass simply because approvals stopped working.+ rc, _ = run(f"{G} send --to [email protected] --from {HEALTHY} --body hi", home)+ ok = rc == 0+ fail += not ok+ print(f" {'ok ' if ok else 'FAIL'} approved recipient still bypasses on a healthy alias (exit={rc})")++ os.remove(os.path.join(home, ".claude", "state", "outbound-approvals.json"))++ # An empty list must not block anything, or a machine that never ran the+ # refresh script would have every send refused.+ os.remove(os.path.join(home, ".claude", "state", "broken-send-aliases.json"))+ arm(home)+ rc, _ = run(f"{G} send --to [email protected] --from {BROKEN} --body hi", home)+ ok = rc == 0+ fail += not ok+ print(f" {'ok ' if ok else 'FAIL'} no alias list means no extra blocking (exit={rc})")+ finally:+ shutil.rmtree(home, ignore_errors=True)+ # Leave the shared store empty, which is also the safe state.+ disarm()++ print(f"\n{'ALL GOOD' if not fail else str(fail) + ' FAIL'}")+ return 1 if fail else 0+++if __name__ == "__main__":+ sys.exit(main())