Skip to content

Sanctum Firewalla

A pencil-sketched stone gatehouse on a high network ridge — iron portcullis lowered, a hooded stonemason holding a heavy lock at the threshold and a tiny robed scribe passing him a brass tray of keys through a hatch in the wall, a single teal lantern above the gate, one amber halo around the lock, deep shadow elsewhere.

One evening in May 2026, an Apple TV in the den stayed online for two and a half hours past curfew. The bridge that was supposed to have paused it reported success. It had not paused anything. A stale WebSocket and a connection reset had slipped through the gap between two of its several dozen try/catch blocks, and nobody noticed until bedtime had long passed.

That is the whole case against the old bridge, in one sentence: a bridge defended one try/catch at a time is only as honest as the developer who last counted them.

The legacy bridge was ~/.openclaw/firewalla-bridge.js — over 2,600 lines of single-process Node.js wrapping Firewalla’s encipher SDK on loopback port 1984. For years it carried screen-time enforcement and the security sentinels. The Rust port, sanctum-firewalla v1.0.0 in the sanctum-rs workspace, now runs live on :1984 with full 54-route parity, fail-closed SSH, concurrency bounding, and automated contract verification.

Because the encipher SDK will not let you. It is JavaScript-only, undocumented at the wire level, and reverse-engineering its P2P handshake into a standalone crate is a separate research project. So we quarantined it instead of fighting it.

The shape is a Rust HTTP+SSH bridge with a minimal Node sidecar for SDK marshalling, the same pattern used elsewhere. Rust owns roughly 95% of the surface: HTTP serving, bearer auth and per-peer lockout, the 47-service domain catalog and HomeKit safety gate, adaptive discovery, caching, retry budgets, concurrency limits, persistent state, and fail-closed russh SSH fallbacks. Node owns the ~5% that must speak node-firewalla — a small sidecar spawned with --disable-sigusr1 and stripped bridge auth tokens, driven over newline-delimited JSON on stdin/stdout (services/sanctum-firewalla/docs/SIDECAR_IPC.md). If a native Rust encipher client ever arrives, the sidecar drops away behind the existing sdk dispatch seam.

The Rust bridge is response-compatible with the legacy Node bridge across all 54 endpoints (services/sanctum-firewalla/docs/API_CONTRACT.md) so screen-time, sanctum-cli, the Firewalla MCP server, toolkit wrappers, and every sentinel swapped over without changing a single call site.

  • Auth & redaction: Token resolution matches daemon-safe priority ($FIREWALLA_BRIDGE_TOKEN → ~/.sanctum/secrets/firewalla-bridge-token → macOS Keychain). Unauthenticated GET /health returns a minimal non-disclosive {status} only; authenticated GET /health returns full SDK, box, capability, and discovery diagnostics. Every other route requires constant-time bearer auth with per-peer lockout (5 failures in 60s → 5-minute lockout, 429 + Retry-After off-loopback, [auth][lockout] log alert).
  • Full route coverage (54 endpoints): Health/info/ping, host inventory (with ?includeRaw=1 and 10-minute stale-cache fallback), single-host presence (absent returns 200 with present: false plus policy-derived blocked truth), verified device rename (/host/:mac/name), Wake-on-LAN, per-device policy and DNS rules/unrules, bulk chunked /policies/purge, closed-loop pause/unpause, Smart Queue /system/qos and wind-down /throttle//unthrottle, /host/:mac/app-usage, init-cache projections (/features, /network-profiles, /tags), tag CRUD and additive /host/:mac/tags, allowlisted scoped policy writes (/policy/system, /network/:uuid/policy, /tag/:uid/policy), generalized /rules, closed-loop verified /feature/:name/enable|disable, alarms, stats/yearly/live-stats, flows, speedtest, network-monitor, data-plan, pubkey, full /export, SSH-backed custom /dns CRUD, /box/* controls, and hard-gated /raw (404 in production unless both debug opt-in and X-Box-Admin-Scope match).
  • Idempotent duplicate handling: Firewalla’s Policy already exists rejection is treated as idempotent success (never a 500 storm), eliminating hundreds of false-error log lines per day during curfew re-enforcement.
  • HomeKit Safety Doctrine startup gate: At boot, Rust validates all 47 SERVICE_DOMAINS entries and refuses to start (exit 2) if any rule matches RFC 1918 private space, multicast, .local, or HomeKit/APNS/iCloud-gateway endpoints.

The expire contract (learned the hard way)

Section titled “The expire contract (learned the hard way)”

