Personal Telegram developer console for GitHub

feat/self-register-webhook
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
js 186 lines 5.1 KB
Raw
1 const json = (data, status = 200) =>
2 new Response(JSON.stringify(data), {
3 status,
4 headers: { "content-type": "application/json; charset=utf-8" },
5 });
6
7 const text = (body, status = 200) =>
8 new Response(body, {
9 status,
10 headers: { "content-type": "text/plain; charset=utf-8" },
11 });
12
13 async function telegramApi(env, method, payload) {
14 const response = await fetch(`https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/${method}`, {
15 method: "POST",
16 headers: { "content-type": "application/json" },
17 body: JSON.stringify(payload),
18 });
19
20 if (!response.ok) {
21 const body = await response.text();
22 throw new Error(`Telegram API ${method} failed: ${response.status} ${body}`);
23 }
24
25 return response.json();
26 }
27
28 async function sendMessage(env, chatId, message, extra = {}) {
29 return telegramApi(env, "sendMessage", {
30 chat_id: chatId,
31 text: message,
32 parse_mode: "HTML",
33 disable_web_page_preview: true,
34 ...extra,
35 });
36 }
37
38 function isOwner(env, from) {
39 if (!from || !env.OWNER_TELEGRAM_ID) return false;
40 return String(from.id) === String(env.OWNER_TELEGRAM_ID);
41 }
42
43 function githubHeaders(env) {
44 return {
45 Accept: "application/vnd.github+json",
46 Authorization: `Bearer ${env.GITHUB_TOKEN}`,
47 "X-GitHub-Api-Version": "2022-11-28",
48 "User-Agent": "nexa-dev-bot",
49 };
50 }
51
52 async function fetchRepos(env) {
53 const response = await fetch(
54 "https://api.github.com/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member",
55 { headers: githubHeaders(env) }
56 );
57
58 if (!response.ok) {
59 const body = await response.text();
60 throw new Error(`GitHub repos failed: ${response.status} ${body}`);
61 }
62
63 return response.json();
64 }
65
66 function startMessage() {
67 return [
68 "<b>Nexa Dev</b>",
69 "دستیار شخصی توسعه و مدیریت GitHub از داخل تلگرام.",
70 "",
71 "فرمان‌های نسخه اول:",
72 "/repos — نمایش مخزن‌های قابل دسترس",
73 "/status — وضعیت سرویس",
74 ].join("\n");
75 }
76
77 async function handleCommand(env, message) {
78 const chatId = message.chat?.id;
79 const command = (message.text || "").trim().split(/\s+/)[0].split("@")[0].toLowerCase();
80
81 // Personal bot: fail silently for every Telegram user except the owner.
82 if (!isOwner(env, message.from)) return;
83
84 if (command === "/start") {
85 await sendMessage(env, chatId, startMessage());
86 return;
87 }
88
89 if (command === "/status") {
90 await sendMessage(env, chatId, "✅ Nexa Dev آنلاین است.\nGitHub integration: آماده بررسی");
91 return;
92 }
93
94 if (command === "/repos") {
95 if (!env.GITHUB_TOKEN) {
96 await sendMessage(env, chatId, "⚠️ اتصال GitHub هنوز با Secret نهایی نشده است.");
97 return;
98 }
99
100 const repos = await fetchRepos(env);
101 if (!repos.length) {
102 await sendMessage(env, chatId, "هیچ مخزنی پیدا نشد.");
103 return;
104 }
105
106 const lines = repos.slice(0, 20).map((repo, i) => {
107 const visibility = repo.private ? "🔒" : "🌐";
108 return `${i + 1}. ${visibility} <b>${repo.full_name}</b>\n branch: <code>${repo.default_branch}</code>`;
109 });
110
111 await sendMessage(env, chatId, `<b>Repositories</b>\n\n${lines.join("\n\n")}`);
112 return;
113 }
114
115 await sendMessage(env, chatId, "فرمان شناخته نشد. /start را بزن.");
116 }
117
118 async function setupTelegramWebhook(request, env) {
119 if (!env.TELEGRAM_BOT_TOKEN || !env.TELEGRAM_WEBHOOK_SECRET) {
120 return text("Telegram secrets not configured", 503);
121 }
122
123 const url = new URL(request.url);
124 const webhookUrl = `${url.origin}/telegram/webhook`;
125
126 const result = await telegramApi(env, "setWebhook", {
127 url: webhookUrl,
128 secret_token: env.TELEGRAM_WEBHOOK_SECRET,
129 allowed_updates: ["message"],
130 });
131
132 return json({
133 ok: true,
134 webhook: webhookUrl,
135 telegram_ok: Boolean(result?.ok),
136 });
137 }
138
139 async function handleTelegramWebhook(request, env) {
140 const expected = env.TELEGRAM_WEBHOOK_SECRET;
141 if (!expected) return text("Webhook secret not configured", 503);
142
143 const actual = request.headers.get("X-Telegram-Bot-Api-Secret-Token");
144 if (actual !== expected) return text("Forbidden", 403);
145
146 const update = await request.json();
147 if (update.message?.text) {
148 await handleCommand(env, update.message);
149 }
150
151 return text("OK");
152 }
153
154 export default {
155 async fetch(request, env) {
156 const url = new URL(request.url);
157
158 if (request.method === "GET" && url.pathname === "/") {
159 return json({
160 name: "Nexa Dev",
161 status: "ok",
162 version: "0.1.0",
163 });
164 }
165
166 if (request.method === "GET" && url.pathname === "/telegram/setup") {
167 try {
168 return await setupTelegramWebhook(request, env);
169 } catch (error) {
170 console.error(error);
171 return text("Telegram webhook setup failed", 500);
172 }
173 }
174
175 if (request.method === "POST" && url.pathname === "/telegram/webhook") {
176 try {
177 return await handleTelegramWebhook(request, env);
178 } catch (error) {
179 console.error(error);
180 return text("Internal Server Error", 500);
181 }
182 }
183
184 return text("Not Found", 404);
185 },
186 };