Skip to content

channels: LINE bot — webhook receiver mounted on the gateway (Wave 1.5a) - #76

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

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

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

First two-way IM bot beyond Telegram. PR #75 shipped LINE push; this PR closes the loop with a webhook receiver that runs the agent and replies. Three things landed together because all three are needed for any future webhook-based channel (WhatsApp Cloud is next).

1. Gateway "mount webhook" API

TGatewayServer.MountWebhook(Path, Handler) registers an exact-match POST route. The new DispatchWebhook is called from OnCommandGet just before the 404 fall-through, so the channel piggybacks on the same Indy listener PasClaw already runs for /v1 — no second TCP port, no second TLS config, no second auth scheme.

type
  TWebhookHandler = procedure(AContext: TIdContext;
                              ARequest: TIdHTTPRequestInfo;
                              AResponse: TIdHTTPResponseInfo) of object;

Handlers own their own response — signature check, parse, run the agent loop, write the reply. The dispatcher does not authenticate on their behalf.

2. Pure-Pascal SHA-256 + HMAC-SHA-256

src/pkg/crypto/PasClaw.Crypto.HMAC.pas. Indy's TIdHMACSHA256 routes through OpenSSL's EVP_sha256 and OpenSSL 3's export layout is flaky to detect at load time — Indy's IsAvailable returned False even with libssl.so.3 fully loaded. Doing the primitive ourselves removes the whole class of failure mode and runs identical under FPC {$MODE DELPHI} and Delphi 12. Zero native deps, zero compile-time hash unit picker.

Verified against openssl dgst -sha256 -hmac:

HMAC-SHA256("key", "The quick brown fox jumps over the lazy dog")
  hex:    f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
  base64: 97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg=

Includes ConstantTimeEqual for signature compares (never = — early-out leaks one byte at a time).

3. TLineBot

Sits alongside the existing TLinePush in PasClaw.Channels.LINE. Holds Cfg / Provider / Registry directly (mirrors TTelegramChannel — no callback indirection, no abstract bridge). HandleWebhook:

  1. Reads the raw request body — signature is over bytes, not the parsed JSON.
  2. Verifies X-Line-Signature via ConstantTimeEqual(HMACSHA256Base64(secret, body), header).
  3. Returns 401 {"error":"signature"} on mismatch.
  4. Returns 200 immediately so LINE doesn't retry on internal errors (their retry storms duplicate replies).
  5. Parses each event; for type=message + message.type=text, runs RunToolLoop with the user text.
  6. Replies via /v2/bot/message/reply using the one-shot replyToken (free + fast inside ~30 s) and falls back to /v2/bot/message/push when the token expired because the tool loop took longer.

Source ID picks userId / groupId / roomId in order — fallback push works for any chat type.

CLI

pasclaw gateway --line                                    # env: $PASCLAW_LINE_TOKEN + $PASCLAW_LINE_SECRET
pasclaw gateway --line --line-token X --line-secret Y     # explicit

Gateway banner prints POST http://…/webhooks/line (LINE platform) when --line is on, so the URL is copy-pasteable straight into LINE Developers Console.

Build

  • Makefile UNIT_DIRS gains src/pkg/crypto.
  • PasClaw.dproj DCC_UnitSearchPath gains ..\pkg\crypto; DCCReference entry for PasClaw.Crypto.HMAC.pas.
  • README env-var table picks up LINE_TOKEN / LINE_SECRET; gateway example block grows --line.

Verification

  • make — clean build under FPC 3.2.2.
  • HMAC smoke test against openssl dgst -sha256 -hmac: RFC test vector hex + base64, empty-input vector, 4 constant-time equality cases — all 7 pass.
  • pasclaw --help and pasclaw gateway (without --line) byte-identical to pre-change.

Wave 1.5b ahead

WhatsApp Cloud receiver lands next on top of this same MountWebhook API and HMAC helper. WhatsApp adds a GET subscription-verification handler (hub.challenge echo) and uses X-Hub-Signature-256 with hex-encoded HMAC + sha256= prefix; the HMAC primitive already supports both encodings.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

