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 434 lines 13.2 KB
Raw
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { GitHubService } from '../src/github.js';
4 import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
5
6 function makeMenu() {
7 const calls = [];
8 return {
9 calls,
10 async getReposListView() {
11 calls.push('/repos');
12 return { text: 'repos', reply_markup: { inline_keyboard: [] } };
13 },
14 async renderByCallback(data) {
15 calls.push(data);
16 return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
17 }
18 };
19 }
20
21 function makeWorkspaces() {
22 const calls = [];
23 const refs = new Map();
24 const workspaces = new Map();
25 let refCounter = 0;
26 return {
27 calls,
28 refs,
29 workspaces,
30 async createNavigationRefs({ ownerId, refs: input }) {
31 calls.push(['createNavigationRefs', ownerId, structuredClone(input)]);
32 return input.map((ref) => {
33 refCounter += 1;
34 const refId = `R${String(refCounter).padStart(9, '0')}`;
35 refs.set(`${ownerId}:${refId}`, structuredClone(ref));
36 return { refId };
37 });
38 },
39 async resolveNavigationRef({ ownerId, refId }) {
40 calls.push(['resolveNavigationRef', ownerId, refId]);
41 return refs.get(`${ownerId}:${refId}`) || null;
42 },
43 async createWorkspace(payload) {
44 calls.push([
45 'createWorkspace',
46 payload.ownerId,
47 payload.path,
48 payload.baseHeadSha
49 ]);
50 const workspace = {
51 id: 'W000000001',
52 state: 'DRAFT',
53 draftText: payload.originalText,
54 ...payload
55 };
56 workspaces.set(`${payload.ownerId}:${workspace.id}`, workspace);
57 return workspace;
58 },
59 async getWorkspace({ ownerId, workspaceId }) {
60 calls.push(['getWorkspace', ownerId, workspaceId]);
61 return workspaces.get(`${ownerId}:${workspaceId}`) || null;
62 }
63 };
64 }
65
66 function makeGitHub({
67 archived = false,
68 fileText = 'export const ok = true;\n',
69 filePath = 'src/deep/really-long-file-name-for-mobile-editor.js'
70 } = {}) {
71 const calls = [];
72 const headSha = 'a'.repeat(40);
73 const treeSha = 'b'.repeat(40);
74 const blobSha = 'c'.repeat(40);
75 return {
76 calls,
77 headSha,
78 treeSha,
79 blobSha,
80 async getRepository(repoId) {
81 calls.push(['getRepository', Number(repoId)]);
82 return {
83 id: String(repoId),
84 name: 'demo',
85 fullName: 'davood/demo',
86 defaultBranch: 'main',
87 archived
88 };
89 },
90 async listFiles(repoId, path = '', options = {}) {
91 calls.push(['listFiles', Number(repoId), path, options.ref || null]);
92 if (path === 'src/deep') {
93 return [
94 {
95 name: 'nested.js',
96 path: 'src/deep/nested.js',
97 type: 'file',
98 size: 20,
99 sha: 'd'.repeat(40)
100 }
101 ];
102 }
103 return [
104 {
105 name: 'deep',
106 path: 'src/deep',
107 type: 'dir',
108 size: 0,
109 sha: 'e'.repeat(40)
110 },
111 {
112 name: 'really-long-file-name-for-mobile-editor.js',
113 path: filePath,
114 type: 'file',
115 size: new TextEncoder().encode(fileText).byteLength,
116 sha: blobSha
117 }
118 ];
119 },
120 async getBranchSnapshot(repoId, branch) {
121 calls.push(['getBranchSnapshot', Number(repoId), branch]);
122 return { branch, headSha, treeSha };
123 },
124 async getFileAtRef(repoId, path, ref) {
125 calls.push(['getFileAtRef', Number(repoId), path, ref]);
126 return {
127 path,
128 sha: path === filePath ? blobSha : 'd'.repeat(40),
129 size: new TextEncoder().encode(fileText).byteLength,
130 encoding: 'utf-8',
131 content: fileText
132 };
133 }
134 };
135 }
136
137 function flatten(view) {
138 return view.reply_markup?.inline_keyboard?.flat() || [];
139 }
140
141 test('exact files callback resolves side-effect-free then renders path-safe short navigation refs', async () => {
142 const github = makeGitHub();
143 const workspaces = makeWorkspaces();
144 const menu = makeMenu();
145 const plugin = createGitHubPlugin({ github, menu, workspaces });
146
147 const route = plugin.resolveCallback('files:123', { ownerId: '42' });
148 assert.equal(route.actionId, 'github.files.list');
149 assert.deepEqual(github.calls, []);
150 assert.deepEqual(workspaces.calls, []);
151
152 const view = await route.execute();
153 const buttons = flatten(view).filter((button) =>
154 button.callback_data?.startsWith('wnav:')
155 );
156 assert.equal(buttons.length, 2);
157 for (const button of buttons) {
158 assert.match(button.callback_data, /^wnav:[A-Za-z0-9_-]{10}$/);
159 assert.ok(new TextEncoder().encode(button.callback_data).byteLength <= 64);
160 assert.doesNotMatch(button.callback_data, /src|really-long|\.js/);
161 }
162 assert.equal(menu.calls.length, 0);
163 });
164
165 test('nested directory resolves through short ref and preserves the full server-side path', async () => {
166 const github = makeGitHub();
167 const workspaces = makeWorkspaces();
168 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
169 const root = await plugin
170 .resolveCallback('files:123', { ownerId: '42' })
171 .execute();
172 const dirCallback = flatten(root).find((button) =>
173 button.text?.includes('deep')
174 )?.callback_data;
175 assert.match(dirCallback, /^wnav:/);
176
177 github.calls.length = 0;
178 workspaces.calls.length = 0;
179 const route = plugin.resolveCallback(dirCallback, { ownerId: '42' });
180 assert.equal(route.actionId, 'github.workspace.navigate');
181 assert.deepEqual(github.calls, []);
182 assert.deepEqual(workspaces.calls, []);
183 const nested = await route.execute();
184 assert.ok(
185 flatten(nested).some((button) => /^wnav:/.test(button.callback_data || ''))
186 );
187 assert.ok(
188 github.calls.some(
189 (call) => call[0] === 'listFiles' && call[2] === 'src/deep'
190 )
191 );
192 });
193
194 test('eligible file preview including README shows Edit while risky or truly oversized content stays readable with explicit disabled reason', async () => {
195 for (const fixture of [
196 { path: 'src/app.js', text: 'console.log(1);\n', editable: true },
197 {
198 path: 'README.md',
199 text: `# Nexa Dev Bot\n\n${'x'.repeat(8200)}`,
200 editable: true
201 },
202 {
203 path: '.env.production',
204 text: 'NOT_A_REAL_SECRET=value\n',
205 editable: false,
206 reason: /sensitive/i
207 },
208 {
209 path: 'large.txt',
210 text: 'x'.repeat(20001),
211 editable: false,
212 reason: /20,000|20000/
213 },
214 {
215 path: 'asset.txt',
216 text: 'version https://git-lfs.github.com/spec/v1\noid sha256:abc\nsize 9\n',
217 editable: false,
218 reason: /LFS/i
219 }
220 ]) {
221 const github = makeGitHub({
222 fileText: fixture.text,
223 filePath: fixture.path
224 });
225 const workspaces = makeWorkspaces();
226 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
227 const root = await plugin
228 .resolveCallback('files:123', { ownerId: '42' })
229 .execute();
230 const fileCallback = flatten(root).find(
231 (button) =>
232 button.callback_data?.startsWith('wnav:') &&
233 !button.text?.includes('deep')
234 )?.callback_data;
235 const view = await plugin
236 .resolveCallback(fileCallback, { ownerId: '42' })
237 .execute();
238 assert.match(view.text, /پیش.?نمایش|فایل/i);
239 const edit = flatten(view).find((button) =>
240 button.callback_data?.startsWith('wedit:')
241 );
242 if (fixture.editable) {
243 assert.ok(edit, fixture.path);
244 } else {
245 assert.equal(edit, undefined, fixture.path);
246 assert.match(view.text, fixture.reason);
247 }
248 }
249 });
250
251 test('wedit pins default-branch snapshot and exact file before creating a durable draft', async () => {
252 const github = makeGitHub({ filePath: 'src/app.js', fileText: 'before\n' });
253 const workspaces = makeWorkspaces();
254 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
255 const root = await plugin
256 .resolveCallback('files:123', { ownerId: '42' })
257 .execute();
258 const fileCallback = flatten(root).find(
259 (button) =>
260 button.callback_data?.startsWith('wnav:') &&
261 !button.text?.includes('deep')
262 )?.callback_data;
263 const fileView = await plugin
264 .resolveCallback(fileCallback, { ownerId: '42' })
265 .execute();
266 const editCallback = flatten(fileView).find((button) =>
267 button.callback_data?.startsWith('wedit:')
268 )?.callback_data;
269
270 github.calls.length = 0;
271 workspaces.calls.length = 0;
272 const route = plugin.resolveCallback(editCallback, { ownerId: '42' });
273 assert.equal(route.actionId, 'github.workspace.create');
274 assert.deepEqual(github.calls, []);
275 assert.deepEqual(workspaces.calls, []);
276 const draftView = await route.execute();
277
278 const snapshotIndex = github.calls.findIndex(
279 (call) => call[0] === 'getBranchSnapshot'
280 );
281 const fileIndex = github.calls.findIndex(
282 (call) => call[0] === 'getFileAtRef'
283 );
284 const createCall = workspaces.calls.find(
285 (call) => call[0] === 'createWorkspace'
286 );
287 assert.ok(snapshotIndex >= 0 && fileIndex > snapshotIndex);
288 assert.deepEqual(github.calls[fileIndex].slice(2), [
289 'src/app.js',
290 github.headSha
291 ]);
292 assert.deepEqual(createCall, [
293 'createWorkspace',
294 '42',
295 'src/app.js',
296 github.headSha
297 ]);
298 assert.match(draftView.text, /Draft|پیش.?نویس/i);
299 assert.ok(
300 flatten(draftView).some(
301 (button) => button.callback_data === 'ws:W000000001'
302 )
303 );
304 });
305
306 test('archived repository cannot create an editable workspace', async () => {
307 const github = makeGitHub({ archived: true, filePath: 'src/app.js' });
308 const workspaces = makeWorkspaces();
309 const plugin = createGitHubPlugin({ github, menu: makeMenu(), workspaces });
310 const root = await plugin
311 .resolveCallback('files:123', { ownerId: '42' })
312 .execute();
313 const fileCallback = flatten(root).find(
314 (button) =>
315 button.callback_data?.startsWith('wnav:') &&
316 !button.text?.includes('deep')
317 )?.callback_data;
318 const fileView = await plugin
319 .resolveCallback(fileCallback, { ownerId: '42' })
320 .execute();
321 const editCallback = flatten(fileView).find((button) =>
322 button.callback_data?.startsWith('wedit:')
323 )?.callback_data;
324 assert.equal(editCallback, undefined);
325 assert.match(fileView.text, /archiv|آرشیو/i);
326 assert.equal(
327 workspaces.calls.some((call) => call[0] === 'createWorkspace'),
328 false
329 );
330 });
331
332 test('legacy tree blob and path-bearing files callbacks remain on MenuManager path', async () => {
333 const github = makeGitHub();
334 const workspaces = makeWorkspaces();
335 const menu = makeMenu();
336 const plugin = createGitHubPlugin({ github, menu, workspaces });
337
338 for (const callback of [
339 `tree:123:${'a'.repeat(40)}`,
340 `blob:123:${'b'.repeat(40)}`,
341 'files:123:src/deep'
342 ]) {
343 const route = plugin.resolveCallback(callback, { ownerId: '42' });
344 const view = await route.execute();
345 assert.equal(view.text, `legacy:${callback}`);
346 }
347 });
348
349 test('workspace READ actions are declared and all short callback families fit Telegram limit', () => {
350 const plugin = createGitHubPlugin({
351 github: makeGitHub(),
352 menu: makeMenu(),
353 workspaces: makeWorkspaces()
354 });
355 for (const actionId of [
356 'github.workspace.navigate',
357 'github.workspace.create',
358 'github.workspace.view',
359 'github.workspace.input.prepare',
360 'github.workspace.diff',
361 'github.workspace.ready',
362 'github.workspace.cancel'
363 ]) {
364 assert.equal(plugin.manifest.actions[actionId]?.risk, 'READ', actionId);
365 }
366 for (const callback of [
367 'wnav:R123456789',
368 'wedit:R123456789',
369 'ws:W123456789',
370 'wtext:W123456789',
371 'wmsg:W123456789',
372 'wdiff:W123456789',
373 'wready:W123456789',
374 'wcancel:W123456789'
375 ]) {
376 assert.ok(new TextEncoder().encode(callback).byteLength <= 64, callback);
377 }
378 });
379
380 test('GitHubService reads pinned branch snapshot and UTF-8 file at full SHA', async () => {
381 const originalFetch = globalThis.fetch;
382 const seen = [];
383 const headSha = 'a'.repeat(40);
384 const treeSha = 'b'.repeat(40);
385 const blobSha = 'c'.repeat(40);
386 globalThis.fetch = async (url, options = {}) => {
387 seen.push([String(url), options.method || 'GET']);
388 const value = String(url);
389 if (value.endsWith('/repositories/123'))
390 return Response.json({
391 id: 123,
392 name: 'demo',
393 full_name: 'davood/demo',
394 default_branch: 'main'
395 });
396 if (value.endsWith('/repos/davood/demo/git/ref/heads/main'))
397 return Response.json({ object: { sha: headSha } });
398 if (value.endsWith(`/repos/davood/demo/git/commits/${headSha}`))
399 return Response.json({ sha: headSha, tree: { sha: treeSha } });
400 if (
401 value.endsWith(`/repos/davood/demo/contents/src/app.js?ref=${headSha}`)
402 ) {
403 return Response.json({
404 type: 'file',
405 path: 'src/app.js',
406 sha: blobSha,
407 size: 6,
408 encoding: 'base64',
409 content: btoa('hello\n')
410 });
411 }
412 return new Response('unexpected', { status: 500 });
413 };
414 try {
415 const github = new GitHubService('token', 'davood');
416 assert.deepEqual(await github.getBranchSnapshot(123, 'main'), {
417 branch: 'main',
418 headSha,
419 treeSha
420 });
421 assert.deepEqual(await github.getFileAtRef(123, 'src/app.js', headSha), {
422 path: 'src/app.js',
423 sha: blobSha,
424 size: 6,
425 encoding: 'utf-8',
426 content: 'hello\n'
427 });
428 assert.ok(
429 seen.some(([url]) => url.endsWith(`/contents/src/app.js?ref=${headSha}`))
430 );
431 } finally {
432 globalThis.fetch = originalFetch;
433 }
434 });