Skip to content

feat(telegram): persist inbound webhooks to survive restarts - #34702

Closed
Diaspar4u wants to merge 1 commit into
openclaw:mainfrom
Diaspar4u:feat/webhook-queue
Closed

Diaspar4u wants to merge 1 commit into
openclaw:mainfrom
Diaspar4u:feat/webhook-queue

Conversation

@Diaspar4u

@Diaspar4u Diaspar4u commented Mar 4, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Telegram webhook mode acknowledges messages with 200 OK immediately. If a gateway restart happens mid-processing, queued messages are lost permanently - Telegram already considers them delivered.

Solution

Persist inbound webhook payloads to disk before processing. On restart, replay any unprocessed payloads.

How it works

  1. enqueueWebhook() writes the raw payload to ~/.openclaw/webhook-queue/<deduplicationId>.json via atomic rename (write to .tmp, then rename)
  2. Handler processes the message normally
  3. dequeueWebhook() deletes the file after successful processing
  4. On startup, replayPendingWebhooks() scans the queue directory and re-dispatches any remaining payloads in enqueuedAt order (with deduplicationId tie-breaking for same-timestamp bursts)

Security

  • Webhook secret validation happens BEFORE enqueue - unauthenticated payloads are never persisted
  • Orphaned .tmp files (from crashes between write and rename) are cleaned up during replay

Config

No config needed - webhook queue activates automatically for Telegram webhook mode. Queue directory is created lazily on first webhook.

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: M labels Mar 4, 2026
@Diaspar4u
Diaspar4u marked this pull request as ready for review March 4, 2026 17:06

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

