Personal Telegram developer console for GitHub

phase2-20261005-r
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
js 258 lines 11.1 KB
Raw
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { NexaDevBot } from '../src/bot.js';
4 import { PluginRouter } from '../src/core/router.js';
5 import { PluginRegistry } from '../src/core/plugin-registry.js';
6 import { ActionPolicy } from '../src/core/action-policy.js';
7 import { AuditLogger } from '../src/core/audit.js';
8 import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
9 import { digestText } from '../src/core/workspace-policy.js';
10
11 const OWNER = '42';
12 const WORKSPACE_ID = 'W000000001';
13
14 function flatten(view) {
15 return view?.reply_markup?.inline_keyboard?.flat() || [];
16 }
17
18 function makeMenu() {
19 return {
20 async getReposListView() { return { text: 'repos', reply_markup: { inline_keyboard: [] } }; },
21 async renderByCallback(data) { return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } }; }
22 };
23 }
24
25 function makeGitHub() {
26 const calls = [];
27 return {
28 calls,
29 async getRepository(repoId) {
30 calls.push(['getRepository', Number(repoId)]);
31 return { id: String(repoId), name: 'demo', fullName: 'davood/demo', defaultBranch: 'main', archived: false };
32 }
33 };
34 }
35
36 function makeWorkspaces() {
37 const calls = [];
38 let pending = null;
39 let intentCounter = 0;
40 const intents = new Map();
41 const workspace = {
42 id: WORKSPACE_ID,
43 repoId: 123,
44 repoFullName: 'davood/demo',
45 baseBranch: 'main',
46 baseHeadSha: 'a'.repeat(40),
47 baseTreeSha: 'b'.repeat(40),
48 path: 'src/app.js',
49 blobSha: 'c'.repeat(40),
50 originalText: 'before\n',
51 originalDigest: '0'.repeat(64),
52 draftText: 'before\n',
53 draftDigest: '0'.repeat(64),
54 commitMessage: '',
55 commitMessageDigest: '',
56 currentIntentId: null,
57 state: 'DRAFT'
58 };
59
60 return {
61 calls,
62 workspace,
63 intents,
64 async getWorkspace({ ownerId, workspaceId }) {
65 calls.push(['getWorkspace', ownerId, workspaceId]);
66 return ownerId === OWNER && workspaceId === WORKSPACE_ID ? structuredClone(workspace) : null;
67 },
68 async setPendingInput({ ownerId, workspaceId, mode }) {
69 calls.push(['setPendingInput', ownerId, workspaceId, mode]);
70 pending = { workspaceId, mode };
71 return structuredClone(pending);
72 },
73 async getPendingInput({ ownerId }) {
74 calls.push(['getPendingInput', ownerId]);
75 return ownerId === OWNER && pending ? structuredClone(pending) : null;
76 },
77 async consumePendingInput({ ownerId, workspaceId, mode }) {
78 calls.push(['consumePendingInput', ownerId, workspaceId, mode]);
79 if (ownerId !== OWNER || !pending || pending.workspaceId !== workspaceId || pending.mode !== mode) return false;
80 pending = null;
81 return true;
82 },
83 async updateDraft({ ownerId, workspaceId, text, digest }) {
84 calls.push(['updateDraft', ownerId, workspaceId, text, digest]);
85 workspace.draftText = text;
86 workspace.draftDigest = digest;
87 workspace.currentIntentId = null;
88 workspace.state = 'DRAFT';
89 return structuredClone(workspace);
90 },
91 async setCommitMessage({ ownerId, workspaceId, message, digest }) {
92 calls.push(['setCommitMessage', ownerId, workspaceId, message, digest]);
93 workspace.commitMessage = message;
94 workspace.commitMessageDigest = digest;
95 workspace.currentIntentId = null;
96 workspace.state = 'DRAFT';
97 return structuredClone(workspace);
98 },
99 async sealIntent({ ownerId, workspaceId, intent }) {
100 calls.push(['sealIntent', ownerId, workspaceId, structuredClone(intent)]);
101 if (workspace.currentIntentId) {
102 const existing = intents.get(workspace.currentIntentId);
103 if (existing?.intentDigest === intent.intentDigest) return structuredClone(existing);
104 }
105 intentCounter += 1;
106 const id = `I${String(intentCounter).padStart(7, '0')}`;
107 const sealed = { ...structuredClone(intent), id, workspaceId, state: 'READY' };
108 intents.set(id, sealed);
109 workspace.currentIntentId = id;
110 workspace.state = 'READY';
111 return structuredClone(sealed);
112 }
113 };
114 }
115
116 function makePlugin() {
117 const github = makeGitHub();
118 const workspaces = makeWorkspaces();
119 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
120 return { github, workspaces, plugin };
121 }
122
123 test('PluginRouter dispatchMessage applies the same policy boundary without auditing source text', async () => {
124 const auditEvents = [];
125 const plugin = {
126 manifest: { id: 'demo', name: 'Demo', version: 1, commands: [], actions: { 'demo.message': { risk: 'READ' } } },
127 resolveMessage(payload) {
128 if (!payload?.pending) return null;
129 return { actionId: 'demo.message', execute: async () => ({ text: 'accepted' }) };
130 }
131 };
132 const router = new PluginRouter({
133 registry: new PluginRegistry([plugin]),
134 policy: new ActionPolicy(),
135 audit: new AuditLogger({ sink: event => auditEvents.push(event) })
136 });
137 const result = await router.dispatchMessage({ pending: { mode: 'draft' }, text: 'TOP SECRET SOURCE' }, { isOwner: true, ownerId: OWNER });
138 assert.equal(result.text, 'accepted');
139 assert.equal(JSON.stringify(auditEvents).includes('TOP SECRET SOURCE'), false);
140 });
141
142 test('legacy draft input is prepared without GitHub calls and the next owner text is consumed exactly once', async () => {
143 const { github, workspaces, plugin } = makePlugin();
144 const prepare = plugin.resolveCallback(`wtext:${WORKSPACE_ID}`, { ownerId: OWNER });
145 assert.equal(prepare.actionId, 'github.workspace.input.prepare');
146 assert.deepEqual(github.calls, []);
147 const prompt = await prepare.execute();
148 assert.match(prompt.text, /20,000|20000/);
149 assert.deepEqual(github.calls, []);
150
151 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
152 assert.deepEqual(pending, { workspaceId: WORKSPACE_ID, mode: 'draft' });
153 const route = plugin.resolveMessage({ pending, text: 'after <tag>\n' }, { ownerId: OWNER });
154 assert.equal(route.actionId, 'github.workspace.input.apply');
155 const view = await route.execute();
156 assert.match(view.text, /ذخیره|Draft|پیش.?نویس/i);
157 assert.equal(workspaces.workspace.draftText, 'after <tag>\n');
158 assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
159
160 const late = plugin.resolveMessage({ pending: await workspaces.getPendingInput({ ownerId: OWNER }), text: 'late mutation' }, { ownerId: OWNER });
161 assert.equal(late, null);
162 assert.equal(workspaces.workspace.draftText, 'after <tag>\n');
163 assert.deepEqual(github.calls, []);
164 });
165
166 test('oversized multibyte legacy draft input is visibly rejected without mutating the old draft', async () => {
167 const { workspaces, plugin } = makePlugin();
168 await plugin.resolveCallback(`wtext:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
169 const before = workspaces.workspace.draftText;
170 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
171 const route = plugin.resolveMessage({ pending, text: '😀'.repeat(16385) }, { ownerId: OWNER });
172 const view = await route.execute();
173 assert.match(view.text, /65,536|65536|20,000|20000|مجاز|حد/i);
174 assert.equal(workspaces.workspace.draftText, before);
175 assert.equal(await workspaces.getPendingInput({ ownerId: OWNER }), null);
176 });
177
178 test('commit message input normalizes text and diff renders escaped bounded exact counts without GitHub mutation', async () => {
179 const { github, workspaces, plugin } = makePlugin();
180 await plugin.resolveCallback(`wmsg:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
181 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
182 await plugin.resolveMessage({ pending, text: ' chore: update workspace ' }, { ownerId: OWNER }).execute();
183 assert.equal(workspaces.workspace.commitMessage, 'chore: update workspace');
184
185 workspaces.workspace.draftText = 'after <script>\n';
186 workspaces.workspace.draftDigest = await digestText(workspaces.workspace.draftText);
187 const diffRoute = plugin.resolveCallback(`wdiff:${WORKSPACE_ID}`, { ownerId: OWNER });
188 assert.equal(diffRoute.actionId, 'github.workspace.diff');
189 const diffView = await diffRoute.execute();
190 assert.match(diffView.text, /\+1/);
191 assert.match(diffView.text, /-1/);
192 assert.doesNotMatch(diffView.text, /<script>/);
193 assert.match(diffView.text, /&lt;script&gt;/);
194 assert.deepEqual(github.calls, []);
195 });
196
197 test('READY rejects no-change, reuses identical material and mints a new intent after material change', async () => {
198 const { github, workspaces, plugin } = makePlugin();
199 workspaces.workspace.commitMessage = 'edit app';
200 workspaces.workspace.commitMessageDigest = await digestText('edit app');
201
202 const noChange = plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER });
203 await assert.rejects(() => noChange.execute(), /change|تغییر|بدون/i);
204
205 workspaces.workspace.draftText = 'after\n';
206 workspaces.workspace.draftDigest = await digestText('after\n');
207 const ready1 = await plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
208 const commit1 = flatten(ready1).find(button => button.callback_data?.startsWith('wscommit:'))?.callback_data;
209 assert.match(commit1, /^wscommit:123:[A-Za-z0-9_-]{8}$/);
210 assert.ok(new TextEncoder().encode(commit1).byteLength <= 64);
211
212 const ready2 = await plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
213 const commit2 = flatten(ready2).find(button => button.callback_data?.startsWith('wscommit:'))?.callback_data;
214 assert.equal(commit2, commit1);
215
216 workspaces.workspace.draftText = 'after again\n';
217 workspaces.workspace.draftDigest = await digestText('after again\n');
218 workspaces.workspace.currentIntentId = null;
219 workspaces.workspace.state = 'DRAFT';
220 const ready3 = await plugin.resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER }).execute();
221 const commit3 = flatten(ready3).find(button => button.callback_data?.startsWith('wscommit:'))?.callback_data;
222 assert.notEqual(commit3, commit1);
223 assert.deepEqual(github.calls, []);
224 });
225
226 test('bot preserves command precedence and routes raw pending workspace text exactly once', async () => {
227 const bot = new NexaDevBot({});
228 const calls = [];
229 bot.telegram = {
230 async sendMessage(chatId, text, replyMarkup) {
231 calls.push(['sendMessage', chatId, text, replyMarkup]);
232 return { ok: true };
233 }
234 };
235 bot.workspaceStore = {
236 isConfigured: () => true,
237 async getPendingInput({ ownerId }) {
238 calls.push(['getPendingInput', ownerId]);
239 return { workspaceId: WORKSPACE_ID, mode: 'draft' };
240 }
241 };
242 bot.router = {
243 async dispatchMessage(payload, context) {
244 calls.push(['dispatchMessage', structuredClone(payload), structuredClone(context)]);
245 return { text: 'workspace accepted', reply_markup: { inline_keyboard: [] } };
246 }
247 };
248
249 await bot.handleMessage({ chat: { id: 7 }, from: { id: 42 }, text: '/status' });
250 assert.equal(calls.some(call => call[0] === 'getPendingInput'), false);
251 assert.equal(calls.some(call => call[0] === 'dispatchMessage'), false);
252
253 calls.length = 0;
254 await bot.handleMessage({ chat: { id: 7 }, from: { id: 42 }, text: ' exact draft text \n' });
255 const dispatch = calls.find(call => call[0] === 'dispatchMessage');
256 assert.equal(dispatch[1].text, ' exact draft text \n');
257 assert.deepEqual(dispatch[2], { isOwner: true, ownerId: OWNER });
258 });