Personal Telegram developer console for GitHub

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