Personal Telegram developer console for GitHub

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