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