Personal Telegram developer console for GitHub

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