Personal Telegram developer console for GitHub

security: reject Telegram secrets and route source editing through Mini App

Codex committed Oct 25, 2026 at 17:25 UTC 515333d224a5cd9133023a479512fa0a458f9f25
16 files changed +881 -485
src/bot-legacy.js
+19 -132
@@ -1,4 +1,5 @@
1 import { TelegramClient } from './telegram.js';
2 +import { workspaceEditorUrl } from './config.js';
3 import { GitHubService } from './github.js';
4 import { MenuManager } from './menu.js';
5 import { PluginRegistry } from './core/plugin-registry.js';
@@ -6,7 +7,7 @@ import { ActionPolicy } from './core/action-policy.js';
7 import { ApprovalService } from './core/approval.js';
8 import { DurableApprovalReplayStore } from './core/durable-replay-store.js';
9 import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
9 -import { WORKSPACE_EDITOR_LIMITS } from './core/workspace-policy.js';
10 +import { interceptTelegramSecretMessage } from './core/telegram-secret-guard.js';
11 import { AuditLogger } from './core/audit.js';
12 import { PluginRouter } from './core/router.js';
13 import {
@@ -25,13 +26,6 @@ const QUICK_MENU = Object.freeze({
26 '🔧 ابزارها': 'tools',
27 '🔐 امنیت': 'security'
28 });
28 -const escapeHtml = (value) =>
29 - String(value ?? '')
30 - .replaceAll('&', '&')
31 - .replaceAll('<', '&lt;')
32 - .replaceAll('>', '&gt;')
33 - .replaceAll('"', '&quot;');
34 -
29 function persistentQuickMenuMarkup() {
30 return {
31 keyboard: [
@@ -45,14 +39,6 @@ function persistentQuickMenuMarkup() {
39 };
40 }
41
48 -function focusedCodeInputMarkup() {
49 - return {
50 - force_reply: true,
51 - selective: true,
52 - input_field_placeholder: 'کد یا متن را اینجا Paste کنید…'
53 - };
54 -}
55 -
42 function approvalSourceCallback(payload = {}) {
43 const repoId = payload.input?.repoId;
44 if (!Number.isSafeInteger(Number(repoId)))
@@ -148,6 +134,7 @@ export class NexaDevBot {
134 this.githubPlugin = createGitHubPlugin({
135 github: this.github,
136 menu: this.menu,
137 + editorUrl: workspaceEditorUrl(env.WORKSPACE_EDITOR_URL),
138 workspaces: this.workspaceStore.isConfigured()
139 ? this.workspaceStore
140 : null
@@ -185,6 +172,12 @@ export class NexaDevBot {
172
173 async handleUpdate(update) {
174 if (!update) return { ok: false, error: 'Empty update' };
175 + const intercepted = await interceptTelegramSecretMessage({
176 + message: update.message || update.edited_message,
177 + telegram: this.telegram,
178 + ownerId: this.env.OWNER_TELEGRAM_ID
179 + });
180 + if (intercepted) return intercepted;
181 if (update.callback_query)
182 return this.handleCallbackQuery(update.callback_query);
183 if (update.message) return this.handleMessage(update.message);
@@ -394,20 +387,6 @@ export class NexaDevBot {
387 };
388
389 const view = routed || (await this.menu.renderByCallback(data));
397 - if (data.startsWith('wtext:') && routed) {
398 - const res = await this.telegram.sendMessage(
399 - chatId,
400 - view.text,
401 - focusedCodeInputMarkup()
402 - );
403 - return {
404 - ok: true,
405 - inputPrompt: true,
406 - callbackAnswered,
407 - sent: true,
408 - res
409 - };
410 - }
390 const res = await this.telegram.editMessageText(
391 chatId,
392 messageId,
@@ -450,6 +429,12 @@ export class NexaDevBot {
429 }
430
431 async handleMessage(message) {
432 + const intercepted = await interceptTelegramSecretMessage({
433 + message,
434 + telegram: this.telegram,
435 + ownerId: this.env.OWNER_TELEGRAM_ID
436 + });
437 + if (intercepted) return intercepted;
438 const chatId = message.chat?.id;
439 const rawText = typeof message.text === 'string' ? message.text : '';
440 const text = rawText.trim();
@@ -545,108 +530,10 @@ export class NexaDevBot {
530 ownerId: String(ownerId)
531 });
532 if (pending) {
548 - let payload = { pending, text: rawText };
549 - if (pending.mode === 'draft_file') {
550 - const document = message.document;
551 - const maxUploadBytes = WORKSPACE_EDITOR_LIMITS.maxBytes;
552 - if (!document?.file_id) {
553 - const view = {
554 - text: `📎 <b>یک فایل متنی ارسال کنید</b>\nاین Workspace در حالت بارگذاری فایل است. فایل باید UTF-8 معتبر و حداکثر ${maxUploadBytes.toLocaleString('en-US')} بایت باشد.`,
555 - reply_markup: {
556 - inline_keyboard: [
557 - [
558 - {
559 - text: '↩️ بازگشت به Draft',
560 - callback_data: `ws:${pending.workspaceId}`
561 - }
562 - ]
563 - ]
564 - }
565 - };
566 - const res = await this.telegram.sendMessage(
567 - chatId,
568 - view.text,
569 - view.reply_markup
570 - );
571 - return {
572 - ok: true,
573 - workspaceInput: true,
574 - inputRequired: 'document',
575 - res
576 - };
577 - }
578 - if (
579 - Number.isFinite(Number(document.file_size)) &&
580 - Number(document.file_size) > maxUploadBytes
581 - ) {
582 - const view = {
583 - text: `⚠️ <b>فایل پذیرفته نشد</b>\nحجم فایل بیشتر از سقف ${maxUploadBytes.toLocaleString('en-US')} بایت است. Draft تغییر نکرد؛ یک فایل کوچک‌تر ارسال کنید.`,
584 - reply_markup: {
585 - inline_keyboard: [
586 - [
587 - {
588 - text: '↩️ بازگشت به Draft',
589 - callback_data: `ws:${pending.workspaceId}`
590 - }
591 - ]
592 - ]
593 - }
594 - };
595 - const res = await this.telegram.sendMessage(
596 - chatId,
597 - view.text,
598 - view.reply_markup
599 - );
600 - return {
601 - ok: false,
602 - workspaceInput: true,
603 - inputRejected: true,
604 - error: `Telegram file exceeds ${maxUploadBytes} byte size limit`,
605 - res
606 - };
607 - }
608 - let downloaded;
609 - try {
610 - downloaded = await this.telegram.downloadTextFile(
611 - document.file_id,
612 - { maxBytes: maxUploadBytes }
613 - );
614 - } catch (error) {
615 - const view = {
616 - text: `⚠️ <b>فایل پذیرفته نشد</b>\n${escapeHtml(error?.message || 'Telegram file download failed')}\n\nDraft تغییر نکرد و می‌توانید فایل دیگری ارسال کنید.`,
617 - reply_markup: {
618 - inline_keyboard: [
619 - [
620 - {
621 - text: '↩️ بازگشت به Draft',
622 - callback_data: `ws:${pending.workspaceId}`
623 - }
624 - ]
625 - ]
626 - }
627 - };
628 - const res = await this.telegram.sendMessage(
629 - chatId,
630 - view.text,
631 - view.reply_markup
632 - );
633 - return {
634 - ok: false,
635 - workspaceInput: true,
636 - inputRejected: true,
637 - error: error?.message || 'Telegram file download failed',
638 - res
639 - };
640 - }
641 - payload = {
642 - pending,
643 - file: {
644 - name: String(document.file_name || 'uploaded.txt'),
645 - text: downloaded.text,
646 - byteLength: downloaded.byteLength
647 - }
648 - };
649 - }
533 + // Historical source-input modes can only expire/redirect to Mini App.
534 + // Their message bodies and documents never reach controller dispatch.
535 + const sourceInput = ['draft', 'draft_file'].includes(pending.mode);
536 + const payload = sourceInput ? { pending } : { pending, text: rawText };
537
538 const routed = await this.router.dispatchMessage(payload, {
539 isOwner: true,
src/config.js
+21
@@ -10,3 +10,24 @@ export const DEFAULT_CONFIG = {
10 }
11 ]
12 };
13 +
14 +export function workspaceEditorUrl(
15 + configured = DEFAULT_CONFIG.workspaceEditorUrl
16 +) {
17 + if (typeof configured !== 'string' || !configured.trim()) return '';
18 + try {
19 + const url = new URL(configured);
20 + if (
21 + url.protocol !== 'https:' ||
22 + url.username ||
23 + url.password ||
24 + url.search ||
25 + url.hash ||
26 + url.pathname !== '/workspace/editor'
27 + )
28 + return '';
29 + return url.href;
30 + } catch {
31 + return '';
32 + }
33 +}
src/core/telegram-secret-guard.js new
+50
@@ -0,0 +1,50 @@
1 +const GITHUB_TOKEN_PREFIX = /^\s*(?:github_pat_|gh[pousr]_)/;
2 +const REVOCATION_WARNING =
3 + '⚠️ <b>توکن در چت قرار گرفت و باید در GitHub باطل شود</b>\n' +
4 + 'همین حالا توکن را از صفحه مربوط در GitHub باطل کنید:\n' +
5 + '<a href="https://github.com/settings/personal-access-tokens">توکن‌های Fine-grained</a>\n' +
6 + '<a href="https://github.com/settings/tokens">سایر توکن‌ها</a>\n\n' +
7 + 'توکن را فقط داخل Mini App وارد کنید.';
8 +
9 +export function containsGitHubTokenMessage(message) {
10 + return [message?.text, message?.caption].some(
11 + (value) => typeof value === 'string' && GITHUB_TOKEN_PREFIX.test(value)
12 + );
13 +}
14 +
15 +export async function interceptTelegramSecretMessage({
16 + message,
17 + telegram,
18 + ownerId
19 +} = {}) {
20 + if (!containsGitHubTokenMessage(message)) return null;
21 + // This guard must not introduce an alternate route around the owner boundary.
22 + if (
23 + !ownerId ||
24 + message?.from?.id === undefined ||
25 + message?.from?.id === null ||
26 + String(message.from.id) !== String(ownerId)
27 + )
28 + return { ok: true, ignored: true };
29 +
30 + const chatId = message?.chat?.id;
31 + const messageId = message?.message_id;
32 + let deleted = false;
33 + let warned = false;
34 + if (Number.isSafeInteger(chatId) && Number.isSafeInteger(messageId)) {
35 + // Delete is the first effect. Never send raw content, persist it, or expose
36 + // provider errors: both Telegram response bodies and errors may echo input.
37 + try {
38 + await telegram.deleteMessage(chatId, messageId);
39 + deleted = true;
40 + } catch {}
41 + const warning = deleted
42 + ? REVOCATION_WARNING
43 + : `${REVOCATION_WARNING}\n\nحذف خودکار پیام تأیید نشد؛ پیام را نیز دستی حذف کنید.`;
44 + try {
45 + await telegram.sendMessage(chatId, warning);
46 + warned = true;
47 + } catch {}
48 + }
49 + return { ok: true, secretRejected: true, deleted, warned };
50 +}
src/guide-menu.js
+1 -1
@@ -34,7 +34,7 @@ function guidePage(page) {
34
35 2: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۲. پروژه، فایل‌ها و مشاهده کد</b>\n➖➖➖➖➖➖➖➖➖➖\n\n<b>نام Repository</b>\nصفحهٔ پروژه را با Metadata زنده GitHub باز می‌کند.\n\n<b>📂 فایل‌ها</b>\nساختار فایل‌ها و پوشه‌ها را باز می‌کند؛ 📁 وارد پوشه و 📄 اطلاعات فایل را باز می‌کند؛ محتوا فقط در Mini App احراز هویت‌شده دیده می‌شود.\n\n<b>✏️ Edit</b>\nبرای فایل متنی مجاز Workspace امن می‌سازد. فایل حساس، باینری، Git LFS یا خارج از Policy قابل Edit نیست.\n\n<b>🔀 Pull Requestها / PR</b>\nPRها و جزئیات آن‌ها را می‌خواند. Files / Diff فقط نام فایل و شمارش تغییرات را در تلگرام نشان می‌دهد؛ متن patch وارد پیام نمی‌شود. Checks نتیجهٔ کنترل‌هاست.\n\n<b>📝 Commitها</b>\nآخرین Commitهای Repository را نمایش می‌دهد. با انتخاب هر مورد، <b>جزئیات Commit</b> شامل SHA، نویسنده، زمان، پیام کامل، تعداد additions/deletions و فایل‌های تغییرکرده مستقیماً از GitHub باز می‌شود.\n\n<b>📊 وضعیت / تست‌ها</b>\nآخرین وضعیت Workflowهای پروژه را خلاصه می‌کند.\n\n<b>🧪 CI / Actions</b>\nWorkflow Runها را باز می‌کند؛ جزئیات در فصل ۵ است.\n\n<b>🌿 Branches</b>\nBranchها و Compare نسبت به شاخهٔ پیش‌فرض را نشان می‌دهد.\n\n<b>🐛 Issues</b>\nIssueهای Repository را صفحه‌بندی می‌کند. با انتخاب هر مورد، <b>جزئیات Issue</b> شامل وضعیت، نویسنده، برچسب‌ها، مسئول‌ها، زمان بروزرسانی و متن Issue از GitHub نمایش داده می‌شود.\n\n<b>🏷 Releases</b>\nReleaseهای GitHub را نمایش می‌دهد. با انتخاب هر Release، <b>Release notes</b>، Tag، Target، نویسنده، زمان انتشار و وضعیت draft/pre-release از منبع GitHub باز می‌شود.\n\n<b>⬅️ جدیدتر / قدیمی‌تر ➡️</b>\nبین صفحات نتایج جابه‌جا می‌شود و WRITE انجام نمی‌دهد.`,
36
37 - 3: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۳. Workspace و دکمه‌های ویرایش</b>\n➖➖➖➖➖➖➖➖➖➖\n\nپس از <b>✏️ Edit</b> یک Draft Durable ساخته می‌شود و هنوز GitHub تغییر نکرده است. Workspace در <code>WORKSPACE_STORE</code> نگهداری می‌شود.\n\n<b>📝 Workspace / باز کردن Draft</b>\nوضعیت Draft، Base snapshot و پیام Commit را نشان می‌دهد.\n\n<b>🧑‍💻 Editor</b>\nTelegram Mini App چندخطی را باز می‌کند. «ذخیره Draft» فقط Draft را در WORKSPACE_STORE ذخیره می‌کند و GitHub WRITE ندارد.\n\n<b>📎 بارگذاری فایل</b>\nمحتوای یک فایل متنی UTF-8 را جایگزین Draft می‌کند؛ مسیر مقصد Repository عوض نمی‌شود.\n\n<b>📝 Paste متن</b>\nمسیر fallback قدیمی با ورودی عادی Telegram است؛ مسیر اصلی V2.1 همان Mini App Editor است.\n\n<b>✍️ پیام Commit</b>\nپیام Commit بعدی را ثبت می‌کند.\n\n<b>🔍 Diff</b>\nOriginal و Draft را پیش از WRITE مقایسه می‌کند.\n\n<b>✅ آماده Commit</b>\nتغییر، Base و پیام Commit را اعتبارسنجی و Intent امن می‌سازد.\n\n<b>🗑 لغو Draft</b>\nWorkspace جاری را لغو می‌کند و GitHub دست‌نخورده می‌ماند.`,
37 + 3: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۳. Workspace و دکمه‌های ویرایش</b>\n➖➖➖➖➖➖➖➖➖➖\n\nپس از <b>✏️ Edit</b> یک Draft Durable ساخته می‌شود و هنوز GitHub تغییر نکرده است. Workspace در <code>WORKSPACE_STORE</code> نگهداری می‌شود.\n\n<b>📝 Workspace / باز کردن Draft</b>\nوضعیت Draft، Base snapshot و پیام Commit را نشان می‌دهد.\n\n<b>🧑‍💻 Editor</b>\nTelegram Mini App چندخطی را باز می‌کند. «ذخیره Draft» فقط Draft را در WORKSPACE_STORE ذخیره می‌کند و GitHub WRITE ندارد.\n\nمتن منبع و فایل را در چت ارسال نکنید؛ ویرایش Draft فقط در Mini App احراز هویت‌شده انجام می‌شود. دکمه‌های قدیمی ویرایش چت نیز همین Editor را باز می‌کنند. اگر Editor در دسترس نیست، ابتدا پیکربندی Mini App باید اصلاح شود.\n\n<b>✍️ پیام Commit</b>\nپیام Commit بعدی را ثبت می‌کند.\n\n<b>🔍 Diff</b>\nOriginal و Draft را پیش از WRITE مقایسه می‌کند.\n\n<b>✅ آماده Commit</b>\nتغییر، Base و پیام Commit را اعتبارسنجی و Intent امن می‌سازد.\n\n<b>🗑 لغو Draft</b>\nWorkspace جاری را لغو می‌کند و GitHub دست‌نخورده می‌ماند.`,
38
39 4: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۴. اصلاح فایل از ابتدا تا Commit</b>\n➖➖➖➖➖➖➖➖➖➖\n\n<b>۱ — پروژه‌ها</b>\nRepository موردنظر را انتخاب کنید.\n\n<b>۲ — فایل‌ها</b>\nفایل متنی را پیدا و باز کنید.\n\n<b>۳ — Edit</b>\nEdit را بزنید؛ Snapshot شاخهٔ پیش‌فرض Pin و Draft ساخته می‌شود.\n\n<b>۴ — Editor</b>\nکد یا متن را اصلاح کنید و «ذخیره Draft» را بزنید. این مرحله هنوز GitHub WRITE نیست.\n\n<b>۵ — Diff</b>\nتغییر را دقیق بررسی کنید؛ اگر اشتباه است به Editor برگردید یا Draft را لغو کنید.\n\n<b>۶ — پیام Commit</b>\nیک پیام روشن ثبت کنید؛ نمونه: <code>docs: clarify bot guide</code>.\n\n<b>۷ — آماده Commit</b>\nIntent نهایی ساخته و مواد Commit قفل می‌شود.\n\n<b>۸ — Safe Approval</b>\nصفحهٔ تأیید باز می‌شود. فقط «✅ تأیید و اجرا» اجازهٔ WRITE نهایی را می‌دهد؛ انصراف هیچ WRITEای انجام نمی‌دهد.\n\n<b>۹ — نتیجه</b>\nBot یک Branch به شکل <code>nexa/edit-*</code> و Commit روی همان Branch می‌سازد. <b>main مستقیماً تغییر نمی‌کند.</b> Merge یا تغییر شاخهٔ پیش‌فرض عملیات جداگانه است.`,
40
src/index.js
+9 -4
@@ -27,7 +27,10 @@ const publicHealthPayload = () => ({
27 mode: 'Cloudflare Worker Webhook'
28 });
29 const senderIdFromUpdate = (u) =>
30 - u?.message?.from?.id ?? u?.callback_query?.from?.id ?? null;
30 + u?.message?.from?.id ??
31 + u?.edited_message?.from?.id ??
32 + u?.callback_query?.from?.id ??
33 + null;
34 const isOwnerUpdate = (u, e) =>
35 !!e.OWNER_TELEGRAM_ID &&
36 senderIdFromUpdate(u) !== null &&
@@ -112,9 +115,11 @@ export default {
115 // Claim before effects: retries are at-most-once; a process crash after the
116 // durable claim can lose this update. No raw update is retained for replay.
117 try {
115 - const result = await new KillSwitchGuidedNexaDevBot(env).handleUpdate(
116 - update
117 - );
118 + const result = await new KillSwitchGuidedNexaDevBot({
119 + ...env,
120 + WORKSPACE_EDITOR_URL:
121 + env.WORKSPACE_EDITOR_URL ?? new URL('/workspace/editor', url).href
122 + }).handleUpdate(update);
123 if (result?.ok !== false) return jsonResponse(result);
124 } catch {
125 // Provider messages can contain tokens or draft text; log metadata only.
src/ops-menu.js
+5 -2
@@ -1,5 +1,5 @@
1 import { GuideMenuManager } from './guide-menu.js';
2 -import { DEFAULT_CONFIG } from './config.js';
2 +import { workspaceEditorUrl } from './config.js';
3
4 const escapeHtml = (value) =>
5 String(value ?? '')
@@ -317,11 +317,14 @@ WRITE فقط بعد از تأیید معتبر اجرا می‌شود و Approva
317 }
318
319 getEditorConfigView() {
320 + const editorUrl = workspaceEditorUrl(
321 + this.diagnostics?.env?.WORKSPACE_EDITOR_URL
322 + );
323 return {
324 text: `🧑‍💻 <b>پیکربندی Workspace Editor</b>
325 ➖➖➖➖➖➖➖➖➖➖
326 • نوع: <b>Telegram Mini App</b>
324 -• URL: <code>${escapeHtml(DEFAULT_CONFIG.workspaceEditorUrl)}</code>
327 +• URL: <code>${editorUrl ? escapeHtml(editorUrl) : 'پیکربندی نشده'}</code>
328 • ذخیره: <b>Durable Draft در WORKSPACE_STORE</b>
329 • GitHub WRITE مستقیم از Editor: <b>ندارد</b>
330 • Commit نهایی: <b>Branch-only + Safe Approval</b>`,
src/plugins/github/plugin-legacy.js
+7 -2
@@ -913,11 +913,16 @@ function resolveWriteCallback(data) {
913 return null;
914 }
915
916 -export function createGitHubPlugin({ github, menu, workspaces } = {}) {
916 +export function createGitHubPlugin({
917 + github,
918 + menu,
919 + workspaces,
920 + editorUrl
921 +} = {}) {
922 if (!github) throw new Error('GitHub plugin requires github service');
923 if (!menu) throw new Error('GitHub plugin requires menu manager');
924 const workspaceController = workspaces
920 - ? createWorkspaceController({ github, workspaces })
925 + ? createWorkspaceController({ github, workspaces, editorUrl })
926 : null;
927
928 return {
src/plugins/github/workspace.js
+31 -77
@@ -3,8 +3,7 @@ import {
3 digestText,
4 makeTargetBranch,
5 normalizeCommitMessage,
6 - validateEditableFile,
7 - WORKSPACE_EDITOR_LIMITS
6 + validateEditableFile
7 } from '../../core/workspace-policy.js';
8 import { DEFAULT_CONFIG } from '../../config.js';
9 import { commitWorkspaceIntent } from './workspace-commit.js';
@@ -13,7 +12,6 @@ export { commitWorkspaceIntent } from './workspace-commit.js';
12
13 const HANDLE_10 = '[A-Za-z0-9_-]{10}';
14 const INTENT_8 = '[A-Za-z0-9_-]{8}';
16 -const editorLimitHint = `${WORKSPACE_EDITOR_LIMITS.maxChars.toLocaleString('en-US')} کاراکتر Unicode و ${WORKSPACE_EDITOR_LIMITS.maxBytes.toLocaleString('en-US')} بایت UTF-8`;
15 const escapeHtml = (value) =>
16 String(value ?? '')
17 .replaceAll('&', '&amp;')
@@ -155,19 +153,8 @@ function editorUrlFor(workspace, editorUrl, path = '') {
153
154 function workspaceButtons(workspace, editorUrl) {
155 const editor = editorUrlFor(workspace, editorUrl);
158 - const firstRow = [];
159 - if (editor) firstRow.push({ text: '🧑‍💻 Editor', web_app: { url: editor } });
160 - firstRow.push({
161 - text: '📎 بارگذاری فایل',
162 - callback_data: `wfile:${workspace.id}`
163 - });
164 - if (!editor)
165 - firstRow.push({
166 - text: '📝 Paste متن',
167 - callback_data: `wtext:${workspace.id}`
168 - });
156 return [
170 - firstRow,
157 + ...(editor ? [[{ text: '🧑‍💻 Editor', web_app: { url: editor } }]] : []),
158 [{ text: '✍️ پیام Commit', callback_data: `wmsg:${workspace.id}` }],
159 [
160 { text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` },
@@ -180,6 +167,12 @@ function workspaceButtons(workspace, editorUrl) {
167 ];
168 }
169
170 +function draftInputNotice(workspace, editorUrl) {
171 + return editorUrlFor(workspace, editorUrl)
172 + ? 'متن منبع و فایل را در چت ارسال نکنید؛ ویرایش Draft فقط در Mini App احراز هویت‌شده انجام می‌شود.'
173 + : 'Editor در دسترس نیست؛ پیکربندی Mini App باید اصلاح شود. متن منبع و فایل را در چت ارسال نکنید.';
174 +}
175 +
176 function workspaceCommitResultView(repoId, intent, result) {
177 const rows = [[{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }]];
178 if (intent?.workspaceId) {
@@ -368,7 +361,7 @@ export function createWorkspaceController({
361 )
362 .join('\n');
363 const buttons = workspaceButtons(workspace, editorUrl);
371 - if (editorUrl && files.length > 1) {
364 + if (editorUrlFor(workspace, editorUrl) && files.length > 1) {
365 const fileEditors = files.map((file) => [
366 {
367 text: 'Edit ' + short(file.path, 34),
@@ -380,10 +373,7 @@ export function createWorkspaceController({
373 const genericEditorIndex = buttons.findIndex((row) =>
374 row.some((button) => button.web_app?.url === genericEditorUrl)
375 );
383 - if (genericEditorIndex >= 0)
384 - buttons[genericEditorIndex] = buttons[genericEditorIndex].filter(
385 - (button) => !button.web_app
386 - );
376 + if (genericEditorIndex >= 0) buttons.splice(genericEditorIndex, 1);
377 }
378 buttons.unshift([
379 {
@@ -399,7 +389,7 @@ export function createWorkspaceController({
389 }
390 ]);
391 return {
402 - text: `📝 <b>Repository Workspace</b>\nChange Set: <b>${files.length} فایل</b> · تغییرکرده: <b>${changedCount}</b>\n${list}\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>\nپیام Commit: ${commitMessage}\n\nذخیره فقط Draft محلی را تغییر می‌دهد؛ GitHub فقط بعد از Diff، Ready و Safe Approval تغییر می‌کند.`,
392 + text: `📝 <b>Repository Workspace</b>\nChange Set: <b>${files.length} فایل</b> · تغییرکرده: <b>${changedCount}</b>\n${list}\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>\nپیام Commit: ${commitMessage}\n\n${draftInputNotice(workspace, editorUrl)}\nذخیره فقط Draft محلی را تغییر می‌دهد؛ GitHub فقط بعد از Diff، Ready و Safe Approval تغییر می‌کند.`,
393 reply_markup: { inline_keyboard: buttons }
394 };
395 };
@@ -501,15 +491,18 @@ export function createWorkspaceController({
491
492 const prepareInput = async (workspaceId, mode, ownerId) => {
493 const workspace = await requireWorkspace(workspaceId, ownerId);
494 + if (mode !== 'commit_message') {
495 + await workspaces.consumePendingInput({ ownerId, workspaceId, mode });
496 + return {
497 + text: `📝 <b>ویرایش Draft در Mini App</b>\n${draftInputNotice(workspace, editorUrl)}`,
498 + reply_markup: {
499 + inline_keyboard: workspaceButtons(workspace, editorUrl)
500 + }
501 + };
502 + }
503 await workspaces.setPendingInput({ ownerId, workspaceId, mode });
505 - const fileMode = mode === 'draft_file';
506 - const draftMode = mode === 'draft';
504 return {
508 - text: fileMode
509 - ? `📎 <b>فایل متنی جایگزین را ارسال کنید</b>\nمقصد در مخزن: <code>${escapeHtml(workspace.path)}</code>\n\nفایل ارسال‌شده فقط به‌عنوان محتوای جایگزین Draft استفاده می‌شود؛ نام فایل مقصد را تغییر نمی‌دهد. سقف Policy: ${editorLimitHint} معتبر. فایل‌های باینری، LFS یا محتوای غیرمجاز رد می‌شوند.`
510 - : draftMode
511 - ? `📝 <b>ورودی متنی قدیمی Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nاین مسیر فقط برای سازگاری پیام‌های قدیمی باقی مانده است. Editor جدید مسیر اصلی است. سقف: ${editorLimitHint}.`
512 - : `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
505 + text: `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
506 reply_markup: {
507 inline_keyboard: [
508 [{ text: '↩️ بازگشت به Draft', callback_data: `ws:${workspace.id}` }]
@@ -518,7 +511,7 @@ export function createWorkspaceController({
511 };
512 };
513
521 - const applyPendingInput = async ({ pending, text, file }, ownerId) => {
514 + const applyPendingInput = async ({ pending, text }, ownerId) => {
515 const workspaceId = String(pending?.workspaceId || '');
516 const mode = String(pending?.mode || '');
517 if (
@@ -528,12 +521,6 @@ export function createWorkspaceController({
521 throw new Error('Pending workspace input is invalid');
522 }
523
531 - if (mode === 'draft_file' && (!file || typeof file.text !== 'string')) {
532 - throw new Error(
533 - 'A UTF-8 Telegram document is required for this workspace input'
534 - );
535 - }
536 -
524 const consumed = await workspaces.consumePendingInput({
525 ownerId,
526 workspaceId,
@@ -545,44 +532,12 @@ export function createWorkspaceController({
532 );
533 const workspace = await requireWorkspace(workspaceId, ownerId);
534
548 - if (mode === 'draft' || mode === 'draft_file') {
549 - const inputText = mode === 'draft_file' ? file.text : text;
550 - const inputBytes =
551 - mode === 'draft_file' ? Number(file.byteLength) : undefined;
552 - const policy = validateEditableFile({
553 - path: workspace.path,
554 - text: inputText,
555 - byteLength: inputBytes
556 - });
557 - if (!policy.editable) {
558 - return {
559 - text: `⚠️ <b>Draft تغییر نکرد</b>\n${escapeHtml(policy.reason || 'محتوای ارسال‌شده مجاز نیست.')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره ${mode === 'draft_file' ? '«بارگذاری فایل»' : 'Editor'} را باز کنید.`,
560 - reply_markup: {
561 - inline_keyboard: [
562 - [
563 - {
564 - text: '📝 بازگشت به Draft',
565 - callback_data: `ws:${workspace.id}`
566 - }
567 - ]
568 - ]
569 - }
570 - };
571 - }
572 - const digest = await digestText(policy.text);
573 - const updated = await workspaces.updateDraft({
574 - ownerId,
575 - workspaceId,
576 - text: policy.text,
577 - digest
578 - });
579 - const source =
580 - mode === 'draft_file'
581 - ? `\nفایل ورودی: <code>${escapeHtml(short(file.name || 'uploaded file', 100))}</code>`
582 - : '';
535 + if (mode !== 'commit_message') {
536 return {
584 - text: `✅ <b>Draft محلی ذخیره شد</b>\nفایل مقصد: <code>${escapeHtml(updated.path)}</code>${source}\nکاراکتر: <b>${policy.charLength}</b> · بایت UTF-8: <b>${policy.byteLength}</b>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
585 - reply_markup: { inline_keyboard: workspaceButtons(updated, editorUrl) }
537 + text: `⚠️ <b>Draft تغییر نکرد</b>\nورودی قدیمی چت لغو شد. ${draftInputNotice(workspace, editorUrl)}`,
538 + reply_markup: {
539 + inline_keyboard: workspaceButtons(workspace, editorUrl)
540 + }
541 };
542 }
543
@@ -884,11 +839,10 @@ export function createWorkspaceController({
839 applyPendingInput(
840 {
841 pending,
887 - text: String(payload?.text ?? ''),
888 - file:
889 - payload?.file && typeof payload.file === 'object'
890 - ? payload.file
891 - : null
842 + text:
843 + pending.mode === 'commit_message'
844 + ? String(payload?.text ?? '')
845 + : undefined
846 },
847 ownerFrom(context)
848 )
src/telegram.js
+7
@@ -104,6 +104,13 @@ export class TelegramClient {
104 return this.callApi('sendMessage', payload);
105 }
106
107 + async deleteMessage(chatId, messageId) {
108 + return this.callApi('deleteMessage', {
109 + chat_id: chatId,
110 + message_id: messageId
111 + });
112 + }
113 +
114 async editMessageText(
115 chatId,
116 messageId,
test/github-workspace-file-upload.test.js
+189 -239
@@ -1,26 +1,49 @@
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 -import { NexaDevBot } from '../src/bot.js';
4 -import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
3 +import { DurableWorkspaceStoreClient } from '../src/core/workspace-store.js';
4 +import { WorkspaceStore } from '../src/durable/workspace-store.js';
5 +import { createWorkspaceController } from '../src/plugins/github/workspace.js';
6
7 const OWNER = '42';
7 -const WORKSPACE_ID = 'W000000001';
8 +const EDITOR_URL = 'https://example.com/workspace/editor';
9 +const ORIGINAL = 'node_modules/\n';
10 +const SENTINEL = 'SOURCE_MUST_STAY_OUT_OF_TELEGRAM_WORKFLOW';
11
9 -function makeMenu() {
10 - return {
11 - async getReposListView() {
12 - return { text: 'repos', reply_markup: { inline_keyboard: [] } };
13 - },
14 - async renderByCallback(data) {
15 - return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
12 +async function fixture(editorUrl = EDITOR_URL) {
13 + const states = new Map();
14 + const workspaces = new DurableWorkspaceStoreClient({
15 + now: () => 1000,
16 + namespace: {
17 + idFromName: (name) => String(name),
18 + get(id) {
19 + if (!states.has(id)) {
20 + const data = new Map();
21 + const storage = {
22 + async get(key) {
23 + return data.get(key);
24 + },
25 + async put(key, value) {
26 + data.set(key, structuredClone(value));
27 + },
28 + async delete(key) {
29 + return data.delete(key);
30 + },
31 + async list() {
32 + return new Map(data);
33 + },
34 + async transaction(fn) {
35 + return fn(storage);
36 + },
37 + async setAlarm() {}
38 + };
39 + states.set(id, new WorkspaceStore({ storage }));
40 + }
41 + return { fetch: (request) => states.get(id).fetch(request) };
42 + }
43 }
17 - };
18 -}
19 -
20 -function makeWorkspaces() {
21 - let pending = null;
22 - const workspace = {
23 - id: WORKSPACE_ID,
44 + });
45 + const workspace = await workspaces.createWorkspace({
46 + ownerId: OWNER,
47 repoId: 123,
48 repoFullName: 'davood/demo',
49 baseBranch: 'main',
@@ -28,244 +51,171 @@ function makeWorkspaces() {
51 baseTreeSha: 'b'.repeat(40),
52 path: '.gitignore',
53 blobSha: 'c'.repeat(40),
31 - originalText: 'node_modules/\n',
32 - draftText: 'node_modules/\n',
33 - commitMessage: '',
34 - state: 'DRAFT'
35 - };
54 + originalText: ORIGINAL,
55 + originalDigest: 'd'.repeat(64)
56 + });
57 return {
58 workspace,
38 - async getWorkspace({ ownerId, workspaceId }) {
39 - return ownerId === OWNER && workspaceId === WORKSPACE_ID
40 - ? structuredClone(workspace)
41 - : null;
42 - },
43 - async setPendingInput({ ownerId, workspaceId, mode }) {
44 - assert.equal(ownerId, OWNER);
45 - pending = { workspaceId, mode };
46 - return structuredClone(pending);
47 - },
48 - async getPendingInput({ ownerId }) {
49 - return ownerId === OWNER && pending ? structuredClone(pending) : null;
50 - },
51 - async consumePendingInput({ ownerId, workspaceId, mode }) {
52 - if (
53 - ownerId !== OWNER ||
54 - !pending ||
55 - pending.workspaceId !== workspaceId ||
56 - pending.mode !== mode
57 - )
58 - return false;
59 - pending = null;
60 - return true;
61 - },
62 - async updateDraft({ ownerId, workspaceId, text, digest }) {
63 - assert.equal(ownerId, OWNER);
64 - assert.equal(workspaceId, WORKSPACE_ID);
65 - workspace.draftText = text;
66 - workspace.draftDigest = digest;
67 - workspace.state = 'DRAFT';
68 - return structuredClone(workspace);
69 - }
70 - };
71 -}
72 -
73 -function makePlugin() {
74 - const workspaces = makeWorkspaces();
75 - const github = {
76 - async getRepository(repoId) {
77 - return {
78 - id: String(repoId),
79 - name: 'demo',
80 - fullName: 'davood/demo',
81 - defaultBranch: 'main',
82 - archived: false
83 - };
84 - }
85 - };
86 - return {
59 workspaces,
88 - plugin: createGitHubPlugin({ github, menu: makeMenu(), workspaces })
60 + controller: createWorkspaceController({ github: {}, workspaces, editorUrl })
61 };
62 }
63
92 -test('workspace keeps file upload as a secondary bounded draft input route', async () => {
93 - const { workspaces, plugin } = makePlugin();
94 - const workspaceView = await plugin
95 - .resolveCallback(`ws:${WORKSPACE_ID}`, { ownerId: OWNER })
96 - .execute();
97 - const buttons = workspaceView.reply_markup.inline_keyboard.flat();
98 - const upload = buttons.find(
99 - (button) => button.callback_data === `wfile:${WORKSPACE_ID}`
100 - );
101 - assert.ok(upload);
102 - assert.match(upload.text, /file|فایل|upload|بارگذاری/i);
103 - assert.ok(new TextEncoder().encode(upload.callback_data).byteLength <= 64);
64 +function buttons(view) {
65 + return view.reply_markup.inline_keyboard.flat();
66 +}
67
105 - const route = plugin.resolveCallback(upload.callback_data, {
106 - ownerId: OWNER
107 - });
108 - assert.equal(route.actionId, 'github.workspace.input.prepare');
109 - const prompt = await route.execute();
110 - assert.match(prompt.text, /65,?536|65536/);
111 - assert.match(prompt.text, /20,?000|20000/);
112 - assert.match(prompt.text, /UTF-?8|فایل/i);
113 - assert.deepEqual(await workspaces.getPendingInput({ ownerId: OWNER }), {
114 - workspaceId: WORKSPACE_ID,
115 - mode: 'draft_file'
116 - });
117 -});
68 +function assertEditor(view, workspaceId) {
69 + const editor = buttons(view).find((button) => button.web_app);
70 + assert.ok(editor, 'the rejected source-input route must offer the Mini App');
71 + assert.equal(editor.web_app.url, `${EDITOR_URL}?workspaceId=${workspaceId}`);
72 + assert.doesNotMatch(JSON.stringify(view), new RegExp(SENTINEL));
73 +}
74
119 -test('uploaded text file replaces only the local draft and preserves the repository target path', async () => {
120 - const { workspaces, plugin } = makePlugin();
121 - await plugin
122 - .resolveCallback(`wfile:${WORKSPACE_ID}`, { ownerId: OWNER })
123 - .execute();
124 - const pending = await workspaces.getPendingInput({ ownerId: OWNER });
125 - const route = plugin.resolveMessage(
126 - {
127 - pending,
75 +test('workspace offers only Mini App editing even when the editor is unavailable', async () => {
76 + for (const editorUrl of [EDITOR_URL, '', 'http://example.com/editor']) {
77 + const { controller, workspace, workspaces } = await fixture(editorUrl);
78 + await workspaces.upsertWorkspaceFile({
79 + ownerId: OWNER,
80 + workspaceId: workspace.id,
81 file: {
129 - name: 'replacement.txt',
130 - text: 'node_modules/\n# smoke\n',
131 - byteLength: 22
82 + path: 'README.md',
83 + blobSha: 'e'.repeat(40),
84 + originalText: '# Demo\n',
85 + draftText: '# Demo\n',
86 + originalDigest: 'f'.repeat(64),
87 + draftDigest: 'f'.repeat(64)
88 }
133 - },
134 - { ownerId: OWNER }
135 - );
136 - assert.equal(route.actionId, 'github.workspace.input.apply');
137 - const view = await route.execute();
138 - assert.match(view.text, /Draft|ذخیره|فایل/i);
139 - assert.equal(workspaces.workspace.path, '.gitignore');
140 - assert.equal(workspaces.workspace.draftText, 'node_modules/\n# smoke\n');
141 - assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
142 -});
143 -
144 -test('bot downloads a pending workspace document using the expanded workspace byte ceiling', async () => {
145 - const bot = new NexaDevBot({});
146 - const calls = [];
147 - bot.workspaceStore = {
148 - isConfigured: () => true,
149 - async getPendingInput({ ownerId }) {
150 - calls.push(['getPendingInput', ownerId]);
151 - return { workspaceId: WORKSPACE_ID, mode: 'draft_file' };
152 - }
153 - };
154 - bot.telegram = {
155 - async downloadTextFile(fileId, options) {
156 - calls.push(['downloadTextFile', fileId, options]);
157 - return {
158 - text: 'node_modules/\n# smoke\n',
159 - byteLength: 22,
160 - filePath: 'documents/replacement.txt'
161 - };
162 - },
163 - async sendMessage(chatId, text, replyMarkup) {
164 - calls.push(['sendMessage', chatId, text, replyMarkup]);
165 - return { ok: true };
89 + });
90 + const view = await controller
91 + .resolveCallback(`ws:${workspace.id}`, { ownerId: OWNER })
92 + .execute();
93 + assert.ok(
94 + view.reply_markup.inline_keyboard.every((row) => row.length > 0),
95 + 'the multi-file workspace must send usable keyboard rows'
96 + );
97 + assert.equal(
98 + buttons(view).some((button) =>
99 + /^w(?:text|file):/.test(button.callback_data || '')
100 + ),
101 + false,
102 + `Telegram source input must remain disabled for ${editorUrl || 'missing editor'}`
103 + );
104 + if (editorUrl === EDITOR_URL)
105 + assert.deepEqual(
106 + buttons(view)
107 + .filter((button) => button.web_app)
108 + .map((button) => button.web_app.url),
109 + [
110 + `${EDITOR_URL}?workspaceId=${workspace.id}&path=.gitignore`,
111 + `${EDITOR_URL}?workspaceId=${workspace.id}&path=README.md`
112 + ]
113 + );
114 + else {
115 + assert.equal(
116 + buttons(view).some((button) => button.web_app),
117 + false
118 + );
119 + assert.match(view.text, /Editor.*دسترس|Mini App.*دسترس/);
120 }
167 - };
168 - bot.router = {
169 - async dispatchMessage(payload, context) {
170 - calls.push([
171 - 'dispatchMessage',
172 - structuredClone(payload),
173 - structuredClone(context)
174 - ]);
175 - return { text: 'file accepted', reply_markup: { inline_keyboard: [] } };
176 - }
177 - };
121 + }
122 +});
123
179 - const result = await bot.handleMessage({
180 - chat: { id: 7 },
181 - from: { id: 42 },
182 - document: {
183 - file_id: 'FILE123',
184 - file_name: 'replacement.txt',
185 - file_size: 22
186 - }
124 +for (const [prefix, mode] of [
125 + ['wtext', 'draft'],
126 + ['wfile', 'draft_file']
127 +]) {
128 + test(`stale ${prefix} callback clears its old pending source input and redirects to Mini App`, async () => {
129 + const { controller, workspace, workspaces } = await fixture();
130 + await workspaces.setPendingInput({
131 + ownerId: OWNER,
132 + workspaceId: workspace.id,
133 + mode
134 + });
135 + const view = await controller
136 + .resolveCallback(`${prefix}:${workspace.id}`, { ownerId: OWNER })
137 + .execute();
138 + assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
139 + assertEditor(view, workspace.id);
140 + const saved = await workspaces.getWorkspace({
141 + ownerId: OWNER,
142 + workspaceId: workspace.id
143 + });
144 + assert.equal(saved.draftText, ORIGINAL);
145 });
146
189 - assert.equal(result.workspaceInput, true);
190 - assert.deepEqual(
191 - calls.find((call) => call[0] === 'downloadTextFile'),
192 - ['downloadTextFile', 'FILE123', { maxBytes: 65536 }]
193 - );
194 - const dispatch = calls.find((call) => call[0] === 'dispatchMessage');
195 - assert.deepEqual(dispatch[1].file, {
196 - name: 'replacement.txt',
197 - text: 'node_modules/\n# smoke\n',
198 - byteLength: 22
147 + test(`stale ${prefix} callback preserves an active commit-message input`, async () => {
148 + const { controller, workspace, workspaces } = await fixture();
149 + await workspaces.setPendingInput({
150 + ownerId: OWNER,
151 + workspaceId: workspace.id,
152 + mode: 'commit_message'
153 + });
154 + const view = await controller
155 + .resolveCallback(`${prefix}:${workspace.id}`, { ownerId: OWNER })
156 + .execute();
157 + assert.deepEqual(await workspaces.getPendingInput({ ownerId: OWNER }), {
158 + workspaceId: workspace.id,
159 + mode: 'commit_message'
160 + });
161 + assertEditor(view, workspace.id);
162 });
200 - assert.deepEqual(dispatch[2], { isOwner: true, ownerId: OWNER });
201 -});
202 -
203 -test('wrong message type while file upload is pending does not dispatch or consume the workspace input', async () => {
204 - const bot = new NexaDevBot({});
205 - let dispatches = 0;
206 - bot.workspaceStore = {
207 - isConfigured: () => true,
208 - async getPendingInput() {
209 - return { workspaceId: WORKSPACE_ID, mode: 'draft_file' };
210 - }
211 - };
212 - bot.telegram = {
213 - async sendMessage() {
214 - return { ok: true };
215 - },
216 - async downloadTextFile() {
217 - throw new Error('must not download');
218 - }
219 - };
220 - bot.router = {
221 - async dispatchMessage() {
222 - dispatches += 1;
223 - return null;
224 - }
225 - };
163
227 - const result = await bot.handleMessage({
228 - chat: { id: 7 },
229 - from: { id: 42 },
230 - text: 'not a file'
164 + test(`pending ${mode} is consumed without accessing or saving Telegram source fields`, async () => {
165 + const { controller, workspace, workspaces } = await fixture();
166 + await workspaces.setPendingInput({
167 + ownerId: OWNER,
168 + workspaceId: workspace.id,
169 + mode
170 + });
171 + const pending = await workspaces.getPendingInput({ ownerId: OWNER });
172 + let sourceReads = 0;
173 + const payload = {
174 + pending,
175 + get text() {
176 + sourceReads += 1;
177 + return SENTINEL;
178 + },
179 + get file() {
180 + sourceReads += 1;
181 + return { name: 'replacement.txt', text: SENTINEL, byteLength: 100 };
182 + }
183 + };
184 + const view = await controller
185 + .resolveMessage(payload, { ownerId: OWNER })
186 + .execute();
187 + assert.equal(
188 + sourceReads,
189 + 0,
190 + 'disabled source input must not inspect Telegram body fields'
191 + );
192 + assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
193 + const saved = await workspaces.getWorkspace({
194 + ownerId: OWNER,
195 + workspaceId: workspace.id
196 + });
197 + assert.equal(saved.draftText, ORIGINAL);
198 + assert.equal(saved.files[0].draftText, ORIGINAL);
199 + assertEditor(view, workspace.id);
200 });
232 - assert.equal(result.workspaceInput, true);
233 - assert.equal(result.inputRequired, 'document');
234 - assert.equal(dispatches, 0);
235 -});
236 -
237 -test('oversized Telegram document is rejected before download or workspace dispatch so owner can retry', async () => {
238 - const bot = new NexaDevBot({});
239 - let downloads = 0;
240 - let dispatches = 0;
241 - bot.workspaceStore = {
242 - isConfigured: () => true,
243 - async getPendingInput() {
244 - return { workspaceId: WORKSPACE_ID, mode: 'draft_file' };
245 - }
246 - };
247 - bot.telegram = {
248 - async sendMessage() {
249 - return { ok: true };
250 - },
251 - async downloadTextFile() {
252 - downloads += 1;
253 - return { text: 'unexpected', byteLength: 10 };
254 - }
255 - };
256 - bot.router = {
257 - async dispatchMessage() {
258 - dispatches += 1;
259 - return null;
260 - }
261 - };
201
263 - const result = await bot.handleMessage({
264 - chat: { id: 7 },
265 - from: { id: 42 },
266 - document: { file_id: 'HUGE', file_name: 'huge.txt', file_size: 65537 }
202 + test(`pending ${mode} redirects with metadata alone and cannot be replayed`, async () => {
203 + const { controller, workspace, workspaces } = await fixture();
204 + await workspaces.setPendingInput({
205 + ownerId: OWNER,
206 + workspaceId: workspace.id,
207 + mode
208 + });
209 + const pending = await workspaces.getPendingInput({ ownerId: OWNER });
210 + const route = controller.resolveMessage({ pending }, { ownerId: OWNER });
211 + const view = await route.execute();
212 + assertEditor(view, workspace.id);
213 + assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
214 + await assert.rejects(() => route.execute(), /consumed|expired/i);
215 + const saved = await workspaces.getWorkspace({
216 + ownerId: OWNER,
217 + workspaceId: workspace.id
218 + });
219 + assert.equal(saved.draftText, ORIGINAL);
220 });
268 - assert.equal(result.inputRejected, true);
269 - assert.equal(downloads, 0);
270 - assert.equal(dispatches, 0);
271 -});
221 +}
test/github-workspace-integration.test.js
+27 -16
@@ -178,55 +178,66 @@ test('PluginRouter dispatchMessage applies the same policy boundary without audi
178 );
179 });
180
181 -test('legacy draft input is prepared without GitHub calls and the next owner text is consumed exactly once', async () => {
181 +test('commit-message input is prepared without GitHub calls and the next owner message is consumed exactly once', async () => {
182 const { github, workspaces, plugin } = makePlugin();
183 - const prepare = plugin.resolveCallback(`wtext:${WORKSPACE_ID}`, {
183 + const prepare = plugin.resolveCallback(`wmsg:${WORKSPACE_ID}`, {
184 ownerId: OWNER
185 });
186 assert.equal(prepare.actionId, 'github.workspace.input.prepare');
187 assert.deepEqual(github.calls, []);
188 const prompt = await prepare.execute();
189 - assert.match(prompt.text, /20,000|20000/);
189 + assert.match(prompt.text, /120/);
190 assert.deepEqual(github.calls, []);
191
192 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
193 - assert.deepEqual(pending, { workspaceId: WORKSPACE_ID, mode: 'draft' });
193 + assert.deepEqual(pending, {
194 + workspaceId: WORKSPACE_ID,
195 + mode: 'commit_message'
196 + });
197 const route = plugin.resolveMessage(
195 - { pending, text: 'after <tag>\n' },
198 + { pending, text: 'chore: update ignore rules' },
199 { ownerId: OWNER }
200 );
201 assert.equal(route.actionId, 'github.workspace.input.apply');
202 const view = await route.execute();
203 assert.match(view.text, /ذخیره|Draft|پیش.?نویس/i);
201 - assert.equal(workspaces.workspace.draftText, 'after <tag>\n');
204 + assert.equal(
205 + workspaces.workspace.commitMessage,
206 + 'chore: update ignore rules'
207 + );
208 + assert.equal(workspaces.workspace.draftText, 'before\n');
209 assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
210
211 const late = plugin.resolveMessage(
212 {
213 pending: await workspaces.getPendingInput({ ownerId: OWNER }),
207 - text: 'late mutation'
214 + text: 'late commit message'
215 },
216 { ownerId: OWNER }
217 );
218 assert.equal(late, null);
212 - assert.equal(workspaces.workspace.draftText, 'after <tag>\n');
219 + assert.equal(
220 + workspaces.workspace.commitMessage,
221 + 'chore: update ignore rules'
222 + );
223 assert.deepEqual(github.calls, []);
224 });
225
216 -test('oversized multibyte legacy draft input is visibly rejected without mutating the old draft', async () => {
226 +test('oversized commit-message input is consumed without mutating the old commit message or draft', async () => {
227 const { workspaces, plugin } = makePlugin();
228 await plugin
219 - .resolveCallback(`wtext:${WORKSPACE_ID}`, { ownerId: OWNER })
229 + .resolveCallback(`wmsg:${WORKSPACE_ID}`, { ownerId: OWNER })
230 .execute();
231 const before = workspaces.workspace.draftText;
232 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
233 const route = plugin.resolveMessage(
224 - { pending, text: '😀'.repeat(16385) },
234 + { pending, text: 'x'.repeat(121) },
235 { ownerId: OWNER }
236 );
237 const view = await route.execute();
228 - assert.match(view.text, /65,536|65536|20,000|20000|مجاز|حد/i);
238 + assert.match(view.text, /120|Commit.*ذخیره نشد/);
239 assert.equal(workspaces.workspace.draftText, before);
240 + assert.equal(workspaces.workspace.commitMessage, '');
241 assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
242 });
243
@@ -308,7 +319,7 @@ test('READY rejects no-change, reuses identical material and mints a new intent
319 assert.deepEqual(github.calls, []);
320 });
321
311 -test('bot preserves command precedence and routes raw pending workspace text exactly once', async () => {
322 +test('bot preserves command precedence and routes permitted commit-message text exactly once', async () => {
323 const bot = new NexaDevBot({});
324 const calls = [];
325 bot.telegram = {
@@ -321,7 +332,7 @@ test('bot preserves command precedence and routes raw pending workspace text exa
332 isConfigured: () => true,
333 async getPendingInput({ ownerId }) {
334 calls.push(['getPendingInput', ownerId]);
324 - return { workspaceId: WORKSPACE_ID, mode: 'draft' };
335 + return { workspaceId: WORKSPACE_ID, mode: 'commit_message' };
336 }
337 };
338 bot.router = {
@@ -356,9 +367,9 @@ test('bot preserves command precedence and routes raw pending workspace text exa
367 await bot.handleMessage({
368 chat: { id: 7 },
369 from: { id: 42 },
359 - text: ' exact draft text \n'
370 + text: ' chore: update ignore rules \n'
371 });
372 const dispatch = calls.find((call) => call[0] === 'dispatchMessage');
362 - assert.equal(dispatch[1].text, ' exact draft text \n');
373 + assert.equal(dispatch[1].text, ' chore: update ignore rules \n');
374 assert.deepEqual(dispatch[2], { isOwner: true, ownerId: OWNER });
375 });
test/help-guide.test.js
+2 -2
@@ -92,8 +92,6 @@ describe('Nexa Dev Bot - in-app V2.1 guide', () => {
92 'Editor',
93 'Mini App',
94 'WORKSPACE_STORE',
95 - 'بارگذاری فایل',
96 - 'Paste متن',
95 'پیام Commit',
96 'Diff',
97 'آماده Commit',
@@ -104,6 +102,8 @@ describe('Nexa Dev Bot - in-app V2.1 guide', () => {
102 `workspace guide missing ${label}`
103 );
104 }
105 + assert.doesNotMatch(workspaceHelp.text, /Paste متن|بارگذاری فایل/);
106 + assert.match(workspaceHelp.text, /متن منبع.*چت.*ارسال نکنید/);
107
108 const ciHelp = await menu.renderByCallback('help:5');
109 for (const label of [
test/telegram-persistent-menu-input.test.js
+87 -10
@@ -69,7 +69,7 @@ test('persistent menu text has precedence over pending draft input', async () =>
69 assert.match(sent.at(-1).text, /Nexa Dev Bot/);
70 });
71
72 -test('Paste text opens a focused ForceReply prompt without replacing the workspace message', async () => {
72 +test('legacy Paste callbacks replace the workspace message with the Mini App redirect', async () => {
73 const bot = new NexaDevBot({});
74 const sent = [];
75 const edited = [];
@@ -86,10 +86,10 @@ test('Paste text opens a focused ForceReply prompt without replacing the workspa
86 bot.router.dispatchCallback = async (data) => {
87 assert.equal(data, `wtext:${WORKSPACE_ID}`);
88 return {
89 - text: '📝 متن جدید Draft را ارسال کنید',
89 + text: 'متن را فقط در Mini App ویرایش کنید',
90 reply_markup: {
91 inline_keyboard: [
92 - [{ text: '↩️ بازگشت', callback_data: `ws:${WORKSPACE_ID}` }]
92 + [{ text: 'Editor', web_app: { url: 'https://example.test/editor' } }]
93 ]
94 }
95 };
@@ -103,11 +103,88 @@ test('Paste text opens a focused ForceReply prompt without replacing the workspa
103 });
104
105 assert.equal(result.ok, true);
106 - assert.equal(result.inputPrompt, true);
107 - assert.equal(edited.length, 0);
108 - assert.equal(sent.length, 1);
109 - assert.equal(sent[0].replyMarkup.force_reply, true);
110 - assert.equal(sent[0].replyMarkup.selective, true);
111 - assert.match(sent[0].replyMarkup.input_field_placeholder, /Paste|کد|متن/i);
112 - assert.equal(sent[0].replyMarkup.inline_keyboard, undefined);
106 + assert.equal(result.edited, true);
107 + assert.equal(result.inputPrompt, undefined);
108 + assert.equal(sent.length, 0);
109 + assert.equal(edited.length, 1);
110 + assert.equal(edited[0][1], 55);
111 + assert.equal(edited[0][3].force_reply, undefined);
112 + assert.equal(
113 + edited[0][3].inline_keyboard[0][0].web_app.url,
114 + 'https://example.test/editor'
115 + );
116 +});
117 +
118 +test('stale draft input sends only pending metadata to the Mini App redirect route', async () => {
119 + const bot = new NexaDevBot({});
120 + const pending = { workspaceId: WORKSPACE_ID, mode: 'draft' };
121 + const payloadKeys = [];
122 + const sent = [];
123 + bot.workspaceStore = {
124 + isConfigured: () => true,
125 + async getPendingInput() {
126 + return pending;
127 + }
128 + };
129 + bot.router.dispatchMessage = async (payload, context) => {
130 + payloadKeys.push(Object.keys(payload));
131 + assert.deepEqual(payload.pending, pending);
132 + assert.equal(context.ownerId, '42');
133 + return { text: 'ویرایش فقط در Mini App' };
134 + };
135 + bot.telegram.sendMessage = async (chatId, text) => {
136 + sent.push({ chatId, text });
137 + return { ok: true };
138 + };
139 +
140 + const result = await bot.handleMessage({
141 + message_id: 55,
142 + chat: { id: 7 },
143 + from: { id: 42 },
144 + text: 'SOURCE_BODY_MUST_NOT_REACH_CONTROLLER'
145 + });
146 +
147 + assert.deepEqual(payloadKeys, [['pending']]);
148 + assert.equal(result.workspaceInput, true);
149 + assert.equal(
150 + JSON.stringify({ sent, result }).includes('SOURCE_BODY_'),
151 + false
152 + );
153 +});
154 +
155 +test('stale upload input redirects before downloading or requesting another file', async () => {
156 + for (const document of [
157 + undefined,
158 + { file_id: 'synthetic-file', file_size: 10 }
159 + ]) {
160 + const bot = new NexaDevBot({});
161 + let downloads = 0;
162 + const payloadKeys = [];
163 + bot.workspaceStore = {
164 + isConfigured: () => true,
165 + async getPendingInput() {
166 + return { workspaceId: WORKSPACE_ID, mode: 'draft_file' };
167 + }
168 + };
169 + bot.telegram.downloadTextFile = async () => {
170 + downloads++;
171 + return { text: 'SOURCE_BODY', byteLength: 11 };
172 + };
173 + bot.router.dispatchMessage = async (payload) => {
174 + payloadKeys.push(Object.keys(payload));
175 + return { text: 'ویرایش فقط در Mini App' };
176 + };
177 + bot.telegram.sendMessage = async () => ({ ok: true });
178 +
179 + const result = await bot.handleMessage({
180 + chat: { id: 7 },
181 + from: { id: 42 },
182 + document
183 + });
184 +
185 + assert.equal(downloads, 0);
186 + assert.deepEqual(payloadKeys, [['pending']]);
187 + assert.equal(result.workspaceInput, true);
188 + assert.equal(result.inputRequired, undefined);
189 + }
190 });
test/telegram-secret-guard.test.js new
+206
@@ -0,0 +1,206 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { KillSwitchGuidedNexaDevBot } from '../src/kill-switch-bot.js';
4 +
5 +const OWNER = '42';
6 +const syntheticToken = (prefix) => `${prefix}synthetic_noncredential_fixture`;
7 +const ownerMessage = (text, extra = {}) => ({
8 + message_id: 17,
9 + from: { id: Number(OWNER) },
10 + chat: { id: Number(OWNER), type: 'private' },
11 + text,
12 + ...extra
13 +});
14 +
15 +function guardedBot({ ownerId = OWNER, failures = {} } = {}) {
16 + const bot = new KillSwitchGuidedNexaDevBot({
17 + OWNER_TELEGRAM_ID: ownerId,
18 + TELEGRAM_BOT_TOKEN: 'synthetic-bot-credential'
19 + });
20 + const effects = [];
21 + bot.telegram.fetchFn = async (url, options) => {
22 + const method = new URL(url).pathname.split('/').at(-1);
23 + const payload = JSON.parse(options.body);
24 + effects.push({ method, payload });
25 + if (failures[method]) throw new Error(failures[method]);
26 + return Response.json({
27 + ok: true,
28 + result: method === 'sendMessage' ? { message_id: 18 } : true
29 + });
30 + };
31 + return { bot, effects };
32 +}
33 +
34 +test('all GitHub token prefixes delete the message before a Persian revocation warning', async (t) => {
35 + for (const prefix of [
36 + 'github_pat_',
37 + 'ghp_',
38 + 'gho_',
39 + 'ghu_',
40 + 'ghs_',
41 + 'ghr_'
42 + ]) {
43 + await t.test(prefix, async () => {
44 + const { bot, effects } = guardedBot();
45 + const text = syntheticToken(prefix);
46 + const result = await bot.handleUpdate({ message: ownerMessage(text) });
47 +
48 + assert.equal(result.secretRejected, true);
49 + assert.deepEqual(
50 + effects.map(({ method }) => method),
51 + ['deleteMessage', 'sendMessage']
52 + );
53 + assert.deepEqual(effects[0].payload, { chat_id: 42, message_id: 17 });
54 + assert.match(effects[1].payload.text, /توکن در چت قرار گرفت/);
55 + assert.match(effects[1].payload.text, /باید در GitHub باطل شود/);
56 + assert.match(
57 + effects[1].payload.text,
58 + /https:\/\/github\.com\/settings\//
59 + );
60 + assert.equal(JSON.stringify({ effects, result }).includes(text), false);
61 + assert.equal(result.deleted, true);
62 + assert.equal(result.warned, true);
63 + });
64 + }
65 +});
66 +
67 +test('token interception precedes pending workspace reads, file download, routing and audit', async () => {
68 + const { bot, effects } = guardedBot();
69 + const reached = [];
70 + bot.workspaceStore = {
71 + isConfigured: () => true,
72 + async getPendingInput() {
73 + reached.push('pending');
74 + return { workspaceId: 'W000000001', mode: 'draft_file' };
75 + }
76 + };
77 + bot.telegram.downloadTextFile = async () => {
78 + reached.push('download');
79 + return { text: 'safe fixture', byteLength: 12 };
80 + };
81 + bot.router.dispatchMessage = async () => {
82 + reached.push('dispatch');
83 + return { text: 'generic response' };
84 + };
85 + bot.audit.log = () => reached.push('audit');
86 +
87 + const result = await bot.handleUpdate({
88 + message: ownerMessage(` \n${syntheticToken('github_pat_')}`, {
89 + document: { file_id: 'synthetic-file', file_size: 12 }
90 + })
91 + });
92 +
93 + assert.deepEqual(reached, []);
94 + assert.equal(result.secretRejected, true);
95 + assert.equal(effects.length, 2);
96 +});
97 +
98 +test('direct message handling also rejects tokens before pending input', async () => {
99 + const { bot } = guardedBot();
100 + let pendingReads = 0;
101 + bot.workspaceStore = {
102 + isConfigured: () => true,
103 + async getPendingInput() {
104 + pendingReads++;
105 + return null;
106 + }
107 + };
108 +
109 + const result = await bot.handleMessage(ownerMessage(syntheticToken('ghp_')));
110 +
111 + assert.equal(pendingReads, 0);
112 + assert.equal(result.secretRejected, true);
113 +});
114 +
115 +test('edited token messages are intercepted before the generic message dispatcher', async () => {
116 + const { bot, effects } = guardedBot();
117 + let dispatched = false;
118 + bot.handleMessage = async () => {
119 + dispatched = true;
120 + return { ok: true, generic: true };
121 + };
122 +
123 + const result = await bot.handleUpdate({
124 + edited_message: ownerMessage(syntheticToken('gho_'))
125 + });
126 +
127 + assert.equal(result.secretRejected, true);
128 + assert.equal(dispatched, false);
129 + assert.deepEqual(
130 + effects.map(({ method }) => method),
131 + ['deleteMessage', 'sendMessage']
132 + );
133 +});
134 +
135 +test('document captions beginning with a token are rejected before upload processing', async () => {
136 + const { bot, effects } = guardedBot();
137 + const result = await bot.handleUpdate({
138 + message: ownerMessage(undefined, {
139 + caption: syntheticToken('ghs_'),
140 + document: { file_id: 'synthetic-file', file_size: 12 }
141 + })
142 + });
143 +
144 + assert.equal(result.secretRejected, true);
145 + assert.equal(effects[0].method, 'deleteMessage');
146 +});
147 +
148 +test('a failed delete still warns without claiming deletion or echoing a raw provider error', async () => {
149 + const text = syntheticToken('github_pat_');
150 + const { bot, effects } = guardedBot({
151 + failures: { deleteMessage: `provider included ${text}` }
152 + });
153 + const result = await bot.handleUpdate({ message: ownerMessage(text) });
154 +
155 + assert.equal(result.secretRejected, true);
156 + assert.equal(result.deleted, false);
157 + assert.equal(result.warned, true);
158 + assert.equal(effects[1].method, 'sendMessage');
159 + assert.match(effects[1].payload.text, /حذف.*تأیید نشد/);
160 + assert.equal(JSON.stringify({ effects, result }).includes(text), false);
161 +});
162 +
163 +test('warning failures return only metadata and never fall back to a generic handler', async () => {
164 + const text = syntheticToken('ghu_');
165 + const { bot, effects } = guardedBot({
166 + failures: { sendMessage: `provider included ${text}` }
167 + });
168 + let dispatched = false;
169 + bot.handleMessage = async () => {
170 + dispatched = true;
171 + return { ok: true };
172 + };
173 + const result = await bot.handleUpdate({ message: ownerMessage(text) });
174 +
175 + assert.equal(result.secretRejected, true);
176 + assert.equal(result.warned, false);
177 + assert.equal(result.deleted, true);
178 + assert.equal(dispatched, false);
179 + assert.equal(JSON.stringify({ effects, result }).includes(text), false);
180 +});
181 +
182 +test('secret messages cannot cross the configured owner boundary or run without an owner', async () => {
183 + for (const ownerId of [OWNER, '']) {
184 + const { bot, effects } = guardedBot({ ownerId });
185 + const result = await bot.handleUpdate({
186 + message: ownerMessage(syntheticToken('ghr_'), { from: { id: 99 } })
187 + });
188 + assert.equal(result.ignored, true);
189 + assert.deepEqual(effects, []);
190 + }
191 +});
192 +
193 +test('ordinary messages keep their existing dispatch and ordinary edits remain ignored', async () => {
194 + const { bot, effects } = guardedBot();
195 + const ordinary = await bot.handleUpdate({ message: ownerMessage('/help') });
196 + assert.equal(ordinary.ok, true);
197 + assert.equal(ordinary.secretRejected, undefined);
198 + assert.equal(effects.length, 1);
199 + assert.equal(effects[0].method, 'sendMessage');
200 +
201 + const edited = await bot.handleUpdate({
202 + edited_message: ownerMessage('/help')
203 + });
204 + assert.deepEqual(edited, { ok: true, ignored: true });
205 + assert.equal(effects.length, 1);
206 +});
test/telegram-secret-webhook.test.js new
+95
@@ -0,0 +1,95 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import worker from '../src/index.js';
4 +import { makeReplayNamespace } from './helpers/replay-namespace.js';
5 +
6 +const secret = 'github_pat_WEBHOOK_ONLY_SENTINEL_3021';
7 +const request = (update) =>
8 + new Request('https://acceptance.test/telegram/webhook', {
9 + method: 'POST',
10 + headers: { 'X-Telegram-Bot-Api-Secret-Token': 'webhook' },
11 + body: JSON.stringify(update)
12 + });
13 +const environment = (namespace) => ({
14 + OWNER_TELEGRAM_ID: '42',
15 + TELEGRAM_BOT_TOKEN: '12345:test',
16 + TELEGRAM_WEBHOOK_SECRET: 'webhook',
17 + APPROVAL_REPLAY_GUARD: namespace,
18 + WORKSPACE_STORE: {
19 + idFromName: () => {
20 + throw new Error('must not read pending input');
21 + },
22 + get: () => {}
23 + }
24 +});
25 +
26 +test('new and edited token messages are deleted once with no source in replies, logs or durable state', async () => {
27 + const previousFetch = globalThis.fetch;
28 + const previousLog = console.log;
29 + const previousError = console.error;
30 + const outbound = [];
31 + const logs = [];
32 + globalThis.fetch = async (url, options) => {
33 + outbound.push({
34 + method: new URL(url).pathname.split('/').pop(),
35 + body: JSON.parse(options.body)
36 + });
37 + return Response.json({ ok: true, result: true });
38 + };
39 + console.log = console.error = (...args) =>
40 + logs.push(args.map(String).join(' '));
41 + try {
42 + const namespace = makeReplayNamespace();
43 + const env = environment(namespace);
44 + for (const [index, kind] of ['message', 'edited_message'].entries()) {
45 + const update = {
46 + update_id: index + 1,
47 + [kind]: {
48 + message_id: 20 + index,
49 + chat: { id: 42 },
50 + from: { id: 42 },
51 + text: secret
52 + }
53 + };
54 + const response = await worker.fetch(request(update), env);
55 + assert.equal(response.status, 200);
56 + assert.equal((await response.json()).secretRejected, true, kind);
57 + const duplicate = await worker.fetch(request(update), env);
58 + assert.equal((await duplicate.json()).duplicate, true);
59 + }
60 + assert.deepEqual(
61 + outbound.map((call) => call.method),
62 + ['deleteMessage', 'sendMessage', 'deleteMessage', 'sendMessage']
63 + );
64 + assert.doesNotMatch(JSON.stringify({ outbound, logs }), new RegExp(secret));
65 + const state = [...namespace.states.values()].map((item) => [...item.data]);
66 + assert.doesNotMatch(JSON.stringify(state), new RegExp(secret));
67 + assert.ok(
68 + state.every((rows) =>
69 + rows.every(([, value]) => typeof value === 'number')
70 + )
71 + );
72 + } finally {
73 + globalThis.fetch = previousFetch;
74 + console.log = previousLog;
75 + console.error = previousError;
76 + }
77 +});
78 +
79 +test('edited nonowner token updates cannot allocate a claim or contact Telegram', async () => {
80 + const namespace = makeReplayNamespace();
81 + const response = await worker.fetch(
82 + request({
83 + update_id: 9,
84 + edited_message: {
85 + message_id: 22,
86 + chat: { id: 7 },
87 + from: { id: 7 },
88 + text: secret
89 + }
90 + }),
91 + environment(namespace)
92 + );
93 + assert.equal((await response.json()).ignored, true);
94 + assert.equal(namespace.states.size, 0);
95 +});
test/workspace-editor-environment.test.js new
+125
@@ -0,0 +1,125 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import * as config from '../src/config.js';
4 +import { NexaDevBot } from '../src/bot-legacy.js';
5 +import worker from '../src/index.js';
6 +import { KillSwitchGuidedNexaDevBot } from '../src/kill-switch-bot.js';
7 +import { makeReplayNamespace } from './helpers/replay-namespace.js';
8 +
9 +const workspace = {
10 + id: 'W000000001',
11 + repoId: 1,
12 + path: 'README.md',
13 + state: 'DRAFT',
14 + originalText: 'one',
15 + draftText: 'two',
16 + baseHeadSha: 'a'.repeat(40)
17 +};
18 +async function editorLinks(configured) {
19 + const bot = new NexaDevBot({
20 + WORKSPACE_EDITOR_URL: configured,
21 + WORKSPACE_STORE: { idFromName: (name) => name, get: () => ({}) }
22 + });
23 + bot.workspaceStore.getWorkspace = async () => workspace;
24 + bot.workspaceStore.createNavigationRefs = async () => [];
25 + const view = await bot.githubPlugin
26 + .resolveCallback('ws:W000000001', { ownerId: '42' })
27 + .execute();
28 + return view.reply_markup.inline_keyboard
29 + .flat()
30 + .filter((button) => button.web_app)
31 + .map((button) => button.web_app.url);
32 +}
33 +
34 +test('bot workspace editor links use the configured acceptance environment', async () => {
35 + const links = await editorLinks('https://acceptance.test/workspace/editor');
36 + assert.ok(links.length > 0);
37 + for (const link of links) {
38 + assert.equal(new URL(link).origin, 'https://acceptance.test');
39 + assert.equal(new URL(link).pathname, '/workspace/editor');
40 + assert.equal(new URL(link).searchParams.get('workspaceId'), workspace.id);
41 + }
42 +});
43 +
44 +test('editor URL configuration rejects credentials, queries, fragments and unexpected routes', async () => {
45 + for (const value of [
46 + 'http://acceptance.test/workspace/editor',
47 + 'https://user:password@acceptance.test/workspace/editor',
48 + 'https://acceptance.test/workspace/editor?token=private',
49 + 'https://acceptance.test/workspace/editor#private',
50 + 'https://acceptance.test/other',
51 + 'not a url',
52 + ''
53 + ]) {
54 + assert.deepEqual(await editorLinks(value), [], value);
55 + }
56 +});
57 +
58 +test('the established editor URL remains the default for direct bot construction', async () => {
59 + const links = await editorLinks(undefined);
60 + assert.ok(links.length > 0);
61 + assert.equal(
62 + new URL(links[0]).origin,
63 + new URL(config.DEFAULT_CONFIG.workspaceEditorUrl).origin
64 + );
65 +});
66 +
67 +test('configuration view reports the validated environment URL without rejected credential text', () => {
68 + const configured = new KillSwitchGuidedNexaDevBot({
69 + WORKSPACE_EDITOR_URL: 'https://acceptance.test/workspace/editor'
70 + });
71 + assert.match(
72 + configured.menu.getEditorConfigView().text,
73 + /https:\/\/acceptance\.test\/workspace\/editor/
74 + );
75 + const invalid = new KillSwitchGuidedNexaDevBot({
76 + WORKSPACE_EDITOR_URL:
77 + 'https://user:PRIVATE_URL_SENTINEL@acceptance.test/workspace/editor'
78 + });
79 + assert.doesNotMatch(
80 + invalid.menu.getEditorConfigView().text,
81 + /PRIVATE_URL_SENTINEL|nexa-dev-bot\.davoodmehraban89/
82 + );
83 + assert.match(invalid.menu.getEditorConfigView().text, /پیکربندی نشده/);
84 +});
85 +
86 +test('webhook editor default stays on its own Worker origin and respects explicit configuration', async () => {
87 + const original = KillSwitchGuidedNexaDevBot.prototype.handleUpdate;
88 + KillSwitchGuidedNexaDevBot.prototype.handleUpdate = async function () {
89 + return { ok: true, editorUrl: this.env.WORKSPACE_EDITOR_URL };
90 + };
91 + try {
92 + for (const configured of [
93 + undefined,
94 + 'https://custom.test/workspace/editor',
95 + ''
96 + ]) {
97 + const response = await worker.fetch(
98 + new Request('https://acceptance.test/telegram/webhook', {
99 + method: 'POST',
100 + headers: { 'X-Telegram-Bot-Api-Secret-Token': 'webhook' },
101 + body: JSON.stringify({
102 + update_id: 1,
103 + message: { from: { id: 42 }, chat: { id: 42 }, text: '/help' }
104 + })
105 + }),
106 + {
107 + OWNER_TELEGRAM_ID: '42',
108 + TELEGRAM_BOT_TOKEN: '12345:test',
109 + TELEGRAM_WEBHOOK_SECRET: 'webhook',
110 + APPROVAL_REPLAY_GUARD: makeReplayNamespace(),
111 + ...(configured === undefined
112 + ? {}
113 + : { WORKSPACE_EDITOR_URL: configured })
114 + }
115 + );
116 + assert.equal(response.status, 200);
117 + assert.equal(
118 + (await response.json()).editorUrl,
119 + configured ?? 'https://acceptance.test/workspace/editor'
120 + );
121 + }
122 + } finally {
123 + KillSwitchGuidedNexaDevBot.prototype.handleUpdate = original;
124 + }
125 +});