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(pocket): pocket-env-broker + observability + opt-in notifications; release 2.12.0 (#375)

Aurora Capitalc4b950a67923
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index b408c6ae..a3d24a8d 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -11,7 +11,7 @@
"name": "ops",
"description": "Business operations command center for Claude Code — 37 skills, 19 agents, smart background daemon. Manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (AWS), revenue (Stripe+RevenueCat), e-commerce, marketing, monitoring (Datadog/New Relic/OTEL), voice, and smart home (Homey Pro). Includes /gtm go-to-market planner, /ops:projects portfolio dashboard, /ops:ops-home control surface, and YOLO autonomous mode with 4 parallel C-suite agents.",
"source": "./claude-ops",
- "version": "2.11.9",
+ "version": "2.12.0",
"category": "productivity",
"keywords": [
"ops",
diff --git a/claude-ops/.claude-plugin/plugin.json b/claude-ops/.claude-plugin/plugin.json
index 6dcfc47b..6a954583 100644
--- a/claude-ops/.claude-plugin/plugin.json
+++ b/claude-ops/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "ops",
- "version": "2.11.9",
+ "version": "2.12.0",
"description": "Business operations command center for Claude Code — 37 skills, 19 agents, and a smart background daemon that manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (all AWS services), revenue (Stripe + RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4/GSC), monitoring (Datadog/New Relic/OTEL), and voice (Bland AI/ElevenLabs/Whisper). Includes /gtm go-to-market planner, /ops:projects portfolio dashboard, YOLO mode for autonomous operation with 4 parallel C-suite agents, and /ops:ops-home smart home control via Homey Pro.",
"author": {
"name": "Lifecycle Innovations Limited",
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index ce0747d0..2486c660 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -4,6 +4,15 @@ All notable changes to this project will be documented in this file.
## [Unreleased]
+## [2.12.0] — 2026-05-29
+
+### Added
+
+- **pocket-env-broker — peer-authenticated secrets broker for restricted pocket workers.** Restricted background workers (which no longer inherit the orchestrator's secret env, per 2.11.9) can now request a *specific allowlisted* secret at runtime via the `pocket-env <VAR>` client, instead of all-or-nothing. The broker (`scripts/pocket-env-broker.py`, runs as the privileged orchestrator user) listens on a unix socket, authenticates the caller with SO_PEERCRED (must be the worker uid), checks a **default-deny** allowlist (`env-broker-policy.json`), returns the value over the socket only (never to disk), and audits every grant/deny. Ships with the client, policy + systemd templates, docs, and tests; the pocket executor forwards the broker socket path + task/worker ids to workers.
+- **Env-broker observability.** The broker keeps a metrics snapshot (`env-broker-health.json`: request/grant/deny/uid-rejection counters, recent denials, `anomaly` flag), exposes `pocket-env-broker --status [--json]`, and surfaces an `Env-broker` line in `/ops:ops-status` that raises a `⚠` anomaly on any uid rejection (a prompt-injection probing signal).
+- **Env-broker push notifications (opt-in).** Set `POCKET_ENV_BROKER_NOTIFY_CMD` (+ `POCKET_ENV_BROKER_NOTIFY_COOLDOWN`, default 300s) and the broker fires that command with an alert on uid rejections / not-allowed denials — rate-limited, best-effort, never blocking request handling. Wired to the operator's own chat it is a self-notification (outbound-comms-gate exempt).
+
+
## [2.11.9] — 2026-05-29
### Security
diff --git a/claude-ops/bin/ops-status b/claude-ops/bin/ops-status
index 857c0830..b93523cb 100755
--- a/claude-ops/bin/ops-status
+++ b/claude-ops/bin/ops-status
@@ -252,6 +252,29 @@ if has_cmd claude && has_cmd jq; then
fi
fi
+# ─── 7c. Pocket env-broker ─────────────────────────────────────────────────
+# Secrets broker for restricted pocket workers. Surfaces request counts and
+# flags denials / uid-rejections (a prompt-injection probing signal).
+BROKER_STATE="not-configured"
+BROKER_REQ=0
+BROKER_DENIED=0
+BROKER_UID_REJ=0
+BROKER_HEALTH="${POCKET_STATE_DIR:-/var/lib/pocket-pipeline}/env-broker-health.json"
+if [ -f "$BROKER_HEALTH" ]; then
+ if has_cmd jq && jq empty "$BROKER_HEALTH" >/dev/null 2>&1; then
+ BROKER_REQ="$(jq -r '.totals.requests // 0' "$BROKER_HEALTH" 2>/dev/null || echo 0)"
+ BROKER_DENIED="$(jq -r '.totals.denied // 0' "$BROKER_HEALTH" 2>/dev/null || echo 0)"
+ BROKER_UID_REJ="$(jq -r '.totals.uid_rejected // 0' "$BROKER_HEALTH" 2>/dev/null || echo 0)"
+ if [ "$BROKER_UID_REJ" -gt 0 ]; then
+ BROKER_STATE="anomaly"
+ else
+ BROKER_STATE="ok"
+ fi
+ else
+ BROKER_STATE="unhealthy"
+ fi
+fi
+
# ─── 8. Registry ────────────────────────────────────────────────────────────
REGISTRY_STATE="missing"
REGISTRY_COUNT=0
@@ -365,6 +388,14 @@ render_pretty() {
*) printf ' Claude bg ○ idle (interactive: %s)\n' "$CC_BG_INTERACTIVE" ;;
esac
+ # Pocket env-broker (secrets broker for restricted workers)
+ case "$BROKER_STATE" in
+ ok) printf ' Env-broker ✓ %s reqs, %s denied\n' "$BROKER_REQ" "$BROKER_DENIED" ;;
+ anomaly) printf ' Env-broker ⚠ %s uid-rejections! (%s reqs) — check env-broker-audit.log\n' "$BROKER_UID_REJ" "$BROKER_REQ" ;;
+ unhealthy)printf ' Env-broker ✗ invalid env-broker-health.json\n' ;;
+ *) printf ' Env-broker ○ not running\n' ;;
+ esac
+
# Registry
case "$REGISTRY_STATE" in
ok) printf ' Registry ✓ %s projects\n' "$REGISTRY_COUNT" ;;
diff --git a/claude-ops/docs/pocket-env-broker.md b/claude-ops/docs/pocket-env-broker.md
new file mode 100644
index 00000000..713e72d9
--- /dev/null
+++ b/claude-ops/docs/pocket-env-broker.md
@@ -0,0 +1,113 @@
+# pocket-env-broker
+
+A peer-authenticated secrets broker that lets **restricted** pocket workers request
+specific allowlisted secrets at runtime — instead of the all-or-nothing choice
+between "worker inherits every secret" and "worker has none".
+
+## Why
+
+The pocket executor spawns autonomous `claude --bg` workers as a restricted unix
+user (`POCKET_WORKER_USER`, e.g. `pocket-worker`) that deliberately does not
+inherit the orchestrator's secret environment (see the worker-isolation change in
+2.11.9). That cap is good for blast-radius, but some legitimate tasks need a
+specific secret (e.g. a Gmail account id). The broker is the supervising
+orchestrator's controlled way to hand out **one named, allowlisted** secret at a
+time, over an authenticated channel, with an audit trail.
+
+## Architecture
+
+```
+restricted worker (uid: pocket-worker) orchestrator (privileged uid)
+┌───────────────────────────────┐ ┌──────────────────────────────┐
+│ claude --bg task │ AF_UNIX │ pocket-env-broker.py (daemon) │
+│ $ pocket-env GOG_ACCOUNT ──┼──socket────▶│ 1. SO_PEERCRED → uid check │
+│ ▲ value │ │ 2. allowlist (default-deny) │
+│ └───────────────────────┼◀───────────┤ 3. value from OWN env │
+└───────────────────────────────┘ │ 4. append audit record │
+ └──────────────────────────────┘
+```
+
+- **Transport:** unix-domain socket. Secrets are returned over the socket only —
+ they are never written to disk.
+- **Peer auth:** the broker reads the caller's uid with `SO_PEERCRED` and rejects
+ any uid that is not the worker user's. Filesystem perms on the socket
+ (group/ACL) gate who can even connect; `SO_PEERCRED` is the application-layer
+ backstop.
+- **Policy:** `env-broker-policy.json` → `{"allow": ["VAR", ...]}`. **Default-deny**
+ — a missing or malformed policy grants nothing. A variable is only returned if
+ it is both in the allowlist *and* present in the broker's environment.
+- **Secret source:** the broker's own process environment, populated the same way
+ the executor's secrets are (e.g. an `EnvironmentFile` / a wrapper that sources
+ `~/.mcp-secrets.env`). The broker never reads a secrets file itself.
+- **Audit:** every request — granted or denied — is appended to
+ `env-broker-audit.log` as `{ts, uid, var, task_id, worker_id, decision}`.
+
+## Components
+
+| File | Role |
+|------|------|
+| `scripts/pocket-env-broker.py` | the daemon (server) — runs as the orchestrator user |
+| `scripts/pocket-env` | worker-side client CLI — on the worker's PATH |
+| `scripts/env-broker-policy.example.json` | allowlist template (copy + edit) |
+| `scripts/systemd/pocket-env-broker.service.template` | systemd unit template |
+
+## Worker usage
+
+```bash
+# In a worker task (runs as the restricted user):
+ACCOUNT=$(pocket-env GOG_ACCOUNT) || { echo "no access to GOG_ACCOUNT"; exit 1; }
+```
+
+`pocket-env` prints the value to stdout with no trailing newline (so command
+substitution captures it exactly), or exits non-zero and prints the denial reason
+to stderr.
+
+## Configuration (env)
+
+| Variable | Default | Used by |
+|----------|---------|---------|
+| `POCKET_ENV_BROKER_SOCK` | `$POCKET_STATE_DIR/env-broker.sock` | broker + client |
+| `POCKET_ENV_BROKER_POLICY` | `$POCKET_STATE_DIR/env-broker-policy.json` | broker |
+| `POCKET_ENV_BROKER_AUDIT` | `$POCKET_STATE_DIR/env-broker-audit.log` | broker |
+| `POCKET_STATE_DIR` | `/var/lib/pocket-pipeline` | broker + client |
+| `POCKET_WORKER_USER` | `pocket-worker` | broker (uid to authorize) |
+| `POCKET_ENV_BROKER_HEALTH` | `$POCKET_STATE_DIR/env-broker-health.json` | broker (metrics snapshot) |
+| `POCKET_ENV_BROKER_NOTIFY_CMD` | _(unset — off)_ | broker (alert command; alert text appended as final arg) |
+| `POCKET_ENV_BROKER_NOTIFY_COOLDOWN` | `300` | broker (per-event rate-limit, seconds) |
+
+## Security notes
+
+- **Never** add high-blast-radius secrets (AWS keys, SSH material, Doppler service
+ tokens) to the allowlist. The point of the worker isolation is that those stay
+ out of worker reach; the broker is for narrowly-scoped, lower-sensitivity values.
+- The socket is `0660`; provisioning grants the worker user connect access via
+ group or ACL. Even if a third user could connect, `SO_PEERCRED` denies them.
+- Review `env-broker-audit.log` to see exactly which secrets workers have pulled.
+
+## Observability
+
+The broker is observable at three levels:
+
+1. **Live status** — `pocket-env-broker --status` (add `--json` for machine output)
+ prints request counters (`requests / granted / denied / unknown_var /
+ uid_rejected`), last-request time, and the most recent denials. Backed by a
+ metrics snapshot the broker rewrites after every request at
+ `env-broker-health.json` (`POCKET_ENV_BROKER_HEALTH`).
+2. **Ops dashboard** — `/ops:ops-status` shows an `Env-broker` line with request
+ and denial counts, and raises a `⚠` anomaly when there are any **uid
+ rejections** (a non-worker uid attempting to pull secrets — a probing signal).
+3. **Audit + logs** — `env-broker-audit.log` (every grant/deny, append-only JSON)
+ and the daemon's structured stderr via `journalctl -u pocket-env-broker`.
+4. **Push notifications (opt-in)** — set `POCKET_ENV_BROKER_NOTIFY_CMD` to a
+ command (e.g. a Telegram self-send helper) and the broker fires it with an
+ alert message on a **uid rejection** or a **not-allowed denial** — the
+ prompt-injection probing signals. Rate-limited per event by
+ `POCKET_ENV_BROKER_NOTIFY_COOLDOWN` (default 300s) so it can't spam. The
+ command receives the alert text as its final argument; delivery is best-effort
+ and never blocks request handling. Because the broker runs as the orchestrator
+ user, wiring this to the operator's own chat is an operational self-notification
+ (exempt from the per-message outbound-comms approval gate).
+
+The health snapshot carries an `anomaly: true` flag whenever denials or uid
+rejections have occurred, so downstream monitors can alert on it without parsing
+counters themselves.
diff --git a/claude-ops/package.json b/claude-ops/package.json
index a3b00a04..3ccddef5 100644
--- a/claude-ops/package.json
+++ b/claude-ops/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-ops-bin",
- "version": "2.11.9",
+ "version": "2.12.0",
"private": true,
"description": "Runtime dependencies for claude-ops bin scripts (ops-telegram-autolink.mjs, ops-slack-autolink.mjs). Installed separately from telegram-server/ so the .mjs scripts resolve modules from claude-ops/node_modules regardless of invocation cwd.",
"type": "module",
diff --git a/claude-ops/scripts/env-broker-policy.example.json b/claude-ops/scripts/env-broker-policy.example.json
new file mode 100644
index 00000000..4994eb85
--- /dev/null
+++ b/claude-ops/scripts/env-broker-policy.example.json
@@ -0,0 +1,4 @@
+{
+ "_comment": "pocket-env-broker allowlist. DEFAULT-DENY: only variable names listed in 'allow' are grantable to a worker, and only if the broker's own environment actually holds a value for them. Copy to $POCKET_STATE_DIR/env-broker-policy.json and edit. NEVER add high-blast-radius secrets here (AWS keys, SSH material, Doppler service tokens) — those should stay out of worker reach entirely. Every request (granted or denied) is recorded in env-broker-audit.log.",
+ "allow": ["GOG_ACCOUNT"]
+}
diff --git a/claude-ops/scripts/ops-cron-pocket-executor.py b/claude-ops/scripts/ops-cron-pocket-executor.py
index fc87dc4f..e72a83be 100755
--- a/claude-ops/scripts/ops-cron-pocket-executor.py
+++ b/claude-ops/scripts/ops-cron-pocket-executor.py
@@ -350,6 +350,9 @@ def spawn_worker(task: dict) -> dict | None:
# ignored by --bg (would leave the session idle with "(send a prompt)").
env = os.environ.copy()
env["CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS"] = "0"
+ # Identify the worker to the env-broker audit log (pocket-env client reads these).
+ env["POCKET_TASK_ID"] = str(task_id)
+ env["POCKET_WORKER_ID"] = worker_id
if WORKER_USER and WORKER_CLAUDE_CONFIG_DIR:
# Point the restricted worker at a Claude config dir it can read.
env["CLAUDE_CONFIG_DIR"] = WORKER_CLAUDE_CONFIG_DIR
@@ -368,7 +371,7 @@ def spawn_worker(task: dict) -> dict | None:
# rather than hanging); `-H` sets HOME to the worker user's home so Claude
# writes session state there; --preserve-env carries only the vars the
# worker needs, dropping the executor user's secrets from the environment.
- _preserve = "PATH,CLAUDE_CONFIG_DIR,CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,ANTHROPIC_API_KEY,POCKET_WORKER_MODEL"
+ _preserve = "PATH,CLAUDE_CONFIG_DIR,CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,ANTHROPIC_API_KEY,POCKET_WORKER_MODEL,POCKET_ENV_BROKER_SOCK,POCKET_STATE_DIR,POCKET_TASK_ID,POCKET_WORKER_ID"
cmd = ["sudo", "-n", "-H", "-u", WORKER_USER, f"--preserve-env={_preserve}", "--", *cmd]
try:
diff --git a/claude-ops/scripts/pocket-env b/claude-ops/scripts/pocket-env
new file mode 100755
index 00000000..68906b83
--- /dev/null
+++ b/claude-ops/scripts/pocket-env
@@ -0,0 +1,69 @@
+#!/usr/bin/env python3
+"""pocket-env — worker-side client for the pocket-env-broker.
+
+A restricted pocket worker requests a single allowlisted secret from the
+supervising orchestrator and prints its value to stdout (nothing else), so it can
+be captured in a shell assignment:
+
+ TOKEN=$(pocket-env GOG_KEYRING_PASSWORD)
+
+Exit codes:
+ 0 granted — value printed to stdout
+ 1 denied / not allowed / unknown var
+ 2 usage or transport error (broker unreachable)
+
+The value is printed with no trailing newline so command substitution captures it
+exactly. Denial reasons go to stderr.
+
+Env:
+ POCKET_ENV_BROKER_SOCK socket path (default $POCKET_STATE_DIR/env-broker.sock)
+ POCKET_STATE_DIR base dir (default /var/lib/pocket-pipeline)
+ POCKET_TASK_ID optional, included in the audit record
+ POCKET_WORKER_ID optional, included in the audit record
+"""
+from __future__ import annotations
+
+import json
+import os
+import socket
+import sys
+
+STATE_DIR = os.environ.get("POCKET_STATE_DIR", "/var/lib/pocket-pipeline")
+SOCK_PATH = os.environ.get("POCKET_ENV_BROKER_SOCK", os.path.join(STATE_DIR, "env-broker.sock"))
+
+
+def main(argv: list[str]) -> int:
+ if len(argv) != 2 or argv[1] in ("-h", "--help"):
+ print("usage: pocket-env <VAR_NAME>", file=sys.stderr)
+ return 2
+ var = argv[1].strip()
+ req = {
+ "var": var,
+ "task_id": os.environ.get("POCKET_TASK_ID", ""),
+ "worker_id": os.environ.get("POCKET_WORKER_ID", ""),
+ }
+ try:
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ s.settimeout(5)
+ s.connect(SOCK_PATH)
+ s.sendall(json.dumps(req).encode() + b"\n")
+ raw = s.recv(65536)
+ s.close()
+ except OSError as e:
+ print(f"pocket-env: broker unreachable at {SOCK_PATH}: {e}", file=sys.stderr)
+ return 2
+ try:
+ resp = json.loads(raw.decode("utf-8").strip() or "{}")
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ print("pocket-env: malformed broker response", file=sys.stderr)
+ return 2
+ if resp.get("ok"):
+ sys.stdout.write(resp.get("value", ""))
+ sys.stdout.flush()
+ return 0
+ print(f"pocket-env: DENIED ({resp.get('error', 'denied')}) for {var}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/claude-ops/scripts/pocket-env-broker.py b/claude-ops/scripts/pocket-env-broker.py
new file mode 100755
index 00000000..aa528792
--- /dev/null
+++ b/claude-ops/scripts/pocket-env-broker.py
@@ -0,0 +1,379 @@
+#!/usr/bin/env python3
+"""pocket-env-broker — peer-authenticated secrets broker for restricted pocket workers.
+
+The pocket executor spawns autonomous `claude --bg` workers as a restricted unix
+user (POCKET_WORKER_USER, e.g. `pocket-worker`) that deliberately does NOT inherit
+the orchestrator's secret environment. This broker lets such a worker request a
+*specific* allowlisted secret at runtime, instead of getting all-or-nothing.
+
+Design:
+ • Runs as the privileged orchestrator user (the one that has the secrets in its
+ environment — launched via the same env wrapper as the executor).
+ • Listens on a unix-domain socket. Secrets are returned over the socket only —
+ they never touch disk.
+ • Every connection is peer-authenticated with SO_PEERCRED: the caller's uid MUST
+ equal the worker user's uid, otherwise the request is denied.
+ • A default-deny allowlist (env-broker-policy.json → {"allow": [...]}) decides
+ which variable names are grantable. Values come from this process's own
+ environment (so the deployment populates them the same way the executor's
+ secrets are populated — e.g. sourcing ~/.mcp-secrets.env in the env wrapper).
+ • Every request (granted or denied) is appended to an audit log.
+
+Protocol (line-delimited JSON over the socket):
+ request : {"var": "GOG_ACCOUNT", "task_id": "...", "worker_id": "..."}\n
+ reply : {"ok": true, "value": "..."}\n
+ {"ok": false, "error": "denied|unknown_var|not_allowed_uid|bad_request"}\n
+
+Env:
+ POCKET_ENV_BROKER_SOCK socket path (default $POCKET_STATE_DIR/env-broker.sock)
+ POCKET_ENV_BROKER_POLICY policy json (default $POCKET_STATE_DIR/env-broker-policy.json)
+ POCKET_ENV_BROKER_AUDIT audit log (default $POCKET_STATE_DIR/env-broker-audit.log)
+ POCKET_STATE_DIR base dir (default /var/lib/pocket-pipeline)
+ POCKET_WORKER_USER unix user allowed to request (default pocket-worker)
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import pwd
+import shlex
+import signal
+import socket
+import struct
+import subprocess
+import sys
+import threading
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+
+STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", "/var/lib/pocket-pipeline"))
+SOCK_PATH = Path(
+ os.environ.get("POCKET_ENV_BROKER_SOCK", str(STATE_DIR / "env-broker.sock"))
+)
+POLICY_PATH = Path(
+ os.environ.get(
+ "POCKET_ENV_BROKER_POLICY", str(STATE_DIR / "env-broker-policy.json")
+ )
+)
+AUDIT_PATH = Path(
+ os.environ.get("POCKET_ENV_BROKER_AUDIT", str(STATE_DIR / "env-broker-audit.log"))
+)
+HEALTH_PATH = Path(
+ os.environ.get(
+ "POCKET_ENV_BROKER_HEALTH", str(STATE_DIR / "env-broker-health.json")
+ )
+)
+WORKER_USER = os.environ.get("POCKET_WORKER_USER", "pocket-worker").strip()
+MAX_REQUEST_BYTES = 4096
+
+# Optional push notifications on security-relevant events. Opt-in: set
+# POCKET_ENV_BROKER_NOTIFY_CMD to a command (e.g. a Telegram self-send helper);
+# the broker appends the alert text as a final argument and runs it best-effort
+# when a uid-rejection or a not-allowed denial occurs. Rate-limited per
+# (decision,var,uid) by POCKET_ENV_BROKER_NOTIFY_COOLDOWN seconds to avoid spam.
+# Default unset = no notifications (status/dashboard/audit still work).
+NOTIFY_CMD = os.environ.get("POCKET_ENV_BROKER_NOTIFY_CMD", "").strip()
+NOTIFY_COOLDOWN = int(os.environ.get("POCKET_ENV_BROKER_NOTIFY_COOLDOWN", "300"))
+NOTIFY_DECISIONS = {"not_allowed_uid", "not_allowed"}
+_NOTIFY_STATE: dict[str, float] = {} # dedupe key -> last-sent monotonic time
+
+# In-memory observability counters, snapshotted to HEALTH_PATH after each request
+# so `ops-status` / `pocket-env-broker --status` can surface broker activity and
+# flag anomalies (denials, uid rejections) instead of leaving them in a log.
+_METRICS_LOCK = threading.Lock()
+_METRICS = {
+ "started_at": None,
+ "last_request_ts": None,
+ "totals": {
+ "requests": 0,
+ "granted": 0,
+ "denied": 0,
+ "unknown_var": 0,
+ "uid_rejected": 0,
+ },
+ "by_var": {},
+ "recent_denials": [], # last 20 non-granted decisions, newest first
+}
+_DECISION_TO_COUNTER = {
+ "granted": "granted",
+ "not_allowed": "denied",
+ "bad_request": "denied",
+ "unknown_var": "unknown_var",
+ "not_allowed_uid": "uid_rejected",
+}
+
+
+def record_metric(uid: int, var: str, decision: str) -> None:
+ with _METRICS_LOCK:
+ t = _METRICS["totals"]
+ t["requests"] += 1
+ t[_DECISION_TO_COUNTER.get(decision, "denied")] += 1
+ bv = _METRICS["by_var"].setdefault(var or "<none>", {"granted": 0, "denied": 0})
+ bv["granted" if decision == "granted" else "denied"] += 1
+ _METRICS["last_request_ts"] = now_iso()
+ if decision != "granted":
+ _METRICS["recent_denials"].insert(
+ 0, {"ts": now_iso(), "uid": uid, "var": var, "decision": decision}
+ )
+ del _METRICS["recent_denials"][20:]
+ snapshot = _health_snapshot_locked()
+ _write_health(snapshot)
+ maybe_notify(uid, var, decision)
+
+
+def maybe_notify(uid: int, var: str, decision: str) -> None:
+ """Fire the configured notify command on a security-relevant event,
+ rate-limited per (decision,var,uid). Best-effort: never let a notify failure
+ affect request handling."""
+ if not NOTIFY_CMD or decision not in NOTIFY_DECISIONS:
+ return
+ key = f"{decision}:{var}:{uid}"
+ now = time.monotonic()
+ with _METRICS_LOCK:
+ last = _NOTIFY_STATE.get(key, 0.0)
+ if now - last < NOTIFY_COOLDOWN:
+ return
+ _NOTIFY_STATE[key] = now
+ if decision == "not_allowed_uid":
+ msg = f"⚠ pocket-env-broker: BLOCKED secret request from non-worker uid={uid} (var={var or '?'})"
+ else:
+ msg = f"⚠ pocket-env-broker: DENIED non-allowlisted secret '{var}' requested by uid={uid}"
+ try:
+ subprocess.run(
+ shlex.split(NOTIFY_CMD) + [msg],
+ stdin=subprocess.DEVNULL,
+ capture_output=True,
+ timeout=15,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError) as e:
+ log(f"notify failed: {e}")
+
+
+def _health_snapshot_locked() -> dict:
+ t = _METRICS["totals"]
+ # "anomaly" flags the security-relevant signals worth surfacing/alerting on.
+ anomaly = t["uid_rejected"] > 0 or t["denied"] > 0
+ return {
+ "status": "ok",
+ "anomaly": anomaly,
+ "started_at": _METRICS["started_at"],
+ "last_request_ts": _METRICS["last_request_ts"],
+ "totals": dict(t),
+ "by_var": {k: dict(v) for k, v in _METRICS["by_var"].items()},
+ "recent_denials": list(_METRICS["recent_denials"]),
+ "updated_at": now_iso(),
+ }
+
+
+def _write_health(snapshot: dict) -> None:
+ try:
+ HEALTH_PATH.parent.mkdir(parents=True, exist_ok=True)
+ tmp = HEALTH_PATH.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps(snapshot, indent=2))
+ tmp.replace(HEALTH_PATH)
+ except OSError as e:
+ log(f"health write failed: {e}")
+
+
+def now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def log(msg: str) -> None:
+ print(f"{now_iso()} [pocket-env-broker] {msg}", file=sys.stderr, flush=True)
+
+
+def allowed_uid() -> int | None:
+ """Resolve the uid the worker user runs as. None if the user does not exist."""
+ try:
+ return pwd.getpwnam(WORKER_USER).pw_uid
+ except KeyError:
+ return None
+
+
+def load_policy() -> set[str]:
+ """Return the set of grantable variable names. Default-deny: missing/broken
+ policy yields an empty allowlist (deny everything)."""
+ try:
+ data = json.loads(POLICY_PATH.read_text())
+ allow = data.get("allow", [])
+ return {str(v) for v in allow if isinstance(v, str)}
+ except (OSError, json.JSONDecodeError, AttributeError):
+ return set()
+
+
+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:
+ f.write(json.dumps(record) + "\n")
+ except OSError as e:
+ log(f"audit write failed: {e}")
+
+
+def peer_uid(conn: socket.socket) -> int:
+ """Read the connected peer's uid via SO_PEERCRED (Linux). Raises on failure."""
+ creds = conn.getsockopt(
+ socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")
+ )
+ _pid, uid, _gid = struct.unpack("3i", creds)
+ return uid
+
+
+def decide(var: str, policy: set[str]) -> tuple[bool, str | None, str]:
+ """Pure policy decision. Returns (ok, value_or_None, reason)."""
+ if not var:
+ return False, None, "bad_request"
+ if var not in policy:
+ return False, None, "not_allowed"
+ value = os.environ.get(var)
+ if value is None:
+ # In the allowlist but the broker has no such value in its environment.
+ return False, None, "unknown_var"
+ return True, value, "granted"
+
+
+def handle(conn: socket.socket, want_uid: int | None) -> None:
+ try:
+ conn.settimeout(5)
+ # Peer authentication first — reject any caller that is not the worker user.
+ uid = peer_uid(conn)
+ raw = conn.recv(MAX_REQUEST_BYTES)
+ try:
+ req = json.loads(raw.decode("utf-8").strip() or "{}")
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ req = {}
+ var = str(req.get("var", "")).strip()
+ task_id = str(req.get("task_id", ""))[:128]
+ worker_id = str(req.get("worker_id", ""))[:128]
+
+ if want_uid is None or uid != want_uid:
+ audit(
+ {
+ "uid": uid,
+ "var": var,
+ "task_id": task_id,
+ "worker_id": worker_id,
+ "decision": "not_allowed_uid",
+ }
+ )
+ record_metric(uid, var, "not_allowed_uid")
+ conn.sendall(
+ json.dumps({"ok": False, "error": "not_allowed_uid"}).encode() + b"\n"
+ )
+ return
+
+ ok, value, reason = decide(var, load_policy())
+ audit(
+ {
+ "uid": uid,
+ "var": var,
+ "task_id": task_id,
+ "worker_id": worker_id,
+ "decision": reason,
+ }
+ )
+ record_metric(uid, var, reason)
+ if ok:
+ conn.sendall(json.dumps({"ok": True, "value": value}).encode() + b"\n")
+ else:
+ conn.sendall(json.dumps({"ok": False, "error": reason}).encode() + b"\n")
+ except (OSError, socket.timeout) as e:
+ log(f"connection error: {e}")
+ finally:
+ try:
+ conn.close()
+ except OSError:
+ pass
+
+
+def serve() -> int:
+ want_uid = allowed_uid()
+ if want_uid is None:
+ log(
+ 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.unlink()
+
+ srv = 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)
+ srv.listen(16)
+ with _METRICS_LOCK:
+ _METRICS["started_at"] = now_iso()
+ _write_health(_health_snapshot_locked())
+ log(f"listening on {SOCK_PATH} (grant uid={want_uid}, policy={POLICY_PATH})")
+
+ stop = threading.Event()
+
+ def _shutdown(*_):
+ stop.set()
+ try:
+ srv.close()
+ except OSError:
+ pass
+
+ signal.signal(signal.SIGTERM, _shutdown)
+ signal.signal(signal.SIGINT, _shutdown)
+
+ while not stop.is_set():
+ try:
+ conn, _ = srv.accept()
+ except OSError:
+ break
+ threading.Thread(target=handle, args=(conn, want_uid), daemon=True).start()
+
+ try:
+ if SOCK_PATH.exists():
+ SOCK_PATH.unlink()
+ except OSError:
+ pass
+ log("stopped")
+ return 0
+
+
+def print_status(as_json: bool) -> int:
+ """Read the health snapshot and print it. Observability entry point used by
+ `pocket-env-broker --status` and surfaced by ops-status."""
+ try:
+ snap = json.loads(HEALTH_PATH.read_text())
+ except (OSError, json.JSONDecodeError):
+ print(
+ json.dumps({"status": "down", "reason": "no health file"})
+ if as_json
+ else "pocket-env-broker: DOWN (no health file — broker not running?)"
+ )
+ return 1
+ if as_json:
+ print(json.dumps(snap))
+ return 0
+ t = snap.get("totals", {})
+ flag = " ⚠ ANOMALY" if snap.get("anomaly") else ""
+ print(f"pocket-env-broker: {snap.get('status', '?')}{flag}")
+ print(
+ f" started {snap.get('started_at')} · last req {snap.get('last_request_ts') or '(none)'}"
+ )
+ print(
+ f" requests={t.get('requests', 0)} granted={t.get('granted', 0)} "
+ f"denied={t.get('denied', 0)} unknown={t.get('unknown_var', 0)} uid_rejected={t.get('uid_rejected', 0)}"
+ )
+ for d in snap.get("recent_denials", [])[:5]:
+ print(
+ f" denied: {d.get('ts')} uid={d.get('uid')} var={d.get('var')} ({d.get('decision')})"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ if len(sys.argv) > 1 and sys.argv[1] == "--status":
+ sys.exit(print_status(as_json="--json" in sys.argv[2:]))
+ sys.exit(serve())
diff --git a/claude-ops/scripts/systemd/pocket-env-broker.service.template b/claude-ops/scripts/systemd/pocket-env-broker.service.template
new file mode 100644
index 00000000..2ea55d22
--- /dev/null
+++ b/claude-ops/scripts/systemd/pocket-env-broker.service.template
@@ -0,0 +1,37 @@
+# pocket-env-broker — peer-authenticated secrets broker for restricted pocket workers.
+# Template: copy to a systemd unit dir, fill the <PLACEHOLDERS>, then enable.
+# system : /etc/systemd/system/pocket-env-broker.service (sudo systemctl ...)
+# user : ~/.config/systemd/user/pocket-env-broker.service (systemctl --user ...)
+#
+# The broker must run as the PRIVILEGED orchestrator user (the one whose env holds
+# the secrets) — NOT as the restricted worker user. It loads grantable values from
+# its own environment, so it is launched through the same env wrapper that
+# populates the executor's secrets (e.g. an EnvironmentFile or a wrapper that
+# sources ~/.mcp-secrets.env). Keep it a long-running daemon (Type=simple) so it
+# can answer worker requests with low latency.
+
+[Unit]
+Description=pocket-env-broker (secrets broker for restricted pocket workers)
+After=network.target
+
+[Service]
+Type=simple
+User=<ORCHESTRATOR_USER>
+# Populate the grantable secrets into the broker's environment. Use ONE of:
+# EnvironmentFile=<PATH_TO_SECRETS_ENV_FILE>
+# or an ExecStart wrapper that sources them before exec'ing the broker.
+EnvironmentFile=-<PATH_TO_SECRETS_ENV_FILE>
+Environment=POCKET_STATE_DIR=<POCKET_STATE_DIR>
+Environment=POCKET_WORKER_USER=<WORKER_USER>
+ExecStart=<PYTHON_BIN> <REPO>/claude-ops/scripts/pocket-env-broker.py
+Restart=on-failure
+RestartSec=5
+# Hardening — the broker handles secrets; keep its own footprint minimal.
+NoNewPrivileges=true
+ProtectSystem=strict
+ProtectHome=read-only
+ReadWritePaths=<POCKET_STATE_DIR>
+PrivateTmp=true
+
+[Install]
+WantedBy=multi-user.target
diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.sh
index 0af7502e..551dedb7 100755
--- a/claude-ops/tests/run-all.sh
+++ b/claude-ops/tests/run-all.sh
@@ -41,6 +41,7 @@ run_suite "$TESTS_DIR/test-template.sh"
run_suite "$TESTS_DIR/test-claude-md.sh"
run_suite "$TESTS_DIR/test-no-secrets.sh"
run_suite "$TESTS_DIR/test-agent-teams.sh"
+run_suite "$TESTS_DIR/test-pocket-env-broker.sh"
run_suite "$TESTS_DIR/test-ops-daemon-manager.sh"
run_suite "$TESTS_DIR/test-ops-package.sh"
run_suite "$TESTS_DIR/test-safety-hooks.sh"
diff --git a/claude-ops/tests/test-pocket-env-broker.sh b/claude-ops/tests/test-pocket-env-broker.sh
new file mode 100755
index 00000000..51e134f6
--- /dev/null
+++ b/claude-ops/tests/test-pocket-env-broker.sh
@@ -0,0 +1,161 @@
+#!/usr/bin/env bash
+# test-pocket-env-broker.sh — exercises the secrets broker: allowlist grant/deny,
+# socket round-trip, uid peer-auth gate, and audit logging. No sudo required:
+# the broker is told the current user is the authorized worker user, so the
+# same-process client round-trips; a negative case points it at a different user.
+set -uo pipefail
+
+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BROKER="$PLUGIN_ROOT/scripts/pocket-env-broker.py"
+CLIENT="$PLUGIN_ROOT/scripts/pocket-env"
+PY="$(command -v python3 || true)"
+
+pass=0
+fail=0
+ok() { echo " PASS: $1"; pass=$((pass + 1)); }
+err() {
+ echo " FAIL: $1 — $2"
+ fail=$((fail + 1))
+}
+
+echo "Testing pocket-env-broker"
+echo ""
+
+if [[ -z "$PY" ]]; then
+ echo " SKIP: python3 not available"
+ echo "test-pocket-env-broker.sh: 0 passed, 0 failed (skipped)"
+ exit 0
+fi
+
+TMP="$(mktemp -d)"
+BROKER_PID=""
+cleanup() {
+ [[ -n "$BROKER_PID" ]] && kill "$BROKER_PID" 2>/dev/null
+ rm -rf "$TMP"
+}
+trap cleanup EXIT
+
+SOCK="$TMP/env-broker.sock"
+POLICY="$TMP/policy.json"
+AUDIT="$TMP/audit.log"
+HEALTH="$TMP/health.json"
+NOTIFY_LOG="$TMP/notify.log"
+NOTIFY_STUB="$TMP/notify.sh"
+# Stub notify command: appends the final arg (the alert message) to NOTIFY_LOG.
+printf '%s\n' '#!/usr/bin/env bash' 'echo "${!#}" >> "'"$NOTIFY_LOG"'"' >"$NOTIFY_STUB"
+chmod +x "$NOTIFY_STUB"
+printf '%s\n' '{"allow":["FOO_OK"]}' >"$POLICY"
+
+start_broker() { # $1 = worker user to authorize
+ POCKET_ENV_BROKER_SOCK="$SOCK" POCKET_ENV_BROKER_POLICY="$POLICY" \
+ POCKET_ENV_BROKER_AUDIT="$AUDIT" POCKET_ENV_BROKER_HEALTH="$HEALTH" \
+ POCKET_ENV_BROKER_NOTIFY_CMD="bash $NOTIFY_STUB" POCKET_ENV_BROKER_NOTIFY_COOLDOWN="0" \
+ POCKET_WORKER_USER="$1" \
+ FOO_OK="the-secret-value" BAR_SECRET="should-not-leak" \
+ "$PY" "$BROKER" &
+ BROKER_PID=$!
+ for _ in $(seq 1 50); do
+ [[ -S "$SOCK" ]] && return 0
+ sleep 0.1
+ done
+ return 1
+}
+
+run_client() { # $1 = var → prints value, sets global RC
+ OUT="$(POCKET_ENV_BROKER_SOCK="$SOCK" POCKET_STATE_DIR="$TMP" "$PY" "$CLIENT" "$1" 2>/dev/null)"
+ RC=$?
+}
+
+# ── Case A: authorized uid (current user) ───────────────────────────────────
+ME="$(id -un)"
+if start_broker "$ME"; then
+ ok "broker started and bound socket"
+else
+ err "broker startup" "socket never appeared"
+ echo "test-pocket-env-broker.sh: $pass passed, $((fail + 1)) failed"
+ exit 1
+fi
+
+run_client FOO_OK
+if [[ $RC -eq 0 && "$OUT" == "the-secret-value" ]]; then
+ ok "allowlisted var granted with correct value"
+else
+ err "grant FOO_OK" "rc=$RC out='$OUT'"
+fi
+
+run_client BAR_SECRET
+if [[ $RC -eq 1 && -z "$OUT" ]]; then
+ ok "non-allowlisted var denied (not in policy)"
+else
+ err "deny BAR_SECRET" "rc=$RC out='$OUT' (should be denied, no value)"
+fi
+
+run_client NOT_IN_ENV_EITHER
+if [[ $RC -eq 1 ]]; then
+ ok "unknown var denied"
+else
+ err "deny unknown" "rc=$RC"
+fi
+
+# audit log should contain a granted + a denied record
+if grep -q '"decision": "granted"' "$AUDIT" && grep -q '"decision": "not_allowed"' "$AUDIT"; then
+ ok "audit log records granted + denied decisions"
+else
+ err "audit log" "missing expected decision records: $(cat "$AUDIT" 2>/dev/null)"
+fi
+
+# observability: health file written with counters, anomaly flagged on denial
+if [[ -f "$HEALTH" ]] && grep -q '"requests"' "$HEALTH" && grep -q '"anomaly": true' "$HEALTH"; then
+ ok "health file written with counters + anomaly flag"
+else
+ err "health file" "missing/incomplete: $(cat "$HEALTH" 2>/dev/null)"
+fi
+
+# --status reader reports the metrics
+STAT="$(POCKET_ENV_BROKER_HEALTH="$HEALTH" "$PY" "$BROKER" --status --json 2>/dev/null)"
+if echo "$STAT" | grep -q '"granted": 1' && echo "$STAT" | grep -q '"uid_rejected"'; then
+ ok "--status reports granted/denied counters"
+else
+ err "--status" "unexpected: $STAT"
+fi
+
+# notifications: a denial fires the notify command; a grant does not
+sleep 0.5 # notify runs after the response is sent
+if [[ -f "$NOTIFY_LOG" ]] && grep -q "BAR_SECRET" "$NOTIFY_LOG"; then
+ ok "notify command fired on denial"
+else
+ err "notify on denial" "no alert for BAR_SECRET: $(cat "$NOTIFY_LOG" 2>/dev/null)"
+fi
+if grep -q "FOO_OK" "$NOTIFY_LOG" 2>/dev/null; then
+ err "notify on grant" "grant should NOT notify, but FOO_OK appeared in alerts"
+else
+ ok "grant does not fire a notification"
+fi
+
+kill "$BROKER_PID" 2>/dev/null
+wait "$BROKER_PID" 2>/dev/null
+BROKER_PID=""
+rm -f "$SOCK"
+
+# ── Case B: uid gate — broker authorizes a DIFFERENT user → current user denied ─
+OTHER="nobody"
+if id "$OTHER" >/dev/null 2>&1; then
+ if start_broker "$OTHER"; then
+ run_client FOO_OK
+ if [[ $RC -eq 1 && -z "$OUT" ]]; then
+ ok "peer-auth gate denies a non-authorized uid"
+ else
+ err "uid gate" "rc=$RC out='$OUT' (current user should be rejected as != $OTHER)"
+ fi
+ grep -q '"decision": "not_allowed_uid"' "$AUDIT" && ok "audit records uid rejection" \
+ || err "audit uid" "no not_allowed_uid record"
+ else
+ err "broker startup (case B)" "socket never appeared"
+ fi
+else
+ echo " SKIP: user '$OTHER' not present — uid-gate negative case"
+fi
+
+echo ""
+echo "test-pocket-env-broker.sh: $pass passed, $fail failed"
+[[ $fail -eq 0 ]]