Personal Telegram developer console for GitHub

feat/studio-g0-foundation
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 579 lines 18.6 KB
Raw
1 import { TelegramClient } from './telegram.js';
2 import { workspaceEditorUrl } from './config.js';
3 import { GitHubService } from './github.js';
4 import { MenuManager } from './menu.js';
5 import { PluginRegistry } from './core/plugin-registry.js';
6 import { ActionPolicy } from './core/action-policy.js';
7 import { ApprovalService } from './core/approval.js';
8 import { DurableApprovalReplayStore } from './core/durable-replay-store.js';
9 import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
10 import { interceptTelegramSecretMessage } from './core/telegram-secret-guard.js';
11 import { AuditLogger } from './core/audit.js';
12 import { PluginRouter } from './core/router.js';
13 import {
14 buildApprovedActionFailedView,
15 buildCallbackFailureView
16 } from './core/callback-failure-view.js';
17 import { createGitHubPlugin } from './plugins/github/plugin.js';
18 import { CloudflareService } from './plugins/cloudflare/service.js';
19 import { createCloudflarePlugin } from './plugins/cloudflare/plugin.js';
20
21 const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
22 const QUICK_MENU = Object.freeze({
23 '🏠 منوی اصلی': 'main',
24 '📁 پروژه‌ها': 'repos',
25 '📊 وضعیت': 'status',
26 '🔧 ابزارها': 'tools',
27 '🔐 امنیت': 'security'
28 });
29 function persistentQuickMenuMarkup() {
30 return {
31 keyboard: [
32 [{ text: '🏠 منوی اصلی' }, { text: '📁 پروژه‌ها' }],
33 [{ text: '📊 وضعیت' }, { text: '🔧 ابزارها' }],
34 [{ text: '🔐 امنیت' }]
35 ],
36 resize_keyboard: true,
37 is_persistent: true,
38 input_field_placeholder: 'Nexa Dev — یک گزینه را انتخاب کنید'
39 };
40 }
41
42 function approvalSourceCallback(payload = {}) {
43 const repoId = payload.input?.repoId;
44 if (!Number.isSafeInteger(Number(repoId)))
45 throw new Error('Approval input is invalid');
46
47 if (payload.actionId === 'github.workspace.commit_branch') {
48 const intentId = String(payload.input?.intentId || '');
49 if (!INTENT_ID_PATTERN.test(intentId))
50 throw new Error('Approval input is invalid');
51 return `wscommit:${repoId}:${intentId}`;
52 }
53
54 const runId = payload.input?.runId;
55 if (!Number.isSafeInteger(Number(runId)))
56 throw new Error('Approval input is invalid');
57 if (payload.actionId === 'github.workflow.dispatch')
58 return `dispatchwf:${repoId}:${runId}`;
59 if (payload.actionId === 'github.workflow.job.rerun')
60 return `rerunjob:${repoId}:${runId}`;
61 if (payload.actionId === 'github.workflow.run.rerun_failed')
62 return `rerun:${repoId}:${runId}`;
63 if (payload.actionId === 'github.workflow.run.cancel')
64 return `cancelrun:${repoId}:${runId}`;
65 throw new Error('Approval action is not supported');
66 }
67
68 function approvalView({ label, token, cancelCallback = 'menu:main' }) {
69 return {
70 text: `⚠️ <b>تأیید عملیات لازم است</b>
71 ➖➖➖➖➖➖➖➖➖➖
72 عملیات: <b>${label}</b>
73 این عملیات روی GitHub تغییر ایجاد می‌کند و فقط پس از تأیید شما اجرا می‌شود.
74
75 اگر مطمئن هستید، «تأیید و اجرا» را بزنید.`,
76 reply_markup: {
77 inline_keyboard: [
78 [{ text: '✅ تأیید و اجرا', callback_data: `approve:${token}` }],
79 [{ text: '↩️ انصراف', callback_data: cancelCallback }]
80 ]
81 }
82 };
83 }
84
85 function approvalRejectedView(message, error) {
86 const reason = String(error?.message || 'Approval rejected');
87 const expired = /expired/i.test(reason);
88 const used = /already used|replay/i.test(reason);
89 const fallback =
90 message?.reply_markup?.inline_keyboard
91 ?.flat()
92 .map((button) => String(button?.callback_data || ''))
93 .find((callback) => callback && !callback.startsWith('approve:')) ||
94 'menu:main';
95
96 let detail = 'این تأیید معتبر نیست و هیچ تغییری اجرا نشد.';
97 if (expired) detail = 'مهلت این تأیید تمام شده است و هیچ تغییری اجرا نشد.';
98 if (used) detail = 'این تأیید قبلاً استفاده شده است و دوباره اجرا نمی‌شود.';
99 const backText = fallback.startsWith('run:')
100 ? '↩️ بازگشت به Run'
101 : '↩️ بازگشت';
102
103 return {
104 text: `⚠️ <b>عملیات اجرا نشد</b>
105 ➖➖➖➖➖➖➖➖➖➖
106 ${detail}
107
108 برای ادامه برگردید و در صورت نیاز یک تأیید تازه ایجاد کنید.`,
109 reply_markup: {
110 inline_keyboard: [[{ text: backText, callback_data: fallback }]]
111 }
112 };
113 }
114
115 export class NexaDevBot {
116 constructor(env = {}) {
117 this.env = env;
118 this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
119 this.github = new GitHubService(
120 env.GITHUB_TOKEN || '',
121 env.GITHUB_OWNER || 'davoodmehraban89'
122 );
123 this.menu = new MenuManager(this.github);
124 this.replayStore = new DurableApprovalReplayStore({
125 namespace: env.APPROVAL_REPLAY_GUARD
126 });
127 this.workspaceStore = new DurableWorkspaceStoreClient({
128 namespace: env.WORKSPACE_STORE
129 });
130 this.approvals = new ApprovalService({
131 secret: env.APPROVAL_SIGNING_SECRET || env.TELEGRAM_WEBHOOK_SECRET || '',
132 replayStore: this.replayStore
133 });
134 this.githubPlugin = createGitHubPlugin({
135 github: this.github,
136 menu: this.menu,
137 editorUrl: workspaceEditorUrl(env.WORKSPACE_EDITOR_URL),
138 workspaces: this.workspaceStore.isConfigured()
139 ? this.workspaceStore
140 : null
141 });
142 this.cloudflare = new CloudflareService({
143 token: env.CLOUDFLARE_API_TOKEN || '',
144 accountId: env.CLOUDFLARE_ACCOUNT_ID || '',
145 workerName: env.CLOUDFLARE_WORKER_NAME || 'nexa-dev-bot'
146 });
147 this.cloudflarePlugin = createCloudflarePlugin({
148 cloudflare: this.cloudflare,
149 github: this.github
150 });
151 this.registry = new PluginRegistry([
152 this.githubPlugin,
153 this.cloudflarePlugin
154 ]);
155 this.policy = new ActionPolicy();
156 this.audit = new AuditLogger({
157 secrets: [
158 env.TELEGRAM_BOT_TOKEN,
159 env.TELEGRAM_WEBHOOK_SECRET,
160 env.GITHUB_TOKEN,
161 env.CLOUDFLARE_API_TOKEN,
162 env.APPROVAL_SIGNING_SECRET,
163 env.DESTRUCTIVE_TOTP_SECRET
164 ]
165 });
166 this.router = new PluginRouter({
167 registry: this.registry,
168 policy: this.policy,
169 audit: this.audit
170 });
171 }
172
173 async handleUpdate(update) {
174 if (!update) return { ok: false, error: 'Empty update' };
175 const intercepted = await interceptTelegramSecretMessage({
176 message: update.message || update.edited_message,
177 telegram: this.telegram,
178 ownerId: this.env.OWNER_TELEGRAM_ID
179 });
180 if (intercepted) return intercepted;
181 if (update.callback_query)
182 return this.handleCallbackQuery(update.callback_query);
183 if (update.message) return this.handleMessage(update.message);
184 return { ok: true, ignored: true };
185 }
186
187 async handleCallbackQuery(query) {
188 const callbackId = query.id;
189 const data = query.data || 'menu:main';
190 const message = query.message;
191 const chatId = message?.chat?.id;
192 const messageId = message?.message_id;
193 const ownerId = query.from?.id;
194
195 let callbackAnswered = true;
196 try {
197 await this.telegram.answerCallbackQuery(callbackId);
198 } catch {
199 callbackAnswered = false;
200 }
201 if (!chatId || !messageId)
202 return {
203 ok: false,
204 error: 'Missing message context for callback',
205 callbackAnswered
206 };
207
208 try {
209 if (data.startsWith('approve:')) {
210 if (ownerId === undefined || ownerId === null)
211 throw new Error('Approval owner is required');
212 const token = data.slice('approve:'.length);
213 let payload;
214 try {
215 payload = await this.approvals.consume(token, {
216 ownerId: String(ownerId),
217 pluginId: 'github',
218 risk: 'WRITE'
219 });
220 } catch (error) {
221 this.audit.log({
222 event: 'approval_rejected',
223 pluginId: 'github',
224 risk: 'WRITE',
225 outcome: 'rejected',
226 error: error?.message || 'Approval rejected'
227 });
228 const view = approvalRejectedView(message, error);
229 const res = await this.telegram.editMessageText(
230 chatId,
231 messageId,
232 view.text,
233 view.reply_markup
234 );
235 return {
236 ok: false,
237 approvalRejected: true,
238 error: error?.message || 'Approval rejected',
239 callbackAnswered,
240 edited: true,
241 res
242 };
243 }
244
245 this.audit.log({
246 event: 'approval_verified',
247 pluginId: payload.pluginId,
248 actionId: payload.actionId,
249 risk: payload.risk,
250 outcome: 'verified'
251 });
252 const sourceCallback = approvalSourceCallback(payload);
253 let routed;
254 try {
255 routed = await this.router.dispatchCallback(sourceCallback, {
256 isOwner: true,
257 ownerId: String(ownerId),
258 approved: true
259 });
260 if (!routed || routed.requiresApproval || routed.denied)
261 throw new Error('Approved action could not be dispatched');
262 } catch (error) {
263 const view = await buildApprovedActionFailedView({
264 payload,
265 error,
266 ownerId,
267 workspaces: this.workspaceStore
268 });
269 const res = await this.telegram.editMessageText(
270 chatId,
271 messageId,
272 view.text,
273 view.reply_markup
274 );
275 return {
276 ok: false,
277 approved: true,
278 providerError: true,
279 actionId: payload.actionId,
280 error: error?.message || 'GitHub operation failed',
281 callbackAnswered,
282 edited: true,
283 res
284 };
285 }
286
287 const res = await this.telegram.editMessageText(
288 chatId,
289 messageId,
290 routed.text,
291 routed.reply_markup
292 );
293 return {
294 ok: true,
295 approved: true,
296 actionId: payload.actionId,
297 callbackAnswered,
298 edited: true,
299 res
300 };
301 }
302
303 const routed = await this.router.dispatchCallback(data, {
304 isOwner: true,
305 ownerId:
306 ownerId === undefined || ownerId === null ? '' : String(ownerId)
307 });
308 if (!routed) {
309 const view = await this.menu.renderByCallback(data);
310 const res = await this.telegram.editMessageText(
311 chatId,
312 messageId,
313 view.text,
314 view.reply_markup
315 );
316 return { ok: true, edited: true, callbackAnswered, res };
317 }
318 if (routed?.requiresApproval) {
319 const approval = routed.approval;
320 const repoId = approval?.input?.repoId;
321 if (!approval || !Number.isSafeInteger(Number(repoId)))
322 throw new Error('Approval metadata is missing');
323 const workspaceApproval =
324 routed.actionId === 'github.workspace.commit_branch';
325 const runId = approval?.input?.runId;
326 const intentId = String(approval?.input?.intentId || '');
327 if (workspaceApproval) {
328 if (!INTENT_ID_PATTERN.test(intentId))
329 throw new Error('Approval metadata is missing');
330 } else if (!Number.isSafeInteger(Number(runId))) {
331 throw new Error('Approval metadata is missing');
332 }
333 if (ownerId === undefined || ownerId === null)
334 throw new Error('Approval owner is required');
335 if (!this.approvals.isReplayProtected())
336 throw new Error(
337 'Durable approval replay protection is not configured'
338 );
339
340 const token = await this.approvals.issue({
341 pluginId: routed.pluginId,
342 actionId: routed.actionId,
343 risk: routed.risk,
344 ownerId: String(ownerId),
345 input: approval.input
346 });
347 this.audit.log({
348 event: 'approval_issued',
349 pluginId: routed.pluginId,
350 actionId: routed.actionId,
351 risk: routed.risk,
352 outcome: 'pending'
353 });
354 const cancelCallback =
355 approval.cancelCallback ||
356 (Number.isSafeInteger(Number(runId))
357 ? `run:${repoId}:${runId}`
358 : `repo:${repoId}`);
359 const view = approvalView({
360 label: approval.label || routed.actionId,
361 token,
362 cancelCallback
363 });
364 const res = await this.telegram.editMessageText(
365 chatId,
366 messageId,
367 view.text,
368 view.reply_markup
369 );
370 return {
371 ok: true,
372 approvalRequired: true,
373 actionId: routed.actionId,
374 risk: routed.risk,
375 callbackAnswered,
376 edited: true,
377 res
378 };
379 }
380 if (routed?.denied)
381 return {
382 ok: false,
383 denied: true,
384 actionId: routed.actionId,
385 reason: routed.reason,
386 callbackAnswered
387 };
388
389 const view = routed || (await this.menu.renderByCallback(data));
390 const res = await this.telegram.editMessageText(
391 chatId,
392 messageId,
393 view.text,
394 view.reply_markup
395 );
396 return { ok: true, edited: true, callbackAnswered, res };
397 } catch (err) {
398 if (err.message && err.message.includes('message is not modified'))
399 return { ok: true, unmodified: true, callbackAnswered };
400 if (!data.startsWith('approve:')) {
401 try {
402 const view = await buildCallbackFailureView({
403 data,
404 error: err,
405 ownerId,
406 workspaces: this.workspaceStore
407 });
408 const res = await this.telegram.editMessageText(
409 chatId,
410 messageId,
411 view.text,
412 view.reply_markup
413 );
414 return {
415 ok: false,
416 error: err.message,
417 providerError: !view.validationError,
418 validationError: Boolean(view.validationError),
419 callbackAnswered,
420 edited: true,
421 res
422 };
423 } catch {
424 // Preserve the original provider/navigation error when feedback delivery also fails.
425 }
426 }
427 return { ok: false, error: err.message, callbackAnswered };
428 }
429 }
430
431 async handleMessage(message) {
432 const intercepted = await interceptTelegramSecretMessage({
433 message,
434 telegram: this.telegram,
435 ownerId: this.env.OWNER_TELEGRAM_ID
436 });
437 if (intercepted) return intercepted;
438 const chatId = message.chat?.id;
439 const rawText = typeof message.text === 'string' ? message.text : '';
440 const text = rawText.trim();
441 if (!chatId) return { ok: false, error: 'Missing chat_id' };
442
443 if (text === '/start' || text === '/menu' || text.startsWith('/start')) {
444 const quickMenuRes = await this.telegram.sendMessage(
445 chatId,
446 '⌨️ <b>منوی سریع Nexa Dev فعال شد</b>\nاین منو پایین صفحه می‌ماند و از هر بخش قابل استفاده است.',
447 persistentQuickMenuMarkup()
448 );
449 const view = this.menu.getMainMenuView();
450 const res = await this.telegram.sendMessage(
451 chatId,
452 view.text,
453 view.reply_markup
454 );
455 return {
456 ok: true,
457 command: 'start',
458 persistentMenu: true,
459 quickMenuRes,
460 res
461 };
462 }
463
464 const quickMenu = QUICK_MENU[text];
465 if (quickMenu) {
466 let view;
467 if (quickMenu === 'main') {
468 view = this.menu.getMainMenuView();
469 } else if (quickMenu === 'repos') {
470 const routed = await this.router.dispatchCommand('/repos', {
471 isOwner: true
472 });
473 if (routed?.requiresApproval || routed?.denied || !routed) {
474 return {
475 ok: false,
476 quickMenu,
477 error: routed?.reason || 'GitHub repository route unavailable'
478 };
479 }
480 view = routed;
481 } else if (quickMenu === 'status') {
482 view = await this.menu.getServiceStatusView();
483 } else if (quickMenu === 'tools') {
484 view = this.menu.getToolsView();
485 } else {
486 view = this.menu.getSecurityView();
487 }
488 const res = await this.telegram.sendMessage(
489 chatId,
490 view.text,
491 view.reply_markup
492 );
493 return { ok: true, quickMenu, res };
494 }
495
496 if (text === '/repos') {
497 const routed = await this.router.dispatchCommand(text, { isOwner: true });
498 if (routed?.requiresApproval || routed?.denied || !routed) {
499 return {
500 ok: false,
501 command: 'repos',
502 error: routed?.reason || 'GitHub repository route unavailable'
503 };
504 }
505 const res = await this.telegram.sendMessage(
506 chatId,
507 routed.text,
508 routed.reply_markup
509 );
510 return { ok: true, command: 'repos', res };
511 }
512
513 if (text === '/status') {
514 const view = await this.menu.getServiceStatusView();
515 const res = await this.telegram.sendMessage(
516 chatId,
517 view.text,
518 view.reply_markup
519 );
520 return { ok: true, command: 'status', res };
521 }
522
523 const ownerId = message.from?.id;
524 if (
525 ownerId !== undefined &&
526 ownerId !== null &&
527 this.workspaceStore.isConfigured()
528 ) {
529 const pending = await this.workspaceStore.getPendingInput({
530 ownerId: String(ownerId)
531 });
532 if (pending) {
533 // Historical source-input modes can only expire/redirect to Mini App.
534 // Their message bodies and documents never reach controller dispatch.
535 const sourceInput = ['draft', 'draft_file'].includes(pending.mode);
536 const payload = sourceInput ? { pending } : { pending, text: rawText };
537
538 const routed = await this.router.dispatchMessage(payload, {
539 isOwner: true,
540 ownerId: String(ownerId)
541 });
542 if (routed?.requiresApproval || routed?.denied || !routed) {
543 return {
544 ok: false,
545 error: routed?.reason || 'Workspace input route unavailable'
546 };
547 }
548 const res = await this.telegram.sendMessage(
549 chatId,
550 routed.text,
551 routed.reply_markup
552 );
553 return { ok: true, workspaceInput: true, res };
554 }
555 }
556
557 const defaultText =
558 '💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:';
559 const view = {
560 text: defaultText,
561 reply_markup: {
562 inline_keyboard: [
563 [
564 {
565 text: '⚡ باز کردن منوی اصلی Nexa Dev',
566 callback_data: 'menu:main'
567 }
568 ]
569 ]
570 }
571 };
572 const res = await this.telegram.sendMessage(
573 chatId,
574 view.text,
575 view.reply_markup
576 );
577 return { ok: true, default: true, res };
578 }
579 }