Personal Telegram developer console for GitHub

phase2-20261005-s
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 163 lines 6.16 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, { method = 'GET', body } = {}) {
44 this.requireConfigured();
45 let response;
46 try {
47 const options = { method, headers: this.headers };
48 if (body !== undefined) options.body = JSON.stringify(body);
49 response = await this.fetchImpl(this.endpoint(suffix), options);
50 } catch (error) {
51 throw new Error(redact(`${label} failed: ${error?.message || error}`, this.token));
52 }
53
54 let raw = '';
55 try {
56 raw = await response.text();
57 } catch {
58 raw = '';
59 }
60
61 let payload = null;
62 if (raw) {
63 try { payload = JSON.parse(raw); } catch { payload = null; }
64 }
65
66 if (!response.ok || payload?.success === false) {
67 const detail = firstError(payload) || raw.slice(0, 240) || 'request failed';
68 throw new Error(redact(`${label} failed: ${response.status} ${detail}`, this.token));
69 }
70
71 if (payload === null) throw new Error(`${label} failed: invalid JSON response`);
72 return payload?.result ?? payload;
73 }
74
75 async listVersions() {
76 const result = await this.requestJson('/versions', 'Cloudflare versions');
77 const items = Array.isArray(result?.items) ? result.items : Array.isArray(result) ? result : [];
78 return items.slice(0, 20).map(item => ({
79 id: clean(item?.id),
80 createdOn: clean(item?.created_on),
81 triggeredBy: clean(item?.annotations?.['workers/triggered_by'])
82 })).filter(item => item.id);
83 }
84
85 async listDeployments() {
86 const result = await this.requestJson('/deployments', 'Cloudflare deployments');
87 const items = Array.isArray(result?.deployments) ? result.deployments : Array.isArray(result) ? result : [];
88 return items.slice(0, 20).map(item => ({
89 id: clean(item?.id),
90 createdOn: clean(item?.created_on),
91 versions: (Array.isArray(item?.versions) ? item.versions : []).map(version => ({
92 versionId: clean(version?.version_id),
93 percentage: Number.isFinite(Number(version?.percentage)) ? Number(version.percentage) : 0
94 }))
95 }));
96 }
97
98 async deployVersion(versionId) {
99 const target = clean(versionId);
100 if (!/^[0-9a-f-]{36}$/i.test(target)) throw new Error('Cloudflare version ID is invalid');
101 const versions = await this.listVersions();
102 if (!versions.some(version => version.id === target)) throw new Error('Cloudflare version is not known');
103 await this.requestJson('/deployments', 'Cloudflare deploy version', {
104 method: 'POST',
105 body: { strategy: 'percentage', versions: [{ percentage: 100, version_id: target }] }
106 });
107 const snapshot = await this.getWorkerSnapshot();
108 const active = snapshot.deployment?.versions || [];
109 if (active.length !== 1 || active[0].versionId !== target || Number(active[0].percentage) !== 100) {
110 throw new Error('Cloudflare deployment verification failed');
111 }
112 return { versionId: target, deploymentId: snapshot.deployment?.id || '', verified: true };
113 }
114
115 async getWorkerSnapshot() {
116 this.requireConfigured();
117 const [deploymentsResult, versionsResult, settingsResult] = await Promise.all([
118 this.requestJson('/deployments', 'Cloudflare deployments'),
119 this.requestJson('/versions', 'Cloudflare versions'),
120 this.requestJson('/settings', 'Cloudflare settings')
121 ]);
122
123 const deployments = Array.isArray(deploymentsResult?.deployments)
124 ? deploymentsResult.deployments
125 : Array.isArray(deploymentsResult) ? deploymentsResult : [];
126 const versions = Array.isArray(versionsResult?.items)
127 ? versionsResult.items
128 : Array.isArray(versionsResult) ? versionsResult : [];
129
130 const latestDeployment = deployments[0] || null;
131 const latestVersion = versions[0] || null;
132 const bindings = Array.isArray(settingsResult?.bindings)
133 ? settingsResult.bindings
134 .map(binding => ({ name: clean(binding?.name), type: clean(binding?.type) }))
135 .filter(binding => binding.name || binding.type)
136 : [];
137 const observability = settingsResult?.observability || {};
138
139 return {
140 workerName: this.workerName,
141 deployment: latestDeployment ? {
142 id: clean(latestDeployment.id),
143 createdOn: clean(latestDeployment.created_on),
144 versions: (Array.isArray(latestDeployment.versions) ? latestDeployment.versions : []).map(item => ({
145 versionId: clean(item?.version_id),
146 percentage: Number.isFinite(Number(item?.percentage)) ? Number(item.percentage) : 0
147 }))
148 } : null,
149 version: latestVersion ? {
150 id: clean(latestVersion.id),
151 createdOn: clean(latestVersion.created_on),
152 triggeredBy: clean(latestVersion.annotations?.['workers/triggered_by'])
153 } : null,
154 bindings,
155 observability: {
156 enabled: observability.enabled === true,
157 logsEnabled: observability.logs?.enabled === true,
158 invocationLogs: observability.logs?.invocation_logs === true,
159 tracesEnabled: observability.traces?.enabled === true
160 }
161 };
162 }
163 }