Personal Telegram developer console for GitHub
phase2-20261005-l
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 { NexaDevBot as LegacyNexaDevBot } from './bot-legacy.js'; |
| 2 | import { TotpVerifier } from './core/totp.js'; |
| 3 | |
| 4 | const escapeHtml = value => String(value ?? '') |
| 5 | .replaceAll('&', '&') |
| 6 | .replaceAll('<', '<') |
| 7 | .replaceAll('>', '>'); |
| 8 | |
| 9 | function destructiveSourceCallback(payload = {}) { |
| 10 | if (payload.actionId === 'cloudflare.worker.deploy_version') { |
| 11 | const versionId = String(payload.input?.versionId || ''); |
| 12 | if (!versionId) throw new Error('Destructive approval target is invalid'); |
| 13 | return `cfdeploy:${versionId}`; |
| 14 | } |
| 15 | if (payload.actionId === 'github.pull_request.merge') { |
| 16 | const repoId = Number(payload.input?.repoId); |
| 17 | const prNumber = Number(payload.input?.prNumber); |
| 18 | const headSha = String(payload.input?.headSha || ''); |
| 19 | if (!Number.isSafeInteger(repoId) || !Number.isSafeInteger(prNumber) || !/^[a-f0-9]{40}$/i.test(headSha)) { |
| 20 | throw new Error('Destructive approval target is invalid'); |
| 21 | } |
| 22 | return `mergepr:${repoId.toString(36)}:${prNumber.toString(36)}:${headSha}`; |
| 23 | } |
| 24 | throw new Error('Destructive approval action is not supported'); |
| 25 | } |
| 26 | |
| 27 | function secondFactorFailureMarkup(payload = {}) { |
| 28 | if (payload.actionId === 'cloudflare.worker.deploy_version') { |
| 29 | return { inline_keyboard: [[{ text: '↩️ نسخهها', callback_data: 'cf:versions' }]] }; |
| 30 | } |
| 31 | return { inline_keyboard: [[{ text: '↩️ پروژهها', callback_data: 'menu:repos' }]] }; |
| 32 | } |
| 33 | |
| 34 | export class NexaDevBot extends LegacyNexaDevBot { |
| 35 | constructor(env = {}) { |
| 36 | super(env); |
| 37 | this.destructiveTotp = new TotpVerifier({ secret: env.DESTRUCTIVE_TOTP_SECRET || '' }); |
| 38 | } |
| 39 | |
| 40 | async handleCallbackQuery(query) { |
| 41 | const data = query?.data || 'menu:main'; |
| 42 | const ownerId = query?.from?.id; |
| 43 | const chatId = query?.message?.chat?.id; |
| 44 | const messageId = query?.message?.message_id; |
| 45 | |
| 46 | if (data.startsWith('approve:') && ownerId !== undefined && ownerId !== null) { |
| 47 | const token = data.slice(8); |
| 48 | let preview = null; |
| 49 | try { preview = await this.approvals.verify(token, { ownerId: String(ownerId) }); } catch {} |
| 50 | |
| 51 | if (preview?.risk === 'DESTRUCTIVE') { |
| 52 | let callbackAnswered = true; |
| 53 | try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; } |
| 54 | |
| 55 | if (!this.destructiveTotp.isConfigured()) { |
| 56 | const error = 'Destructive second factor (TOTP) is not configured'; |
| 57 | this.audit.log({ event: 'second_factor_unavailable', pluginId: preview.pluginId, actionId: preview.actionId, risk: 'DESTRUCTIVE', outcome: 'rejected' }); |
| 58 | const res = await this.telegram.editMessageText( |
| 59 | chatId, |
| 60 | messageId, |
| 61 | `⚠️ <b>عملیات متوقف شد</b>\nعامل دوم TOTP برای عملیات DESTRUCTIVE پیکربندی نشده است.\nهیچ تغییری اجرا نشد.`, |
| 62 | secondFactorFailureMarkup(preview) |
| 63 | ); |
| 64 | return { ok: false, secondFactorRequired: true, approvalRejected: true, error, callbackAnswered, edited: true, res }; |
| 65 | } |
| 66 | |
| 67 | try { |
| 68 | await this.replayStore.setSecondFactorPending({ |
| 69 | ownerId: String(ownerId), |
| 70 | token, |
| 71 | expiresAt: preview.expiresAt, |
| 72 | attempts: 0 |
| 73 | }); |
| 74 | this.audit.log({ event: 'second_factor_required', pluginId: preview.pluginId, actionId: preview.actionId, risk: 'DESTRUCTIVE', outcome: 'pending' }); |
| 75 | const res = await this.telegram.editMessageText( |
| 76 | chatId, |
| 77 | messageId, |
| 78 | '🔐 <b>عامل دوم لازم است</b>\nApproval تلگرام معتبر است، اما عملیات هنوز اجرا نشده.\n\nکد ۶ رقمی برنامه Authenticator را به شکل زیر ارسال کنید:\n<code>/totp 123456</code>\n\nکد یا Secret در Audit ذخیره نمیشود.', |
| 79 | secondFactorFailureMarkup(preview) |
| 80 | ); |
| 81 | return { ok: true, secondFactorRequired: true, actionId: preview.actionId, risk: preview.risk, callbackAnswered, edited: true, res }; |
| 82 | } catch (error) { |
| 83 | const res = await this.telegram.editMessageText( |
| 84 | chatId, |
| 85 | messageId, |
| 86 | `⚠️ <b>عامل دوم آماده نشد</b>\nهیچ تغییر DESTRUCTIVE اجرا نشد.\n\n${escapeHtml(error?.message || 'Second factor unavailable')}`, |
| 87 | secondFactorFailureMarkup(preview) |
| 88 | ); |
| 89 | return { ok: false, secondFactorRequired: true, approvalRejected: true, error: error?.message, callbackAnswered, edited: true, res }; |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | if (data.startsWith('cfdeploy:')) { |
| 95 | let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; } |
| 96 | try { |
| 97 | const routed = await this.router.dispatchCallback(data, { isOwner: true, ownerId: String(ownerId ?? '') }); |
| 98 | if (!routed?.requiresApproval || routed.actionId !== 'cloudflare.worker.deploy_version') throw new Error(routed?.reason || 'Cloudflare approval route unavailable'); |
| 99 | if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required'); |
| 100 | const token = await this.approvals.issue({ pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, ownerId: String(ownerId), input: routed.approval.input }); |
| 101 | const callback = `approve:${token}`; if (callback.length > 64) throw new Error('Approval callback exceeds Telegram limit'); |
| 102 | const text = `⚠️ <b>تأیید نهایی Cloudflare لازم است</b>\nVersion: <code>${routed.approval.input.versionId}</code>\n\nTraffic این Worker روی نسخه انتخابشده قرار میگیرد. پس از این تأیید، عامل دوم TOTP نیز لازم است.`; |
| 103 | const markup = { inline_keyboard: [[{ text: '✅ ادامه تأیید Deploy / Rollback', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: 'cf:versions' }]] }; |
| 104 | const res = await this.telegram.editMessageText(chatId, messageId, text, markup); |
| 105 | return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res }; |
| 106 | } catch (error) { |
| 107 | const text = `⚠️ <b>Cloudflare Deploy آماده نشد</b>\n${escapeHtml(error?.message || 'Unavailable')}`; |
| 108 | const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ نسخهها', callback_data: 'cf:versions' }]] }); |
| 109 | return { ok: false, error: error?.message, callbackAnswered, edited: true, res }; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | if (data.startsWith('mergepr:')) { |
| 114 | let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; } |
| 115 | try { |
| 116 | const routed = await this.router.dispatchCallback(data, { isOwner: true, ownerId: String(ownerId ?? '') }); |
| 117 | if (!routed?.requiresApproval || routed.actionId !== 'github.pull_request.merge') throw new Error(routed?.reason || 'Merge approval route unavailable'); |
| 118 | if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required'); |
| 119 | const token = await this.approvals.issue({ pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, ownerId: String(ownerId), input: routed.approval.input }); |
| 120 | const callback = `approve:${token}`; if (callback.length > 64) throw new Error('Approval callback exceeds Telegram limit'); |
| 121 | const text = `⚠️ <b>تأیید نهایی Merge لازم است</b>\nPR #${routed.approval.input.prNumber}\nHead: <code>${routed.approval.input.headSha.slice(0,12)}</code>\n\nMerge فقط برای همین Head و فقط یکبار قابل اجراست. پس از این تأیید، عامل دوم TOTP نیز لازم است.`; |
| 122 | const markup = { inline_keyboard: [[{ text: '✅ ادامه تأیید Merge', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: routed.approval.cancelCallback }]] }; |
| 123 | const res = await this.telegram.editMessageText(chatId, messageId, text, markup); |
| 124 | return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res }; |
| 125 | } catch (error) { |
| 126 | const text = `⚠️ <b>Merge آماده نشد</b>\n${escapeHtml(error?.message || 'Merge unavailable')}`; |
| 127 | const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ پروژهها', callback_data: 'menu:repos' }]] }); |
| 128 | return { ok: false, error: error?.message, callbackAnswered, edited: true, res }; |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | return super.handleCallbackQuery(query); |
| 133 | } |
| 134 | |
| 135 | async handleMessage(message) { |
| 136 | const rawText = typeof message?.text === 'string' ? message.text.trim() : ''; |
| 137 | if (!rawText.startsWith('/totp')) return super.handleMessage(message); |
| 138 | |
| 139 | const chatId = message?.chat?.id; |
| 140 | const ownerId = message?.from?.id; |
| 141 | if (!chatId || ownerId === undefined || ownerId === null) { |
| 142 | return { ok: false, secondFactorRejected: true, error: 'Second-factor owner context is missing' }; |
| 143 | } |
| 144 | |
| 145 | if (!this.destructiveTotp.isConfigured()) { |
| 146 | const error = 'Destructive second factor (TOTP) is not configured'; |
| 147 | const res = await this.telegram.sendMessage(chatId, '⚠️ <b>عامل دوم پیکربندی نشده است</b>\nهیچ عملیات DESTRUCTIVE اجرا نشد.'); |
| 148 | return { ok: false, secondFactorRejected: true, error, res }; |
| 149 | } |
| 150 | |
| 151 | const match = rawText.match(/^\/totp\s+(\d{6})$/); |
| 152 | if (!match) { |
| 153 | const res = await this.telegram.sendMessage(chatId, '⚠️ فرمت کد درست نیست. فقط به شکل <code>/totp 123456</code> ارسال کنید.'); |
| 154 | return { ok: false, secondFactorRejected: true, error: 'Invalid TOTP format', res }; |
| 155 | } |
| 156 | |
| 157 | let pending; |
| 158 | try { |
| 159 | pending = await this.replayStore.getSecondFactorPending({ ownerId: String(ownerId) }); |
| 160 | } catch (error) { |
| 161 | const res = await this.telegram.sendMessage(chatId, '⚠️ وضعیت عامل دوم در دسترس نیست؛ عملیات متوقف شد.'); |
| 162 | return { ok: false, secondFactorRejected: true, error: error?.message || 'Second-factor state unavailable', res }; |
| 163 | } |
| 164 | |
| 165 | if (!pending) { |
| 166 | const res = await this.telegram.sendMessage(chatId, '⚠️ درخواست DESTRUCTIVE منتظر عامل دوم پیدا نشد. از ابتدا یک Approval تازه ایجاد کنید.'); |
| 167 | return { ok: false, secondFactorRejected: true, error: 'Second-factor challenge is unavailable', res }; |
| 168 | } |
| 169 | |
| 170 | const validCode = await this.destructiveTotp.verify(match[1]); |
| 171 | if (!validCode) { |
| 172 | const attempts = Number(pending.attempts || 0) + 1; |
| 173 | if (attempts >= 5) { |
| 174 | await this.replayStore.clearSecondFactorPending({ ownerId: String(ownerId) }); |
| 175 | } else { |
| 176 | await this.replayStore.setSecondFactorPending({ ownerId: String(ownerId), token: pending.token, expiresAt: pending.expiresAt, attempts }); |
| 177 | } |
| 178 | this.audit.log({ event: 'second_factor_rejected', risk: 'DESTRUCTIVE', outcome: 'rejected', reason: attempts >= 5 ? 'attempt_limit' : 'invalid_code' }); |
| 179 | const res = await this.telegram.sendMessage( |
| 180 | chatId, |
| 181 | attempts >= 5 |
| 182 | ? '⚠️ <b>عامل دوم رد شد</b>\nتعداد تلاش مجاز تمام شد. برای ادامه Approval تازه بسازید.' |
| 183 | : '⚠️ <b>کد TOTP معتبر نیست</b>\nهیچ تغییری اجرا نشد.' |
| 184 | ); |
| 185 | return { ok: false, secondFactorRejected: true, error: 'Invalid TOTP code', res }; |
| 186 | } |
| 187 | |
| 188 | let payload; |
| 189 | try { |
| 190 | const preview = await this.approvals.verify(pending.token, { ownerId: String(ownerId), risk: 'DESTRUCTIVE' }); |
| 191 | payload = await this.approvals.consume(pending.token, { |
| 192 | ownerId: String(ownerId), |
| 193 | pluginId: preview.pluginId, |
| 194 | actionId: preview.actionId, |
| 195 | risk: 'DESTRUCTIVE' |
| 196 | }); |
| 197 | await this.replayStore.clearSecondFactorPending({ ownerId: String(ownerId) }); |
| 198 | this.audit.log({ event: 'second_factor_verified', pluginId: payload.pluginId, actionId: payload.actionId, risk: 'DESTRUCTIVE', outcome: 'verified' }); |
| 199 | |
| 200 | const routed = await this.router.dispatchCallback(destructiveSourceCallback(payload), { |
| 201 | isOwner: true, |
| 202 | ownerId: String(ownerId), |
| 203 | approved: true |
| 204 | }); |
| 205 | if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved destructive action could not be dispatched'); |
| 206 | |
| 207 | const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup); |
| 208 | return { ok: true, approved: true, secondFactorVerified: true, actionId: payload.actionId, res }; |
| 209 | } catch (error) { |
| 210 | try { await this.replayStore.clearSecondFactorPending({ ownerId: String(ownerId) }); } catch {} |
| 211 | const res = await this.telegram.sendMessage( |
| 212 | chatId, |
| 213 | `⚠️ <b>عملیات DESTRUCTIVE اجرا نشد</b>\nهیچ Success ساختگی ثبت نمیشود.\n\n${escapeHtml(error?.message || 'Approval rejected')}`, |
| 214 | secondFactorFailureMarkup(payload || {}) |
| 215 | ); |
| 216 | return { ok: false, secondFactorRejected: true, error: error?.message || 'Destructive approval rejected', res }; |
| 217 | } |
| 218 | } |
| 219 | } |