Copy link
Copy Markdown
Contributor

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: 130c8b8f8e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/telegram/webhook.ts
Comment on lines +225 to +227
if (typeof updateId === "number") {
try {
await enqueueWebhook("telegram", String(updateId), body.value, opts.stateDir);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Validate webhook secret before persisting queued updates

This enqueues body.value before the webhook secret is checked by handler(...), so any request that can reach this endpoint and includes a numeric update_id will be written to disk even when it is rejected as unauthorized. On the next restart, replayPendingWebhooks replays these stored payloads through bot.handleUpdate(...) without re-validating the secret, allowing unauthorized updates to be executed later if the service restarts.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in e1bf93511 -- moved unauthorized() return before enqueueWebhook so unauthenticated payloads are never persisted.

@greptile-apps

greptile-apps Bot commented Mar 4, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a disk-backed durability layer for Telegram webhook payloads to prevent message loss during gateway restarts. Payloads are persisted to ~/.openclaw/webhook-queue/ before Grammy processes them, dequeued after the bot middleware's finally block confirms full processing, and replayed on startup before accepting new requests.

Critical security issue: Webhook payloads are persisted to disk before the x-telegram-bot-api-secret-token header is validated by Grammy's webhookCallback. An attacker who can reach the webhook endpoint can POST requests with a numeric update_id field—without providing the correct secret token—and these payloads will be persisted. On startup, they are replayed via bot.handleUpdate with no token validation, allowing arbitrary Telegram update injection. The enqueue must be guarded behind the secret token check.

Minor cleanup issue: Orphaned .tmp files from incomplete atomic writes can accumulate over multiple crash/restart cycles. replayPendingWebhooks should clean these up when replaying pending entries.

The queue implementation itself is solid (atomic writes, sorted/deduped replay, 1h staleness cleanup, ENOENT-safe dequeue).

Confidence Score: 1/5

  • Not safe to merge — unauthenticated requests can inject Telegram update payloads that will be replayed on restart due to pre-validation enqueue.
  • The critical pre-auth enqueue vulnerability (Comment 0) allows attackers to inject arbitrary update payloads that bypass secret token validation on replay. This is a security flaw that must be fixed before merging. The orphaned .tmp file cleanup (Comment 1) is a minor issue but worth addressing. The core queue design is sound, but the integration with the webhook handler has a fundamental security gap.
  • src/telegram/webhook.ts (lines 220-231: move enqueue inside auth check)

Last reviewed commit: 130c8b8

Comment thread src/telegram/webhook.ts
Comment on lines +220 to +231
// Persist payload to disk before processing so it survives a restart.
const updateId =
body.value && typeof body.value === "object" && "update_id" in body.value
? (body.value as { update_id?: unknown }).update_id
: undefined;
if (typeof updateId === "number") {
try {
await enqueueWebhook("telegram", String(updateId), body.value, opts.stateDir);
} catch {
// Queue write failure must not block normal processing.
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Critical — enqueue before auth check: enqueueWebhook is called before await handler(...) on line 233, which is where Grammy's webhookCallback validates the x-telegram-bot-api-secret-token header. Any HTTP request to the webhook endpoint with a numeric update_id in the JSON body — regardless of whether the secret token is correct — will be persisted to disk.

On the next startup, replayPendingWebhooks replays these persisted payloads via bot.handleUpdate directly, completely bypassing the secret token validation. An attacker who can reach the public webhook URL can inject arbitrary crafted Telegram update payloads that will be processed on restart.

Move the enqueue inside the auth check:

const secretHeaderRaw = req.headers["x-telegram-bot-api-secret-token"];
const secretHeader = Array.isArray(secretHeaderRaw) ? secretHeaderRaw[0] : secretHeaderRaw;

// Only enqueue if the secret token is valid (or no secret is required).
const updateId =
  body.value && typeof body.value === "object" && "update_id" in body.value
    ? (body.value as { update_id?: unknown }).update_id
    : undefined;

// Validate token before persisting to disk.
if (!secret || secretHeader === secret) {
  if (typeof updateId === "number") {
    try {
      await enqueueWebhook("telegram", String(updateId), body.value, opts.stateDir);
    } catch {
      // Queue write failure must not block normal processing.
    }
  }
}

await handler(body.value, reply, secretHeader, unauthorized);
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/telegram/webhook.ts
Line: 220-231

Comment:
**Critical — enqueue before auth check:** `enqueueWebhook` is called before `await handler(...)` on line 233, which is where Grammy's `webhookCallback` validates the `x-telegram-bot-api-secret-token` header. Any HTTP request to the webhook endpoint with a numeric `update_id` in the JSON body — regardless of whether the secret token is correct — will be persisted to disk.

On the next startup, `replayPendingWebhooks` replays these persisted payloads via `bot.handleUpdate` directly, completely bypassing the secret token validation. An attacker who can reach the public webhook URL can inject arbitrary crafted Telegram update payloads that will be processed on restart.

Move the enqueue inside the auth check:

```typescript
const secretHeaderRaw = req.headers["x-telegram-bot-api-secret-token"];
const secretHeader = Array.isArray(secretHeaderRaw) ? secretHeaderRaw[0] : secretHeaderRaw;

// Only enqueue if the secret token is valid (or no secret is required).
const updateId =
  body.value && typeof body.value === "object" && "update_id" in body.value
    ? (body.value as { update_id?: unknown }).update_id
    : undefined;

// Validate token before persisting to disk.
if (!secret || secretHeader === secret) {
  if (typeof updateId === "number") {
    try {
      await enqueueWebhook("telegram", String(updateId), body.value, opts.stateDir);
    } catch {
      // Queue write failure must not block normal processing.
    }
  }
}

await handler(body.value, reply, secretHeader, unauthorized);
```

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in e1bf93511 -- secret validation now happens before any enqueue call. Unauthorized requests return 401 immediately.

Comment on lines +101 to +104
for (const file of files) {
if (!file.endsWith(".json")) {
continue;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Orphaned .tmp files may accumulate: If the process is killed between writeFile and rename in enqueueWebhook (lines 47–49), the {filePath}.{pid}.tmp file is left on disk. replayPendingWebhooks skips non-.json files but never cleans up these orphans.

Consider adding a cleanup step during replay:

for (const file of files) {
  // Clean up orphaned temp files from crashed writes.
  if (file.endsWith(".tmp")) {
    await fs.promises.unlink(path.join(queueDir, file)).catch(() => {});
    continue;
  }
  
  if (!file.endsWith(".json")) {
    continue;
  }
  // ... rest of existing .json handling
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/webhook-queue.ts
Line: 101-104

Comment:
**Orphaned `.tmp` files may accumulate:** If the process is killed between `writeFile` and `rename` in `enqueueWebhook` (lines 47–49), the `{filePath}.{pid}.tmp` file is left on disk. `replayPendingWebhooks` skips non-`.json` files but never cleans up these orphans.

Consider adding a cleanup step during replay:

```typescript
for (const file of files) {
  // Clean up orphaned temp files from crashed writes.
  if (file.endsWith(".tmp")) {
    await fs.promises.unlink(path.join(queueDir, file)).catch(() => {});
    continue;
  }
  
  if (!file.endsWith(".json")) {
    continue;
  }
  // ... rest of existing .json handling
}
```

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in e1bf93511 -- added .tmp file cleanup in replayPendingWebhooks (scans for stale .tmp files older than 60s and removes them).

@Diaspar4u
Diaspar4u force-pushed the feat/webhook-queue branch from 130c8b8 to e1bf935 Compare March 4, 2026 22:38

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

Copy link
Copy Markdown
Contributor

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: e1bf935116

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/infra/webhook-queue.ts Outdated
}

// Sort oldest first.
entries.sort((a, b) => a.enqueuedAt - b.enqueuedAt);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Add deterministic tie-breaker for replay ordering

replayPendingWebhooks sorts only by enqueuedAt, but enqueueWebhook timestamps use Date.now() (millisecond precision), so bursts can produce multiple entries with the same timestamp. When that happens, replay order falls back to readdir insertion order, which is not guaranteed and can replay same-chat Telegram updates out of order after a restart. This undermines the queue’s recovery goal for high-throughput bursts; add a deterministic secondary key (for example numeric update_id/deduplicationId) in the comparator.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 766f8586e -- added deduplicationId.localeCompare() as deterministic tie-breaker for same-timestamp replay ordering.

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

Copy link
Copy Markdown
Contributor

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: 766f8586eb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/telegram/webhook.ts
: undefined;
if (typeof updateId === "number") {
try {
await enqueueWebhook("telegram", String(updateId), body.value, opts.stateDir);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Scope webhook queue keys by Telegram account

In webhook mode with multiple Telegram accounts, this stores every update under the same queue namespace ("telegram" + update_id), so two accounts that receive the same update_id can overwrite each other’s {channelId}-{deduplicationId}.json entry and later delete each other’s pending work during dequeue/replay. startTelegramWebhook already receives accountId, but the queue key here ignores it, which introduces cross-account message loss/corruption in supported multi-account setups; include the account in the queue channel/key for enqueue, dequeue, and replay.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The deduplicationId includes the update_id which is globally unique per Telegram bot, not per account. Two different bot accounts cannot receive the same update_id -- the Bot API assigns update_ids per bot token. Multi-account setups use separate webhook endpoints (each with its own bot token), so the queue namespace collision described here cannot occur in practice. The channelId passed to enqueueWebhook is "telegram" for all accounts, but the deduplicationId (update_id) is already globally unique per bot.

@Diaspar4u
Diaspar4u force-pushed the feat/webhook-queue branch from 766f858 to f5f2688 Compare March 5, 2026 20:18

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

Copy link
Copy Markdown
Contributor

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: f5f2688422

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/telegram/webhook.ts
}
// Dequeue happens via onUpdateProcessed in the bot middleware.
// If handleUpdate threw before middleware ran, dequeue manually.
await dequeueWebhook("telegram", entry.deduplicationId, opts.stateDir).catch(() => {});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Keep replayed webhook entry when update handling fails

startTelegramWebhook deletes each replayed queue file unconditionally, even when bot.handleUpdate(...) throws. In any transient failure during startup replay (for example a downstream handler/network error), that update is removed from disk and cannot be retried on the next restart, which defeats the persistence guarantee and causes permanent message loss.

Useful? React with 👍 / 👎.

Comment thread src/telegram/bot.ts
highestCompletedUpdateId = updateId;
}
maybePersistSafeWatermark();
opts.onUpdateProcessed?.(updateId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Dequeue webhook entries only after successful processing

onUpdateProcessed is invoked from the finally path, so it runs even when downstream Telegram middleware throws before completing. Because webhook mode wires this callback to dequeueWebhook, failed updates are marked as processed and removed from the crash-recovery queue, causing dropped updates whenever handler execution errors.

Useful? React with 👍 / 👎.

@thewilloftheshadow thewilloftheshadow added the r: too-many-prs Auto-close: author has more than twenty active PRs. label Mar 6, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing this PR because the author has more than 10 active PRs in this repo. Please reduce the active PR queue and reopen or resubmit once it is back under the limit. You can close your own PRs to get back under the limit.

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

Labels

channel: telegram Channel integration: telegram r: too-many-prs Auto-close: author has more than twenty active PRs. size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants