Personal Telegram developer console for GitHub

feat(bot): handle destructive PR merge approvals

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