Personal Telegram developer console for GitHub

fix/telegram-callback-updates
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 382 lines 12.3 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 async function answerCallback(env, callbackQueryId) {
39 return telegramApi(env, "answerCallbackQuery", { callback_query_id: callbackQueryId });
40 }
41
42 function isOwner(env, from) {
43 if (!from || !env.OWNER_TELEGRAM_ID) return false;
44 return String(from.id) === String(env.OWNER_TELEGRAM_ID);
45 }
46
47 function githubHeaders(env) {
48 return {
49 Accept: "application/vnd.github+json",
50 Authorization: `Bearer ${env.GITHUB_TOKEN}`,
51 "X-GitHub-Api-Version": "2022-11-28",
52 "User-Agent": "nexa-dev-bot",
53 };
54 }
55
56 async function githubJson(env, url, label) {
57 const response = await fetch(url, { headers: githubHeaders(env) });
58 if (!response.ok) {
59 const body = await response.text();
60 const error = new Error(`${label} failed: ${response.status} ${body}`);
61 error.status = response.status;
62 throw error;
63 }
64 return response.json();
65 }
66
67 async function fetchRepos(env) {
68 return githubJson(
69 env,
70 "https://api.github.com/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member",
71 "GitHub repos"
72 );
73 }
74
75 async function fetchRepoById(env, repoId) {
76 return githubJson(env, `https://api.github.com/repositories/${repoId}`, "GitHub repository");
77 }
78
79 function repoPath(fullName) {
80 return fullName.split("/").map(encodeURIComponent).join("/");
81 }
82
83 function escapeHtml(value = "") {
84 return String(value)
85 .replaceAll("&", "&")
86 .replaceAll("<", "&lt;")
87 .replaceAll(">", "&gt;")
88 .replaceAll('"', "&quot;");
89 }
90
91 function decodeBase64Utf8(value) {
92 const binary = atob(String(value || "").replace(/\s/g, ""));
93 const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
94 return new TextDecoder().decode(bytes);
95 }
96
97 function startMessage() {
98 return [
99 "<b>Nexa Dev</b>",
100 "دستیار شخصی توسعه و مدیریت GitHub از داخل تلگرام.",
101 "",
102 "فرمان‌ها:",
103 "/repos — مرور مخزن‌ها با دکمه‌های لمسی",
104 "/status — وضعیت سرویس",
105 ].join("\n");
106 }
107
108 function repoButtons(repos) {
109 return repos.slice(0, 20).map((repo) => [{
110 text: `${repo.private ? "🔒" : "🌐"} ${repo.name}`,
111 callback_data: `repo:${repo.id}`,
112 }]);
113 }
114
115 async function showRepos(env, chatId) {
116 if (!env.GITHUB_TOKEN) {
117 await sendMessage(env, chatId, "⚠️ اتصال GitHub هنوز با Secret نهایی نشده است.");
118 return;
119 }
120
121 const repos = await fetchRepos(env);
122 if (!repos.length) {
123 await sendMessage(env, chatId, "هیچ مخزنی پیدا نشد.");
124 return;
125 }
126
127 await sendMessage(env, chatId, "<b>Repositories</b>\nیک مخزن را انتخاب کن:", {
128 reply_markup: { inline_keyboard: repoButtons(repos) },
129 });
130 }
131
132 function repoMenu(repo) {
133 return {
134 inline_keyboard: [
135 [{ text: "📁 فایل‌ها", callback_data: `files:${repo.id}` }],
136 [
137 { text: "🧾 کامیت‌ها", callback_data: `commits:${repo.id}` },
138 { text: "🔀 Pull Requestها", callback_data: `prs:${repo.id}` },
139 ],
140 [{ text: "⬅️ مخزن‌ها", callback_data: "repos" }],
141 ],
142 };
143 }
144
145 async function showRepo(env, chatId, repoId) {
146 const repo = await fetchRepoById(env, repoId);
147 const visibility = repo.private ? "🔒 خصوصی" : "🌐 عمومی";
148 const description = repo.description ? `\n${escapeHtml(repo.description)}` : "";
149 await sendMessage(
150 env,
151 chatId,
152 `<b>${escapeHtml(repo.full_name)}</b>\n${visibility}\nbranch: <code>${escapeHtml(repo.default_branch)}</code>${description}`,
153 { reply_markup: repoMenu(repo) }
154 );
155 }
156
157 function fileButtons(repoId, items, back = `repo:${repoId}`) {
158 const rows = items.slice(0, 30).map((item) => {
159 const isDir = item.type === "dir" || item.type === "tree";
160 const isFile = item.type === "file" || item.type === "blob";
161 const callback = isDir
162 ? `tree:${repoId}:${item.sha}`
163 : isFile
164 ? `blob:${repoId}:${item.sha}`
165 : null;
166 return callback ? [{ text: `${isDir ? "📁" : "📄"} ${item.name || item.path}`, callback_data: callback }] : [];
167 }).filter((row) => row.length);
168 rows.push([{ text: "⬅️ برگشت", callback_data: back }]);
169 return { inline_keyboard: rows };
170 }
171
172 async function showRootFiles(env, chatId, repoId) {
173 const repo = await fetchRepoById(env, repoId);
174 const full = repoPath(repo.full_name);
175 const branch = encodeURIComponent(repo.default_branch);
176 const items = await githubJson(
177 env,
178 `https://api.github.com/repos/${full}/contents?ref=${branch}`,
179 "GitHub contents"
180 );
181
182 await sendMessage(env, chatId, `📁 <b>${escapeHtml(repo.full_name)}</b> /`, {
183 reply_markup: fileButtons(repoId, Array.isArray(items) ? items : [], `repo:${repoId}`),
184 });
185 }
186
187 async function showTree(env, chatId, repoId, sha) {
188 const repo = await fetchRepoById(env, repoId);
189 const full = repoPath(repo.full_name);
190 const tree = await githubJson(
191 env,
192 `https://api.github.com/repos/${full}/git/trees/${encodeURIComponent(sha)}`,
193 "GitHub tree"
194 );
195
196 await sendMessage(env, chatId, `📁 <b>${escapeHtml(repo.full_name)}</b>`, {
197 reply_markup: fileButtons(repoId, tree.tree || [], `files:${repoId}`),
198 });
199 }
200
201 async function showBlob(env, chatId, repoId, sha) {
202 const repo = await fetchRepoById(env, repoId);
203 const full = repoPath(repo.full_name);
204 const blob = await githubJson(
205 env,
206 `https://api.github.com/repos/${full}/git/blobs/${encodeURIComponent(sha)}`,
207 "GitHub blob"
208 );
209
210 if (blob.encoding !== "base64" || blob.size > 100000) {
211 await sendMessage(env, chatId, "این فایل برای نمایش مستقیم در تلگرام مناسب نیست.", {
212 reply_markup: { inline_keyboard: [[{ text: "⬅️ فایل‌ها", callback_data: `files:${repoId}` }]] },
213 });
214 return;
215 }
216
217 const decoded = decodeBase64Utf8(blob.content);
218 const preview = decoded.length > 3000 ? `${decoded.slice(0, 3000)}\n…` : decoded;
219 await sendMessage(env, chatId, `<pre>${escapeHtml(preview)}</pre>`, {
220 reply_markup: { inline_keyboard: [[{ text: "⬅️ فایل‌ها", callback_data: `files:${repoId}` }]] },
221 });
222 }
223
224 async function showCommits(env, chatId, repoId) {
225 const repo = await fetchRepoById(env, repoId);
226 const full = repoPath(repo.full_name);
227 const commits = await githubJson(
228 env,
229 `https://api.github.com/repos/${full}/commits?per_page=5&sha=${encodeURIComponent(repo.default_branch)}`,
230 "GitHub commits"
231 );
232 const lines = commits.map((commit) => {
233 const title = String(commit.commit?.message || "").split("\n")[0];
234 const author = commit.author?.login || commit.commit?.author?.name || "unknown";
235 return `• <code>${escapeHtml(String(commit.sha).slice(0, 7))}</code> ${escapeHtml(title)} — ${escapeHtml(author)}`;
236 });
237 await sendMessage(env, chatId, `<b>آخرین کامیت‌ها</b>\n\n${lines.join("\n") || "کامیتی پیدا نشد."}`, {
238 reply_markup: { inline_keyboard: [[{ text: "⬅️ مخزن", callback_data: `repo:${repoId}` }]] },
239 });
240 }
241
242 async function showPullRequests(env, chatId, repoId) {
243 const repo = await fetchRepoById(env, repoId);
244 const full = repoPath(repo.full_name);
245 const prs = await githubJson(
246 env,
247 `https://api.github.com/repos/${full}/pulls?state=open&per_page=5`,
248 "GitHub pull requests"
249 );
250 const lines = prs.map((pr) => `• <b>#${pr.number}</b> ${escapeHtml(pr.title)} — ${escapeHtml(pr.user?.login || "unknown")}`);
251 await sendMessage(env, chatId, `<b>Pull Requestهای باز</b>\n\n${lines.join("\n") || "PR بازی وجود ندارد."}`, {
252 reply_markup: { inline_keyboard: [[{ text: "⬅️ مخزن", callback_data: `repo:${repoId}` }]] },
253 });
254 }
255
256 async function handleCommand(env, message) {
257 const chatId = message.chat?.id;
258 const command = (message.text || "").trim().split(/\s+/)[0].split("@")[0].toLowerCase();
259
260 if (!isOwner(env, message.from)) return;
261
262 if (command === "/start") {
263 await sendMessage(env, chatId, startMessage());
264 return;
265 }
266
267 if (command === "/status") {
268 await sendMessage(env, chatId, "✅ Nexa Dev آنلاین است.\nGitHub integration: آماده");
269 return;
270 }
271
272 if (command === "/repos") {
273 await showRepos(env, chatId);
274 return;
275 }
276
277 await sendMessage(env, chatId, "فرمان شناخته نشد. /start را بزن.");
278 }
279
280 async function handleCallbackQuery(env, query) {
281 if (!isOwner(env, query.from)) return;
282
283 const chatId = query.message?.chat?.id;
284 const data = String(query.data || "");
285 await answerCallback(env, query.id);
286
287 if (data === "repos") {
288 await showRepos(env, chatId);
289 return;
290 }
291
292 const [action, repoId, sha] = data.split(":");
293 if (!/^\d+$/.test(repoId || "")) return;
294
295 if (action === "repo") return showRepo(env, chatId, repoId);
296 if (action === "files") return showRootFiles(env, chatId, repoId);
297 if (action === "tree" && /^[a-f0-9]{40}$/i.test(sha || "")) return showTree(env, chatId, repoId, sha);
298 if (action === "blob" && /^[a-f0-9]{40}$/i.test(sha || "")) return showBlob(env, chatId, repoId, sha);
299 if (action === "commits") return showCommits(env, chatId, repoId);
300 if (action === "prs") return showPullRequests(env, chatId, repoId);
301 }
302
303 async function setupTelegramWebhook(request, env) {
304 if (!env.TELEGRAM_BOT_TOKEN || !env.TELEGRAM_WEBHOOK_SECRET) {
305 return text("Telegram secrets not configured", 503);
306 }
307
308 const url = new URL(request.url);
309 const webhookUrl = `${url.origin}/telegram/webhook`;
310 const result = await telegramApi(env, "setWebhook", {
311 url: webhookUrl,
312 secret_token: env.TELEGRAM_WEBHOOK_SECRET,
313 allowed_updates: ["message", "callback_query"],
314 });
315
316 return json({
317 ok: true,
318 webhook: webhookUrl,
319 telegram_ok: Boolean(result?.ok),
320 });
321 }
322
323 async function handleTelegramWebhook(request, env) {
324 const expected = env.TELEGRAM_WEBHOOK_SECRET;
325 if (!expected) return text("Webhook secret not configured", 503);
326
327 const actual = request.headers.get("X-Telegram-Bot-Api-Secret-Token");
328 if (actual !== expected) return text("Forbidden", 403);
329
330 const update = await request.json();
331 if (update.message?.text) {
332 await handleCommand(env, update.message);
333 } else if (update.callback_query) {
334 try {
335 await handleCallbackQuery(env, update.callback_query);
336 } catch (error) {
337 console.error(error);
338 if (isOwner(env, update.callback_query.from) && update.callback_query.message?.chat?.id) {
339 const hint = error?.status === 403
340 ? "⚠️ توکن GitHub مجوز Read لازم برای این بخش را ندارد."
341 : "⚠️ دریافت اطلاعات GitHub ناموفق بود.";
342 await sendMessage(env, update.callback_query.message.chat.id, hint);
343 }
344 }
345 }
346
347 return text("OK");
348 }
349
350 export default {
351 async fetch(request, env) {
352 const url = new URL(request.url);
353
354 if (request.method === "GET" && url.pathname === "/") {
355 return json({
356 name: "Nexa Dev",
357 status: "ok",
358 version: "0.2.0",
359 });
360 }
361
362 if (request.method === "GET" && url.pathname === "/telegram/setup") {
363 try {
364 return await setupTelegramWebhook(request, env);
365 } catch (error) {
366 console.error(error);
367 return text("Telegram webhook setup failed", 500);
368 }
369 }
370
371 if (request.method === "POST" && url.pathname === "/telegram/webhook") {
372 try {
373 return await handleTelegramWebhook(request, env);
374 } catch (error) {
375 console.error(error);
376 return text("Internal Server Error", 500);
377 }
378 }
379
380 return text("Not Found", 404);
381 },
382 };