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 527 lines 15.7 KB
Raw
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { ApprovalService } from '../src/core/approval.js';
4 import { PluginRegistry } from '../src/core/plugin-registry.js';
5 import { ActionPolicy } from '../src/core/action-policy.js';
6 import { AuditLogger } from '../src/core/audit.js';
7 import { PluginRouter } from '../src/core/router.js';
8 import { createGitHubPlugin } from '../src/plugins/github/plugin.js';
9 import * as workspaceModule from '../src/plugins/github/workspace.js';
10
11 const OWNER = '42';
12 const REPO_ID = 123;
13 const WORKSPACE_ID = 'W123456789';
14 const INTENT_ID = 'Ab12_cdE';
15 const BASE_HEAD = 'a'.repeat(40);
16 const BASE_TREE = 'b'.repeat(40);
17 const SOURCE_BLOB = 'c'.repeat(40);
18 const CONTENT_BLOB = 'd'.repeat(40);
19 const NEW_TREE = 'e'.repeat(40);
20 const COMMIT_SHA = 'f'.repeat(40);
21 const TARGET_BRANCH = `nexa/edit-${WORKSPACE_ID}`;
22 const TIMESTAMP = '2026-10-03T09:00:00.000Z';
23 const CONTENT_DIGEST = '1'.repeat(64);
24 const MESSAGE_DIGEST = '2'.repeat(64);
25
26 function replayStore() {
27 const seen = new Set();
28 return {
29 async consume({ ownerId, nonce }) {
30 const key = `${ownerId}:${nonce}`;
31 if (seen.has(key)) return false;
32 seen.add(key);
33 return true;
34 }
35 };
36 }
37
38 function makeIntent(overrides = {}) {
39 return {
40 id: INTENT_ID,
41 workspaceId: WORKSPACE_ID,
42 repoId: REPO_ID,
43 baseBranch: 'main',
44 baseHeadSha: BASE_HEAD,
45 baseTreeSha: BASE_TREE,
46 path: 'src/app.js',
47 sourceBlobSha: SOURCE_BLOB,
48 contentDigest: CONTENT_DIGEST,
49 commitMessageDigest: MESSAGE_DIGEST,
50 targetBranch: TARGET_BRANCH,
51 commitTimestamp: TIMESTAMP,
52 intentDigest: '3'.repeat(64),
53 state: 'READY',
54 candidateCommitSha: null,
55 commitSha: null,
56 branch: null,
57 ...overrides
58 };
59 }
60
61 function makeWorkspace(overrides = {}) {
62 return {
63 id: WORKSPACE_ID,
64 repoId: REPO_ID,
65 currentIntentId: INTENT_ID,
66 state: 'READY',
67 baseBranch: 'main',
68 baseHeadSha: BASE_HEAD,
69 baseTreeSha: BASE_TREE,
70 path: 'src/app.js',
71 blobSha: SOURCE_BLOB,
72 originalText: 'before\n',
73 draftText: 'after\n',
74 draftDigest: CONTENT_DIGEST,
75 commitMessage: 'edit app',
76 commitMessageDigest: MESSAGE_DIGEST,
77 ...overrides
78 };
79 }
80
81 function makeWorkspaces({
82 intent = makeIntent(),
83 workspace = makeWorkspace(),
84 disposition = 'start'
85 } = {}) {
86 const calls = [];
87 let mutableIntent = structuredClone(intent);
88 return {
89 calls,
90 async getIntent({ ownerId, intentId }) {
91 calls.push(['getIntent', ownerId, intentId]);
92 return ownerId === OWNER && intentId === mutableIntent.id
93 ? structuredClone(mutableIntent)
94 : null;
95 },
96 async getWorkspace({ ownerId, workspaceId }) {
97 calls.push(['getWorkspace', ownerId, workspaceId]);
98 return ownerId === OWNER && workspaceId === workspace.id
99 ? structuredClone(workspace)
100 : null;
101 },
102 async beginCommit({ ownerId, intentId }) {
103 calls.push(['beginCommit', ownerId, intentId]);
104 if (mutableIntent.state === 'COMMITTED')
105 return {
106 disposition: 'committed',
107 intent: structuredClone(mutableIntent)
108 };
109 if (mutableIntent.state === 'COMMITTING')
110 return {
111 disposition: 'resume',
112 intent: structuredClone(mutableIntent)
113 };
114 mutableIntent = { ...mutableIntent, state: 'COMMITTING' };
115 return { disposition, intent: structuredClone(mutableIntent) };
116 },
117 async setCandidateCommit({ ownerId, intentId, commitSha }) {
118 calls.push(['setCandidateCommit', ownerId, intentId, commitSha]);
119 mutableIntent = {
120 ...mutableIntent,
121 candidateCommitSha: commitSha,
122 state: 'COMMITTING'
123 };
124 return structuredClone(mutableIntent);
125 },
126 async completeCommit({ ownerId, intentId, commitSha, branch }) {
127 calls.push(['completeCommit', ownerId, intentId, commitSha, branch]);
128 mutableIntent = {
129 ...mutableIntent,
130 commitSha,
131 branch,
132 state: 'COMMITTED'
133 };
134 return structuredClone(mutableIntent);
135 },
136 async markStale({ ownerId, intentId, reason }) {
137 calls.push(['markStale', ownerId, intentId, reason]);
138 mutableIntent = { ...mutableIntent, state: 'STALE', staleReason: reason };
139 return structuredClone(mutableIntent);
140 }
141 };
142 }
143
144 function makeGitHub({
145 baseHead = BASE_HEAD,
146 existingRef = null,
147 createRefError = null
148 } = {}) {
149 const calls = [];
150 return {
151 calls,
152 async getBranchSnapshot(repoId, branch) {
153 calls.push(['getBranchSnapshot', repoId, branch]);
154 return { branch, headSha: baseHead, treeSha: BASE_TREE };
155 },
156 async getGitRef(repoId, branch, options) {
157 calls.push(['getGitRef', repoId, branch, options]);
158 return existingRef ? structuredClone(existingRef) : null;
159 },
160 async createGitBlob(repoId, text) {
161 calls.push(['createGitBlob', repoId, text]);
162 return { sha: CONTENT_BLOB };
163 },
164 async createGitTree(repoId, input) {
165 calls.push(['createGitTree', repoId, structuredClone(input)]);
166 return { sha: NEW_TREE };
167 },
168 async createGitCommit(repoId, input) {
169 calls.push(['createGitCommit', repoId, structuredClone(input)]);
170 return { sha: COMMIT_SHA };
171 },
172 async createGitBranchRef(repoId, input) {
173 calls.push(['createGitBranchRef', repoId, structuredClone(input)]);
174 if (createRefError) throw createRefError;
175 return { ref: `refs/heads/${input.branch}`, sha: input.sha };
176 }
177 };
178 }
179
180 function minimalMenu() {
181 return {
182 async getReposListView() {
183 return { text: 'repos', reply_markup: { inline_keyboard: [] } };
184 },
185 async renderByCallback(data) {
186 return { text: `legacy:${data}`, reply_markup: { inline_keyboard: [] } };
187 }
188 };
189 }
190
191 test('workspace approval uses compact <=56 byte token and binds owner action risk repo and exact 8-char intent', async () => {
192 let now = 1_700_000_000_000;
193 const approvals = new ApprovalService({
194 secret: 'workspace-secret',
195 now: () => now,
196 ttlMs: 120_000,
197 replayStore: replayStore()
198 });
199 const token = await approvals.issue({
200 pluginId: 'github',
201 actionId: 'github.workspace.commit_branch',
202 risk: 'WRITE',
203 ownerId: OWNER,
204 input: { repoId: REPO_ID, intentId: INTENT_ID }
205 });
206 assert.ok(new TextEncoder().encode(token).byteLength <= 56);
207 assert.ok(new TextEncoder().encode(`approve:${token}`).byteLength <= 64);
208 const payload = await approvals.consume(token, {
209 ownerId: OWNER,
210 pluginId: 'github',
211 actionId: 'github.workspace.commit_branch',
212 risk: 'WRITE'
213 });
214 assert.deepEqual(payload.input, { repoId: REPO_ID, intentId: INTENT_ID });
215 await assert.rejects(
216 () => approvals.consume(token, { ownerId: OWNER }),
217 /already used/i
218 );
219
220 const second = await approvals.issue({
221 pluginId: 'github',
222 actionId: 'github.workspace.commit_branch',
223 risk: 'WRITE',
224 ownerId: OWNER,
225 input: { repoId: REPO_ID, intentId: INTENT_ID }
226 });
227 now += 121_000;
228 await assert.rejects(
229 () => approvals.verify(second, { ownerId: OWNER }),
230 /expired/i
231 );
232 await assert.rejects(
233 () =>
234 approvals.issue({
235 pluginId: 'github',
236 actionId: 'github.workspace.commit_branch',
237 risk: 'WRITE',
238 ownerId: OWNER,
239 input: { repoId: REPO_ID, intentId: 'too-short' }
240 }),
241 /intent/i
242 );
243 });
244
245 test('wscommit resolves to WRITE approval metadata before execution and performs zero GitHub or workspace calls pre-approval', async () => {
246 const github = makeGitHub();
247 const workspaces = makeWorkspaces();
248 const plugin = createGitHubPlugin({
249 github,
250 menu: minimalMenu(),
251 workspaces
252 });
253 const router = new PluginRouter({
254 registry: new PluginRegistry([plugin]),
255 policy: new ActionPolicy(),
256 audit: new AuditLogger({ sink: () => {} })
257 });
258 const result = await router.dispatchCallback(
259 `wscommit:${REPO_ID}:${INTENT_ID}`,
260 { isOwner: true, ownerId: OWNER }
261 );
262 assert.equal(result.requiresApproval, true);
263 assert.equal(result.actionId, 'github.workspace.commit_branch');
264 assert.deepEqual(result.approval.input, {
265 repoId: REPO_ID,
266 intentId: INTENT_ID
267 });
268 assert.equal(result.approval.cancelCallback, `repo:${REPO_ID}`);
269 assert.deepEqual(github.calls, []);
270 assert.deepEqual(workspaces.calls, []);
271 });
272
273 test('approved orchestration fails closed on changed workspace material or stale base before any Git object creation', async () => {
274 assert.equal(typeof workspaceModule.commitWorkspaceIntent, 'function');
275
276 const changedWorkspaces = makeWorkspaces({
277 workspace: makeWorkspace({
278 currentIntentId: null,
279 draftDigest: '9'.repeat(64)
280 })
281 });
282 const changedGitHub = makeGitHub();
283 await assert.rejects(
284 () =>
285 workspaceModule.commitWorkspaceIntent({
286 github: changedGitHub,
287 workspaces: changedWorkspaces,
288 ownerId: OWNER,
289 repoId: REPO_ID,
290 intentId: INTENT_ID
291 }),
292 /intent|material|changed|stale/i
293 );
294 assert.equal(
295 changedGitHub.calls.some((call) => call[0].startsWith('createGit')),
296 false
297 );
298
299 const staleWorkspaces = makeWorkspaces();
300 const staleGitHub = makeGitHub({ baseHead: '9'.repeat(40) });
301 await assert.rejects(
302 () =>
303 workspaceModule.commitWorkspaceIntent({
304 github: staleGitHub,
305 workspaces: staleWorkspaces,
306 ownerId: OWNER,
307 repoId: REPO_ID,
308 intentId: INTENT_ID
309 }),
310 /base|stale|changed/i
311 );
312 assert.equal(
313 staleGitHub.calls.some((call) => call[0].startsWith('createGit')),
314 false
315 );
316 assert.ok(staleWorkspaces.calls.some((call) => call[0] === 'markStale'));
317 });
318
319 test('approved orchestration rejects an unexpected existing target branch without creating Git objects', async () => {
320 const workspaces = makeWorkspaces();
321 const github = makeGitHub({
322 existingRef: { branch: TARGET_BRANCH, sha: '8'.repeat(40) }
323 });
324 await assert.rejects(
325 () =>
326 workspaceModule.commitWorkspaceIntent({
327 github,
328 workspaces,
329 ownerId: OWNER,
330 repoId: REPO_ID,
331 intentId: INTENT_ID
332 }),
333 /already exists|target branch|unexpected/i
334 );
335 assert.equal(
336 github.calls.some((call) => call[0].startsWith('createGit')),
337 false
338 );
339 });
340
341 test('successful approved orchestration is blob -> tree -> commit -> durable candidate -> create ref -> durable COMMITTED', async () => {
342 const workspaces = makeWorkspaces();
343 const github = makeGitHub();
344 const result = await workspaceModule.commitWorkspaceIntent({
345 github,
346 workspaces,
347 ownerId: OWNER,
348 repoId: REPO_ID,
349 intentId: INTENT_ID
350 });
351 assert.deepEqual(result, {
352 commitSha: COMMIT_SHA,
353 branch: TARGET_BRANCH,
354 idempotent: false
355 });
356 assert.deepEqual(
357 github.calls.map((call) => call[0]),
358 [
359 'getBranchSnapshot',
360 'getGitRef',
361 'createGitBlob',
362 'createGitTree',
363 'createGitCommit',
364 'createGitBranchRef'
365 ]
366 );
367 const blobCall = github.calls.find((call) => call[0] === 'createGitBlob');
368 assert.equal(blobCall[2], 'after\n');
369 const treeCall = github.calls.find((call) => call[0] === 'createGitTree');
370 assert.deepEqual(treeCall[2], {
371 baseTreeSha: BASE_TREE,
372 entries: [
373 { path: 'src/app.js', mode: '100644', type: 'blob', sha: CONTENT_BLOB }
374 ]
375 });
376 const commitCall = github.calls.find((call) => call[0] === 'createGitCommit');
377 assert.deepEqual(commitCall[2], {
378 message: 'edit app',
379 treeSha: NEW_TREE,
380 parentSha: BASE_HEAD,
381 timestamp: TIMESTAMP
382 });
383 assert.ok(
384 workspaces.calls.some(
385 (call) => call[0] === 'setCandidateCommit' && call[3] === COMMIT_SHA
386 )
387 );
388 assert.ok(
389 workspaces.calls.some(
390 (call) =>
391 call[0] === 'completeCommit' &&
392 call[3] === COMMIT_SHA &&
393 call[4] === TARGET_BRANCH
394 )
395 );
396 });
397
398 test('COMMITTED and COMMITTING retries reconcile idempotently without a second provider write', async () => {
399 const committedIntent = makeIntent({
400 state: 'COMMITTED',
401 commitSha: COMMIT_SHA,
402 branch: TARGET_BRANCH
403 });
404 const committedWorkspaces = makeWorkspaces({ intent: committedIntent });
405 const committedGitHub = makeGitHub();
406 assert.deepEqual(
407 await workspaceModule.commitWorkspaceIntent({
408 github: committedGitHub,
409 workspaces: committedWorkspaces,
410 ownerId: OWNER,
411 repoId: REPO_ID,
412 intentId: INTENT_ID
413 }),
414 { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true }
415 );
416 assert.deepEqual(committedGitHub.calls, []);
417
418 const resumingIntent = makeIntent({
419 state: 'COMMITTING',
420 candidateCommitSha: COMMIT_SHA
421 });
422 const resumingWorkspaces = makeWorkspaces({ intent: resumingIntent });
423 const resumingGitHub = makeGitHub({
424 existingRef: { branch: TARGET_BRANCH, sha: COMMIT_SHA }
425 });
426 assert.deepEqual(
427 await workspaceModule.commitWorkspaceIntent({
428 github: resumingGitHub,
429 workspaces: resumingWorkspaces,
430 ownerId: OWNER,
431 repoId: REPO_ID,
432 intentId: INTENT_ID
433 }),
434 { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true }
435 );
436 assert.deepEqual(
437 resumingGitHub.calls.map((call) => call[0]),
438 ['getGitRef']
439 );
440 assert.ok(
441 resumingWorkspaces.calls.some((call) => call[0] === 'completeCommit')
442 );
443 });
444
445 test('ambiguous create-ref error reconciles only the exact candidate SHA and rejects different or missing refs', async () => {
446 const ambiguous = new Error(
447 'GitHub create branch ref failed: 422 Reference already exists'
448 );
449 const sequenceGitHub = makeGitHub({ createRefError: ambiguous });
450 let refReads = 0;
451 sequenceGitHub.getGitRef = async (repoId, branch, options) => {
452 sequenceGitHub.calls.push(['getGitRef', repoId, branch, options]);
453 refReads += 1;
454 return refReads === 1 ? null : { branch, sha: COMMIT_SHA };
455 };
456 const workspaces = makeWorkspaces();
457 assert.deepEqual(
458 await workspaceModule.commitWorkspaceIntent({
459 github: sequenceGitHub,
460 workspaces,
461 ownerId: OWNER,
462 repoId: REPO_ID,
463 intentId: INTENT_ID
464 }),
465 { commitSha: COMMIT_SHA, branch: TARGET_BRANCH, idempotent: true }
466 );
467
468 for (const ref of [null, { branch: TARGET_BRANCH, sha: '7'.repeat(40) }]) {
469 const github = makeGitHub({ createRefError: ambiguous });
470 let reads = 0;
471 github.getGitRef = async (repoId, branch, options) => {
472 github.calls.push(['getGitRef', repoId, branch, options]);
473 reads += 1;
474 return reads === 1 ? null : ref;
475 };
476 await assert.rejects(
477 () =>
478 workspaceModule.commitWorkspaceIntent({
479 github,
480 workspaces: makeWorkspaces(),
481 ownerId: OWNER,
482 repoId: REPO_ID,
483 intentId: INTENT_ID
484 }),
485 /422|reconcile|branch|candidate/i
486 );
487 }
488 });
489
490 test('router audit merges only allowlisted workspace metadata and never source draft text or signed token material', async () => {
491 const events = [];
492 const plugin = {
493 manifest: {
494 id: 'safe',
495 name: 'safe',
496 version: 1,
497 commands: [],
498 actions: { 'safe.write': { risk: 'WRITE' } }
499 },
500 resolveCallback() {
501 return {
502 actionId: 'safe.write',
503 audit: {
504 repoId: REPO_ID,
505 workspaceId: WORKSPACE_ID,
506 intentId: INTENT_ID,
507 path: 'src/app.js',
508 contentDigest: CONTENT_DIGEST,
509 commitSha: COMMIT_SHA,
510 draftText: 'DO NOT LOG THIS',
511 token: 'approve:DO_NOT_LOG'
512 },
513 execute: async () => ({ text: 'ok' })
514 };
515 }
516 };
517 const router = new PluginRouter({
518 registry: new PluginRegistry([plugin]),
519 policy: new ActionPolicy(),
520 audit: new AuditLogger({ sink: (event) => events.push(event) })
521 });
522 await router.dispatchCallback('x', { isOwner: true, approved: true });
523 const serialized = JSON.stringify(events);
524 assert.match(serialized, /src\/app\.js/);
525 assert.match(serialized, new RegExp(INTENT_ID));
526 assert.doesNotMatch(serialized, /DO NOT LOG THIS|DO_NOT_LOG|draftText|token/);
527 });