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 165 lines 5.8 KB
Raw
1 import { KillSwitchGuidedNexaDevBot } from './kill-switch-bot.js';
2 import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
3 import { RELEASE_VERSION } from './version.js';
4 import { GitHubService } from './github.js';
5 import { handleStudioAssetsRequest } from './studio-assets.js';
6 import { handleStudioApiRequest } from './studio-api.js';
7 import {
8 consumeTelegramUpdate,
9 telegramBotIdentity
10 } from './core/telegram-update-guard.js';
11 import {
12 handleWorkspaceEditorRequest,
13 workspaceEditorPageResponse
14 } from './workspace-editor.js';
15 export { ApprovalReplayGuard } from './durable/approval-replay-guard.js';
16 export { WorkspaceStore } from './durable/workspace-store.js';
17 export { IncidentStore } from './durable/incident-store.js';
18 export { AutomationStore } from './durable/automation-store.js';
19 export { KillSwitchStore } from './durable/kill-switch-store.js';
20 const jsonResponse = (p, s = 200) =>
21 new Response(JSON.stringify(p), {
22 status: s,
23 headers: { 'Content-Type': 'application/json; charset=utf-8' }
24 });
25 const publicHealthPayload = () => ({
26 status: 'online',
27 bot: 'Nexa Dev Bot',
28 version: RELEASE_VERSION,
29 mode: 'Cloudflare Worker Webhook'
30 });
31 const senderIdFromUpdate = (u) =>
32 u?.message?.from?.id ??
33 u?.edited_message?.from?.id ??
34 u?.callback_query?.from?.id ??
35 null;
36 const isOwnerUpdate = (u, e) =>
37 !!e.OWNER_TELEGRAM_ID &&
38 senderIdFromUpdate(u) !== null &&
39 String(senderIdFromUpdate(u)) === String(e.OWNER_TELEGRAM_ID);
40 const botEnvironment = (env, url) => ({
41 ...env,
42 STUDIO_URL: env.STUDIO_URL ?? new URL('/studio/', url).href,
43 WORKSPACE_EDITOR_URL:
44 env.WORKSPACE_EDITOR_URL ?? new URL('/workspace/editor', url).href
45 });
46 export default {
47 async fetch(request, env = {}) {
48 const url = new URL(request.url);
49 const studioAssets = await handleStudioAssetsRequest(request, env);
50 if (studioAssets) return studioAssets;
51 if (
52 url.pathname === '/api/v1/studio' ||
53 url.pathname.startsWith('/api/v1/studio/')
54 ) {
55 const bot = new KillSwitchGuidedNexaDevBot(botEnvironment(env, url));
56 return handleStudioApiRequest(request, {
57 env,
58 github: bot.github,
59 workspaces: bot.workspaceStore,
60 bot
61 });
62 }
63 if (request.method === 'GET' && url.pathname === '/workspace/editor')
64 return workspaceEditorPageResponse();
65 if (
66 url.pathname === '/workspace/api/editor' &&
67 (request.method === 'GET' || request.method === 'PUT')
68 )
69 return handleWorkspaceEditorRequest(request, {
70 workspaces: new DurableWorkspaceStoreClient({
71 namespace: env.WORKSPACE_STORE
72 }),
73 github: new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER),
74 botToken: env.TELEGRAM_BOT_TOKEN || '',
75 ownerId: env.OWNER_TELEGRAM_ID || ''
76 });
77 if (request.method === 'GET') {
78 if (url.pathname === '/health')
79 return new Response('ok', {
80 headers: {
81 'content-type': 'text/plain; charset=utf-8',
82 'cache-control': 'no-store'
83 }
84 });
85 if (['/', '/status'].includes(url.pathname))
86 return jsonResponse(publicHealthPayload());
87 return new Response('Not Found', { status: 404 });
88 }
89 if (request.method === 'POST' && url.pathname === '/telegram/webhook') {
90 if (!env.TELEGRAM_WEBHOOK_SECRET)
91 return new Response('Webhook secret not configured', { status: 503 });
92 if (
93 request.headers.get('X-Telegram-Bot-Api-Secret-Token') !==
94 env.TELEGRAM_WEBHOOK_SECRET
95 )
96 return new Response('Forbidden', { status: 403 });
97 if (!env.OWNER_TELEGRAM_ID)
98 return new Response('Owner not configured', { status: 503 });
99 if (!env.TELEGRAM_BOT_TOKEN)
100 return new Response('Telegram bot token not configured', {
101 status: 503
102 });
103 let update;
104 try {
105 update = await request.json();
106 } catch {
107 return jsonResponse(
108 { ok: false, error: 'Invalid Telegram update' },
109 400
110 );
111 }
112 if (!Number.isSafeInteger(update?.update_id) || update.update_id < 0) {
113 return jsonResponse(
114 { ok: false, error: 'Invalid Telegram update_id' },
115 400
116 );
117 }
118 if (!isOwnerUpdate(update, env))
119 return jsonResponse({ ok: true, ignored: true });
120 try {
121 const accepted = await consumeTelegramUpdate({
122 namespace: env.APPROVAL_REPLAY_GUARD,
123 botId: await telegramBotIdentity(env.TELEGRAM_BOT_TOKEN),
124 updateId: update.update_id
125 });
126 if (!accepted) return jsonResponse({ ok: true, duplicate: true });
127 } catch {
128 console.error(
129 'telegram_webhook_guard_error',
130 JSON.stringify({ updateId: update.update_id, outcome: 'unavailable' })
131 );
132 return jsonResponse(
133 { ok: false, error: 'Telegram update guard unavailable' },
134 503
135 );
136 }
137 // Claim before effects: retries are at-most-once; a process crash after the
138 // durable claim can lose this update. No raw update is retained for replay.
139 try {
140 const result = await new KillSwitchGuidedNexaDevBot(
141 botEnvironment(env, url)
142 ).handleUpdate(update);
143 if (result?.ok !== false) return jsonResponse(result);
144 } catch {
145 // Provider messages can contain tokens or draft text; log metadata only.
146 }
147 console.error(
148 'telegram_webhook_error',
149 JSON.stringify({
150 updateId: update.update_id,
151 outcome: 'processed_error'
152 })
153 );
154 return jsonResponse({
155 ok: false,
156 processed_error: true,
157 error: 'Telegram webhook processing failed'
158 });
159 }
160 return new Response(
161 request.method === 'POST' ? 'Not Found' : 'Method Not Allowed',
162 { status: request.method === 'POST' ? 404 : 405 }
163 );
164 }
165 };