⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(telegram): harden integration validation and error handling
Tin210959284b96
diff --git a/apps/api/src/plugins/telegram/config.ts b/apps/api/src/plugins/telegram/config.tsindex 2734f8892..fbc26cfa8 100644--- a/apps/api/src/plugins/telegram/config.ts+++ b/apps/api/src/plugins/telegram/config.ts@@ -18,13 +18,14 @@ const telegramBotTokenSchema = v.pipe(const telegramChatIdSchema = v.pipe(v.string(),+ v.trim(),v.minLength(1, "Chat ID is required"),);export const telegramConfigSchema = v.object({botToken: telegramBotTokenSchema,chatId: telegramChatIdSchema,- threadId: v.optional(v.number()),+ threadId: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))),chatLabel: v.optional(v.string()),events: v.optional(v.object({@@ -54,7 +55,7 @@ export function normalizeTelegramConfig(): TelegramConfig {return {...config,- chatId: config.chatId.trim(),+ chatId: config.chatId,threadId:typeof config.threadId === "number" && Number.isFinite(config.threadId)? config.threadIddiff --git a/apps/api/src/plugins/telegram/events.ts b/apps/api/src/plugins/telegram/events.tsindex 266242060..4ea6915e5 100644--- a/apps/api/src/plugins/telegram/events.ts+++ b/apps/api/src/plugins/telegram/events.ts@@ -1,3 +1,4 @@+import { createHash } from "node:crypto";import { and, eq } from "drizzle-orm";import db from "../../database";import {@@ -66,6 +67,36 @@ function redactBotToken(botToken: string): string {}`;}+function getSafeTelegramTargetIdentifier(config: TelegramConfig): string {+ const hash = createHash("sha256")+ .update(`${config.chatId}:${config.threadId ?? "none"}`)+ .digest("hex")+ .slice(0, 12);++ return `tg:${hash}`;+}++function getTaskUrl(+ clientUrl: string | undefined,+ workspaceId: string,+ projectId: string,+ taskId: string,+): string | null {+ const normalizedClientUrl = clientUrl?.trim();+ if (!normalizedClientUrl) {+ return null;+ }++ try {+ return new URL(+ `/dashboard/workspace/${workspaceId}/project/${projectId}/task/${taskId}`,+ normalizedClientUrl,+ ).toString();+ } catch {+ return null;+ }+}+async function getTelegramEventData(taskId: string,projectId: string,@@ -101,14 +132,16 @@ async function getTelegramEventData(return null;}- const clientUrl = process.env.KANEO_CLIENT_URL || "http://localhost:5173";- const taskUrl = `${clientUrl}/dashboard/workspace/${taskRow.workspaceId}/project/${taskRow.projectId}/task/${taskId}`;-return {taskTitle: taskRow.title,taskNumber: taskRow.number,projectName: taskRow.projectName,- taskUrl,+ taskUrl: getTaskUrl(+ process.env.KANEO_CLIENT_URL,+ taskRow.workspaceId,+ taskRow.projectId,+ taskId,+ ),actorName: user?.name ?? null,status: taskRow.status,priority: taskRow.priority,@@ -152,8 +185,7 @@ async function sendTelegramMessage(console.error("sendTelegramMessage postToTelegram failed", {error,botToken: redactBotToken(config.botToken),- chatId: config.chatId,- threadId: config.threadId ?? null,+ telegramTarget: getSafeTelegramTargetIdentifier(config),taskUrl: data.taskUrl,});}diff --git a/apps/api/src/telegram-integration/controllers/telegram-controller.ts b/apps/api/src/telegram-integration/controllers/telegram-controller.tsnew file mode 100644index 000000000..75311bfe2--- /dev/null+++ b/apps/api/src/telegram-integration/controllers/telegram-controller.ts@@ -0,0 +1,64 @@+import { and, eq } from "drizzle-orm";+import db from "../../database";+import { integrationTable } from "../../database/schema";+import {+ defaultTelegramEvents,+ normalizeTelegramConfig,+ type TelegramConfig,+} from "../../plugins/telegram/config";++function maskBotToken(value: string): string {+ const [prefix, suffix = ""] = value.split(":", 2);+ if (!suffix) {+ return "Configured";+ }++ const maskedSuffix =+ suffix.length > 8 ? `${suffix.slice(0, 4)}…${suffix.slice(-4)}` : "••••";+ return `${prefix}:${maskedSuffix}`;+}++export function toResponse(integration: {+ id: string;+ projectId: string;+ config: string;+ isActive: boolean | null;+ createdAt: Date;+ updatedAt: Date;+}) {+ const config = normalizeTelegramConfig(+ JSON.parse(integration.config) as TelegramConfig,+ );++ return {+ id: integration.id,+ projectId: integration.projectId,+ chatId: config.chatId,+ threadId: config.threadId ?? null,+ chatLabel: config.chatLabel ?? null,+ botTokenConfigured: Boolean(config.botToken),+ maskedBotToken: config.botToken ? maskBotToken(config.botToken) : "",+ events: {+ ...defaultTelegramEvents,+ ...(config.events ?? {}),+ },+ isActive: integration.isActive,+ createdAt: integration.createdAt,+ updatedAt: integration.updatedAt,+ };+}++export async function getTelegramIntegration(projectId: string) {+ const integration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, "telegram"),+ ),+ });++ if (!integration) {+ return null;+ }++ return toResponse(integration);+}diff --git a/apps/api/src/telegram-integration/index.ts b/apps/api/src/telegram-integration/index.tsindex d5d493b15..99ece5551 100644--- a/apps/api/src/telegram-integration/index.ts+++ b/apps/api/src/telegram-integration/index.ts@@ -6,13 +6,13 @@ import * as v from "valibot";import db from "../database";import { integrationTable } from "../database/schema";import {- defaultTelegramEvents,normalizeTelegramConfig,type TelegramConfig,validateTelegramConfig,} from "../plugins/telegram/config";import { telegramIntegrationSchema } from "../schemas";import { workspaceAccess } from "../utils/workspace-access-middleware";+import { getTelegramIntegration } from "./controllers/telegram-controller";const telegramIntegration = new Hono<{Variables: {@@ -26,62 +26,6 @@ const telegramIntegration = new Hono<{};}>();-function maskBotToken(value: string): string {- const [prefix, suffix = ""] = value.split(":", 2);- if (!suffix) {- return "Configured";- }-- const maskedSuffix =- suffix.length > 8 ? `${suffix.slice(0, 4)}…${suffix.slice(-4)}` : "••••";- return `${prefix}:${maskedSuffix}`;-}--function toResponse(integration: {- id: string;- projectId: string;- config: string;- isActive: boolean | null;- createdAt: Date;- updatedAt: Date;-}) {- const config = normalizeTelegramConfig(- JSON.parse(integration.config) as TelegramConfig,- );-- return {- id: integration.id,- projectId: integration.projectId,- chatId: config.chatId,- threadId: config.threadId ?? null,- chatLabel: config.chatLabel ?? null,- botTokenConfigured: Boolean(config.botToken),- maskedBotToken: config.botToken ? maskBotToken(config.botToken) : "",- events: {- ...defaultTelegramEvents,- ...(config.events ?? {}),- },- isActive: integration.isActive,- createdAt: integration.createdAt,- updatedAt: integration.updatedAt,- };-}--async function getTelegramIntegration(projectId: string) {- const integration = await db.query.integrationTable.findFirst({- where: and(- eq(integrationTable.projectId, projectId),- eq(integrationTable.type, "telegram"),- ),- });-- if (!integration) {- return null;- }-- return toResponse(integration);-}-const telegramEventsSchema = v.object({taskCreated: v.optional(v.boolean()),taskStatusChanged: v.optional(v.boolean()),diff --git a/apps/docs/core/integrations/telegram.mdx b/apps/docs/core/integrations/telegram.mdxindex c6fa92056..4be1d8859 100644--- a/apps/docs/core/integrations/telegram.mdx+++ b/apps/docs/core/integrations/telegram.mdx@@ -23,10 +23,10 @@ Treat the bot token like a password. Anyone with the token can send messages asAdd the bot to the private chat, group, supergroup, or channel where you want notifications.-- For a personal chat: start a conversation with the bot and send any message.-- For a group or supergroup: add the bot, then send a message in that chat.-- For a channel: add the bot as an administrator if needed so it can post updates.-- For forum-style supergroups: add the bot to the group and note the topic you want to post into.+- Personal chat: start a conversation with the bot and send any message.+- Add the bot to a group or supergroup, then send a message in that chat.+- A channel may require adding the bot as an administrator so it can post updates.+- Forum-style supergroups need the bot added to the group, plus the topic you want to post into.## Find the chat IDdiff --git a/apps/web/src/components/project/telegram-integration-settings.tsx b/apps/web/src/components/project/telegram-integration-settings.tsxindex 4c2730d61..5813d6abb 100644--- a/apps/web/src/components/project/telegram-integration-settings.tsx+++ b/apps/web/src/components/project/telegram-integration-settings.tsx@@ -103,7 +103,11 @@ export function TelegramIntegrationSettings({[],);- const { data: integration, isLoading } = useGetTelegramIntegration(projectId);+ const {+ data: integration,+ isLoading,+ error,+ } = useGetTelegramIntegration(projectId);const { mutateAsync: createIntegration, isPending: isCreating } =useCreateTelegramIntegration();const { mutateAsync: updateIntegration, isPending: isUpdating } =@@ -155,6 +159,20 @@ export function TelegramIntegrationSettings({lastResetKeyRef.current = resetKey;}, [form.formState.isDirty, normalizedValues, reset, resetKey]);+ React.useEffect(() => {+ if (!error) {+ return;+ }++ const detail =+ error instanceof Error+ ? error.message+ : t("settings:telegramIntegration.toast.saveError");+ toast.error(+ `${t("settings:telegramIntegration.toast.saveError")}: ${detail}`,+ );+ }, [error, t]);+const isConnected = Boolean(integration?.botTokenConfigured);const isBusy = isCreating || isUpdating || isDeleting;@@ -309,6 +327,10 @@ export function TelegramIntegrationSettings({);}+ if (error) {+ return null;+ }+return (<div className="space-y-4"><Form {...form}>