Personal Telegram developer console for GitHub

phase2-20261005-q
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 388 lines 18.8 KB
Raw
1 import { TelegramClient } from './telegram.js';
2 import { GitHubService } from './github.js';
3 import { MenuManager } from './menu.js';
4 import { PluginRegistry } from './core/plugin-registry.js';
5 import { ActionPolicy } from './core/action-policy.js';
6 import { ApprovalService } from './core/approval.js';
7 import { DurableApprovalReplayStore } from './core/durable-replay-store.js';
8 import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
9 import { WORKSPACE_EDITOR_LIMITS } from './core/workspace-policy.js';
10 import { AuditLogger } from './core/audit.js';
11 import { PluginRouter } from './core/router.js';
12 import { buildApprovedActionFailedView, buildCallbackFailureView } from './core/callback-failure-view.js';
13 import { createGitHubPlugin } from './plugins/github/plugin.js';
14 import { CloudflareService } from './plugins/cloudflare/service.js';
15 import { createCloudflarePlugin } from './plugins/cloudflare/plugin.js';
16
17 const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
18 const QUICK_MENU = Object.freeze({
19 '🏠 منوی اصلی': 'main',
20 '📁 پروژه‌ها': 'repos',
21 '📊 وضعیت': 'status',
22 '🔧 ابزارها': 'tools',
23 '🔐 امنیت': 'security'
24 });
25 const escapeHtml = value => String(value ?? '')
26 .replaceAll('&', '&')
27 .replaceAll('<', '&lt;')
28 .replaceAll('>', '&gt;')
29 .replaceAll('"', '&quot;');
30
31 function persistentQuickMenuMarkup() {
32 return {
33 keyboard: [
34 [{ text: '🏠 منوی اصلی' }, { text: '📁 پروژه‌ها' }],
35 [{ text: '📊 وضعیت' }, { text: '🔧 ابزارها' }],
36 [{ text: '🔐 امنیت' }]
37 ],
38 resize_keyboard: true,
39 is_persistent: true,
40 input_field_placeholder: 'Nexa Dev — یک گزینه را انتخاب کنید'
41 };
42 }
43
44 function focusedCodeInputMarkup() {
45 return {
46 force_reply: true,
47 selective: true,
48 input_field_placeholder: 'کد یا متن را اینجا Paste کنید…'
49 };
50 }
51
52 function approvalSourceCallback(payload = {}) {
53 const repoId = payload.input?.repoId;
54 if (!Number.isSafeInteger(Number(repoId))) throw new Error('Approval input is invalid');
55
56 if (payload.actionId === 'github.workspace.commit_branch') {
57 const intentId = String(payload.input?.intentId || '');
58 if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval input is invalid');
59 return `wscommit:${repoId}:${intentId}`;
60 }
61
62 const runId = payload.input?.runId;
63 if (!Number.isSafeInteger(Number(runId))) throw new Error('Approval input is invalid');
64 if (payload.actionId === 'github.workflow.dispatch') return `dispatchwf:${repoId}:${runId}`;
65 if (payload.actionId === 'github.workflow.job.rerun') return `rerunjob:${repoId}:${runId}`;
66 if (payload.actionId === 'github.workflow.run.rerun_failed') return `rerun:${repoId}:${runId}`;
67 if (payload.actionId === 'github.workflow.run.cancel') return `cancelrun:${repoId}:${runId}`;
68 throw new Error('Approval action is not supported');
69 }
70
71 function approvalView({ label, token, cancelCallback = 'menu:main' }) {
72 return {
73 text:
74 `⚠️ <b>تأیید عملیات لازم است</b>
75 ➖➖➖➖➖➖➖➖➖➖
76 عملیات: <b>${label}</b>
77 این عملیات روی GitHub تغییر ایجاد می‌کند و فقط پس از تأیید شما اجرا می‌شود.
78
79 اگر مطمئن هستید، «تأیید و اجرا» را بزنید.`,
80 reply_markup: {
81 inline_keyboard: [
82 [{ text: '✅ تأیید و اجرا', callback_data: `approve:${token}` }],
83 [{ text: '↩️ انصراف', callback_data: cancelCallback }]
84 ]
85 }
86 };
87 }
88
89 function approvalRejectedView(message, error) {
90 const reason = String(error?.message || 'Approval rejected');
91 const expired = /expired/i.test(reason);
92 const used = /already used|replay/i.test(reason);
93 const fallback = message?.reply_markup?.inline_keyboard
94 ?.flat()
95 .map(button => String(button?.callback_data || ''))
96 .find(callback => callback && !callback.startsWith('approve:')) || 'menu:main';
97
98 let detail = 'این تأیید معتبر نیست و هیچ تغییری اجرا نشد.';
99 if (expired) detail = 'مهلت این تأیید تمام شده است و هیچ تغییری اجرا نشد.';
100 if (used) detail = 'این تأیید قبلاً استفاده شده است و دوباره اجرا نمی‌شود.';
101 const backText = fallback.startsWith('run:') ? '↩️ بازگشت به Run' : '↩️ بازگشت';
102
103 return {
104 text:
105 `⚠️ <b>عملیات اجرا نشد</b>
106 ➖➖➖➖➖➖➖➖➖➖
107 ${detail}
108
109 برای ادامه برگردید و در صورت نیاز یک تأیید تازه ایجاد کنید.`,
110 reply_markup: { inline_keyboard: [[{ text: backText, callback_data: fallback }]] }
111 };
112 }
113
114 export class NexaDevBot {
115 constructor(env = {}) {
116 this.env = env;
117 this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
118 this.github = new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER || 'davoodmehraban89');
119 this.menu = new MenuManager(this.github);
120 this.replayStore = new DurableApprovalReplayStore({ namespace: env.APPROVAL_REPLAY_GUARD });
121 this.workspaceStore = new DurableWorkspaceStoreClient({ namespace: env.WORKSPACE_STORE });
122 this.approvals = new ApprovalService({
123 secret: env.APPROVAL_SIGNING_SECRET || env.TELEGRAM_WEBHOOK_SECRET || '',
124 replayStore: this.replayStore
125 });
126 this.githubPlugin = createGitHubPlugin({
127 github: this.github,
128 menu: this.menu,
129 workspaces: this.workspaceStore.isConfigured() ? this.workspaceStore : null
130 });
131 this.cloudflare = new CloudflareService({
132 token: env.CLOUDFLARE_API_TOKEN || '',
133 accountId: env.CLOUDFLARE_ACCOUNT_ID || '',
134 workerName: env.CLOUDFLARE_WORKER_NAME || 'nexa-dev-bot'
135 });
136 this.cloudflarePlugin = createCloudflarePlugin({ cloudflare: this.cloudflare, github: this.github });
137 this.registry = new PluginRegistry([this.githubPlugin, this.cloudflarePlugin]);
138 this.policy = new ActionPolicy();
139 this.audit = new AuditLogger({
140 secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.CLOUDFLARE_API_TOKEN, env.APPROVAL_SIGNING_SECRET, env.DESTRUCTIVE_TOTP_SECRET]
141 });
142 this.router = new PluginRouter({ registry: this.registry, policy: this.policy, audit: this.audit });
143 }
144
145 async handleUpdate(update) {
146 if (!update) return { ok: false, error: 'Empty update' };
147 if (update.callback_query) return this.handleCallbackQuery(update.callback_query);
148 if (update.message) return this.handleMessage(update.message);
149 return { ok: true, ignored: true };
150 }
151
152 async handleCallbackQuery(query) {
153 const callbackId = query.id;
154 const data = query.data || 'menu:main';
155 const message = query.message;
156 const chatId = message?.chat?.id;
157 const messageId = message?.message_id;
158 const ownerId = query.from?.id;
159
160 let callbackAnswered = true;
161 try { await this.telegram.answerCallbackQuery(callbackId); } catch { callbackAnswered = false; }
162 if (!chatId || !messageId) return { ok: false, error: 'Missing message context for callback', callbackAnswered };
163
164 try {
165 if (data.startsWith('approve:')) {
166 if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
167 const token = data.slice('approve:'.length);
168 let payload;
169 try {
170 payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'github', risk: 'WRITE' });
171 } catch (error) {
172 this.audit.log({ event: 'approval_rejected', pluginId: 'github', risk: 'WRITE', outcome: 'rejected', error: error?.message || 'Approval rejected' });
173 const view = approvalRejectedView(message, error);
174 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
175 return { ok: false, approvalRejected: true, error: error?.message || 'Approval rejected', callbackAnswered, edited: true, res };
176 }
177
178 this.audit.log({ event: 'approval_verified', pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, outcome: 'verified' });
179 const sourceCallback = approvalSourceCallback(payload);
180 let routed;
181 try {
182 routed = await this.router.dispatchCallback(sourceCallback, {
183 isOwner: true,
184 ownerId: String(ownerId),
185 approved: true
186 });
187 if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved action could not be dispatched');
188 } catch (error) {
189 const view = await buildApprovedActionFailedView({
190 payload,
191 error,
192 ownerId,
193 workspaces: this.workspaceStore
194 });
195 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
196 return { ok: false, approved: true, providerError: true, actionId: payload.actionId, error: error?.message || 'GitHub operation failed', callbackAnswered, edited: true, res };
197 }
198
199 const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
200 return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
201 }
202
203 const routed = await this.router.dispatchCallback(data, {
204 isOwner: true,
205 ownerId: ownerId === undefined || ownerId === null ? '' : String(ownerId)
206 });
207 if (routed?.requiresApproval) {
208 const approval = routed.approval;
209 const repoId = approval?.input?.repoId;
210 if (!approval || !Number.isSafeInteger(Number(repoId))) throw new Error('Approval metadata is missing');
211 const workspaceApproval = routed.actionId === 'github.workspace.commit_branch';
212 const runId = approval?.input?.runId;
213 const intentId = String(approval?.input?.intentId || '');
214 if (workspaceApproval) {
215 if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval metadata is missing');
216 } else if (!Number.isSafeInteger(Number(runId))) {
217 throw new Error('Approval metadata is missing');
218 }
219 if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
220 if (!this.approvals.isReplayProtected()) throw new Error('Durable approval replay protection is not configured');
221
222 const token = await this.approvals.issue({
223 pluginId: routed.pluginId,
224 actionId: routed.actionId,
225 risk: routed.risk,
226 ownerId: String(ownerId),
227 input: approval.input
228 });
229 this.audit.log({ event: 'approval_issued', pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, outcome: 'pending' });
230 const cancelCallback = approval.cancelCallback || (Number.isSafeInteger(Number(runId)) ? `run:${repoId}:${runId}` : `repo:${repoId}`);
231 const view = approvalView({ label: approval.label || routed.actionId, token, cancelCallback });
232 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
233 return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
234 }
235 if (routed?.denied) return { ok: false, denied: true, actionId: routed.actionId, reason: routed.reason, callbackAnswered };
236
237 const view = routed || await this.menu.renderByCallback(data);
238 if (data.startsWith('wtext:') && routed) {
239 const res = await this.telegram.sendMessage(chatId, view.text, focusedCodeInputMarkup());
240 return { ok: true, inputPrompt: true, callbackAnswered, sent: true, res };
241 }
242 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
243 return { ok: true, edited: true, callbackAnswered, res };
244 } catch (err) {
245 if (err.message && err.message.includes('message is not modified')) return { ok: true, unmodified: true, callbackAnswered };
246 if (!data.startsWith('approve:')) {
247 try {
248 const view = await buildCallbackFailureView({ data, error: err, ownerId, workspaces: this.workspaceStore });
249 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
250 return {
251 ok: false,
252 error: err.message,
253 providerError: !view.validationError,
254 validationError: Boolean(view.validationError),
255 callbackAnswered,
256 edited: true,
257 res
258 };
259 } catch {
260 // Preserve the original provider/navigation error when feedback delivery also fails.
261 }
262 }
263 return { ok: false, error: err.message, callbackAnswered };
264 }
265 }
266
267 async handleMessage(message) {
268 const chatId = message.chat?.id;
269 const rawText = typeof message.text === 'string' ? message.text : '';
270 const text = rawText.trim();
271 if (!chatId) return { ok: false, error: 'Missing chat_id' };
272
273 if (text === '/start' || text === '/menu' || text.startsWith('/start')) {
274 const quickMenuRes = await this.telegram.sendMessage(
275 chatId,
276 '⌨️ <b>منوی سریع Nexa Dev فعال شد</b>\nاین منو پایین صفحه می‌ماند و از هر بخش قابل استفاده است.',
277 persistentQuickMenuMarkup()
278 );
279 const view = this.menu.getMainMenuView();
280 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
281 return { ok: true, command: 'start', persistentMenu: true, quickMenuRes, res };
282 }
283
284 const quickMenu = QUICK_MENU[text];
285 if (quickMenu) {
286 let view;
287 if (quickMenu === 'main') {
288 view = this.menu.getMainMenuView();
289 } else if (quickMenu === 'repos') {
290 const routed = await this.router.dispatchCommand('/repos', { isOwner: true });
291 if (routed?.requiresApproval || routed?.denied || !routed) {
292 return { ok: false, quickMenu, error: routed?.reason || 'GitHub repository route unavailable' };
293 }
294 view = routed;
295 } else if (quickMenu === 'status') {
296 view = this.menu.getServiceStatusView();
297 } else if (quickMenu === 'tools') {
298 view = this.menu.getToolsView();
299 } else {
300 view = this.menu.getSecurityView();
301 }
302 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
303 return { ok: true, quickMenu, res };
304 }
305
306 if (text === '/repos') {
307 const routed = await this.router.dispatchCommand(text, { isOwner: true });
308 if (routed?.requiresApproval || routed?.denied || !routed) {
309 return { ok: false, command: 'repos', error: routed?.reason || 'GitHub repository route unavailable' };
310 }
311 const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
312 return { ok: true, command: 'repos', res };
313 }
314
315 if (text === '/status') {
316 const view = this.menu.getServiceStatusView();
317 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
318 return { ok: true, command: 'status', res };
319 }
320
321 const ownerId = message.from?.id;
322 if (ownerId !== undefined && ownerId !== null && this.workspaceStore.isConfigured()) {
323 const pending = await this.workspaceStore.getPendingInput({ ownerId: String(ownerId) });
324 if (pending) {
325 let payload = { pending, text: rawText };
326 if (pending.mode === 'draft_file') {
327 const document = message.document;
328 const maxUploadBytes = WORKSPACE_EDITOR_LIMITS.maxBytes;
329 if (!document?.file_id) {
330 const view = {
331 text: `📎 <b>یک فایل متنی ارسال کنید</b>\nاین Workspace در حالت بارگذاری فایل است. فایل باید UTF-8 معتبر و حداکثر ${maxUploadBytes.toLocaleString('en-US')} بایت باشد.`,
332 reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
333 };
334 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
335 return { ok: true, workspaceInput: true, inputRequired: 'document', res };
336 }
337 if (Number.isFinite(Number(document.file_size)) && Number(document.file_size) > maxUploadBytes) {
338 const view = {
339 text: `⚠️ <b>فایل پذیرفته نشد</b>\nحجم فایل بیشتر از سقف ${maxUploadBytes.toLocaleString('en-US')} بایت است. Draft تغییر نکرد؛ یک فایل کوچک‌تر ارسال کنید.`,
340 reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
341 };
342 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
343 return { ok: false, workspaceInput: true, inputRejected: true, error: `Telegram file exceeds ${maxUploadBytes} byte size limit`, res };
344 }
345 let downloaded;
346 try {
347 downloaded = await this.telegram.downloadTextFile(document.file_id, { maxBytes: maxUploadBytes });
348 } catch (error) {
349 const view = {
350 text: `⚠️ <b>فایل پذیرفته نشد</b>\n${escapeHtml(error?.message || 'Telegram file download failed')}\n\nDraft تغییر نکرد و می‌توانید فایل دیگری ارسال کنید.`,
351 reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
352 };
353 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
354 return { ok: false, workspaceInput: true, inputRejected: true, error: error?.message || 'Telegram file download failed', res };
355 }
356 payload = {
357 pending,
358 file: {
359 name: String(document.file_name || 'uploaded.txt'),
360 text: downloaded.text,
361 byteLength: downloaded.byteLength
362 }
363 };
364 }
365
366 const routed = await this.router.dispatchMessage(
367 payload,
368 { isOwner: true, ownerId: String(ownerId) }
369 );
370 if (routed?.requiresApproval || routed?.denied || !routed) {
371 return { ok: false, error: routed?.reason || 'Workspace input route unavailable' };
372 }
373 const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
374 return { ok: true, workspaceInput: true, res };
375 }
376 }
377
378 const defaultText = '💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:';
379 const view = {
380 text: defaultText,
381 reply_markup: {
382 inline_keyboard: [[{ text: '⚡ باز کردن منوی اصلی Nexa Dev', callback_data: 'menu:main' }]]
383 }
384 };
385 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
386 return { ok: true, default: true, res };
387 }
388 }