edgefetch

module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT

README

EdgeFetch

CI

Deploy to Cloudflare   Open your Home Assistant instance and show the add app repository dialog with EdgeFetch pre-filled.

EdgeFetch is a security-hardened Go HTTP/2 fetcher and outbound-only distributed standby worker (one Go dependency, with no transitive dependencies) paired with a Cloudflare Hibernating WebSocket Durable Object coordinator (hub/ — complete with a built-in /admin Control Center and self-hosted OAuth 2.1 /mcp server) and a 1-click Home Assistant OS Add-on.

It solves a practical distributed-systems problem: keeping scheduled public feed/document syncs resilient across primary cloud containers (--mode=server) and geo-distributed standby hardware (--mode=agent) without opening inbound router ports, running forward HTTP/SOCKS proxies, or installing VPN/tunnel daemons.


Why EdgeFetch?

  • Minimal Go Supply Chain (One Dependency, Zero Transitive Dependencies): HTTP/2 connection pooling, net/http/httptrace phase telemetry, RFC 9309 robots.txt longest-match + unreachable-disallow evaluation, RFC 9110 Retry-After parsing, three-state circuit breaking, and Linux prctl + setuid privilege dropping use the Go standard library plus github.com/coder/websocket (zero transitive dependencies).
  • Strict Hub / Edge Security Split (~$0 Idle Cloud Cost):
    • Edge Nodes (amd64 / aarch64) host zero inbound HTTP, /admin, or /mcp endpoints. They dial outbound wss:// to /agent/ws, where Cloudflare's WebSocketRequestResponsePair("ping", "pong") answers 30-second keepalives at the edge without waking the Durable Object from hibernation.
    • Cloudflare Hub (hub/) is the sole public control plane — hosting POST /fetch, GET /agents, the /admin Web Control Center, and the OAuth 2.1 /mcp server for Claude Code.
  • Split Control / Data Plane for Asymmetric Links: Small JSON dispatch commands arrive over the hibernated WebSocket (< 1 MiB UTF-8 verified before send), while 0.4–16 MiB HTML/JSON responses (16 MiB default per-batch body budget, lossless bodyEncoding: "utf-8" | "base64") stream back via gzip-compressed HTTP/2 POST /agent/reply (45 s normal upload budget, 10 s shutdown-drain cap so completed results are never lost on SIGTERM).
  • Defense-in-Depth Security (SECURITY.md):
    • Dial-time net.Dialer.Control SSRF guard (RejectNonPublicPeer backed by net/netip) inspects the exact resolved IP right before connect() — eliminating DNS-rebinding TOCTOU races, restricting IPv6 strictly to 2000::/3 global unicast, and blocking 0.0.0.0/8, RFC 1918 LANs (including Home Assistant's 172.30.32.0/23 bridge), loopback, Tailscale/CGNAT (100.64.0.0/10), cloud metadata (169.254.169.254), 6to4 relay (192.88.99.0/24), site-local (fec0::/10), ORCHID/ORCHIDv2 (2001:10::/28, 2001:20::/28), documentation (2001:db8::/32, 3fff::/20), SRv6 (5f00::/16), and IPv6-embedded IPv4 transition prefixes (::/96, 0:0:0:0:ffff:0::/96, 64:ff9b::/96 NAT64, 2002::/16 6to4, 2001::/32 Teredo).
    • Irreversible Linux privilege drop (PR_SET_NO_NEW_PRIVS -> Setgroups([]) -> Setgid(65532) -> Setuid(65532) via AllThreadsSyscall6) inside a ~9 MB shell-free distroless image built reproducibly from the checked-out commit and confined by a custom Home Assistant AppArmor profile.
    • Strictly separated least-privilege tokens (CALLER_TOKEN, per-site AGENT_TOKENS, and mandatory EDGEFETCH_SERVER_TOKEN on non-loopback --mode=server binds) verified in constant time, plus pre-verified jobId + jobNonce binding.

Architecture

flowchart TD
    Admin["Browser (/admin Control Center)"] -->|"HMAC Session + CSRF"| HubW["Cloudflare Hub Worker + AgentHubDO (SQLite)"]
    Claude["Claude Code (/mcp)"] -->|"Self-Hosted OAuth 2.1 + PKCE S256"| HubW
    Caller["Upstream Workflow / Cron"] -->|"POST /fetch (Bearer CALLER_TOKEN)"| HubW
    HubW -->|"1. Primary: LRU Load-Balanced Dispatch"| S1["Site 1 HAOS / Docker (amd64 — outbound only)"]
    HubW -->|"1. Primary: LRU Load-Balanced Dispatch"| S2["Site 2 HAOS / ARM64 (aarch64 — outbound only)"]
    HubW -->|"1. Primary: LRU Load-Balanced Dispatch"| S3["Site 3 HAOS / Baremetal (amd64 — outbound only)"]
    HubW -.->|"2. Overflow ONLY if Remote Nodes hit HTTP 429"| CloudGo["Cloudflare Egress / Container"]
    S1 -.->|"POST /agent/reply (gzip FetchReply)"| HubW
    S2 -.->|"POST /agent/reply (gzip FetchReply)"| HubW
    S3 -.->|"POST /agent/reply (gzip FetchReply)"| HubW

Package Layout

Package Responsibility
cmd/edgefetch Dual-mode binary entrypoint (server vs outbound-only agent), HTTP/2 transport tuning, SIGTERM graceful drain
internal/politeness Context-cancellable chan struct{} per-host locks, robots.txt cache, 3-state circuit breaker, RejectNonPublicPeer SSRF hook
internal/classify Defined string enums (Kind, Outcome) and panic-free JSON/HTML response classification
internal/crawl Bounded worker pool, positive dwell jitter (PauseJitterMs), httptrace phase timing, io.LimitReader(max+1), /fetch handler
internal/ws Hardened coder/websocket client (http/1.1 ALPN, classic ECDHE TLS curves, no redirect token leakage, 1 MiB ceiling)
internal/priv Linux prctl(PR_SET_NO_NEW_PRIVS) + AllThreadsSyscall irreversible root drop (65532:65532)
internal/agent /data/options.json + env loader, jittered reconnect supervisor, agent_hello OTel telemetry, gzipped reply uploader
edgefetch_agent/ Multi-arch (amd64 + aarch64) Home Assistant OS Add-on manifest, apparmor.txt, and distroless Dockerfile
hub/ Cloudflare Hub Worker + AgentHubDO SQLite coordinator + /admin Web UI + Self-Hosted OAuth 2.1 /mcp server

Benchmarks (go test -bench=. -benchmem ./...)

Measured on Linux amd64 (12th Gen Intel Core i9-12900K, Go 1.27):

Benchmark Latency Heap Allocations
BenchmarkParseRetryAfter 4.45 ns/op 0 B/op (0 allocs/op)
BenchmarkRobotsMatch (* wildcards + $ anchor) 52.17 ns/op 0 B/op (0 allocs/op)
BenchmarkIsPublicIP (IPv4 + NAT64 IPv6 check) 155.50 ns/op 0 B/op (0 allocs/op)
BenchmarkClassifyFeedJSON 1,229 ns/op 1,416 B/op (28 allocs/op)

Quickstart (1-Click Easy Buttons)

1. 1-Click Deploy the Cloudflare Hub (hub/)

Deploy to Cloudflare

Clicking Deploy to Cloudflare clones hub/, provisions AgentHubDO (SQLite), and interactively prompts you in the Cloudflare dashboard for CALLER_TOKEN and AGENT_TOKENS (defined in hub/.dev.vars.example and hub/package.json).

Or deploy from your terminal (or .github/workflows/deploy-hub.yml with CLOUDFLARE_API_TOKEN):

cd hub
npm ci
npx wrangler deploy -c wrangler.toml
npx wrangler secret put CALLER_TOKEN -c wrangler.toml
npx wrangler secret put AGENT_TOKENS -c wrangler.toml
# Example AGENT_TOKENS JSON: {"site-1":"<32-char-random>","site-2":"<32-char-random>"}
2. 1-Click Install on Home Assistant OS (amd64 & aarch64)

Open your Home Assistant instance and show the add app repository dialog with EdgeFetch pre-filled.

  1. Click Add Repository to My Home Assistant above (or manually open Settings -> Add-ons -> Add-on Store -> ⋮ -> Repositories and add https://github.com/bartrumb/edgefetch).
  2. Install EdgeFetch Cold-Standby Worker, open Configuration, set hub_url, agent_token, site_id, and user_agent, and click Start.
3. Drive, Monitor & Tune After Setup (Full Reference in docs/USAGE.md)
  • Web Control Center (/admin): Open https://<your-hub>.workers.dev/admin and sign in with CALLER_TOKEN to view live connected edge nodes, 30-minute SQLite host-sticky affinity pins, per-site/IP 429 cooldowns, active OAuth grants, and an interactive URL Crawl Tester with a visual DNS / TCP / TLS / TTFB waterfall bar.
  • Connect Directly to Claude Code (/mcp with Self-Hosted OAuth 2.1 + PKCE):
    claude mcp add --transport http edgefetch https://<your-hub>.workers.dev/mcp
    
    Claude Code auto-discovers RFC 9728 / RFC 8414 metadata, dynamically registers (POST /oauth/register), and opens /oauth/authorize in your browser to grant list_agents, fetch_url, and fetch_batch tools — zero external IdP, zero separate KV namespace, and zero raw tokens stored in config files.
  • Trigger Polite Crawls via REST (POST /fetch):
    curl -X POST "https://<your-hub>.workers.dev/fetch?site=site-1" \
      -H "Authorization: Bearer $CALLER_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"options":{"includeBody":true,"respectRobots":true,"pauseMs":1500},"requests":[{"id":"1","url":"https://example.com/","kind":"page"}]}'
    
  • Single-Pane-of-Glass Logs & Traces: Open Cloudflare Dashboard -> Workers & Pages -> edgefetch-hub -> Observability to query OpenTelemetry traces and structured JSON logs across every site.

Ethical Crawling, Public-IP Host Affinity & Polite 429 Failover

EdgeFetch is an honest, rate-limited HTTP fetcher — never a stealth scraper or anti-bot bypass tool:

  • Honest Identity & Standard TLS: Always sends a transparent, configurable User-Agent (validated printable ASCII) and standard Go net/http TLS/HTTP2 stacks; never solves CAPTCHAs or spoofs browser fingerprints.
  • /robots.txt Enforced on Every Hop (RFC 9309): Both Go (--mode=server / --mode=agent) and the Cloudflare Hub overflow enforce /robots.txt (512 KiB parse cap, UTF-8 BOM stripping, RFC 9309 §2.2.2 percent-encoding normalization, exact User-agent product-token matching, Allow/Disallow longest-match, Crawl-delay, and §2.3.1.4 complete-disallow on 429/5xx/unreachable) on the initial request and every redirect hop (up to 5). Callers cannot disable robots.txt unless the owner explicitly configures ROBOTS_BYPASS_HOSTS / EDGEFETCH_ROBOTS_BYPASS_HOSTS (empty by default, audited in hub_events).
  • Public-IP Load Splitting + 30-Minute Host-Sticky Affinity: AgentHubDO groups connected edge nodes by verified public egress IP (cf-connecting-ip), assigns each origin host to the Least-Recently-Used public IP group, and pins that host for 30 minutes so requests to a single origin never rotate addresses (preserving warm HTTP/2 connections), while distinct origins split evenly across distinct public IPs. Concurrent requests to the same host serialize through a race-free in-DO FIFO lock (withHostLocks).
  • Refusals vs. Polite 429 Cooldown & Wait:
    • 403, 503, and anti-bot challenges (cf-mitigated) stop immediately with zero retries anywhere.
    • On HTTP 429, AgentHubDO cools down both siteId and ip:<publicIp> in SQLite (site_cooldowns) so sibling nodes behind the same WAN IP are skipped, and waits out the origin's full Retry-After window (or a 15 s default throttle pause when Retry-After is absent) inside the host lock before any failover node or Cloudflare overflow re-attempts that host. If Retry-After exceeds the request's maxSeconds budget, the 429 is returned directly to the caller without failing over. Pin ?target=agent&site=<id> whenever single-IP non-failover behavior is desired.

License

MIT

Directories

Path Synopsis
cmd
edgefetch command
Command edgefetch is a minimal-supply-chain HTTP/2 crawler (one Go dependency, with no transitive dependencies) that runs in two modes from one static binary:
Command edgefetch is a minimal-supply-chain HTTP/2 crawler (one Go dependency, with no transitive dependencies) that runs in two modes from one static binary:
internal
agent
Package agent implements the outbound-only WebSocket worker loop for Home Assistant OS and edge standby nodes.
Package agent implements the outbound-only WebSocket worker loop for Home Assistant OS and edge standby nodes.
classify
Package classify categorizes HTTP responses into deterministic crawl outcomes (ok, challenge, stop, gone, skip, error, not_tried) before upstream parsers inspect response bodies.
Package classify categorizes HTTP responses into deterministic crawl outcomes (ok, challenge, stop, gone, skip, error, not_tried) before upstream parsers inspect response bodies.
crawl
Package crawl implements a bounded-concurrency, polite HTTP/2 fetcher with net/http/httptrace phase telemetry, positive dwell jitter, conditional GETs (ETag / If-Modified-Since), and strict memory/SSRF guardrails.
Package crawl implements a bounded-concurrency, polite HTTP/2 fetcher with net/http/httptrace phase telemetry, positive dwell jitter, conditional GETs (ETag / If-Modified-Since), and strict memory/SSRF guardrails.
politeness
Package politeness enforces per-origin serialization, Retry-After cooldowns, three-state circuit breaking, RFC 9309 robots.txt caching, and dial-time DNS-rebinding SSRF protection (net.Dialer.Control).
Package politeness enforces per-origin serialization, Retry-After cooldowns, three-state circuit breaking, RFC 9309 robots.txt caching, and dial-time DNS-rebinding SSRF protection (net.Dialer.Control).
priv
Package priv implements irreversible root privilege dropping on Linux containers.
Package priv implements irreversible root privilege dropping on Linux containers.
ws
Package ws wraps github.com/coder/websocket behind EdgeFetch's outbound control-plane contract: HTTP/1.1 ALPN upgrade, classic ECDHE TLS curves, zero ambient proxy inheritance, no redirect token leakage, disabled per-message compression, 1 MiB message ceiling, and io.EOF peer-close normalization.
Package ws wraps github.com/coder/websocket behind EdgeFetch's outbound control-plane contract: HTTP/1.1 ALPN upgrade, classic ECDHE TLS curves, zero ambient proxy inheritance, no redirect token leakage, disabled per-message compression, 1 MiB message ceiling, and io.EOF peer-close normalization.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL