fix/approval-expiry-feedback
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 325 lines 10.6 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 export class NexaDevBot {
75 constructor(env = {}) {
76 this.env = env;
77 this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
78 this.github = new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER || 'davoodmehraban89');
79 this.menu = new MenuManager(this.github);
80 this.replayStore = new DurableApprovalReplayStore({
81 namespace: env.APPROVAL_REPLAY_GUARD
82 });
83 this.approvals = new ApprovalService({
84 secret: env.APPROVAL_SIGNING_SECRET || env.TELEGRAM_WEBHOOK_SECRET || '',
85 replayStore: this.replayStore
86 });
87
88 this.githubPlugin = createGitHubPlugin({
89 github: this.github,
90 menu: this.menu
91 });
92 this.registry = new PluginRegistry([this.githubPlugin]);
93 this.policy = new ActionPolicy();
94 this.audit = new AuditLogger({
95 secrets: [
96 env.TELEGRAM_BOT_TOKEN,
97 env.TELEGRAM_WEBHOOK_SECRET,
98 env.GITHUB_TOKEN,
99 env.APPROVAL_SIGNING_SECRET
100 ]
101 });
102 this.router = new PluginRouter({
103 registry: this.registry,
104 policy: this.policy,
105 audit: this.audit
106 });
107 }
108
109 async handleUpdate(update) {
110 if (!update) return { ok: false, error: 'Empty update' };
111 if (update.callback_query) return this.handleCallbackQuery(update.callback_query);
112 if (update.message) return this.handleMessage(update.message);
113 return { ok: true, ignored: true };
114 }
115
116 async handleCallbackQuery(query) {
117 const callbackId = query.id;
118 const data = query.data || 'menu:main';
119 const message = query.message;
120 const chatId = message?.chat?.id;
121 const messageId = message?.message_id;
122 const ownerId = query.from?.id;
123
124 let callbackAnswered = true;
125 try {
126 await this.telegram.answerCallbackQuery(callbackId);
127 } catch {
128 callbackAnswered = false;
129 }
130
131 if (!chatId || !messageId) {
132 return { ok: false, error: 'Missing message context for callback', callbackAnswered };
133 }
134
135 try {
136 if (data.startsWith('approve:')) {
137 if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
138 const token = data.slice('approve:'.length);
139 let payload;
140 try {
141 payload = await this.approvals.consume(token, {
142 ownerId: String(ownerId),
143 pluginId: 'github',
144 risk: 'WRITE'
145 });
146 } catch (error) {
147 this.audit.log({
148 event: 'approval_rejected',
149 pluginId: 'github',
150 risk: 'WRITE',
151 outcome: 'rejected',
152 error: error?.message || 'Approval rejected'
153 });
154 const view = approvalRejectedView(message, error);
155 const res = await this.telegram.editMessageText(
156 chatId,
157 messageId,
158 view.text,
159 view.reply_markup
160 );
161 return {
162 ok: false,
163 approvalRejected: true,
164 error: error?.message || 'Approval rejected',
165 callbackAnswered,
166 edited: true,
167 res
168 };
169 }
170
171 this.audit.log({
172 event: 'approval_verified',
173 pluginId: payload.pluginId,
174 actionId: payload.actionId,
175 risk: payload.risk,
176 outcome: 'verified'
177 });
178
179 const sourceCallback = approvalSourceCallback(payload);
180 const routed = await this.router.dispatchCallback(sourceCallback, {
181 isOwner: true,
182 approved: true
183 });
184 if (!routed || routed.requiresApproval || routed.denied) {
185 throw new Error('Approved action could not be dispatched');
186 }
187
188 const res = await this.telegram.editMessageText(
189 chatId,
190 messageId,
191 routed.text,
192 routed.reply_markup
193 );
194 return {
195 ok: true,
196 approved: true,
197 actionId: payload.actionId,
198 callbackAnswered,
199 edited: true,
200 res
201 };
202 }
203
204 const routed = await this.router.dispatchCallback(data, { isOwner: true });
205 if (routed?.requiresApproval) {
206 const approval = routed.approval;
207 const repoId = approval?.input?.repoId;
208 const runId = approval?.input?.runId;
209 if (!approval || !Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(runId))) {
210 throw new Error('Approval metadata is missing');
211 }
212 if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
213 if (!this.approvals.isReplayProtected()) {
214 throw new Error('Durable approval replay protection is not configured');
215 }
216
217 const token = await this.approvals.issue({
218 pluginId: routed.pluginId,
219 actionId: routed.actionId,
220 risk: routed.risk,
221 ownerId: String(ownerId),
222 input: approval.input
223 });
224 this.audit.log({
225 event: 'approval_issued',
226 pluginId: routed.pluginId,
227 actionId: routed.actionId,
228 risk: routed.risk,
229 outcome: 'pending'
230 });
231
232 const view = approvalView({
233 label: approval.label || routed.actionId,
234 token,
235 repoId,
236 runId
237 });
238 const res = await this.telegram.editMessageText(
239 chatId,
240 messageId,
241 view.text,
242 view.reply_markup
243 );
244 return {
245 ok: true,
246 approvalRequired: true,
247 actionId: routed.actionId,
248 risk: routed.risk,
249 callbackAnswered,
250 edited: true,
251 res
252 };
253 }
254 if (routed?.denied) {
255 return {
256 ok: false,
257 denied: true,
258 actionId: routed.actionId,
259 reason: routed.reason,
260 callbackAnswered
261 };
262 }
263
264 const view = routed || await this.menu.renderByCallback(data);
265 const res = await this.telegram.editMessageText(
266 chatId,
267 messageId,
268 view.text,
269 view.reply_markup
270 );
271
272 return { ok: true, edited: true, callbackAnswered, res };
273 } catch (err) {
274 if (err.message && err.message.includes('message is not modified')) {
275 return { ok: true, unmodified: true, callbackAnswered };
276 }
277 return { ok: false, error: err.message, callbackAnswered };
278 }
279 }
280
281 async handleMessage(message) {
282 const chatId = message.chat?.id;
283 const text = (message.text || '').trim();
284
285 if (!chatId) return { ok: false, error: 'Missing chat_id' };
286
287 if (text === '/start' || text === '/menu' || text.startsWith('/start')) {
288 const view = this.menu.getMainMenuView();
289 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
290 return { ok: true, command: 'start', res };
291 }
292
293 if (text === '/repos') {
294 const routed = await this.router.dispatchCommand(text, { isOwner: true });
295 if (routed?.requiresApproval || routed?.denied || !routed) {
296 return {
297 ok: false,
298 command: 'repos',
299 error: routed?.reason || 'GitHub repository route unavailable'
300 };
301 }
302
303 const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
304 return { ok: true, command: 'repos', res };
305 }
306
307 if (text === '/status') {
308 const view = this.menu.getServiceStatusView();
309 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
310 return { ok: true, command: 'status', res };
311 }
312
313 const defaultText = `💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:`;
314 const view = {
315 text: defaultText,
316 reply_markup: {
317 inline_keyboard: [
318 [{ text: '⚡ باز کردن منوی اصلی Nexa Dev', callback_data: 'menu:main' }]
319 ]
320 }
321 };
322 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
323 return { ok: true, default: true, res };
324 }
325 }