openclaw/scripts/e2e/telegram-bot-api.ts
Vincent Koc e1f462b352
Some checks are pending
CI / (push) Blocked by required conditions
CI / -1 (push) Blocked by required conditions
CI / -2 (push) Blocked by required conditions
CI / checks-node-compat-node22 (push) Blocked by required conditions
CI / -3 (push) Blocked by required conditions
CI / check-dependencies (push) Blocked by required conditions
CI / check-guards (push) Blocked by required conditions
CI / check-lint (push) Blocked by required conditions
CI / check-prod-types (push) Blocked by required conditions
CI / check-test-types (push) Blocked by required conditions
CI / check-additional-boundaries-a (push) Blocked by required conditions
CI / check-additional-boundaries-bcd (push) Blocked by required conditions
CI / check-additional-extension-bundled (push) Blocked by required conditions
CI / check-additional-extension-channels (push) Blocked by required conditions
CI / check-additional-extension-package-boundary (push) Blocked by required conditions
CI / check-additional-runtime-topology-architecture (push) Blocked by required conditions
CI / preflight (push) Waiting to run
CI / security-fast (push) Waiting to run
CI / pnpm-store-warmup (push) Blocked by required conditions
CI / build-artifacts (push) Blocked by required conditions
CI / -5 (push) Blocked by required conditions
CI / check-docs (push) Blocked by required conditions
CI / skills-python (push) Blocked by required conditions
CI / -4 (push) Blocked by required conditions
CI / -6 (push) Blocked by required conditions
CI / ci-timings-summary (push) Blocked by required conditions
ClawSweeper Dispatch / dispatch (push) Waiting to run
CodeQL / Security High (actions) (push) Waiting to run
CodeQL / Security High (channel-runtime-boundary) (push) Waiting to run
CodeQL / Security High (core-auth-secrets) (push) Waiting to run
CodeQL / Security High (mcp-process-tool-boundary) (push) Waiting to run
CodeQL / Security High (network-ssrf-boundary) (push) Waiting to run
CodeQL / Security High (plugin-trust-boundary) (push) Waiting to run
Docs Sync Publish Repo / sync-publish-repo (push) Waiting to run
Docs / docs (push) Waiting to run
Plugin NPM Release / preview_plugins_npm (push) Waiting to run
Plugin NPM Release / Validate release publish approval (push) Blocked by required conditions
Plugin NPM Release / preview_plugin_pack (push) Blocked by required conditions
Plugin NPM Release / publish_plugins_npm (push) Blocked by required conditions
CI / macos-swift (push) Blocked by required conditions
Workflow Sanity / generated-doc-baselines (push) Waiting to run
Workflow Sanity / no-tabs (push) Waiting to run
Workflow Sanity / actionlint (push) Waiting to run
fix(e2e): reject loose Telegram Bot API limits
2026-05-30 14:11:43 +02:00

101 lines
3 KiB
TypeScript

import { readBoundedResponseText } from "../lib/bounded-response.ts";
import { readPositiveIntEnv } from "./lib/env-limits.mjs";
type JsonObject = Record<string, unknown>;
type TelegramBotApiOptions = {
baseUrl?: string;
fetchImpl?: (url: string, init: RequestInit) => Promise<Response>;
maxBodyBytes?: number;
timeoutMs?: number;
};
const DEFAULT_BASE_URL =
process.env.OPENCLAW_TELEGRAM_USER_BOT_API_BASE_URL ?? "https://api.telegram.org";
export type TelegramBotApiLimits = {
bodyMaxBytes: number;
timeoutMs: number;
};
export function readTelegramBotApiLimits(
env: NodeJS.ProcessEnv = process.env,
): TelegramBotApiLimits {
return {
bodyMaxBytes: readPositiveIntEnv(
"OPENCLAW_TELEGRAM_USER_BOT_API_BODY_MAX_BYTES",
1024 * 1024,
env,
),
timeoutMs: readPositiveIntEnv("OPENCLAW_TELEGRAM_USER_BOT_API_TIMEOUT_MS", 30000, env),
};
}
const DEFAULT_LIMITS = readTelegramBotApiLimits();
function optionalString(source: JsonObject, key: string) {
const value = source[key];
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
function taggedError(message: string, code: string) {
return Object.assign(new Error(message), { code });
}
function parseJsonPayload(rawPayload: string, label: string) {
try {
return JSON.parse(rawPayload) as JsonObject;
} catch (error) {
throw new Error(`${label} returned invalid JSON`, { cause: error });
}
}
export async function telegramBotApi(
token: string,
method: string,
body: JsonObject = {},
options: TelegramBotApiOptions = {},
) {
const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
const timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_LIMITS.timeoutMs);
const maxBodyBytes = Math.max(1, options.maxBodyBytes ?? DEFAULT_LIMITS.bodyMaxBytes);
const label = `Telegram Bot API ${method}`;
const timeoutError = taggedError(`${label} timed out after ${timeoutMs}ms`, "ETIMEDOUT");
const controller = new AbortController();
let timeout: NodeJS.Timeout | undefined;
const timeoutPromise = new Promise<never>((_, reject) => {
timeout = setTimeout(() => {
controller.abort(timeoutError);
reject(timeoutError);
}, timeoutMs);
timeout.unref?.();
});
try {
const response = await Promise.race([
(options.fetchImpl ?? fetch)(`${baseUrl}/bot${token}/${method}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
signal: controller.signal,
}),
timeoutPromise,
]);
const rawPayload = await readBoundedResponseText(response, label, maxBodyBytes, {
createTooLargeError(message) {
return taggedError(message, "ETOOBIG");
},
timeoutPromise,
});
const payload = parseJsonPayload(rawPayload, label);
if (!response.ok || payload.ok !== true) {
throw new Error(
optionalString(payload, "description") ?? `${method} failed with HTTP ${response.status}`,
);
}
return payload.result;
} finally {
if (timeout) {
clearTimeout(timeout);
}
}
}