Personal Telegram developer console for GitHub

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