Some facts you learn at 1 a.m. with packet captures. This is one of them.

Firewalla’s policy.expire is a duration in seconds since activation, not an epoch timestamp (Policy.js: activatedTime + expire < now). Send an epoch and two things happen, both bad. The rule never expires naturally — leaving thousands of stale rows behind. And if you also set autoDeleteWhenExpires, the box schedules setTimeout(epoch × 1000), which overflows a 32-bit timer and fires the delete immediately. Your rule is born, assigned a PID, and executed within the second. The bridge converts at the boundary (expire_epoch_to_duration in src/policy.rs); callers keep sending Unix epochs and never trip the overflow.

Module Owns
auth Token resolution (env → secret file → Keychain), constant-time bearer verification, per-peer brute-force rate limiter (429 / 401)
policy All 47 SERVICE_DOMAINS, HomeKit safety startup gate, expire_epoch_to_duration, allowlist/input validators, pause & wind-down QoS selectors
http axum Router for all 54 endpoints, 1 MiB body limit, optional-body JSON parsing, closed-loop verification, response shaping
sdk Spawns & supervises the Node sidecar (--disable-sigusr1, stripped tokens), request_id multiplexer, concurrency semaphore (default 4), box retry, init/policy/hosts caches, graceful shutdown
ssh Fail-closed russh executor (known_hosts / FW_SSH_HOST_KEY), anchored POSIX ERE iptables cleanup with --RESIDUAL-- post-checks, dnsmasq probe, single-quoted custom_dns.conf management
discovery Adaptive ladder (FIREWALLA_LAN_IP → fresh topology.json → group.json → DNS/mDNS → gateway probe → stale cache), dual-format cache persistence, live reload push to sidecar on IP change
state AppState, ArcSwap discovery & metrics, atomic-rename state.json persistence, 3-strike reset window
errors BridgeError taxonomy, HTTP status mapping, transient retry classification

The old bridge trusted the socket. This one assumes the socket will betray it, following the same resilience doctrine applied across the fleet.

  1. Bounded box concurrency & retry — A semaphore limits concurrent encipher RPCs (preventing connection-reset bursts on the box’s :8833 listener), and transient blips (Initializing Firewalla Device, ECONNRESET, ECONNREFUSED, timeouts) retry with linear backoff. When /hosts still fails after retries, the bridge serves the last-good inventory with stale: true rather than tripping downstream circuit breakers.
  2. Cloud-login self-healing — The sidecar bounds Networker socket requests to 10s, bounds cloud login to 20s with 60s background retries if Firewalla’s cloud is unreachable, and refreshes the cloud token every 30 minutes.
  3. Adaptive discovery & live reload — On disconnect or 3 consecutive box failures (20s cooldown), Rust re-runs discovery and sends {"verb":"reload","value":{"ip":...}} to the sidecar so FWGroup follows router IP changes without a restart.
  4. Fail-closed SSH fallback — Single and batch policy:delete calls exhaust API retries first, then fall back to russh iptables cleanup with anchored regexes, sudo -n pre/post checks, and --RESIDUAL-- verification.
  5. Provenance & instant rollback — The binary stamps its git commit (--version), writes ~/.sanctum/state/firewalla-bridge-running.json, and ships with a signed binary manifest (bin-manifest-check.py). An operator escape hatch (FIREWALLA_USE_NODE=1 or ~/.sanctum/state/firewalla-use-node) restores the legacy Node bridge on the next service kickstart if ever needed.
  • v0.1.0 — initial 24-route skeleton and sidecar IPC contract.
  • v1.0.0 — complete 54-route parity, HomeKit safety gate, auth lockout, concurrency bounding, fail-closed SSH, and live :1984 production cutover.
Step State
1. Full 54-route parity + 76 automated tests + clippy -D warnings DONE (c879ac4)
2. Side-by-side live shadow parity diff (22/22 read-only routes + SIGTERM drain) DONE
3. Live :1984 cutover (~/.sanctum/bin/sanctum-firewalla-bin, manifest 30/30, sentinels green) DONE (2026-11-22)
4. Soak period with instant Node fallback preserved ACTIVE

Now when Force Flow enforces bedtime curfew, Windu quarantines an unknown host over MCP, Yoda reviews household alarms, or the Holocron health panel polls the gatehouse, the den’s Apple TV pauses on schedule because 76 automated checks and a live 22-route parity run proved it would — not because someone counted try/catch blocks by hand and hoped. The gate finally tells the truth about whether it is closed.