Personal Telegram developer console for GitHub

spec/repository-workspace-editor
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 314 lines 15.7 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 escapeHtml = value => String(value ?? '')
15 .replaceAll('&', '&')
16 .replaceAll('<', '&lt;')
17 .replaceAll('>', '&gt;')
18 .replaceAll('"', '&quot;');
19
20 function approvalSourceCallback(payload = {}) {
21 const repoId = payload.input?.repoId;
22 if (!Number.isSafeInteger(Number(repoId))) throw new Error('Approval input is invalid');
23
24 if (payload.actionId === 'github.workspace.commit_branch') {
25 const intentId = String(payload.input?.intentId || '');
26 if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval input is invalid');
27 return `wscommit:${repoId}:${intentId}`;
28 }
29
30 const runId = payload.input?.runId;
31 if (!Number.isSafeInteger(Number(runId))) throw new Error('Approval input is invalid');
32 if (payload.actionId === 'github.workflow.run.rerun_failed') return `rerun:${repoId}:${runId}`;
33 if (payload.actionId === 'github.workflow.run.cancel') return `cancelrun:${repoId}:${runId}`;
34 throw new Error('Approval action is not supported');
35 }
36
37 function approvalView({ label, token, cancelCallback = 'menu:main' }) {
38 return {
39 text:
40 `⚠️ <b>تأیید عملیات لازم است</b>
41 ➖➖➖➖➖➖➖➖➖➖
42 عملیات: <b>${label}</b>
43 این عملیات روی GitHub تغییر ایجاد می‌کند و فقط پس از تأیید شما اجرا می‌شود.
44
45 اگر مطمئن هستید، «تأیید و اجرا» را بزنید.`,
46 reply_markup: {
47 inline_keyboard: [
48 [{ text: '✅ تأیید و اجرا', callback_data: `approve:${token}` }],
49 [{ text: '↩️ انصراف', callback_data: cancelCallback }]
50 ]
51 }
52 };
53 }
54
55 function approvalRejectedView(message, error) {
56 const reason = String(error?.message || 'Approval rejected');
57 const expired = /expired/i.test(reason);
58 const used = /already used|replay/i.test(reason);
59 const fallback = message?.reply_markup?.inline_keyboard
60 ?.flat()
61 .map(button => String(button?.callback_data || ''))
62 .find(callback => callback && !callback.startsWith('approve:')) || 'menu:main';
63
64 let detail = 'این تأیید معتبر نیست و هیچ تغییری اجرا نشد.';
65 if (expired) detail = 'مهلت این تأیید تمام شده است و هیچ تغییری اجرا نشد.';
66 if (used) detail = 'این تأیید قبلاً استفاده شده است و دوباره اجرا نمی‌شود.';
67 const backText = fallback.startsWith('run:') ? '↩️ بازگشت به Run' : '↩️ بازگشت';
68
69 return {
70 text:
71 `⚠️ <b>عملیات اجرا نشد</b>
72 ➖➖➖➖➖➖➖➖➖➖
73 ${detail}
74
75 برای ادامه برگردید و در صورت نیاز یک تأیید تازه ایجاد کنید.`,
76 reply_markup: { inline_keyboard: [[{ text: backText, callback_data: fallback }]] }
77 };
78 }
79
80 function approvedActionFailedView(payload, error) {
81 const reason = String(error?.message || 'GitHub operation failed');
82 const permissionDenied = /403|resource not accessible by personal access token/i.test(reason);
83 const repoId = payload?.input?.repoId;
84 const runId = payload?.input?.runId;
85 const workspaceAction = payload?.actionId === 'github.workspace.commit_branch';
86 const fallback = workspaceAction && Number.isSafeInteger(Number(repoId))
87 ? `repo:${repoId}`
88 : Number.isSafeInteger(Number(repoId)) && Number.isSafeInteger(Number(runId))
89 ? `run:${repoId}:${runId}`
90 : 'menu:main';
91 const detail = workspaceAction
92 ? permissionDenied
93 ? 'تأیید شما معتبر بود، اما GitHub درخواست Commit شاخه را با خطای 403 رد کرد. دسترسی Contents WRITE توکن فعلی را بررسی کنید.'
94 : `تأیید شما معتبر بود، اما Commit شاخه انجام نشد: ${escapeHtml(reason)}`
95 : permissionDenied
96 ? 'تأیید شما معتبر بود، اما GitHub درخواست را با خطای 403 رد کرد. دسترسی توکن فعلی برای GitHub Actions WRITE کافی نیست.'
97 : 'تأیید شما معتبر بود، اما GitHub عملیات را موفق اعلام نکرد. وضعیت Run را بررسی کنید.';
98 return {
99 text:
100 `⚠️ <b>اجرای عملیات در GitHub ناموفق بود</b>
101 ➖➖➖➖➖➖➖➖➖➖
102 ${detail}
103
104 این تأیید یک‌بار مصرف شده و با همان دکمه دوباره اجرا نمی‌شود.`,
105 reply_markup: { inline_keyboard: [[{ text: workspaceAction ? '↩️ بازگشت به پروژه' : '↩️ بازگشت به Run', callback_data: fallback }]] }
106 };
107 }
108
109 function callbackReadFailedView(data, error) {
110 const reason = String(error?.message || 'Provider read failed');
111 const permissionDenied = /403|resource not accessible by personal access token/i.test(reason);
112 const repoMatch = String(data || '').match(/^[^:]+:(\d+)/);
113 const fallback = repoMatch ? `repo:${repoMatch[1]}` : 'menu:main';
114 const isIssues = String(data || '').startsWith('issues:');
115 const detail = permissionDenied
116 ? isIssues
117 ? 'GitHub درخواست Issues را با خطای 403 رد کرد. در Fine-grained token، مجوز Repository permissions → Issues را روی Read قرار دهید.'
118 : 'GitHub این درخواست خواندنی را با خطای 403 رد کرد. مجوز Read مربوط به این بخش در توکن فعلی کافی نیست.'
119 : 'دریافت اطلاعات از سرویس با خطا مواجه شد. هیچ تغییری انجام نشد.';
120 return {
121 text:
122 `⚠️ <b>دریافت اطلاعات با خطا مواجه شد</b>
123 ➖➖➖➖➖➖➖➖➖➖
124 ${detail}
125
126 این خطا هیچ عملیات تغییردهنده‌ای اجرا نکرد.`,
127 reply_markup: { inline_keyboard: [[{ text: repoMatch ? '↩️ بازگشت به پروژه' : '↩️ منوی اصلی', callback_data: fallback }]] }
128 };
129 }
130
131 export class NexaDevBot {
132 constructor(env = {}) {
133 this.env = env;
134 this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
135 this.github = new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER || 'davoodmehraban89');
136 this.menu = new MenuManager(this.github);
137 this.replayStore = new DurableApprovalReplayStore({ namespace: env.APPROVAL_REPLAY_GUARD });
138 this.workspaceStore = new DurableWorkspaceStoreClient({ namespace: env.WORKSPACE_STORE });
139 this.approvals = new ApprovalService({
140 secret: env.APPROVAL_SIGNING_SECRET || env.TELEGRAM_WEBHOOK_SECRET || '',
141 replayStore: this.replayStore
142 });
143 this.githubPlugin = createGitHubPlugin({
144 github: this.github,
145 menu: this.menu,
146 workspaces: this.workspaceStore.isConfigured() ? this.workspaceStore : null
147 });
148 this.registry = new PluginRegistry([this.githubPlugin]);
149 this.policy = new ActionPolicy();
150 this.audit = new AuditLogger({
151 secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.APPROVAL_SIGNING_SECRET]
152 });
153 this.router = new PluginRouter({ registry: this.registry, policy: this.policy, audit: this.audit });
154 }
155
156 async handleUpdate(update) {
157 if (!update) return { ok: false, error: 'Empty update' };
158 if (update.callback_query) return this.handleCallbackQuery(update.callback_query);
159 if (update.message) return this.handleMessage(update.message);
160 return { ok: true, ignored: true };
161 }
162
163 async handleCallbackQuery(query) {
164 const callbackId = query.id;
165 const data = query.data || 'menu:main';
166 const message = query.message;
167 const chatId = message?.chat?.id;
168 const messageId = message?.message_id;
169 const ownerId = query.from?.id;
170
171 let callbackAnswered = true;
172 try { await this.telegram.answerCallbackQuery(callbackId); } catch { callbackAnswered = false; }
173 if (!chatId || !messageId) return { ok: false, error: 'Missing message context for callback', callbackAnswered };
174
175 try {
176 if (data.startsWith('approve:')) {
177 if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
178 const token = data.slice('approve:'.length);
179 let payload;
180 try {
181 payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'github', risk: 'WRITE' });
182 } catch (error) {
183 this.audit.log({ event: 'approval_rejected', pluginId: 'github', risk: 'WRITE', outcome: 'rejected', error: error?.message || 'Approval rejected' });
184 const view = approvalRejectedView(message, error);
185 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
186 return { ok: false, approvalRejected: true, error: error?.message || 'Approval rejected', callbackAnswered, edited: true, res };
187 }
188
189 this.audit.log({ event: 'approval_verified', pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, outcome: 'verified' });
190 const sourceCallback = approvalSourceCallback(payload);
191 let routed;
192 try {
193 routed = await this.router.dispatchCallback(sourceCallback, {
194 isOwner: true,
195 ownerId: String(ownerId),
196 approved: true
197 });
198 if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved action could not be dispatched');
199 } catch (error) {
200 const view = approvedActionFailedView(payload, error);
201 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
202 return { ok: false, approved: true, providerError: true, actionId: payload.actionId, error: error?.message || 'GitHub operation failed', callbackAnswered, edited: true, res };
203 }
204
205 const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
206 return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
207 }
208
209 const routed = await this.router.dispatchCallback(data, {
210 isOwner: true,
211 ownerId: ownerId === undefined || ownerId === null ? '' : String(ownerId)
212 });
213 if (routed?.requiresApproval) {
214 const approval = routed.approval;
215 const repoId = approval?.input?.repoId;
216 if (!approval || !Number.isSafeInteger(Number(repoId))) throw new Error('Approval metadata is missing');
217 const workspaceApproval = routed.actionId === 'github.workspace.commit_branch';
218 const runId = approval?.input?.runId;
219 const intentId = String(approval?.input?.intentId || '');
220 if (workspaceApproval) {
221 if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval metadata is missing');
222 } else if (!Number.isSafeInteger(Number(runId))) {
223 throw new Error('Approval metadata is missing');
224 }
225 if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
226 if (!this.approvals.isReplayProtected()) throw new Error('Durable approval replay protection is not configured');
227
228 const token = await this.approvals.issue({
229 pluginId: routed.pluginId,
230 actionId: routed.actionId,
231 risk: routed.risk,
232 ownerId: String(ownerId),
233 input: approval.input
234 });
235 this.audit.log({ event: 'approval_issued', pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, outcome: 'pending' });
236 const cancelCallback = approval.cancelCallback || (Number.isSafeInteger(Number(runId)) ? `run:${repoId}:${runId}` : `repo:${repoId}`);
237 const view = approvalView({ label: approval.label || routed.actionId, token, cancelCallback });
238 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
239 return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
240 }
241 if (routed?.denied) return { ok: false, denied: true, actionId: routed.actionId, reason: routed.reason, callbackAnswered };
242
243 const view = routed || await this.menu.renderByCallback(data);
244 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
245 return { ok: true, edited: true, callbackAnswered, res };
246 } catch (err) {
247 if (err.message && err.message.includes('message is not modified')) return { ok: true, unmodified: true, callbackAnswered };
248 if (!data.startsWith('approve:')) {
249 try {
250 const view = callbackReadFailedView(data, err);
251 const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
252 return { ok: false, error: err.message, providerError: true, callbackAnswered, edited: true, res };
253 } catch {
254 // Preserve the original provider/navigation error when feedback delivery also fails.
255 }
256 }
257 return { ok: false, error: err.message, callbackAnswered };
258 }
259 }
260
261 async handleMessage(message) {
262 const chatId = message.chat?.id;
263 const rawText = typeof message.text === 'string' ? message.text : '';
264 const text = rawText.trim();
265 if (!chatId) return { ok: false, error: 'Missing chat_id' };
266
267 if (text === '/start' || text === '/menu' || text.startsWith('/start')) {
268 const view = this.menu.getMainMenuView();
269 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
270 return { ok: true, command: 'start', res };
271 }
272
273 if (text === '/repos') {
274 const routed = await this.router.dispatchCommand(text, { isOwner: true });
275 if (routed?.requiresApproval || routed?.denied || !routed) {
276 return { ok: false, command: 'repos', error: routed?.reason || 'GitHub repository route unavailable' };
277 }
278 const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
279 return { ok: true, command: 'repos', res };
280 }
281
282 if (text === '/status') {
283 const view = this.menu.getServiceStatusView();
284 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
285 return { ok: true, command: 'status', res };
286 }
287
288 const ownerId = message.from?.id;
289 if (ownerId !== undefined && ownerId !== null && this.workspaceStore.isConfigured()) {
290 const pending = await this.workspaceStore.getPendingInput({ ownerId: String(ownerId) });
291 if (pending) {
292 const routed = await this.router.dispatchMessage(
293 { pending, text: rawText },
294 { isOwner: true, ownerId: String(ownerId) }
295 );
296 if (routed?.requiresApproval || routed?.denied || !routed) {
297 return { ok: false, error: routed?.reason || 'Workspace input route unavailable' };
298 }
299 const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
300 return { ok: true, workspaceInput: true, res };
301 }
302 }
303
304 const defaultText = '💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:';
305 const view = {
306 text: defaultText,
307 reply_markup: {
308 inline_keyboard: [[{ text: '⚡ باز کردن منوی اصلی Nexa Dev', callback_data: 'menu:main' }]]
309 }
310 };
311 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
312 return { ok: true, default: true, res };
313 }
314 }