Personal Telegram developer console for GitHub

feat(hardening): gate destructive approvals behind TOTP

davoodmehraban89 committed Oct 5, 2026 at 09:54 UTC 7ac51d147a96dffb011c721ba3e7f444f52cbbf4
1 file changed +168 -31
src/bot.js
+168 -31
@@ -1,46 +1,96 @@
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('<', '&lt;')
7 + .replaceAll('>', '&gt;');
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 {}
13 - if (preview?.actionId === 'cloudflare.worker.deploy_version') {
14 - let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
15 - try {
16 - const payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'cloudflare', actionId: 'cloudflare.worker.deploy_version', risk: 'DESTRUCTIVE' });
17 - const source = `cfdeploy:${payload.input.versionId}`;
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 Cloudflare action 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) {
23 - const text = `⚠️ <b>Cloudflare Deploy اجرا نشد</b>\nهیچ تغییر تأییدنشده‌ای انجام نشد.\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: 'cf:versions' }]] });
25 - return { ok: false, approvalRejected: true, error: error?.message, callbackAnswered, edited: true, res };
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 }
27 - }
28 - if (preview?.actionId === 'github.pull_request.merge') {
29 - let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
66 +
67 try {
31 - const payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'github', actionId: 'github.pull_request.merge', risk: 'DESTRUCTIVE' });
32 - const input = payload.input || {}; const source = `mergepr:${Number(input.repoId).toString(36)}:${Number(input.prNumber).toString(36)}:${input.headSha}`;
33 - const routed = await this.router.dispatchCallback(source, { isOwner: true, ownerId: String(ownerId), approved: true });
34 - if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved merge could not be dispatched');
35 - const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
36 - return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
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) {
38 - const text = `⚠️ <b>Merge اجرا نشد</b>\nهیچ Merge تأییدنشده‌ای انجام نشد.\n\n${String(error?.message || 'Approval rejected').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;')}`;
39 - const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ بازگشت', callback_data: 'menu:repos' }]] });
40 - return { ok: false, approvalRejected: true, error: error?.message, callbackAnswered, edited: true, res };
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 {
@@ -49,16 +99,17 @@ export class NexaDevBot extends LegacyNexaDevBot {
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');
52 - const text = `⚠️ <b>تأیید نهایی Cloudflare لازم است</b>\nVersion: <code>${routed.approval.input.versionId}</code>\n\nTraffic این Worker روی نسخه انتخاب‌شده قرار می‌گیرد.`;
53 - const markup = { inline_keyboard: [[{ text: '✅ تأیید Deploy / Rollback', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: 'cf:versions' }]] };
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) {
57 - const text = `⚠️ <b>Cloudflare Deploy آماده نشد</b>\n${String(error?.message || 'Unavailable').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;')}`;
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 {
@@ -67,16 +118,102 @@ export class NexaDevBot extends LegacyNexaDevBot {
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');
70 - const text = `⚠️ <b>تأیید نهایی Merge لازم است</b>\nPR #${routed.approval.input.prNumber}\nHead: <code>${routed.approval.input.headSha.slice(0,12)}</code>\n\nMerge فقط برای همین Head و فقط یک‌بار قابل اجراست.`;
71 - const markup = { inline_keyboard: [[{ text: '✅ تأیید و Merge', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: routed.approval.cancelCallback }]] };
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) {
75 - const text = `⚠️ <b>Merge آماده نشد</b>\n${String(error?.message || 'Merge unavailable').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;')}`;
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 }