Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 6 additions & 19 deletions assistant/src/config/vellum-skills/telegram-setup/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,26 +43,13 @@ export default () => ({ secret: randomUUID() });

Save this value for the next steps.

### Step 3: Register the Webhook
### Step 3: Webhook Registration (Automatic)

Use `evaluate_typescript_code` to register the webhook with Telegram:
Manual webhook registration is no longer required. The gateway automatically reconciles the Telegram webhook on startup and whenever credentials change. It compares the current webhook URL against `${INGRESS_PUBLIC_BASE_URL}/webhooks/telegram` and updates it if needed, including the webhook secret and allowed updates.

```typescript
export default async (input: { token: string; url: string; secret: string }) => {
const res = await fetch(`https://api.telegram.org/bot${input.token}/setWebhook`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: input.url,
secret_token: input.secret,
allowed_updates: ['message', 'edited_message'],
}),
});
return res.json();
};
```
If the ingress URL or webhook secret changes (e.g., tunnel restart, secret rotation), the gateway will detect the drift and re-register the webhook automatically.

Verify the response has `ok: true`.
You can skip directly to storing credentials.

### Step 4: Register Bot Commands

Expand Down Expand Up @@ -95,8 +82,8 @@ Use `credential_store` twice to securely save the credentials:

Summarize what was done:
- Bot verified: @username (ID: nnn)
- Webhook registered at the provided URL
- Webhook registration: handled automatically by the gateway
- Bot commands registered: /new
- Credentials stored securely in the vault

The gateway automatically detects credentials from the vault and will begin accepting Telegram webhooks shortly. No manual environment variable configuration is needed.
The gateway automatically detects credentials from the vault, reconciles the Telegram webhook registration, and begins accepting Telegram webhooks shortly. No manual environment variable configuration or webhook registration is needed. If the ingress URL or secret changes later, the gateway will automatically re-register the webhook.
191 changes: 191 additions & 0 deletions gateway/src/__tests__/telegram-webhook-manager.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { describe, test, expect, mock, afterEach } from "bun:test";
import { reconcileTelegramWebhook } from "../telegram/webhook-manager.js";
import type { GatewayConfig } from "../config.js";

function makeConfig(overrides: Partial<GatewayConfig> = {}): GatewayConfig {
return {
telegramBotToken: "test-bot-token",
telegramWebhookSecret: "test-webhook-secret",
telegramApiBaseUrl: "https://api.telegram.org",
assistantRuntimeBaseUrl: "http://localhost:7821",
routingEntries: [],
defaultAssistantId: undefined,
unmappedPolicy: "reject",
port: 7830,
runtimeBearerToken: undefined,
runtimeProxyEnabled: false,
runtimeProxyRequireAuth: false,
runtimeProxyBearerToken: undefined,
shutdownDrainMs: 5000,
runtimeTimeoutMs: 30000,
runtimeMaxRetries: 2,
runtimeInitialBackoffMs: 500,
telegramInitialBackoffMs: 1000,
telegramMaxRetries: 0,
telegramTimeoutMs: 15000,
maxWebhookPayloadBytes: 1048576,
logFile: { dir: undefined, retentionDays: 30 },
maxAttachmentBytes: 20971520,
maxAttachmentConcurrency: 3,
twilioAuthToken: undefined,
ingressPublicBaseUrl: "https://example.ngrok.io",
publicUrl: undefined,
...overrides,
};
}

const originalFetch = globalThis.fetch;

afterEach(() => {
globalThis.fetch = originalFetch;
});

function makeTelegramResponse(result: unknown) {
return new Response(JSON.stringify({ ok: true, result }), {
status: 200,
headers: { "content-type": "application/json" },
});
}

describe("reconcileTelegramWebhook", () => {
test("calls setWebhook when URL does not match", async () => {
const calls: { method: string; body: unknown }[] = [];

globalThis.fetch = mock(async (input: string | URL | Request) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (url.includes("/getWebhookInfo")) {
calls.push({ method: "getWebhookInfo", body: null });
return makeTelegramResponse({
url: "https://old-url.example.com/webhooks/telegram",
has_custom_certificate: false,
pending_update_count: 0,
});
}
if (url.includes("/setWebhook")) {
const req = typeof input === "object" && "json" in input ? input : null;
const body = req ? await (req as Request).json() : null;
calls.push({ method: "setWebhook", body });
return makeTelegramResponse(true);
}
return new Response("Not found", { status: 404 });
}) as any;

const config = makeConfig();
await reconcileTelegramWebhook(config);

expect(calls).toHaveLength(2);
expect(calls[0].method).toBe("getWebhookInfo");
expect(calls[1].method).toBe("setWebhook");
expect((calls[1].body as any).url).toBe("https://example.ngrok.io/webhooks/telegram");
expect((calls[1].body as any).secret_token).toBe("test-webhook-secret");
expect((calls[1].body as any).allowed_updates).toEqual(["message", "edited_message"]);
});

test("does not call setWebhook when URL already matches", async () => {
const calls: string[] = [];

globalThis.fetch = mock(async (input: string | URL | Request) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (url.includes("/getWebhookInfo")) {
calls.push("getWebhookInfo");
return makeTelegramResponse({
url: "https://example.ngrok.io/webhooks/telegram",
has_custom_certificate: false,
pending_update_count: 0,
});
}
if (url.includes("/setWebhook")) {
calls.push("setWebhook");
return makeTelegramResponse(true);
}
return new Response("Not found", { status: 404 });
}) as any;

const config = makeConfig();
await reconcileTelegramWebhook(config);

expect(calls).toEqual(["getWebhookInfo"]);
});

test("calls setWebhook when secret may have changed (forceUpdate)", async () => {
const calls: string[] = [];

globalThis.fetch = mock(async (input: string | URL | Request) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (url.includes("/getWebhookInfo")) {
calls.push("getWebhookInfo");
return makeTelegramResponse({
url: "https://example.ngrok.io/webhooks/telegram",
has_custom_certificate: false,
pending_update_count: 0,
});
}
if (url.includes("/setWebhook")) {
calls.push("setWebhook");
return makeTelegramResponse(true);
}
return new Response("Not found", { status: 404 });
}) as any;

const config = makeConfig();
await reconcileTelegramWebhook(config, { forceUpdate: true });

expect(calls).toEqual(["getWebhookInfo", "setWebhook"]);
});

test("skips reconciliation when bot token is not configured", async () => {
const fetchMock = mock(async () => new Response("", { status: 200 }));
globalThis.fetch = fetchMock as any;

const config = makeConfig({ telegramBotToken: undefined });
await reconcileTelegramWebhook(config);

expect(fetchMock).not.toHaveBeenCalled();
});

test("skips reconciliation when webhook secret is not configured", async () => {
const fetchMock = mock(async () => new Response("", { status: 200 }));
globalThis.fetch = fetchMock as any;

const config = makeConfig({ telegramWebhookSecret: undefined });
await reconcileTelegramWebhook(config);

expect(fetchMock).not.toHaveBeenCalled();
});

test("skips reconciliation when ingress URL is not configured", async () => {
const fetchMock = mock(async () => new Response("", { status: 200 }));
globalThis.fetch = fetchMock as any;

const config = makeConfig({ ingressPublicBaseUrl: undefined });
await reconcileTelegramWebhook(config);

expect(fetchMock).not.toHaveBeenCalled();
});

test("calls setWebhook when current URL is empty", async () => {
const calls: string[] = [];

globalThis.fetch = mock(async (input: string | URL | Request) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (url.includes("/getWebhookInfo")) {
calls.push("getWebhookInfo");
return makeTelegramResponse({
url: "",
has_custom_certificate: false,
pending_update_count: 0,
});
}
if (url.includes("/setWebhook")) {
calls.push("setWebhook");
return makeTelegramResponse(true);
}
return new Response("Not found", { status: 404 });
}) as any;

const config = makeConfig();
await reconcileTelegramWebhook(config);

expect(calls).toEqual(["getWebhookInfo", "setWebhook"]);
});
});
7 changes: 7 additions & 0 deletions gateway/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { createOAuthCallbackHandler } from "./http/routes/oauth-callback.js";
import { getLogger, initLogger } from "./logger.js";
import { buildSchema } from "./schema.js";
import { callTelegramApi } from "./telegram/api.js";
import { reconcileTelegramWebhook } from "./telegram/webhook-manager.js";

const log = getLogger("main");

Expand Down Expand Up @@ -131,6 +132,9 @@ function main() {

if (isTelegramConfigured()) {
registerTelegramCommands();
reconcileTelegramWebhook(config).catch((err) => {
log.error({ err }, "Failed to reconcile Telegram webhook on startup");
});
}

const credentialWatcher = new CredentialWatcher((credentials) => {
Expand All @@ -139,6 +143,9 @@ function main() {
config.telegramWebhookSecret = credentials.webhookSecret;
log.info("Telegram credentials loaded from credential vault");
registerTelegramCommands();
reconcileTelegramWebhook(config, { forceUpdate: true }).catch((err) => {
log.error({ err }, "Failed to reconcile Telegram webhook after credential change");
});
} else {
config.telegramBotToken = undefined;
config.telegramWebhookSecret = undefined;
Expand Down
75 changes: 75 additions & 0 deletions gateway/src/telegram/webhook-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type { GatewayConfig } from "../config.js";
import { callTelegramApi } from "./api.js";
import { getLogger } from "../logger.js";

const log = getLogger("webhook-manager");

interface WebhookInfo {
url: string;
has_custom_certificate: boolean;
pending_update_count: number;
/** Telegram does not return the secret itself, but we can detect a mismatch by re-setting. */
}

const ALLOWED_UPDATES = ["message", "edited_message"];

/**
* Reconciles the Telegram webhook registration against the expected state
* derived from the gateway's ingress URL and current webhook secret.
*
* If the currently registered webhook URL differs from the expected URL,
* or if the secret may have changed (we always re-set when the URL matches
* but we can't verify the secret from getWebhookInfo), the webhook is
* re-registered via setWebhook.
*
* This is safe to call repeatedly; Telegram treats setWebhook as idempotent.
*/
export async function reconcileTelegramWebhook(
config: GatewayConfig,
options?: { forceUpdate?: boolean },
): Promise<void> {
if (!config.telegramBotToken || !config.telegramWebhookSecret) {
log.debug("Skipping webhook reconciliation: Telegram credentials not configured");
return;
}

if (!config.ingressPublicBaseUrl) {
log.debug("Skipping webhook reconciliation: INGRESS_PUBLIC_BASE_URL not set");
return;
}

const expectedUrl = `${config.ingressPublicBaseUrl}/webhooks/telegram`;
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 Normalize ingress base URL before composing webhook URL

Building expectedUrl via raw string concatenation means a configured INGRESS_PUBLIC_BASE_URL ending with / produces ...//webhooks/telegram. Telegram will then post to a different path than the gateway route check (/webhooks/telegram), so webhook delivery fails even though reconciliation reports success. Because this commit automates registration, this malformed URL can now be introduced automatically from config instead of only via manual setup mistakes.

Useful? React with 👍 / 👎.


const info = await callTelegramApi<WebhookInfo>(config, "getWebhookInfo", {});

const urlMatches = info.url === expectedUrl;

// Telegram does not expose the current secret_token via getWebhookInfo,
// so we cannot compare it directly. When credentials are refreshed
// (forceUpdate), we always re-set to ensure the secret is current.
if (urlMatches && !options?.forceUpdate) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Re-register webhook when URL matches after secret rotation

This early return skips setWebhook whenever the URL matches, but getWebhookInfo does not expose the currently registered secret token. In the startup path (reconcileTelegramWebhook(config) in gateway/src/index.ts), rotating TELEGRAM_WEBHOOK_SECRET while keeping the same ingress URL leaves Telegram using the old secret, and the gateway then rejects all webhook deliveries with 401 at createTelegramWebhookHandler's secret check. This creates a production outage until someone manually calls setWebhook or triggers a forced reconcile.

Useful? React with 👍 / 👎.

log.info(
{ currentUrl: info.url, expectedUrl },
"Telegram webhook URL matches expected state, no update needed",
);
return;
}

log.info(
{
currentUrl: info.url || "(none)",
expectedUrl,
forceUpdate: !!options?.forceUpdate,
urlMatches,
},
"Telegram webhook state differs from expected, updating",
);

await callTelegramApi(config, "setWebhook", {
url: expectedUrl,
secret_token: config.telegramWebhookSecret,
allowed_updates: ALLOWED_UPDATES,
});

log.info({ url: expectedUrl }, "Telegram webhook registered successfully");
}
Loading