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