Skip to content

channels: WhatsApp Cloud bot — webhook receiver mounted on the gateway (Wave 1.5b) - #77

Merged
FMXExpress merged 1 commit into
mainfrom
claude/channels-whatsapp-bot
May 29, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/channels-whatsapp-bot

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Reuses everything Wave 1.5a put in place: TGatewayServer.MountWebhook, the pure-Pascal PasClaw.Crypto.HMAC helper, and the "hold Cfg/Provider/Registry directly, run RunToolLoop inline" bot shape that mirrors TTelegramChannel and TLineBot. Future channels (Matrix, VK, …) plug in the same way.

Three concrete differences from LINE that the unit addresses

1. Signature header shape

Channel Header Encoding
LINE X-Line-Signature base64, no prefix
WhatsApp X-Hub-Signature-256 sha256=<hex>

PasClaw.Crypto.HMAC already supports both encodings. The bot strips the sha256= prefix, recomputes the hex digest with the App Secret, and ConstantTimeEquals against the remainder.

2. Same URL serves both verbs

GET  /webhooks/whatsapp   →  Meta's subscription verification handshake.
                              Pulls hub.mode, hub.verify_token,
                              hub.challenge from query params; if
                              mode=subscribe and verify_token matches
                              (constant-time), echoes the challenge back
                              as text/plain with 200, otherwise 403.
                              The body MUST be the raw challenge —
                              Meta parses it as text; JSON-wrapping it
                              breaks the verify.

POST /webhooks/whatsapp   →  message events.

DispatchWebhook used to short-circuit on non-POST. Dropped that guard so handlers self-check the verb; added a defensive 405 to LINE's HandleWebhook so a misconfigured GET probe doesn't get a silent 404.

3. Deeper event nesting

LINE: events[].message.text. WhatsApp:

entry[].changes[].value.messages[]{from, type, text.body, …}

ProcessMessage runs RunToolLoop on text-type messages and sends the reply via the same Cloud API messages endpoint TWhatsAppPush already uses — no replyToken mechanism, every reply is a fresh send.

CLI

pasclaw gateway --whatsapp                      # env vars below
pasclaw gateway --whatsapp \
  --whatsapp-token X --whatsapp-phone Y \
  --whatsapp-verify Z --whatsapp-secret S

pasclaw post whatsapp 15551234567 "build done"
Env var Role
PASCLAW_WHATSAPP_TOKEN System-user access token
PASCLAW_WHATSAPP_PHONE_ID Phone-number ID (the numeric ID, not the phone number itself)
PASCLAW_WHATSAPP_VERIFY_TOKEN User-chosen verify string for hub.verify_token
PASCLAW_WHATSAPP_APP_SECRET Meta App Secret used to validate X-Hub-Signature-256

Gateway banner now prints ANY http://…/webhooks/whatsapp (WhatsApp Cloud) — "ANY" instead of "POST" so the user knows the same URL serves the GET subscription handshake.

Tidy-ups

  • Cmd.Post.Help grew the whatsapp row with env-var hints inline, matching the existing line / webhook rows; dispatch table aligned.
  • README env-var table picks up the four WHATSAPP_* entries; gateway example block grows --whatsapp; command-surface post row mentions WhatsApp; repo-layout channels/ line spells out the full set.

Verification

  • make — clean build under FPC 3.2.2; dproj DCCReference added for the new unit; no Makefile change needed (channels dir already on UNIT_DIRS).
  • pasclaw post help lists whatsapp with the env-var hints.
  • pasclaw --help, pasclaw gateway (without --whatsapp), and pasclaw post discord/slack/teams/webhook/line all byte-identical to pre-change.
  • Signature primitives identical to PR channels: LINE bot — webhook receiver mounted on the gateway (Wave 1.5a) #76 — HMACSHA256HexLower already covered by the openssl smoke test that landed there.

What's left in picoclaw's catalog

After this PR, PasClaw covers 7 of picoclaw's 20 channels (Discord, Slack, Telegram, Teams, generic webhook, LINE, WhatsApp). Realistic next waves (excluding Chinese-ecosystem auth, hardware-specific, and *_native variants):

  • Wave 3: Matrix (/sync long-poll), IRC (raw TCP via TIdIRC), VK (long-poll bot API).
  • Wave 4: MQTT (Indy MQTT components).

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

…y (Wave 1.5b)

Reuses everything Wave 1.5a put in place: the gateway MountWebhook
API, the pure-Pascal HMAC-SHA-256 helper, the
"hold Cfg/Provider/Registry directly, run RunToolLoop inline" bot
shape that mirrors TTelegramChannel and TLineBot. The shape is
deliberately uniform so future channels (Matrix, VK, …) plug in the
same way.