First two-way IM bot beyond Telegram. picoclaw's `line` channel
brought into PasClaw by adding three things at once:

1. A gateway "mount webhook" API. TGatewayServer.MountWebhook(Path,
   Handler) registers an exact-match POST route that runs Handler
   (procedure(AContext; ARequest; AResponse) of object) when a
   client posts to it. DispatchWebhook walks the registry from
   OnCommandGet just before the 404 fall-through, so the channel
   reuses the same Indy listener PasClaw already runs for /v1 —
   no second TCP port, no second TLS config, no second auth shape.

2. A pure-Pascal SHA-256 + HMAC-SHA-256 in
   src/pkg/crypto/PasClaw.Crypto.HMAC.pas. Indy's TIdHMACSHA256
   routes through OpenSSL's EVP_sha256, and the OpenSSL 3 export
   shape is flaky to detect at load time (Indy's IsAvailable
   returned False even with OpenSSL 3.0 fully loaded). Doing the
   primitive ourselves removes the whole class of failure mode and
   runs identical under FPC ({$MODE DELPHI}) and Delphi 12 — no
   native deps, no compile-time hash unit picker. Includes a
   constant-time string equality helper since signature compares
   must not early-out on the first byte mismatch.

   Verified against openssl: same hex + base64 output for the
   RFC HMAC-SHA-256("key", "The quick brown fox jumps over the
   lazy dog") test vector.

3. TLineBot in PasClaw.Channels.LINE alongside the existing
   TLinePush. The bot holds Cfg / Provider / Registry directly
   (mirrors TTelegramChannel — no callback indirection, no
   abstract bridge) and exposes HandleWebhook(AContext; ARequest;
   AResponse) which:
     - reads the raw request body (signature is over bytes, not
       the parsed JSON);
     - verifies X-Line-Signature with constant-time-equal HMAC
       against the channel secret;
     - returns 401 with {"error":"signature"} on mismatch;
     - returns 200 immediately so LINE doesn't retry on internal
       errors (their retry storms duplicate replies);
     - parses each event, runs RunToolLoop with the user text;
     - replies via /v2/bot/message/reply using the one-shot
       replyToken (free + fast inside ~30 s) and falls back to
       /v2/bot/message/push when the reply token has already
       expired because the tool loop ran long.

Gateway wiring:
  pasclaw gateway --line                       # default ports
  pasclaw gateway --line --line-token X --line-secret Y
  $PASCLAW_LINE_TOKEN / $PASCLAW_LINE_SECRET as the env fallback.

The user-facing console banner now also prints
  POST http://.../webhooks/line   (LINE platform)
when --line is on, so the user can copy the URL straight into LINE
Developers Console.

Build:
  Makefile UNIT_DIRS gains src/pkg/crypto; .dproj DCCReferences
  gain PasClaw.Crypto.HMAC and the unit search path gets the new
  ..\pkg\crypto entry. README's env-var table picks up LINE_TOKEN
  / LINE_SECRET, the gateway example block grows a --line line.

Verified locally:
  make builds clean (FPC 3.2.2).
  hmac smoke vs openssl: hex + base64 + empty-input + 4
  constant-time equality cases all pass.
  pasclaw --help and pasclaw gateway plain (no --line) behave
  byte-identically to pre-change.

Wave 1.5b (WhatsApp Cloud receiver) lands next on top of this same
MountWebhook API plus the HMAC helper.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 89a2d73 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: f049f9d3d1

ℹ️ 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".

EvObj := Events.ItemObject(i);
if EvObj = nil then Continue;
try
ProcessEvent(EvObj.ToJSON);

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 LINE webhooks before running the agent

When a LINE event triggers a slow model/tool call, this synchronous ProcessEvent call keeps the HTTP response unsent until RunToolLoop and the reply/push API call finish; the ResponseNo := 200 set above is not actually flushed until HandleWebhook returns. In those slow cases LINE treats the delivery as timed out and retries the same event, so this handler can run the agent multiple times and send duplicate replies despite the comment about avoiding retries. Consider returning 200 before the expensive work or deduplicating/enqueuing webhook events.

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