Personal Telegram developer console for GitHub

feat/studio-g0-foundation
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 375 lines 12 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() {
21 return { text: 'repos', reply_markup: { inline_keyboard: [] } };
22 },
23 async renderByCallback(data) {
24 return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
25 }
26 };
27 }
28
29 function makeGitHub() {
30 const calls = [];
31 return {
32 calls,
33 async getRepository(repoId) {
34 calls.push(['getRepository', Number(repoId)]);
35 return {
36 id: String(repoId),
37 name: 'demo',
38 fullName: 'davood/demo',
39 defaultBranch: 'main',
40 archived: false
41 };
42 }
43 };
44 }
45
46 function makeWorkspaces() {
47 const calls = [];
48 let pending = null;
49 let intentCounter = 0;
50 const intents = new Map();
51 const workspace = {
52 id: WORKSPACE_ID,
53 repoId: 123,
54 repoFullName: 'davood/demo',
55 baseBranch: 'main',
56 baseHeadSha: 'a'.repeat(40),
57 baseTreeSha: 'b'.repeat(40),
58 path: 'src/app.js',
59 blobSha: 'c'.repeat(40),
60 originalText: 'before\n',
61 originalDigest: '0'.repeat(64),
62 draftText: 'before\n',
63 draftDigest: '0'.repeat(64),
64 commitMessage: '',
65 commitMessageDigest: '',
66 currentIntentId: null,
67 state: 'DRAFT'
68 };
69
70 return {
71 calls,
72 workspace,
73 intents,
74 async getWorkspace({ ownerId, workspaceId }) {
75 calls.push(['getWorkspace', ownerId, workspaceId]);
76 return ownerId === OWNER && workspaceId === WORKSPACE_ID
77 ? structuredClone(workspace)
78 : null;
79 },
80 async setPendingInput({ ownerId, workspaceId, mode }) {
81 calls.push(['setPendingInput', ownerId, workspaceId, mode]);
82 pending = { workspaceId, mode };
83 return structuredClone(pending);
84 },
85 async getPendingInput({ ownerId }) {
86 calls.push(['getPendingInput', ownerId]);
87 return ownerId === OWNER && pending ? structuredClone(pending) : null;
88 },
89 async consumePendingInput({ ownerId, workspaceId, mode }) {
90 calls.push(['consumePendingInput', ownerId, workspaceId, mode]);
91 if (
92 ownerId !== OWNER ||
93 !pending ||
94 pending.workspaceId !== workspaceId ||
95 pending.mode !== mode
96 )
97 return false;
98 pending = null;
99 return true;
100 },
101 async updateDraft({ ownerId, workspaceId, text, digest }) {
102 calls.push(['updateDraft', ownerId, workspaceId, text, digest]);
103 workspace.draftText = text;
104 workspace.draftDigest = digest;
105 workspace.currentIntentId = null;
106 workspace.state = 'DRAFT';
107 return structuredClone(workspace);
108 },
109 async setCommitMessage({ ownerId, workspaceId, message, digest }) {
110 calls.push(['setCommitMessage', ownerId, workspaceId, message, digest]);
111 workspace.commitMessage = message;
112 workspace.commitMessageDigest = digest;
113 workspace.currentIntentId = null;
114 workspace.state = 'DRAFT';
115 return structuredClone(workspace);
116 },
117 async sealIntent({ ownerId, workspaceId, intent }) {
118 calls.push(['sealIntent', ownerId, workspaceId, structuredClone(intent)]);
119 if (workspace.currentIntentId) {
120 const existing = intents.get(workspace.currentIntentId);
121 if (existing?.intentDigest === intent.intentDigest)
122 return structuredClone(existing);
123 }
124 intentCounter += 1;
125 const id = `I${String(intentCounter).padStart(7, '0')}`;
126 const sealed = {
127 ...structuredClone(intent),
128 id,
129 workspaceId,
130 state: 'READY'
131 };
132 intents.set(id, sealed);
133 workspace.currentIntentId = id;
134 workspace.state = 'READY';
135 return structuredClone(sealed);
136 }
137 };
138 }
139
140 function makePlugin() {
141 const github = makeGitHub();
142 const workspaces = makeWorkspaces();
143 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
144 return { github, workspaces, plugin };
145 }
146
147 test('PluginRouter dispatchMessage applies the same policy boundary without auditing source text', async () => {
148 const auditEvents = [];
149 const plugin = {
150 manifest: {
151 id: 'demo',
152 name: 'Demo',
153 version: 1,
154 commands: [],
155 actions: { 'demo.message': { risk: 'READ' } }
156 },
157 resolveMessage(payload) {
158 if (!payload?.pending) return null;
159 return {
160 actionId: 'demo.message',
161 execute: async () => ({ text: 'accepted' })
162 };
163 }
164 };
165 const router = new PluginRouter({
166 registry: new PluginRegistry([plugin]),
167 policy: new ActionPolicy(),
168 audit: new AuditLogger({ sink: (event) => auditEvents.push(event) })
169 });
170 const result = await router.dispatchMessage(
171 { pending: { mode: 'draft' }, text: 'TOP SECRET SOURCE' },
172 { isOwner: true, ownerId: OWNER }
173 );
174 assert.equal(result.text, 'accepted');
175 assert.equal(
176 JSON.stringify(auditEvents).includes('TOP SECRET SOURCE'),
177 false
178 );
179 });
180
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(`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, /120/);
190 assert.deepEqual(github.calls, []);
191
192 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
193 assert.deepEqual(pending, {
194 workspaceId: WORKSPACE_ID,
195 mode: 'commit_message'
196 });
197 const route = plugin.resolveMessage(
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);
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 }),
214 text: 'late commit message'
215 },
216 { ownerId: OWNER }
217 );
218 assert.equal(late, null);
219 assert.equal(
220 workspaces.workspace.commitMessage,
221 'chore: update ignore rules'
222 );
223 assert.deepEqual(github.calls, []);
224 });
225
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
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(
234 { pending, text: 'x'.repeat(121) },
235 { ownerId: OWNER }
236 );
237 const view = await route.execute();
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
244 test('commit message normalizes and Telegram diff shows counts without source or GitHub mutation', async () => {
245 const { github, workspaces, plugin } = makePlugin();
246 await plugin
247 .resolveCallback(`wmsg:${WORKSPACE_ID}`, { ownerId: OWNER })
248 .execute();
249 const pending = await workspaces.getPendingInput({ ownerId: OWNER });
250 await plugin
251 .resolveMessage(
252 { pending, text: ' chore: update workspace ' },
253 { ownerId: OWNER }
254 )
255 .execute();
256 assert.equal(workspaces.workspace.commitMessage, 'chore: update workspace');
257
258 workspaces.workspace.draftText = 'after <script>\n';
259 workspaces.workspace.draftDigest = await digestText(
260 workspaces.workspace.draftText
261 );
262 const diffRoute = plugin.resolveCallback(`wdiff:${WORKSPACE_ID}`, {
263 ownerId: OWNER
264 });
265 assert.equal(diffRoute.actionId, 'github.workspace.diff');
266 const diffView = await diffRoute.execute();
267 assert.match(diffView.text, /\+1/);
268 assert.match(diffView.text, /-1/);
269 assert.doesNotMatch(diffView.text, /<script>/);
270 assert.doesNotMatch(diffView.text, /&lt;script&gt;|after|before/);
271 assert.ok(
272 diffView.reply_markup.inline_keyboard
273 .flat()
274 .some((button) => button.web_app)
275 );
276 assert.deepEqual(github.calls, []);
277 });
278
279 test('READY rejects no-change, reuses identical material and mints a new intent after material change', async () => {
280 const { github, workspaces, plugin } = makePlugin();
281 workspaces.workspace.commitMessage = 'edit app';
282 workspaces.workspace.commitMessageDigest = await digestText('edit app');
283
284 const noChange = plugin.resolveCallback(`wready:${WORKSPACE_ID}`, {
285 ownerId: OWNER
286 });
287 await assert.rejects(() => noChange.execute(), /change|تغییر|بدون/i);
288
289 workspaces.workspace.draftText = 'after\n';
290 workspaces.workspace.draftDigest = await digestText('after\n');
291 const ready1 = await plugin
292 .resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER })
293 .execute();
294 const commit1 = flatten(ready1).find((button) =>
295 button.callback_data?.startsWith('wscommit:')
296 )?.callback_data;
297 assert.match(commit1, /^wscommit:123:[A-Za-z0-9_-]{8}$/);
298 assert.ok(new TextEncoder().encode(commit1).byteLength <= 64);
299
300 const ready2 = await plugin
301 .resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER })
302 .execute();
303 const commit2 = flatten(ready2).find((button) =>
304 button.callback_data?.startsWith('wscommit:')
305 )?.callback_data;
306 assert.equal(commit2, commit1);
307
308 workspaces.workspace.draftText = 'after again\n';
309 workspaces.workspace.draftDigest = await digestText('after again\n');
310 workspaces.workspace.currentIntentId = null;
311 workspaces.workspace.state = 'DRAFT';
312 const ready3 = await plugin
313 .resolveCallback(`wready:${WORKSPACE_ID}`, { ownerId: OWNER })
314 .execute();
315 const commit3 = flatten(ready3).find((button) =>
316 button.callback_data?.startsWith('wscommit:')
317 )?.callback_data;
318 assert.notEqual(commit3, commit1);
319 assert.deepEqual(github.calls, []);
320 });
321
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 = {
326 async sendMessage(chatId, text, replyMarkup) {
327 calls.push(['sendMessage', chatId, text, replyMarkup]);
328 return { ok: true };
329 }
330 };
331 bot.workspaceStore = {
332 isConfigured: () => true,
333 async getPendingInput({ ownerId }) {
334 calls.push(['getPendingInput', ownerId]);
335 return { workspaceId: WORKSPACE_ID, mode: 'commit_message' };
336 }
337 };
338 bot.router = {
339 async dispatchMessage(payload, context) {
340 calls.push([
341 'dispatchMessage',
342 structuredClone(payload),
343 structuredClone(context)
344 ]);
345 return {
346 text: 'workspace accepted',
347 reply_markup: { inline_keyboard: [] }
348 };
349 }
350 };
351
352 await bot.handleMessage({
353 chat: { id: 7 },
354 from: { id: 42 },
355 text: '/status'
356 });
357 assert.equal(
358 calls.some((call) => call[0] === 'getPendingInput'),
359 false
360 );
361 assert.equal(
362 calls.some((call) => call[0] === 'dispatchMessage'),
363 false
364 );
365
366 calls.length = 0;
367 await bot.handleMessage({
368 chat: { id: 7 },
369 from: { id: 42 },
370 text: ' chore: update ignore rules \n'
371 });
372 const dispatch = calls.find((call) => call[0] === 'dispatchMessage');
373 assert.equal(dispatch[1].text, ' chore: update ignore rules \n');
374 assert.deepEqual(dispatch[2], { isOwner: true, ownerId: OWNER });
375 });