Personal Telegram developer console for GitHub

feat/telegram-pr-merge
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 121 lines 4.15 KB
Raw
1 const API_BASE = 'https://api.cloudflare.com/client/v4';
2
3 const clean = value => String(value ?? '').trim();
4 const safe = value => encodeURIComponent(clean(value));
5
6 function redact(message, token) {
7 const text = String(message || 'Cloudflare request failed');
8 return token ? text.split(token).join('[REDACTED]') : text;
9 }
10
11 function firstError(payload) {
12 const errors = Array.isArray(payload?.errors) ? payload.errors : [];
13 return errors.map(item => item?.message).filter(Boolean).join('; ');
14 }
15
16 export class CloudflareService {
17 constructor({ token = '', accountId = '', workerName = '', fetchImpl = globalThis.fetch } = {}) {
18 this.token = clean(token);
19 this.accountId = clean(accountId);
20 this.workerName = clean(workerName);
21 this.fetchImpl = fetchImpl;
22 }
23
24 isConfigured() {
25 return Boolean(this.token && this.accountId && this.workerName && typeof this.fetchImpl === 'function');
26 }
27
28 requireConfigured() {
29 if (!this.isConfigured()) throw new Error('Cloudflare provider is not configured');
30 }
31
32 get headers() {
33 return {
34 Authorization: `Bearer ${this.token}`,
35 'Content-Type': 'application/json'
36 };
37 }
38
39 endpoint(suffix) {
40 return `${API_BASE}/accounts/${safe(this.accountId)}/workers/scripts/${safe(this.workerName)}${suffix}`;
41 }
42
43 async requestJson(suffix, label) {
44 this.requireConfigured();
45 let response;
46 try {
47 response = await this.fetchImpl(this.endpoint(suffix), { method: 'GET', headers: this.headers });
48 } catch (error) {
49 throw new Error(redact(`${label} failed: ${error?.message || error}`, this.token));
50 }
51
52 let raw = '';
53 try {
54 raw = await response.text();
55 } catch {
56 raw = '';
57 }
58
59 let payload = null;
60 if (raw) {
61 try { payload = JSON.parse(raw); } catch { payload = null; }
62 }
63
64 if (!response.ok || payload?.success === false) {
65 const detail = firstError(payload) || raw.slice(0, 240) || 'request failed';
66 throw new Error(redact(`${label} failed: ${response.status} ${detail}`, this.token));
67 }
68
69 if (payload === null) throw new Error(`${label} failed: invalid JSON response`);
70 return payload?.result ?? payload;
71 }
72
73 async getWorkerSnapshot() {
74 this.requireConfigured();
75 const [deploymentsResult, versionsResult, settingsResult] = await Promise.all([
76 this.requestJson('/deployments', 'Cloudflare deployments'),
77 this.requestJson('/versions', 'Cloudflare versions'),
78 this.requestJson('/settings', 'Cloudflare settings')
79 ]);
80
81 const deployments = Array.isArray(deploymentsResult?.deployments)
82 ? deploymentsResult.deployments
83 : Array.isArray(deploymentsResult) ? deploymentsResult : [];
84 const versions = Array.isArray(versionsResult?.items)
85 ? versionsResult.items
86 : Array.isArray(versionsResult) ? versionsResult : [];
87
88 const latestDeployment = deployments[0] || null;
89 const latestVersion = versions[0] || null;
90 const bindings = Array.isArray(settingsResult?.bindings)
91 ? settingsResult.bindings
92 .map(binding => ({ name: clean(binding?.name), type: clean(binding?.type) }))
93 .filter(binding => binding.name || binding.type)
94 : [];
95 const observability = settingsResult?.observability || {};
96
97 return {
98 workerName: this.workerName,
99 deployment: latestDeployment ? {
100 id: clean(latestDeployment.id),
101 createdOn: clean(latestDeployment.created_on),
102 versions: (Array.isArray(latestDeployment.versions) ? latestDeployment.versions : []).map(item => ({
103 versionId: clean(item?.version_id),
104 percentage: Number.isFinite(Number(item?.percentage)) ? Number(item.percentage) : 0
105 }))
106 } : null,
107 version: latestVersion ? {
108 id: clean(latestVersion.id),
109 createdOn: clean(latestVersion.created_on),
110 triggeredBy: clean(latestVersion.annotations?.['workers/triggered_by'])
111 } : null,
112 bindings,
113 observability: {
114 enabled: observability.enabled === true,
115 logsEnabled: observability.logs?.enabled === true,
116 invocationLogs: observability.logs?.invocation_logs === true,
117 tracesEnabled: observability.traces?.enabled === true
118 }
119 };
120 }
121 }