Repository navigation
Conversation
Disk-backed webhook queue with atomic writes (tmp+rename), deferred dequeue for media groups and text fragments, and ordered replay on startup. Dedup key scoped to channelId+deduplicationId to prevent cross-channel collisions. Validate channelId in replay (clean up malformed entries). At-least-once delivery guarantee.
🔒 Aisle Security AnalysisWe found 3 potential security issue(s) in this PR:
1. 🟠 Unbounded deferred-work await can hang Telegram update completion (debouncer never flushes)
DescriptionThe new deferred-work tracking waits for all registered promises to settle before calling Key points:
Vulnerable code (awaiting deferred work without timeout/cap): const deferred = deferredWork.get(updateId);
if (deferred) {
deferredWork.delete(updateId);
await Promise.all(deferred);
}
opts.onUpdateProcessed?.(updateId);This is a denial-of-service risk because remote Telegram users can keep a conversation “hot” (never idle) and prevent the debounce from flushing, indefinitely postponing update completion and queue dequeue. RecommendationAdd hard limits so deferred-work cannot block indefinitely, and ensure debounced buffers eventually flush. Suggested hardening (do both):
// in createInboundDebouncer
const MAX_WAIT_MS = 2000; // example
const MAX_ITEMS = 50; // example
// store firstEnqueuedAt, and when scheduling, cap delay so flush happens by MAX_WAIT_MS
// also flush immediately when items.length exceeds MAX_ITEMS
const MAX_DEFERRED_WAIT_MS = 5000;
if (deferred?.length) {
await Promise.race([
Promise.allSettled(deferred),
new Promise<void>((r) => setTimeout(r, MAX_DEFERRED_WAIT_MS)),
]);
}If you must preserve replay semantics, consider:
2. 🟡 Pre-auth request body parsing enables unauthenticated resource-consumption DoS on Telegram webhook
DescriptionThe Telegram webhook handler fully reads and parses the request body (up to 1MB with a 30s timeout) before validating the This allows unauthenticated callers to:
Vulnerable flow:
Vulnerable code: const body = await readJsonBodyWithLimit(req, { maxBytes: 1024 * 1024, timeoutMs: 30_000, emptyObjectOnEmpty: false });
...
const secretHeaderRaw = req.headers["x-telegram-bot-api-secret-token"];
const secretHeader = Array.isArray(secretHeaderRaw) ? secretHeaderRaw[0] : secretHeaderRaw;
if (secretHeader !== secret) {
await unauthorized();
return;
}RecommendationValidate the secret header before reading/parsing the request body, and abort the connection early for unauthorized requests. Example fix: const secretHeaderRaw = req.headers["x-telegram-bot-api-secret-token"];
const secretHeader = Array.isArray(secretHeaderRaw) ? secretHeaderRaw[0] : secretHeaderRaw;
if (secretHeader !== secret) {
// Stop reading any additional bytes from the client
respondText(401, "unauthorized");
req.destroy();
return;
}
const body = await readJsonBodyWithLimit(req, {
maxBytes: TELEGRAM_WEBHOOK_MAX_BODY_BYTES,
timeoutMs: TELEGRAM_WEBHOOK_BODY_TIMEOUT_MS,
emptyObjectOnEmpty: false,
});Optionally also add per-IP rate limiting at the reverse proxy/load balancer and consider lowering 3. 🔵 Insecure temporary file write in disk-backed webhook queue enables symlink/hardlink overwrite (local attacker)
DescriptionThe new disk-backed webhook queue writes to a predictable temporary file path using If an attacker can create files inside the queue directory (e.g., due to misconfigured state-dir/queue-dir permissions, group-writable deployments, or the queue directory being replaced with/inside a symlink), they can pre-create Key properties that make this exploitable in such scenarios:
Vulnerable code: const tmp = `${filePath}.${process.pid}.tmp`;
await fs.promises.writeFile(tmp, JSON.stringify(entry), { encoding: "utf-8", mode: 0o600 });
await fs.promises.rename(tmp, filePath);RecommendationHarden the queue directory and temp-file creation:
Example (POSIX-focused): import crypto from "node:crypto";
import { constants as C } from "node:fs";
await fs.promises.mkdir(queueDir, { recursive: true, mode: 0o700 });
const st = await fs.promises.lstat(queueDir);
if (!st.isDirectory() || st.isSymbolicLink()) {
throw new Error("webhook queue dir is not a real directory");
}
// Best-effort tighten perms if it already existed (POSIX)
await fs.promises.chmod(queueDir, 0o700).catch(() => {});
const filePath = path.join(queueDir, entryFilename(channelId, deduplicationId));
const tmp = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
const flags = C.O_WRONLY | C.O_CREAT | C.O_EXCL | (C.O_NOFOLLOW ?? 0);
const fh = await fs.promises.open(tmp, flags, 0o600);
try {
await fh.writeFile(JSON.stringify(entry), { encoding: "utf-8" });
} finally {
await fh.close();
}
await fs.promises.rename(tmp, filePath);This prevents an attacker from planting a link at the temp path and reduces race risk even if directory permissions are not as strict as expected. Analyzed PR: #42523 at commit Last updated on: 2026-03-10T22:20:31Z |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 31ddd254d0
ℹ️ 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".
| for (const entry of pending) { | ||
| try { | ||
| await bot.handleUpdate(entry.payload as Parameters<typeof bot.handleUpdate>[0]); | ||
| // Dequeue happens via onUpdateProcessed in the bot middleware on success. |
There was a problem hiding this comment.
Replay pending webhooks without per-update awaiting
The replay loop currently awaits each bot.handleUpdate before feeding the next queued update, which serializes recovery in a way that breaks cross-update buffering logic. For updates that rely on deferred coalescing (media groups, long-text fragment assembly, inbound debounce), the first replayed update waits for its timer-based flush before the second update is even injected, so grouped updates are processed separately after restart instead of being combined. This causes behavior drift exactly in the restart-recovery path this queue is intended to preserve.
Useful? React with 👍 / 👎.
Greptile SummaryThis PR introduces a disk-backed webhook queue to provide Telegram webhook messages with at-least-once delivery semantics across gateway restarts. The design is well-thought-out: atomic write-then-rename ensures no partial files on disk, the 1-hour TTL prevents unbounded accumulation, deferred-work tracking ensures Two issues warrant attention:
The deferred-work resolver pattern in Confidence Score: 3/5
Last reviewed commit: 31ddd25 |
| function entryFilename(channelId: string, deduplicationId: string): string { | ||
| return `${safeFileKey(channelId)}_${safeFileKey(deduplicationId)}.json`; | ||
| } |
There was a problem hiding this comment.
Filename collision risk when channelId or deduplicationId contains underscores
entryFilename joins the sanitized channelId and deduplicationId with a single _ separator, but safeFileKey preserves underscores already present in either part. This means two distinct (channelId, deduplicationId) pairs can resolve to the same filename.
Example: if accountId = "my_account" then channelId = "telegram_my_account". Pairing it with a Telegram deduplicationId like "100" produces telegram_my_account_100.json. But a future integration using a non-numeric deduplicationId (e.g., ("telegram", "my_account_100")) would produce the same filename, causing one entry to silently overwrite the other.
A safer separator that cannot appear after sanitization would eliminate the ambiguity — for example, two underscores (__), since safeFileKey never produces consecutive underscores:
| function entryFilename(channelId: string, deduplicationId: string): string { | |
| return `${safeFileKey(channelId)}_${safeFileKey(deduplicationId)}.json`; | |
| } | |
| function entryFilename(channelId: string, deduplicationId: string): string { | |
| return `${safeFileKey(channelId)}__${safeFileKey(deduplicationId)}.json`; | |
| } |
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/webhook-queue.ts
Line: 25-27
Comment:
**Filename collision risk when channelId or deduplicationId contains underscores**
`entryFilename` joins the sanitized channelId and deduplicationId with a single `_` separator, but `safeFileKey` preserves underscores already present in either part. This means two distinct `(channelId, deduplicationId)` pairs can resolve to the same filename.
Example: if `accountId = "my_account"` then `channelId = "telegram_my_account"`. Pairing it with a Telegram deduplicationId like `"100"` produces `telegram_my_account_100.json`. But a future integration using a non-numeric deduplicationId (e.g., `("telegram", "my_account_100")`) would produce the same filename, causing one entry to silently overwrite the other.
A safer separator that cannot appear after sanitization would eliminate the ambiguity — for example, two underscores (`__`), since `safeFileKey` never produces consecutive underscores:
```suggestion
function entryFilename(channelId: string, deduplicationId: string): string {
return `${safeFileKey(channelId)}__${safeFileKey(deduplicationId)}.json`;
}
```
How can I resolve this? If you propose a fix, please make it concise.| "code" in err && | ||
| (err as { code?: string }).code !== "ENOENT" | ||
| ) { | ||
| console.warn("[webhook-queue] failed to read queue directory:", err); |
There was a problem hiding this comment.
Uses console.warn instead of the application's logger
The error path in replayPendingWebhooks bypasses the application's logging infrastructure with a bare console.warn. The rest of the codebase routes diagnostics through runtime.log?.(), which allows callers to redirect output to their chosen sink and keeps log formatting consistent.
Since replayPendingWebhooks is called from startTelegramWebhook where runtime is available, consider accepting an optional logging callback and using it as the primary path:
| console.warn("[webhook-queue] failed to read queue directory:", err); | |
| export async function replayPendingWebhooks( | |
| channelId?: string, | |
| stateDir?: string, | |
| onWarn?: (msg: string) => void, | |
| ): Promise<WebhookQueueEntry[]> { | |
| // ... | |
| } catch (err) { | |
| if ( | |
| err && | |
| typeof err === "object" && | |
| "code" in err && | |
| (err as { code?: string }).code !== "ENOENT" | |
| ) { | |
| (onWarn ?? console.warn)("[webhook-queue] failed to read queue directory:", err); | |
| } | |
| return []; | |
| } |
Then pass runtime.log from the caller.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/webhook-queue.ts
Line: 98
Comment:
**Uses `console.warn` instead of the application's logger**
The error path in `replayPendingWebhooks` bypasses the application's logging infrastructure with a bare `console.warn`. The rest of the codebase routes diagnostics through `runtime.log?.()`, which allows callers to redirect output to their chosen sink and keeps log formatting consistent.
Since `replayPendingWebhooks` is called from `startTelegramWebhook` where `runtime` is available, consider accepting an optional logging callback and using it as the primary path:
```suggestion
export async function replayPendingWebhooks(
channelId?: string,
stateDir?: string,
onWarn?: (msg: string) => void,
): Promise<WebhookQueueEntry[]> {
// ...
} catch (err) {
if (
err &&
typeof err === "object" &&
"code" in err &&
(err as { code?: string }).code !== "ENOENT"
) {
(onWarn ?? console.warn)("[webhook-queue] failed to read queue directory:", err);
}
return [];
}
```
Then pass `runtime.log` from the caller.
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Summary
channelId+deduplicationIddedup key prevents cross-channel collisions.channelIdvalidation rejects malformed entries. Filenames usesafeFileKeysanitization (matching the existingpairing-store.tspattern) to prevent path traversal.Design notes
The queue provides at-least-once delivery. Failed updates stay on disk for replay (cleaned up after 1h TTL). This is intentional and documented in code -- idempotency of the downstream handlers already handles duplicates.
Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
User-visible / Behavior Changes
Messages received during a gateway restart window are now replayed on next startup instead of being silently dropped. No new config required -- the queue directory (
webhook-queue/inside the state dir) is created automatically.Security Impact (required)
safeFileKey()strips/\:*?"<>|and..from channel/dedup IDs before constructing filenames. Queue directory created with mode 0o700, files with 0o600. Tested explicitly (see path traversal test).Repro + Verification
Environment
Steps
kill -9oropenclaw gateway restart)Expected
Actual (before this PR)
Evidence
16 unit tests (
src/infra/webhook-queue.test.ts): enqueue/dequeue round-trip, replay ordering, dedup by compound key, TTL cleanup, orphan.tmpcleanup, malformed entry handling, path traversal containment, cross-channel preservation,channelIdvalidation, deterministic tie-breaking, 50-entry bulk replay.1 integration test (
src/telegram/webhook.test.ts): end-to-end enqueue on webhook receipt -> dequeue ononUpdateProcessedcallback.pnpm build,pnpm check,pnpm testgreen.Human Verification (required)
Review Conversations
Compatibility / Migration
Failure Recovery (if this breaks)
rm -rf <stateDir>/webhook-queue)Risks and Mitigations
.tmpfiles cleaned up on replay scanThis PR was developed with AI assistance (Claude). All code was reviewed, tested, and verified by a human contributor.