WhatsApp Cloud differs from LINE in three concrete ways the unit
addresses:

  1. Signature header is X-Hub-Signature-256 with the value prefixed
     by "sha256=" and the digest hex-encoded (LINE: X-Line-Signature,
     no prefix, base64). PasClaw.Crypto.HMAC already supports both
     encodings; the bot strips the prefix, recomputes the hex digest
     with the App Secret, and ConstantTimeEquals against the
     remainder.

  2. The same URL serves BOTH verbs:
       GET  /webhooks/whatsapp  -> Meta's subscription verification
            handshake. The handler pulls hub.mode, hub.verify_token,
            hub.challenge from query params; if mode=subscribe and
            verify_token matches (constant-time), echo the challenge
            back as text/plain with 200, otherwise 403. The body
            MUST be the raw challenge — Meta parses it as text,
            wrapping in JSON breaks the verify.
       POST /webhooks/whatsapp  -> message events.
     TGatewayServer.DispatchWebhook used to short-circuit on
     non-POST. Drop that guard so handlers self-check the verb; add
     a defensive 405 in LINE's HandleWebhook so a misconfigured
     probe doesn't get a silent 404.

  3. Event JSON is nested deeper than LINE's:
       entry[].changes[].value.messages[]{from, type, text.body, …}
     ProcessMessage runs RunToolLoop on text-type messages and
     sends the reply via the same Cloud API messages endpoint
     TWhatsAppPush already uses — no replyToken mechanism, every
     reply is a fresh send.

Both TWhatsAppPush (outbound, used by `pasclaw post whatsapp`) and
TWhatsAppBot (mounted by `pasclaw gateway --whatsapp`) ship in
src/pkg/channels/PasClaw.Channels.WhatsApp.pas.

CLI:
  pasclaw gateway --whatsapp                    # env: TOKEN/PHONE_ID/VERIFY_TOKEN/APP_SECRET
  pasclaw gateway --whatsapp --whatsapp-token X --whatsapp-phone Y \
                              --whatsapp-verify Z --whatsapp-secret S
  pasclaw post whatsapp 15551234567 "build done"

  Env vars:
    PASCLAW_WHATSAPP_TOKEN        access token
    PASCLAW_WHATSAPP_PHONE_ID     phone-number-id (numeric)
    PASCLAW_WHATSAPP_VERIFY_TOKEN user-chosen verify string
    PASCLAW_WHATSAPP_APP_SECRET   Meta App Secret (for HMAC)

The gateway banner now prints
  ANY http://.../webhooks/whatsapp   (WhatsApp Cloud)
("ANY" instead of "POST" so the user knows the same URL serves the
GET subscription handshake too).

Other tidy-ups in this PR:

  - PasClaw.Cmd.Post.Help grew the whatsapp row with env-var hints
    inline, matching the existing line/webhook rows. Dispatch table
    is now aligned.
  - README env-var table adds the four WHATSAPP_ entries with
    one-line roles; gateway example block grows --whatsapp;
    command-surface `post` row mentions WhatsApp; repo-layout
    channels/ line spells out the full set.

Build: `make` clean under FPC 3.2.2; dproj DCCReference for the new
unit; no Makefile change needed (channels dir already on UNIT_DIRS).

Verified: `pasclaw post` help table lists whatsapp; existing
`pasclaw --help`, `pasclaw gateway` (without --whatsapp),
`pasclaw post discord/slack/teams/webhook/line` byte-identical.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 69c8383 into main May 29, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 69099e2e01

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

PasClaw.Crypto.HMAC;

const
WA_API_BASE = 'https://graph.facebook.com/v18.0';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use a supported Graph API version

On current 2026-05-29 builds this hard-codes every WhatsApp send and webhook reply to graph.facebook.com/v18.0/...; Meta retired Graph API v18.0 on January 26, 2026, so pasclaw post whatsapp and bot replies will receive API-version errors before reaching the messages endpoint. Please target a currently supported version or make the Graph API version configurable so the new channel works after version sunsets.

Useful? React with 👍 / 👎.

TextObj.Free;
end;
if (From_ = '') or (Text = '') then Continue;
ProcessMessage(From_, Text);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Acknowledge webhooks before running the model loop

For text messages this calls ProcessMessage, which runs RunToolLoop and performs the outbound send before the HTTP handler returns; Indy does not actually send the 200 response until the handler finishes. When the model or tools take longer than Meta's webhook timeout, Meta will treat the delivery as failed and retry it, causing duplicate processing/replies despite the earlier AResponse.ResponseNo := 200. Queue the work or otherwise flush/return the acknowledgement before doing the slow reply path.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants