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 297 lines 7.97 KB
Raw
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4 import {
5 makeReplayNamespace,
6 withUpdateId
7 } from './helpers/replay-namespace.js';
8
9 const env = {
10 TELEGRAM_WEBHOOK_SECRET: 'right',
11 OWNER_TELEGRAM_ID: '123',
12 TELEGRAM_BOT_TOKEN: 'telegram-test-token',
13 GITHUB_TOKEN: 'github-test-token',
14 GITHUB_OWNER: 'davoodmehraban89',
15 APPROVAL_SIGNING_SECRET: 'approval-test-secret',
16 APPROVAL_REPLAY_GUARD: makeReplayNamespace()
17 };
18
19 function webhook(update) {
20 return new Request('https://example.test/telegram/webhook', {
21 method: 'POST',
22 headers: {
23 'content-type': 'application/json',
24 'X-Telegram-Bot-Api-Secret-Token': 'right'
25 },
26 body: JSON.stringify(withUpdateId(update))
27 });
28 }
29
30 function json(data, status = 200) {
31 return new Response(JSON.stringify(data), {
32 status,
33 headers: { 'content-type': 'application/json' }
34 });
35 }
36
37 function installMock() {
38 const telegramCalls = [];
39 const githubCalls = [];
40 const originalFetch = globalThis.fetch;
41
42 globalThis.fetch = async (url, options = {}) => {
43 const value = String(url);
44
45 if (value.startsWith('https://api.telegram.org/')) {
46 const method = value.split('/').at(-1);
47 const body = options.body ? JSON.parse(options.body) : {};
48 telegramCalls.push({ method, body });
49 return json({
50 ok: true,
51 result: { message_id: body.message_id || 700, ...body }
52 });
53 }
54
55 if (value === 'https://api.github.com/repositories/1001') {
56 githubCalls.push({ url: value, method: options.method || 'GET' });
57 return json({
58 id: 1001,
59 name: 'demo',
60 full_name: 'davoodmehraban89/demo',
61 private: true,
62 default_branch: 'main',
63 archived: false,
64 html_url: 'https://github.com/davoodmehraban89/demo'
65 });
66 }
67
68 if (
69 value ===
70 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs/55/rerun-failed-jobs'
71 ) {
72 githubCalls.push({ url: value, method: options.method || 'GET' });
73 return new Response('', { status: 201 });
74 }
75
76 throw new Error(`Unexpected URL: ${value}`);
77 };
78
79 return {
80 telegramCalls,
81 githubCalls,
82 restore() {
83 globalThis.fetch = originalFetch;
84 }
85 };
86 }
87
88 async function sendUpdate(update, runtime = env) {
89 const response = await worker.fetch(webhook(update), runtime);
90 assert.equal(response.status, 200);
91 return response.json();
92 }
93
94 test('WRITE callback renders owner-bound approval and performs no GitHub write before approval', async () => {
95 const mock = installMock();
96 try {
97 const menuMessage = { message_id: 700, chat: { id: 123 } };
98 const result = await sendUpdate({
99 callback_query: {
100 id: 'rerun-request',
101 from: { id: 123 },
102 data: 'rerun:1001:55',
103 message: menuMessage
104 }
105 });
106
107 assert.equal(result.ok, true);
108 assert.equal(result.approvalRequired, true);
109 assert.equal(
110 mock.githubCalls.length,
111 0,
112 'GitHub write must not execute before approval'
113 );
114
115 const edit = mock.telegramCalls.find(
116 (call) => call.method === 'editMessageText'
117 );
118 assert.ok(edit, 'approval request must edit the existing Telegram message');
119 assert.match(edit.body.text, /تأیید|اجرا/);
120
121 const approveButton = edit.body.reply_markup.inline_keyboard
122 .flat()
123 .find((button) =>
124 String(button.callback_data || '').startsWith('approve:')
125 );
126 assert.ok(approveButton, 'approval button must be present');
127 assert.ok(
128 new TextEncoder().encode(approveButton.callback_data).length <= 64
129 );
130 } finally {
131 mock.restore();
132 }
133 });
134
135 test('approve callback executes exactly once and replay is rejected', async () => {
136 const mock = installMock();
137 try {
138 const menuMessage = { message_id: 701, chat: { id: 123 } };
139
140 await sendUpdate({
141 callback_query: {
142 id: 'rerun-request',
143 from: { id: 123 },
144 data: 'rerun:1001:55',
145 message: menuMessage
146 }
147 });
148
149 const approvalEdit = mock.telegramCalls
150 .filter((call) => call.method === 'editMessageText')
151 .at(-1);
152 const approveButton = approvalEdit.body.reply_markup.inline_keyboard
153 .flat()
154 .find((button) =>
155 String(button.callback_data || '').startsWith('approve:')
156 );
157 assert.ok(approveButton);
158
159 const first = await sendUpdate({
160 callback_query: {
161 id: 'approve-once',
162 from: { id: 123 },
163 data: approveButton.callback_data,
164 message: menuMessage
165 }
166 });
167 assert.equal(first.ok, true);
168
169 const writesAfterFirst = mock.githubCalls.filter(
170 (call) => call.method === 'POST'
171 );
172 assert.equal(writesAfterFirst.length, 1);
173 assert.match(writesAfterFirst[0].url, /rerun-failed-jobs$/);
174
175 const replay = await sendUpdate({
176 callback_query: {
177 id: 'approve-replay',
178 from: { id: 123 },
179 data: approveButton.callback_data,
180 message: menuMessage
181 }
182 });
183 assert.equal(replay.ok, false);
184 assert.equal(replay.processed_error, true);
185 assert.equal(replay.error, 'Telegram webhook processing failed');
186
187 const writesAfterReplay = mock.githubCalls.filter(
188 (call) => call.method === 'POST'
189 );
190 assert.equal(
191 writesAfterReplay.length,
192 1,
193 'replay must not perform a second GitHub write'
194 );
195 } finally {
196 mock.restore();
197 }
198 });
199
200 test('WRITE approval falls back to the configured Telegram webhook secret when no dedicated signing secret exists', async () => {
201 const mock = installMock();
202 try {
203 const result = await sendUpdate(
204 {
205 callback_query: {
206 id: 'fallback-signing-secret',
207 from: { id: 123 },
208 data: 'rerun:1001:55',
209 message: { message_id: 702, chat: { id: 123 } }
210 }
211 },
212 {
213 ...env,
214 APPROVAL_SIGNING_SECRET: ''
215 }
216 );
217
218 assert.equal(result.ok, true);
219 assert.equal(result.approvalRequired, true);
220 assert.equal(mock.githubCalls.length, 0);
221 const edit = mock.telegramCalls
222 .filter((call) => call.method === 'editMessageText')
223 .at(-1);
224 assert.ok(
225 edit.body.reply_markup.inline_keyboard
226 .flat()
227 .some((button) =>
228 String(button.callback_data || '').startsWith('approve:')
229 )
230 );
231 } finally {
232 mock.restore();
233 }
234 });
235
236 test('approval lifecycle is audited without logging signed callback tokens', async () => {
237 const mock = installMock();
238 const originalLog = console.log;
239 const logs = [];
240 console.log = (...args) => logs.push(args.map(String).join(' '));
241
242 try {
243 const menuMessage = { message_id: 703, chat: { id: 123 } };
244 await sendUpdate({
245 callback_query: {
246 id: 'audit-issue',
247 from: { id: 123 },
248 data: 'rerun:1001:55',
249 message: menuMessage
250 }
251 });
252
253 const approvalEdit = mock.telegramCalls
254 .filter((call) => call.method === 'editMessageText')
255 .at(-1);
256 const approveButton = approvalEdit.body.reply_markup.inline_keyboard
257 .flat()
258 .find((button) =>
259 String(button.callback_data || '').startsWith('approve:')
260 );
261 assert.ok(approveButton);
262
263 await sendUpdate({
264 callback_query: {
265 id: 'audit-verify',
266 from: { id: 123 },
267 data: approveButton.callback_data,
268 message: menuMessage
269 }
270 });
271
272 await sendUpdate({
273 callback_query: {
274 id: 'audit-reject',
275 from: { id: 123 },
276 data: approveButton.callback_data,
277 message: menuMessage
278 }
279 });
280
281 const auditText = logs
282 .filter((line) => line.startsWith('nexa_audit '))
283 .join('\n');
284 assert.match(auditText, /"event":"approval_issued"/);
285 assert.match(auditText, /"event":"approval_verified"/);
286 assert.match(auditText, /"event":"approval_rejected"/);
287 assert.doesNotMatch(
288 auditText,
289 new RegExp(
290 approveButton.callback_data.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
291 )
292 );
293 } finally {
294 console.log = originalLog;
295 mock.restore();
296 }
297 });