Files
hermes-agent/scripts
Teknium 57893add23 fix(whatsapp): challenge-first bridge auth on current main; cron senders read the token, bridge refuses without one
Builds on @fangliquanflq's #83432 (cherry-picked first commit; the remaining
eight commits were re-applied by hand because the adapter has since been
refactored into _probe_bridge_health / _reuse_running_bridge / _bridge_req /
_standalone_send). Port prompted by qwibitai/nanoclaw#4013, which closed the
same class (an unauthenticated loopback webhook) on their Discord bridge.

Why: the bridge binds 127.0.0.1 and checks the Host header, but loopback does
not identify the caller — any local process could GET /messages (read every
inbound) or POST /send (send as the user), and a process that bound the port
first and mirrored /health with the derivable scriptHash was adopted as the
bridge (#83395, #80096).

What:
- bridge.js: every route except GET /auth-proof requires
  `Authorization: Bearer <HERMES_WHATSAPP_BRIDGE_TOKEN>` (constant-time);
  /auth-proof answers HMAC(token, challenge); express.json() runs only after
  the gate; the bridge exits when spawned without a token; bridge_auth.js is
  folded into scriptHash so stale auth code is never adopted.
- adapter: per-session secret at platforms/whatsapp/session/.bridge-token
  (0600, created once under a cross-process lock), passed to the spawned
  bridge via env; _probe_bridge_health is challenge-first so an impostor
  never sees the bearer and is replaced; the long-lived aiohttp session
  carries the bearer as a default header, so every send/edit/media/typing/
  read/poll call is authenticated with no per-call-site change.
- _standalone_send (cron / `hermes send` out of process): READS the persisted
  token, never mints one (a bridge spawned without it would not know it) and
  reports "No WhatsApp bridge token" until the gateway has started once;
  pinned to 127.0.0.1 like the bridge's bind.
- docs: whatsapp.md "Bridge API authentication" + env-var reference row.

Live repro (real bridge.js + real impostor HTTP server, real aiohttp):
  origin/main: anon GET /messages 200, wrong bearer /health 200,
               impostor accepted by probe = true
  this branch: anon GET /messages 401, anon POST /send 401, wrong bearer 401,
               adapter probe real bridge ok=true / wrong token ok=false,
               impostor accepted = false, impostor saw bearer = false,
               impostor requests = [/auth-proof] only
Tests: 2 impostor invariants + adopted-with-bearer in test_whatsapp_stale_bridge
(red on origin/main adapter, green here); token lock + proof binding in
test_whatsapp_bridge_auth; standalone harness answers the challenge.
2026-11-12 03:08:11 +01:00
..