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 364 lines 10.9 KB
Raw
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import worker from '../src/index.js';
4 import { ApprovalReplayGuard } from '../src/durable/approval-replay-guard.js';
5 import { KillSwitchGuidedNexaDevBot } from '../src/kill-switch-bot.js';
6 import {
7 makeReplayNamespace,
8 makeReplayState
9 } from './helpers/replay-namespace.js';
10
11 let module = {};
12 try {
13 module = await import('../src/core/telegram-update-guard.js');
14 } catch {}
15 const consume = (input) => {
16 assert.equal(
17 typeof module.consumeTelegramUpdate,
18 'function',
19 'durable Telegram update claims must exist'
20 );
21 return module.consumeTelegramUpdate(input);
22 };
23 const identity = (token) => {
24 assert.equal(
25 typeof module.telegramBotIdentity,
26 'function',
27 'bot identity derivation must exist'
28 );
29 return module.telegramBotIdentity(token);
30 };
31 const DAY = 86_400_000;
32 const fixedTime = 1_800_000_000_000;
33 const ownerUpdate = (updateId = 7) => ({
34 update_id: updateId,
35 message: {
36 message_id: 4,
37 from: { id: 123 },
38 chat: { id: 123 },
39 text: '/help'
40 }
41 });
42 const webhook = (update) =>
43 new Request('https://example.test/telegram/webhook', {
44 method: 'POST',
45 headers: {
46 'content-type': 'application/json',
47 'X-Telegram-Bot-Api-Secret-Token': 'right'
48 },
49 body: typeof update === 'string' ? update : JSON.stringify(update)
50 });
51 const env = (namespace = makeReplayNamespace()) => ({
52 TELEGRAM_WEBHOOK_SECRET: 'right',
53 OWNER_TELEGRAM_ID: '123',
54 TELEGRAM_BOT_TOKEN: '12345:test-secret',
55 APPROVAL_REPLAY_GUARD: namespace
56 });
57
58 test('durable claims reject duplicates across object recreation without storing update content', async () => {
59 const namespace = makeReplayNamespace();
60 assert.equal(await consume({ namespace, botId: '12345', updateId: 0 }), true);
61 assert.equal(
62 await consume({ namespace, botId: '12345', updateId: 0 }),
63 false
64 );
65 const [key, state] = [...namespace.states][0];
66 assert.equal(key, 'telegram-webhook:v1:12345:0');
67 assert.equal(state.data.size, 1);
68 assert.ok(
69 [...state.data.values()].every((value) => typeof value === 'number')
70 );
71 });
72
73 test('claims expire exactly after 24 hours even when the cleanup alarm is delayed', async () => {
74 const previousNow = Date.now;
75 let current = fixedTime;
76 Date.now = () => current;
77 try {
78 const namespace = makeReplayNamespace();
79 const claim = () =>
80 consume({ namespace, botId: '12345', updateId: 9, now: Date.now });
81 assert.equal(await claim(), true);
82 const state = [...namespace.states.values()][0];
83 assert.equal(state.alarm, fixedTime + DAY);
84 current += DAY - 1;
85 assert.equal(await claim(), false);
86 assert.equal(
87 state.alarm,
88 fixedTime + DAY,
89 'a duplicate must not extend retention'
90 );
91 current += 1;
92 assert.equal(await claim(), true);
93 assert.equal(state.alarm, fixedTime + 2 * DAY);
94 await new ApprovalReplayGuard(state).alarm();
95 assert.equal(
96 await claim(),
97 false,
98 'a delayed old alarm must not delete a renewed claim'
99 );
100 current += DAY;
101 await new ApprovalReplayGuard(state).alarm();
102 assert.equal(state.data.size, 0);
103 assert.equal(state.alarm, null);
104 } finally {
105 Date.now = previousNow;
106 }
107 });
108
109 test('concurrent deliveries have one durable claim winner', async () => {
110 const namespace = makeReplayNamespace();
111 const results = await Promise.all(
112 Array.from({ length: 12 }, () =>
113 consume({ namespace, botId: '12345', updateId: 8 })
114 )
115 );
116 assert.equal(results.filter(Boolean).length, 1);
117 });
118
119 test('different bots and approval nonces do not share webhook claims', async () => {
120 const namespace = makeReplayNamespace();
121 for (const botId of ['12345', '67890'])
122 assert.equal(await consume({ namespace, botId, updateId: 7 }), true);
123 const approval = await namespace.get(namespace.idFromName('12345:7')).fetch(
124 new Request('https://approval-replay/consume', {
125 method: 'POST',
126 body: JSON.stringify({ expiresAt: Date.now() + 60_000 })
127 })
128 );
129 assert.equal(approval.status, 200);
130 });
131
132 test('invalid update ids cannot allocate durable objects', async () => {
133 assert.equal(typeof module.consumeTelegramUpdate, 'function');
134 let calls = 0;
135 const namespace = {
136 idFromName() {
137 calls++;
138 },
139 get() {
140 calls++;
141 }
142 };
143 for (const updateId of [
144 undefined,
145 null,
146 '1',
147 -1,
148 1.5,
149 NaN,
150 Infinity,
151 Number.MAX_SAFE_INTEGER + 1
152 ]) {
153 await assert.rejects(
154 async () => consume({ namespace, botId: '12345', updateId }),
155 /update|integer/i
156 );
157 }
158 assert.equal(calls, 0);
159 });
160
161 test('guard configuration and unexpected replies fail closed', async () => {
162 await assert.rejects(
163 async () => consume({ botId: '12345', updateId: 1 }),
164 /configured/i
165 );
166 for (const response of [
167 Response.json({}),
168 Response.json({ accepted: true }, { status: 500 }),
169 Response.json({ accepted: false }, { status: 409 })
170 ]) {
171 const namespace = {
172 idFromName: (name) => name,
173 get: () => ({ fetch: async () => response })
174 };
175 await assert.rejects(
176 async () => consume({ namespace, botId: '12345', updateId: 1 }),
177 /guard|claim/i
178 );
179 }
180 });
181
182 test('bot identities survive token rotation and nonstandard tokens are hashed', async () => {
183 assert.equal(await identity('12345:old-secret'), '12345');
184 assert.equal(await identity('12345:new-secret'), '12345');
185 const hashed = await identity('nonstandard-test-secret');
186 assert.match(hashed, /^sha256:[a-f0-9]{64}$/);
187 assert.equal(await identity('nonstandard-test-secret'), hashed);
188 assert.notEqual(await identity('another-test-secret'), hashed);
189 assert.doesNotMatch(hashed, /nonstandard|test-secret/);
190 });
191
192 test('claim expiry and cleanup alarm roll back together when alarm scheduling fails', async () => {
193 assert.equal(typeof module.consumeTelegramUpdate, 'function');
194 const state = makeReplayState({ failAlarm: true });
195 const namespace = {
196 idFromName: (name) => name,
197 get: () => ({
198 fetch: (request) => new ApprovalReplayGuard(state).fetch(request)
199 })
200 };
201 await assert.rejects(async () =>
202 consume({ namespace, botId: '12345', updateId: 1 })
203 );
204 assert.equal(state.data.size, 0);
205 });
206
207 test('webhook duplicate and concurrent deliveries produce only one bot response', async () => {
208 const originalFetch = globalThis.fetch;
209 let effects = 0;
210 globalThis.fetch = async () => {
211 effects++;
212 return Response.json({ ok: true, result: { message_id: 9 } });
213 };
214 try {
215 const runtime = env();
216 const responses = await Promise.all(
217 Array.from({ length: 5 }, () =>
218 worker.fetch(webhook(ownerUpdate()), runtime)
219 )
220 );
221 assert.ok(responses.every((response) => response.status === 200));
222 const bodies = await Promise.all(
223 responses.map((response) => response.json())
224 );
225 assert.equal(effects, 1);
226 assert.equal(bodies.filter((body) => body.duplicate === true).length, 4);
227 } finally {
228 globalThis.fetch = originalFetch;
229 }
230 });
231
232 test('webhook rejects malformed JSON and invalid update ids before side effects', async () => {
233 const originalFetch = globalThis.fetch;
234 let effects = 0;
235 globalThis.fetch = async () => {
236 effects++;
237 throw new Error('must not execute');
238 };
239 try {
240 for (const update of [
241 '{',
242 { ...ownerUpdate(), update_id: undefined },
243 ownerUpdate('7'),
244 ownerUpdate(-1)
245 ]) {
246 assert.equal((await worker.fetch(webhook(update), env())).status, 400);
247 }
248 assert.equal(effects, 0);
249 } finally {
250 globalThis.fetch = originalFetch;
251 }
252 });
253
254 test('owner updates fail closed if the durable guard is absent or unavailable', async () => {
255 const originalFetch = globalThis.fetch;
256 const originalError = console.error;
257 let effects = 0;
258 globalThis.fetch = async () => {
259 effects++;
260 return Response.json({ ok: true });
261 };
262 console.error = () => {};
263 try {
264 for (const namespace of [
265 null,
266 {
267 idFromName: (name) => name,
268 get: () => ({
269 fetch: async () => {
270 throw new Error('private provider text');
271 }
272 })
273 }
274 ]) {
275 assert.equal(
276 (await worker.fetch(webhook(ownerUpdate()), env(namespace))).status,
277 503
278 );
279 }
280 assert.equal(effects, 0);
281 } finally {
282 globalThis.fetch = originalFetch;
283 console.error = originalError;
284 }
285 });
286
287 test('nonowner updates do not claim durable keys or execute the bot', async () => {
288 let claims = 0;
289 const namespace = {
290 idFromName() {
291 claims++;
292 throw new Error('must not claim');
293 },
294 get() {
295 claims++;
296 }
297 };
298 const update = ownerUpdate();
299 update.message.from.id = 999;
300 const response = await worker.fetch(webhook(update), env(namespace));
301 assert.equal(response.status, 200);
302 assert.equal((await response.json()).ignored, true);
303 assert.equal(claims, 0);
304 });
305
306 test('claimed handler failures acknowledge once and log only fixed metadata', async () => {
307 const originalFetch = globalThis.fetch;
308 const originalError = console.error;
309 const logs = [];
310 let effects = 0;
311 const privateText =
312 'private draft github_pat_unconfigured-token upstream error';
313 globalThis.fetch = async () => {
314 effects++;
315 throw new Error(privateText);
316 };
317 console.error = (...values) => logs.push(values.map(String).join(' '));
318 try {
319 const runtime = env();
320 const response = await worker.fetch(webhook(ownerUpdate()), runtime);
321 assert.equal(response.status, 200);
322 assert.deepEqual(await response.json(), {
323 ok: false,
324 processed_error: true,
325 error: 'Telegram webhook processing failed'
326 });
327 const retry = await worker.fetch(webhook(ownerUpdate()), runtime);
328 assert.equal(retry.status, 200);
329 assert.equal((await retry.json()).duplicate, true);
330 assert.equal(effects, 1);
331 assert.equal(logs.length, 1);
332 assert.match(logs[0], /telegram_webhook_error/);
333 assert.doesNotMatch(logs.join('\n'), /private|github_pat_|upstream|draft/);
334 } finally {
335 globalThis.fetch = originalFetch;
336 console.error = originalError;
337 }
338 });
339
340 test('handled bot failures cannot return provider or source text from the webhook', async () => {
341 const originalHandleUpdate =
342 KillSwitchGuidedNexaDevBot.prototype.handleUpdate;
343 const originalError = console.error;
344 const logs = [];
345 KillSwitchGuidedNexaDevBot.prototype.handleUpdate = async () => ({
346 ok: false,
347 error: 'private draft provider error'
348 });
349 console.error = (...values) => logs.push(values.map(String).join(' '));
350 try {
351 const response = await worker.fetch(webhook(ownerUpdate()), env());
352 assert.equal(response.status, 200);
353 assert.deepEqual(await response.json(), {
354 ok: false,
355 processed_error: true,
356 error: 'Telegram webhook processing failed'
357 });
358 assert.equal(logs.length, 1);
359 assert.doesNotMatch(logs.join('\n'), /private|draft|provider/);
360 } finally {
361 KillSwitchGuidedNexaDevBot.prototype.handleUpdate = originalHandleUpdate;
362 console.error = originalError;
363 }
364 });