Repository navigation
Conversation
There was a problem hiding this comment.
💡 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".
| if (typeof updateId === "number") { | ||
| try { | ||
| await enqueueWebhook("telegram", String(updateId), body.value, opts.stateDir); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Fixed in e1bf93511 -- moved unauthorized() return before enqueueWebhook so unauthenticated payloads are never persisted.
Greptile SummaryThis PR adds a disk-backed durability layer for Telegram webhook payloads to prevent message loss during gateway restarts. Payloads are persisted to Critical security issue: Webhook payloads are persisted to disk before the Minor cleanup issue: Orphaned The queue implementation itself is solid (atomic writes, sorted/deduped replay, 1h staleness cleanup, ENOENT-safe dequeue). Confidence Score: 1/5
Last reviewed commit: 130c8b8 |
| // 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. | ||
| } | ||
| } |
There was a problem hiding this 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:
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.There was a problem hiding this comment.
Fixed in e1bf93511 -- secret validation now happens before any enqueue call. Unauthorized requests return 401 immediately.
| for (const file of files) { | ||
| if (!file.endsWith(".json")) { | ||
| continue; | ||
| } |
There was a problem hiding this 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:
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.There was a problem hiding this comment.
Fixed in e1bf93511 -- added .tmp file cleanup in replayPendingWebhooks (scans for stale .tmp files older than 60s and removes them).
130c8b8 to
e1bf935
Compare
There was a problem hiding this comment.
💡 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".
| } | ||
|
|
||
| // Sort oldest first. | ||
| entries.sort((a, b) => a.enqueuedAt - b.enqueuedAt); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Fixed in 766f8586e -- added deduplicationId.localeCompare() as deterministic tie-breaker for same-timestamp replay ordering.
There was a problem hiding this comment.
💡 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".
| : undefined; | ||
| if (typeof updateId === "number") { | ||
| try { | ||
| await enqueueWebhook("telegram", String(updateId), body.value, opts.stateDir); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
766f858 to
f5f2688
Compare
There was a problem hiding this comment.
💡 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".
| } | ||
| // Dequeue happens via onUpdateProcessed in the bot middleware. | ||
| // If handleUpdate threw before middleware ran, dequeue manually. | ||
| await dequeueWebhook("telegram", entry.deduplicationId, opts.stateDir).catch(() => {}); |
There was a problem hiding this comment.
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 👍 / 👎.
| highestCompletedUpdateId = updateId; | ||
| } | ||
| maybePersistSafeWatermark(); | ||
| opts.onUpdateProcessed?.(updateId); |
There was a problem hiding this comment.
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 👍 / 👎.
|
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. |
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
enqueueWebhook()writes the raw payload to~/.openclaw/webhook-queue/<deduplicationId>.jsonvia atomic rename (write to.tmp, thenrename)dequeueWebhook()deletes the file after successful processingreplayPendingWebhooks()scans the queue directory and re-dispatches any remaining payloads inenqueuedAtorder (withdeduplicationIdtie-breaking for same-timestamp bursts)Security
.tmpfiles (from crashes between write and rename) are cleaned up during replayConfig
No config needed - webhook queue activates automatically for Telegram webhook mode. Queue directory is created lazily on first webhook.