Personal Telegram developer console for GitHub

fix/issues-permission-release-empty-ux
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 318 lines 15.7 KB
Raw
1 import { DEFAULT_CONFIG } from './config.js';
2
3 const clampPage = value => Math.max(1, Math.min(100, Number(value) || 1));
4 const clampPerPage = (value, fallback = 10) => Math.max(1, Math.min(20, Number(value) || fallback));
5 const boundedPatch = value => String(value || '').slice(0, 1200);
6 const numericId = (value, label) => {
7 const text = String(value ?? '');
8 if (!/^\d+$/.test(text)) throw new Error(`Invalid ${label} ID`);
9 return text;
10 };
11 const fullSha = (value, label = 'Git commit') => {
12 const text = String(value || '');
13 if (!/^[a-f0-9]{40}$/i.test(text)) throw new Error(`Invalid ${label} SHA`);
14 return text;
15 };
16
17 export class GitHubService {
18 constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) {
19 this.token = token;
20 this.owner = owner;
21 this.baseUrl = 'https://api.github.com';
22 }
23
24 requireToken() {
25 if (!this.token) throw new Error('GITHUB_TOKEN is not configured');
26 }
27
28 getHeaders() {
29 this.requireToken();
30 return {
31 'User-Agent': 'Nexa-Dev-Bot-v1.1',
32 'Accept': 'application/vnd.github+json',
33 'Authorization': `Bearer ${this.token}`,
34 'X-GitHub-Api-Version': '2022-11-28'
35 };
36 }
37
38 async requestJson(url, label, { method = 'GET', body, allowEmpty = false } = {}) {
39 const headers = this.getHeaders();
40 const options = { method, headers };
41 if (body !== undefined) {
42 options.body = JSON.stringify(body);
43 options.headers = { ...headers, 'Content-Type': 'application/json' };
44 }
45 const res = await fetch(url, options);
46 const raw = await res.text();
47 let parsed = null;
48 if (raw) {
49 try { parsed = JSON.parse(raw); } catch { parsed = null; }
50 }
51 if (!res.ok) {
52 const providerMessage = parsed?.message || raw.slice(0, 240);
53 const detail = providerMessage ? ` ${providerMessage}` : '';
54 throw new Error(`${label} failed: ${res.status}${detail}`);
55 }
56 if (allowEmpty) return { accepted: true, status: res.status };
57 if (!raw) return null;
58 if (parsed === null) throw new Error(`${label} failed: invalid JSON response`);
59 return parsed;
60 }
61
62 async requestText(url, label, { maxChars = 12000 } = {}) {
63 const res = await fetch(url, { method: 'GET', headers: this.getHeaders() });
64 const raw = await res.text();
65 if (!res.ok) {
66 const detail = raw ? ` ${raw.slice(0, 240)}` : '';
67 throw new Error(`${label} failed: ${res.status}${detail}`);
68 }
69 const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000));
70 return { text: raw.length > limit ? raw.slice(-limit) : raw, truncated: raw.length > limit };
71 }
72
73 repoUrl(repo, suffix = '') {
74 return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`;
75 }
76
77 repositoryLookupUrl(repoRef) {
78 const value = String(repoRef || '');
79 return /^\d+$/.test(value) ? `${this.baseUrl}/repositories/${value}` : this.repoUrl(value);
80 }
81
82 repositoryApiBase(fullName) {
83 const parts = String(fullName || '').split('/').filter(Boolean);
84 if (parts.length !== 2) throw new Error('GitHub repository full_name is invalid');
85 return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`;
86 }
87
88 async getRepositoryContext(repoRef) {
89 const raw = await this.requestJson(this.repositoryLookupUrl(repoRef), 'GitHub repository');
90 return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
91 }
92
93 mapRepository(r) {
94 return {
95 id: String(r.id ?? r.name), name: r.name, fullName: r.full_name, private: !!r.private,
96 description: r.description || '', defaultBranch: r.default_branch || 'main', archived: !!r.archived,
97 htmlUrl: r.html_url || '', stars: r.stargazers_count ?? 0, forks: r.forks_count ?? 0
98 };
99 }
100
101 mapWorkflowRun(run = {}) {
102 return {
103 id: run.id, name: run.name || 'Workflow', status: run.status || '', conclusion: run.conclusion || null,
104 event: run.event || '', branch: run.head_branch || '', sha: String(run.head_sha || '').slice(0, 7),
105 runNumber: run.run_number ?? null, url: run.html_url || '', createdAt: run.created_at || '', updatedAt: run.updated_at || ''
106 };
107 }
108
109 mapWorkflowJob(job = {}) {
110 return {
111 id: job.id, name: job.name || 'Job', status: job.status || '', conclusion: job.conclusion || null,
112 startedAt: job.started_at || '', completedAt: job.completed_at || '', url: job.html_url || '',
113 steps: (job.steps || []).slice(0, 30).map(step => ({
114 number: step.number, name: step.name || 'Step', status: step.status || '', conclusion: step.conclusion || null
115 }))
116 };
117 }
118
119 mapPullRequestFile(file = {}) {
120 return {
121 filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0,
122 deletions: file.deletions ?? 0, changes: file.changes ?? 0, patch: boundedPatch(file.patch)
123 };
124 }
125
126 mapIssue(issue = {}) {
127 return {
128 number: issue.number,
129 title: issue.title || '',
130 state: issue.state || '',
131 author: issue.user?.login || 'unknown',
132 comments: issue.comments ?? 0,
133 url: issue.html_url || ''
134 };
135 }
136
137 async listRepositories() {
138 const data = await this.requestJson(`${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`, 'GitHub repositories');
139 return data.map(r => { const repo = this.mapRepository(r); return { ...repo, title: `${repo.name} ${repo.private ? '🔒' : '🌐'}` }; });
140 }
141
142 async getRepository(repoRef) {
143 const { raw } = await this.getRepositoryContext(repoRef);
144 return this.mapRepository(raw);
145 }
146
147 async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) {
148 const count = clampPerPage(perPage, 10);
149 const pageNumber = clampPage(page);
150 const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
151 const { apiBase } = await this.getRepositoryContext(repoRef);
152 const data = await this.requestJson(`${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`, 'GitHub pull requests');
153 return data.map(pr => ({
154 number: pr.number, title: pr.title, author: pr.user?.login || 'unknown', state: pr.state,
155 merged: !!pr.merged_at, createdAt: pr.created_at, url: pr.html_url
156 }));
157 }
158
159 async getPullRequest(repoRef, prNumber) {
160 const number = numericId(prNumber, 'pull request');
161 const { apiBase } = await this.getRepositoryContext(repoRef);
162 const pr = await this.requestJson(`${apiBase}/pulls/${number}`, 'GitHub pull request');
163 return {
164 number: pr.number, title: pr.title || '', author: pr.user?.login || 'unknown', state: pr.state || '',
165 merged: !!(pr.merged ?? pr.merged_at), body: pr.body || '', url: pr.html_url || '', head: pr.head?.ref || '',
166 headSha: pr.head?.sha || '', base: pr.base?.ref || '', additions: pr.additions ?? 0,
167 deletions: pr.deletions ?? 0, changedFiles: pr.changed_files ?? 0
168 };
169 }
170
171 async listPullRequestFiles(repoRef, prNumber, { perPage = 20, page = 1 } = {}) {
172 const number = numericId(prNumber, 'pull request');
173 const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
174 const { apiBase } = await this.getRepositoryContext(repoRef);
175 const data = await this.requestJson(`${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`, 'GitHub pull request files');
176 return data.map(file => this.mapPullRequestFile(file));
177 }
178
179 async listCommits(repoRef) {
180 const { apiBase } = await this.getRepositoryContext(repoRef);
181 const data = await this.requestJson(`${apiBase}/commits?per_page=5`, 'GitHub commits');
182 return data.map(c => ({
183 sha: c.sha.slice(0, 7), message: String(c.commit?.message || '').split('\n')[0],
184 author: c.author?.login || c.commit?.author?.name || 'Unknown', date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : ''
185 }));
186 }
187
188 async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) {
189 const commitSha = fullSha(sha); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
190 const { apiBase } = await this.getRepositoryContext(repoRef);
191 const data = await this.requestJson(`${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`, 'GitHub check runs');
192 return (data.check_runs || []).map(check => ({ id: check.id, name: check.name || 'Check', status: check.status || '', conclusion: check.conclusion || null, url: check.html_url || '' }));
193 }
194
195 async listFiles(repoRef, path = '') {
196 const { apiBase } = await this.getRepositoryContext(repoRef);
197 const suffix = path ? `/contents/${path.split('/').map(encodeURIComponent).join('/')}` : '/contents';
198 const data = await this.requestJson(`${apiBase}${suffix}`, 'GitHub contents');
199 if (!Array.isArray(data)) throw new Error('GitHub contents response is not a directory listing');
200 return data.map(item => ({ name: item.name, path: item.path, type: item.type === 'dir' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' }));
201 }
202
203 async listTree(repoRef, sha) {
204 if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git tree SHA');
205 const { apiBase } = await this.getRepositoryContext(repoRef);
206 const data = await this.requestJson(`${apiBase}/git/trees/${encodeURIComponent(sha)}`, 'GitHub tree');
207 return (data.tree || []).filter(item => item.type === 'tree' || item.type === 'blob').map(item => ({
208 name: item.path, path: item.path, type: item.type === 'tree' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || ''
209 }));
210 }
211
212 async getBlob(repoRef, sha) {
213 if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git blob SHA');
214 const { apiBase } = await this.getRepositoryContext(repoRef);
215 const data = await this.requestJson(`${apiBase}/git/blobs/${encodeURIComponent(sha)}`, 'GitHub blob');
216 return { encoding: data.encoding || '', size: data.size ?? 0, content: data.content || '' };
217 }
218
219 async getRepoStatus(repoRef) {
220 const { raw, apiBase } = await this.getRepositoryContext(repoRef);
221 const runsData = await this.requestJson(`${apiBase}/actions/runs?per_page=3`, 'GitHub Actions runs');
222 const runs = runsData.workflow_runs || [];
223 return {
224 repo: String(repoRef), repoName: raw.name, defaultBranch: raw.default_branch || 'main',
225 lastRuns: runs.map(r => ({ name: r.name, status: r.status, conclusion: r.conclusion, commit: r.head_commit?.message?.slice(0, 80) || '', url: r.html_url || '' }))
226 };
227 }
228
229 async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) {
230 const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page);
231 const { apiBase } = await this.getRepositoryContext(repoRef);
232 const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
233 const data = await this.requestJson(`${apiBase}/actions/runs?per_page=${count}${pageQuery}`, 'GitHub workflow runs');
234 return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run));
235 }
236
237 async getWorkflowRun(repoRef, runId) {
238 const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
239 return this.mapWorkflowRun(await this.requestJson(`${apiBase}/actions/runs/${id}`, 'GitHub workflow run'));
240 }
241
242 async listWorkflowJobs(repoRef, runId) {
243 const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
244 const data = await this.requestJson(`${apiBase}/actions/runs/${id}/jobs?per_page=20`, 'GitHub workflow jobs');
245 return (data.jobs || []).map(job => this.mapWorkflowJob(job));
246 }
247
248 async getWorkflowJob(repoRef, jobId) {
249 const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
250 return this.mapWorkflowJob(await this.requestJson(`${apiBase}/actions/jobs/${id}`, 'GitHub workflow job'));
251 }
252
253 async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) {
254 const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
255 return this.requestText(`${apiBase}/actions/jobs/${id}/logs`, 'GitHub workflow job log', { maxChars });
256 }
257
258 async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) {
259 const id = numericId(runId, 'workflow run'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
260 const { apiBase } = await this.getRepositoryContext(repoRef);
261 const data = await this.requestJson(`${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`, 'GitHub workflow artifacts');
262 return (data.artifacts || []).map(artifact => ({
263 id: artifact.id, name: artifact.name || 'Artifact', size: artifact.size_in_bytes ?? 0, expired: !!artifact.expired,
264 createdAt: artifact.created_at || '', expiresAt: artifact.expires_at || '', downloadUrl: artifact.archive_download_url || ''
265 }));
266 }
267
268 async listBranches(repoRef, { perPage = 20, page = 1 } = {}) {
269 const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
270 const data = await this.requestJson(`${apiBase}/branches?per_page=${count}&page=${pageNumber}`, 'GitHub branches');
271 return data.map(branch => ({ name: branch.name || '', sha: branch.commit?.sha || '', protected: !!branch.protected }));
272 }
273
274 async compareWithDefault(repoRef, headSha) {
275 const head = fullSha(headSha); const { raw, apiBase } = await this.getRepositoryContext(repoRef); const base = raw.default_branch || 'main';
276 const data = await this.requestJson(`${apiBase}/compare/${encodeURIComponent(base)}...${head}`, 'GitHub compare');
277 return {
278 base, head, status: data.status || '', aheadBy: data.ahead_by ?? 0, behindBy: data.behind_by ?? 0,
279 totalCommits: data.total_commits ?? 0, baseSha: data.base_commit?.sha || '', mergeBaseSha: data.merge_base_commit?.sha || '',
280 files: (data.files || []).slice(0, 20).map(file => this.mapPullRequestFile(file))
281 };
282 }
283
284 async listIssues(repoRef, { perPage = 10, page = 1 } = {}) {
285 const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
286 const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`, 'GitHub issues');
287 return data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue));
288 }
289
290 async listIssuesPage(repoRef, { page = 1 } = {}) {
291 const pageNumber = clampPage(page);
292 const { apiBase } = await this.getRepositoryContext(repoRef);
293 const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`, 'GitHub issues');
294 return {
295 items: data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)),
296 hasMore: data.length === 20
297 };
298 }
299
300 async listReleases(repoRef, { perPage = 10, page = 1 } = {}) {
301 const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
302 const data = await this.requestJson(`${apiBase}/releases?per_page=${count}&page=${pageNumber}`, 'GitHub releases');
303 return data.map(release => ({
304 id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', draft: !!release.draft,
305 prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', url: release.html_url || ''
306 }));
307 }
308
309 async rerunFailedWorkflowRun(repoRef, runId) {
310 const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
311 return this.requestJson(`${apiBase}/actions/runs/${id}/rerun-failed-jobs`, 'GitHub rerun failed jobs', { method: 'POST', allowEmpty: true });
312 }
313
314 async cancelWorkflowRun(repoRef, runId) {
315 const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
316 return this.requestJson(`${apiBase}/actions/runs/${id}/cancel`, 'GitHub cancel workflow run', { method: 'POST', allowEmpty: true });
317 }
318 }