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