Personal Telegram developer console for GitHub

feat: secure Telegram pull-request merge flow

* test(github): define safe PR merge contract * feat(github): classify PR merge as destructive * feat(github): add exact-head pull request merge * test: use full head SHA in PR merge contract * fix(github): restore service and add guarded PR merge * feat(approval): bind destructive PR merge to exact head * test(github): cover exact-head destructive merge approval * feat(approval): persist destructive approval context * feat(approval): store exact destructive intent durably * fix(approval): keep exact PR head in durable approval context * test(approval): model durable destructive context * feat(github): wire safe Telegram PR merge action * feat(bot): handle destructive PR merge approvals

davoodmehraban89 committed Oct 5, 2026 at 05:10 UTC fd06683a82b521959ee7e3c189883f93a5a4f5a7
10 files changed +1155 -1739
src/bot-legacy.js new
+386
@@ -0,0 +1,386 @@
1 +import { TelegramClient } from './telegram.js';
2 +import { GitHubService } from './github.js';
3 +import { MenuManager } from './menu.js';
4 +import { PluginRegistry } from './core/plugin-registry.js';
5 +import { ActionPolicy } from './core/action-policy.js';
6 +import { ApprovalService } from './core/approval.js';
7 +import { DurableApprovalReplayStore } from './core/durable-replay-store.js';
8 +import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
9 +import { WORKSPACE_EDITOR_LIMITS } from './core/workspace-policy.js';
10 +import { AuditLogger } from './core/audit.js';
11 +import { PluginRouter } from './core/router.js';
12 +import { buildApprovedActionFailedView, buildCallbackFailureView } from './core/callback-failure-view.js';
13 +import { createGitHubPlugin } from './plugins/github/plugin.js';
14 +import { CloudflareService } from './plugins/cloudflare/service.js';
15 +import { createCloudflarePlugin } from './plugins/cloudflare/plugin.js';
16 +
17 +const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
18 +const QUICK_MENU = Object.freeze({
19 + '🏠 منوی اصلی': 'main',
20 + '📁 پروژه‌ها': 'repos',
21 + '📊 وضعیت': 'status',
22 + '🔧 ابزارها': 'tools',
23 + '🔐 امنیت': 'security'
24 +});
25 +const escapeHtml = value => String(value ?? '')
26 + .replaceAll('&', '&')
27 + .replaceAll('<', '&lt;')
28 + .replaceAll('>', '&gt;')
29 + .replaceAll('"', '&quot;');
30 +
31 +function persistentQuickMenuMarkup() {
32 + return {
33 + keyboard: [
34 + [{ text: '🏠 منوی اصلی' }, { text: '📁 پروژه‌ها' }],
35 + [{ text: '📊 وضعیت' }, { text: '🔧 ابزارها' }],
36 + [{ text: '🔐 امنیت' }]
37 + ],
38 + resize_keyboard: true,
39 + is_persistent: true,
40 + input_field_placeholder: 'Nexa Dev — یک گزینه را انتخاب کنید'
41 + };
42 +}
43 +
44 +function focusedCodeInputMarkup() {
45 + return {
46 + force_reply: true,
47 + selective: true,
48 + input_field_placeholder: 'کد یا متن را اینجا Paste کنید…'
49 + };
50 +}
51 +
52 +function approvalSourceCallback(payload = {}) {
53 + const repoId = payload.input?.repoId;
54 + if (!Number.isSafeInteger(Number(repoId))) throw new Error('Approval input is invalid');
55 +
56 + if (payload.actionId === 'github.workspace.commit_branch') {
57 + const intentId = String(payload.input?.intentId || '');
58 + if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval input is invalid');
59 + return `wscommit:${repoId}:${intentId}`;
60 + }
61 +
62 + const runId = payload.input?.runId;
63 + if (!Number.isSafeInteger(Number(runId))) throw new Error('Approval input is invalid');
64 + if (payload.actionId === 'github.workflow.run.rerun_failed') return `rerun:${repoId}:${runId}`;
65 + if (payload.actionId === 'github.workflow.run.cancel') return `cancelrun:${repoId}:${runId}`;
66 + throw new Error('Approval action is not supported');
67 +}
68 +
69 +function approvalView({ label, token, cancelCallback = 'menu:main' }) {
70 + return {
71 + text:
72 +`⚠️ <b>تأیید عملیات لازم است</b>
73 +➖➖➖➖➖➖➖➖➖➖
74 +عملیات: <b>${label}</b>
75 +این عملیات روی GitHub تغییر ایجاد می‌کند و فقط پس از تأیید شما اجرا می‌شود.
76 +
77 +اگر مطمئن هستید، «تأیید و اجرا» را بزنید.`,
78 + reply_markup: {
79 + inline_keyboard: [
80 + [{ text: '✅ تأیید و اجرا', callback_data: `approve:${token}` }],
81 + [{ text: '↩️ انصراف', callback_data: cancelCallback }]
82 + ]
83 + }
84 + };
85 +}
86 +
87 +function approvalRejectedView(message, error) {
88 + const reason = String(error?.message || 'Approval rejected');
89 + const expired = /expired/i.test(reason);
90 + const used = /already used|replay/i.test(reason);
91 + const fallback = message?.reply_markup?.inline_keyboard
92 + ?.flat()
93 + .map(button => String(button?.callback_data || ''))
94 + .find(callback => callback && !callback.startsWith('approve:')) || 'menu:main';
95 +
96 + let detail = 'این تأیید معتبر نیست و هیچ تغییری اجرا نشد.';
97 + if (expired) detail = 'مهلت این تأیید تمام شده است و هیچ تغییری اجرا نشد.';
98 + if (used) detail = 'این تأیید قبلاً استفاده شده است و دوباره اجرا نمی‌شود.';
99 + const backText = fallback.startsWith('run:') ? '↩️ بازگشت به Run' : '↩️ بازگشت';
100 +
101 + return {
102 + text:
103 +`⚠️ <b>عملیات اجرا نشد</b>
104 +➖➖➖➖➖➖➖➖➖➖
105 +${detail}
106 +
107 +برای ادامه برگردید و در صورت نیاز یک تأیید تازه ایجاد کنید.`,
108 + reply_markup: { inline_keyboard: [[{ text: backText, callback_data: fallback }]] }
109 + };
110 +}
111 +
112 +export class NexaDevBot {
113 + constructor(env = {}) {
114 + this.env = env;
115 + this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
116 + this.github = new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER || 'davoodmehraban89');
117 + this.menu = new MenuManager(this.github);
118 + this.replayStore = new DurableApprovalReplayStore({ namespace: env.APPROVAL_REPLAY_GUARD });
119 + this.workspaceStore = new DurableWorkspaceStoreClient({ namespace: env.WORKSPACE_STORE });
120 + this.approvals = new ApprovalService({
121 + secret: env.APPROVAL_SIGNING_SECRET || env.TELEGRAM_WEBHOOK_SECRET || '',
122 + replayStore: this.replayStore
123 + });
124 + this.githubPlugin = createGitHubPlugin({
125 + github: this.github,
126 + menu: this.menu,
127 + workspaces: this.workspaceStore.isConfigured() ? this.workspaceStore : null
128 + });
129 + this.cloudflare = new CloudflareService({
130 + token: env.CLOUDFLARE_API_TOKEN || '',
131 + accountId: env.CLOUDFLARE_ACCOUNT_ID || '',
132 + workerName: env.CLOUDFLARE_WORKER_NAME || 'nexa-dev-bot'
133 + });
134 + this.cloudflarePlugin = createCloudflarePlugin({ cloudflare: this.cloudflare });
135 + this.registry = new PluginRegistry([this.githubPlugin, this.cloudflarePlugin]);
136 + this.policy = new ActionPolicy();
137 + this.audit = new AuditLogger({
138 + secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.CLOUDFLARE_API_TOKEN, env.APPROVAL_SIGNING_SECRET]
139 + });
140 + this.router = new PluginRouter({ registry: this.registry, policy: this.policy, audit: this.audit });
141 + }
142 +
143 + async handleUpdate(update) {
144 + if (!update) return { ok: false, error: 'Empty update' };
145 + if (update.callback_query) return this.handleCallbackQuery(update.callback_query);
146 + if (update.message) return this.handleMessage(update.message);
147 + return { ok: true, ignored: true };
148 + }
149 +
150 + async handleCallbackQuery(query) {
151 + const callbackId = query.id;
152 + const data = query.data || 'menu:main';
153 + const message = query.message;
154 + const chatId = message?.chat?.id;
155 + const messageId = message?.message_id;
156 + const ownerId = query.from?.id;
157 +
158 + let callbackAnswered = true;
159 + try { await this.telegram.answerCallbackQuery(callbackId); } catch { callbackAnswered = false; }
160 + if (!chatId || !messageId) return { ok: false, error: 'Missing message context for callback', callbackAnswered };
161 +
162 + try {
163 + if (data.startsWith('approve:')) {
164 + if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
165 + const token = data.slice('approve:'.length);
166 + let payload;
167 + try {
168 + payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'github', risk: 'WRITE' });
169 + } catch (error) {
170 + this.audit.log({ event: 'approval_rejected', pluginId: 'github', risk: 'WRITE', outcome: 'rejected', error: error?.message || 'Approval rejected' });
171 + const view = approvalRejectedView(message, error);
172 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
173 + return { ok: false, approvalRejected: true, error: error?.message || 'Approval rejected', callbackAnswered, edited: true, res };
174 + }
175 +
176 + this.audit.log({ event: 'approval_verified', pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, outcome: 'verified' });
177 + const sourceCallback = approvalSourceCallback(payload);
178 + let routed;
179 + try {
180 + routed = await this.router.dispatchCallback(sourceCallback, {
181 + isOwner: true,
182 + ownerId: String(ownerId),
183 + approved: true
184 + });
185 + if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved action could not be dispatched');
186 + } catch (error) {
187 + const view = await buildApprovedActionFailedView({
188 + payload,
189 + error,
190 + ownerId,
191 + workspaces: this.workspaceStore
192 + });
193 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
194 + return { ok: false, approved: true, providerError: true, actionId: payload.actionId, error: error?.message || 'GitHub operation failed', callbackAnswered, edited: true, res };
195 + }
196 +
197 + const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
198 + return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
199 + }
200 +
201 + const routed = await this.router.dispatchCallback(data, {
202 + isOwner: true,
203 + ownerId: ownerId === undefined || ownerId === null ? '' : String(ownerId)
204 + });
205 + if (routed?.requiresApproval) {
206 + const approval = routed.approval;
207 + const repoId = approval?.input?.repoId;
208 + if (!approval || !Number.isSafeInteger(Number(repoId))) throw new Error('Approval metadata is missing');
209 + const workspaceApproval = routed.actionId === 'github.workspace.commit_branch';
210 + const runId = approval?.input?.runId;
211 + const intentId = String(approval?.input?.intentId || '');
212 + if (workspaceApproval) {
213 + if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval metadata is missing');
214 + } else if (!Number.isSafeInteger(Number(runId))) {
215 + throw new Error('Approval metadata is missing');
216 + }
217 + if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
218 + if (!this.approvals.isReplayProtected()) throw new Error('Durable approval replay protection is not configured');
219 +
220 + const token = await this.approvals.issue({
221 + pluginId: routed.pluginId,
222 + actionId: routed.actionId,
223 + risk: routed.risk,
224 + ownerId: String(ownerId),
225 + input: approval.input
226 + });
227 + this.audit.log({ event: 'approval_issued', pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, outcome: 'pending' });
228 + const cancelCallback = approval.cancelCallback || (Number.isSafeInteger(Number(runId)) ? `run:${repoId}:${runId}` : `repo:${repoId}`);
229 + const view = approvalView({ label: approval.label || routed.actionId, token, cancelCallback });
230 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
231 + return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
232 + }
233 + if (routed?.denied) return { ok: false, denied: true, actionId: routed.actionId, reason: routed.reason, callbackAnswered };
234 +
235 + const view = routed || await this.menu.renderByCallback(data);
236 + if (data.startsWith('wtext:') && routed) {
237 + const res = await this.telegram.sendMessage(chatId, view.text, focusedCodeInputMarkup());
238 + return { ok: true, inputPrompt: true, callbackAnswered, sent: true, res };
239 + }
240 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
241 + return { ok: true, edited: true, callbackAnswered, res };
242 + } catch (err) {
243 + if (err.message && err.message.includes('message is not modified')) return { ok: true, unmodified: true, callbackAnswered };
244 + if (!data.startsWith('approve:')) {
245 + try {
246 + const view = await buildCallbackFailureView({ data, error: err, ownerId, workspaces: this.workspaceStore });
247 + const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
248 + return {
249 + ok: false,
250 + error: err.message,
251 + providerError: !view.validationError,
252 + validationError: Boolean(view.validationError),
253 + callbackAnswered,
254 + edited: true,
255 + res
256 + };
257 + } catch {
258 + // Preserve the original provider/navigation error when feedback delivery also fails.
259 + }
260 + }
261 + return { ok: false, error: err.message, callbackAnswered };
262 + }
263 + }
264 +
265 + async handleMessage(message) {
266 + const chatId = message.chat?.id;
267 + const rawText = typeof message.text === 'string' ? message.text : '';
268 + const text = rawText.trim();
269 + if (!chatId) return { ok: false, error: 'Missing chat_id' };
270 +
271 + if (text === '/start' || text === '/menu' || text.startsWith('/start')) {
272 + const quickMenuRes = await this.telegram.sendMessage(
273 + chatId,
274 + '⌨️ <b>منوی سریع Nexa Dev فعال شد</b>\nاین منو پایین صفحه می‌ماند و از هر بخش قابل استفاده است.',
275 + persistentQuickMenuMarkup()
276 + );
277 + const view = this.menu.getMainMenuView();
278 + const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
279 + return { ok: true, command: 'start', persistentMenu: true, quickMenuRes, res };
280 + }
281 +
282 + const quickMenu = QUICK_MENU[text];
283 + if (quickMenu) {
284 + let view;
285 + if (quickMenu === 'main') {
286 + view = this.menu.getMainMenuView();
287 + } else if (quickMenu === 'repos') {
288 + const routed = await this.router.dispatchCommand('/repos', { isOwner: true });
289 + if (routed?.requiresApproval || routed?.denied || !routed) {
290 + return { ok: false, quickMenu, error: routed?.reason || 'GitHub repository route unavailable' };
291 + }
292 + view = routed;
293 + } else if (quickMenu === 'status') {
294 + view = this.menu.getServiceStatusView();
295 + } else if (quickMenu === 'tools') {
296 + view = this.menu.getToolsView();
297 + } else {
298 + view = this.menu.getSecurityView();
299 + }
300 + const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
301 + return { ok: true, quickMenu, res };
302 + }
303 +
304 + if (text === '/repos') {
305 + const routed = await this.router.dispatchCommand(text, { isOwner: true });
306 + if (routed?.requiresApproval || routed?.denied || !routed) {
307 + return { ok: false, command: 'repos', error: routed?.reason || 'GitHub repository route unavailable' };
308 + }
309 + const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
310 + return { ok: true, command: 'repos', res };
311 + }
312 +
313 + if (text === '/status') {
314 + const view = this.menu.getServiceStatusView();
315 + const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
316 + return { ok: true, command: 'status', res };
317 + }
318 +
319 + const ownerId = message.from?.id;
320 + if (ownerId !== undefined && ownerId !== null && this.workspaceStore.isConfigured()) {
321 + const pending = await this.workspaceStore.getPendingInput({ ownerId: String(ownerId) });
322 + if (pending) {
323 + let payload = { pending, text: rawText };
324 + if (pending.mode === 'draft_file') {
325 + const document = message.document;
326 + const maxUploadBytes = WORKSPACE_EDITOR_LIMITS.maxBytes;
327 + if (!document?.file_id) {
328 + const view = {
329 + text: `📎 <b>یک فایل متنی ارسال کنید</b>\nاین Workspace در حالت بارگذاری فایل است. فایل باید UTF-8 معتبر و حداکثر ${maxUploadBytes.toLocaleString('en-US')} بایت باشد.`,
330 + reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
331 + };
332 + const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
333 + return { ok: true, workspaceInput: true, inputRequired: 'document', res };
334 + }
335 + if (Number.isFinite(Number(document.file_size)) && Number(document.file_size) > maxUploadBytes) {
336 + const view = {
337 + text: `⚠️ <b>فایل پذیرفته نشد</b>\nحجم فایل بیشتر از سقف ${maxUploadBytes.toLocaleString('en-US')} بایت است. Draft تغییر نکرد؛ یک فایل کوچک‌تر ارسال کنید.`,
338 + reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
339 + };
340 + const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
341 + return { ok: false, workspaceInput: true, inputRejected: true, error: `Telegram file exceeds ${maxUploadBytes} byte size limit`, res };
342 + }
343 + let downloaded;
344 + try {
345 + downloaded = await this.telegram.downloadTextFile(document.file_id, { maxBytes: maxUploadBytes });
346 + } catch (error) {
347 + const view = {
348 + text: `⚠️ <b>فایل پذیرفته نشد</b>\n${escapeHtml(error?.message || 'Telegram file download failed')}\n\nDraft تغییر نکرد و می‌توانید فایل دیگری ارسال کنید.`,
349 + reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
350 + };
351 + const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
352 + return { ok: false, workspaceInput: true, inputRejected: true, error: error?.message || 'Telegram file download failed', res };
353 + }
354 + payload = {
355 + pending,
356 + file: {
357 + name: String(document.file_name || 'uploaded.txt'),
358 + text: downloaded.text,
359 + byteLength: downloaded.byteLength
360 + }
361 + };
362 + }
363 +
364 + const routed = await this.router.dispatchMessage(
365 + payload,
366 + { isOwner: true, ownerId: String(ownerId) }
367 + );
368 + if (routed?.requiresApproval || routed?.denied || !routed) {
369 + return { ok: false, error: routed?.reason || 'Workspace input route unavailable' };
370 + }
371 + const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
372 + return { ok: true, workspaceInput: true, res };
373 + }
374 + }
375 +
376 + const defaultText = '💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:';
377 + const view = {
378 + text: defaultText,
379 + reply_markup: {
380 + inline_keyboard: [[{ text: '⚡ باز کردن منوی اصلی Nexa Dev', callback_data: 'menu:main' }]]
381 + }
382 + };
383 + const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
384 + return { ok: true, default: true, res };
385 + }
386 +}
src/bot.js
+37 -374
@@ -1,386 +1,49 @@
1 -import { TelegramClient } from './telegram.js';
2 -import { GitHubService } from './github.js';
3 -import { MenuManager } from './menu.js';
4 -import { PluginRegistry } from './core/plugin-registry.js';
5 -import { ActionPolicy } from './core/action-policy.js';
6 -import { ApprovalService } from './core/approval.js';
7 -import { DurableApprovalReplayStore } from './core/durable-replay-store.js';
8 -import { DurableWorkspaceStoreClient } from './core/workspace-store.js';
9 -import { WORKSPACE_EDITOR_LIMITS } from './core/workspace-policy.js';
10 -import { AuditLogger } from './core/audit.js';
11 -import { PluginRouter } from './core/router.js';
12 -import { buildApprovedActionFailedView, buildCallbackFailureView } from './core/callback-failure-view.js';
13 -import { createGitHubPlugin } from './plugins/github/plugin.js';
14 -import { CloudflareService } from './plugins/cloudflare/service.js';
15 -import { createCloudflarePlugin } from './plugins/cloudflare/plugin.js';
16 -
17 -const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
18 -const QUICK_MENU = Object.freeze({
19 - '🏠 منوی اصلی': 'main',
20 - '📁 پروژه‌ها': 'repos',
21 - '📊 وضعیت': 'status',
22 - '🔧 ابزارها': 'tools',
23 - '🔐 امنیت': 'security'
24 -});
25 -const escapeHtml = value => String(value ?? '')
26 - .replaceAll('&', '&amp;')
27 - .replaceAll('<', '&lt;')
28 - .replaceAll('>', '&gt;')
29 - .replaceAll('"', '&quot;');
30 -
31 -function persistentQuickMenuMarkup() {
32 - return {
33 - keyboard: [
34 - [{ text: '🏠 منوی اصلی' }, { text: '📁 پروژه‌ها' }],
35 - [{ text: '📊 وضعیت' }, { text: '🔧 ابزارها' }],
36 - [{ text: '🔐 امنیت' }]
37 - ],
38 - resize_keyboard: true,
39 - is_persistent: true,
40 - input_field_placeholder: 'Nexa Dev — یک گزینه را انتخاب کنید'
41 - };
42 -}
43 -
44 -function focusedCodeInputMarkup() {
45 - return {
46 - force_reply: true,
47 - selective: true,
48 - input_field_placeholder: 'کد یا متن را اینجا Paste کنید…'
49 - };
50 -}
51 -
52 -function approvalSourceCallback(payload = {}) {
53 - const repoId = payload.input?.repoId;
54 - if (!Number.isSafeInteger(Number(repoId))) throw new Error('Approval input is invalid');
55 -
56 - if (payload.actionId === 'github.workspace.commit_branch') {
57 - const intentId = String(payload.input?.intentId || '');
58 - if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval input is invalid');
59 - return `wscommit:${repoId}:${intentId}`;
60 - }
61 -
62 - const runId = payload.input?.runId;
63 - if (!Number.isSafeInteger(Number(runId))) throw new Error('Approval input is invalid');
64 - if (payload.actionId === 'github.workflow.run.rerun_failed') return `rerun:${repoId}:${runId}`;
65 - if (payload.actionId === 'github.workflow.run.cancel') return `cancelrun:${repoId}:${runId}`;
66 - throw new Error('Approval action is not supported');
67 -}
68 -
69 -function approvalView({ label, token, cancelCallback = 'menu:main' }) {
70 - return {
71 - text:
72 -`⚠️ <b>تأیید عملیات لازم است</b>
73 -➖➖➖➖➖➖➖➖➖➖
74 -عملیات: <b>${label}</b>
75 -این عملیات روی GitHub تغییر ایجاد می‌کند و فقط پس از تأیید شما اجرا می‌شود.
76 -
77 -اگر مطمئن هستید، «تأیید و اجرا» را بزنید.`,
78 - reply_markup: {
79 - inline_keyboard: [
80 - [{ text: '✅ تأیید و اجرا', callback_data: `approve:${token}` }],
81 - [{ text: '↩️ انصراف', callback_data: cancelCallback }]
82 - ]
83 - }
84 - };
85 -}
86 -
87 -function approvalRejectedView(message, error) {
88 - const reason = String(error?.message || 'Approval rejected');
89 - const expired = /expired/i.test(reason);
90 - const used = /already used|replay/i.test(reason);
91 - const fallback = message?.reply_markup?.inline_keyboard
92 - ?.flat()
93 - .map(button => String(button?.callback_data || ''))
94 - .find(callback => callback && !callback.startsWith('approve:')) || 'menu:main';
95 -
96 - let detail = 'این تأیید معتبر نیست و هیچ تغییری اجرا نشد.';
97 - if (expired) detail = 'مهلت این تأیید تمام شده است و هیچ تغییری اجرا نشد.';
98 - if (used) detail = 'این تأیید قبلاً استفاده شده است و دوباره اجرا نمی‌شود.';
99 - const backText = fallback.startsWith('run:') ? '↩️ بازگشت به Run' : '↩️ بازگشت';
100 -
101 - return {
102 - text:
103 -`⚠️ <b>عملیات اجرا نشد</b>
104 -➖➖➖➖➖➖➖➖➖➖
105 -${detail}
106 -
107 -برای ادامه برگردید و در صورت نیاز یک تأیید تازه ایجاد کنید.`,
108 - reply_markup: { inline_keyboard: [[{ text: backText, callback_data: fallback }]] }
109 - };
110 -}
111 -
112 -export class NexaDevBot {
113 - constructor(env = {}) {
114 - this.env = env;
115 - this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
116 - this.github = new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER || 'davoodmehraban89');
117 - this.menu = new MenuManager(this.github);
118 - this.replayStore = new DurableApprovalReplayStore({ namespace: env.APPROVAL_REPLAY_GUARD });
119 - this.workspaceStore = new DurableWorkspaceStoreClient({ namespace: env.WORKSPACE_STORE });
120 - this.approvals = new ApprovalService({
121 - secret: env.APPROVAL_SIGNING_SECRET || env.TELEGRAM_WEBHOOK_SECRET || '',
122 - replayStore: this.replayStore
123 - });
124 - this.githubPlugin = createGitHubPlugin({
125 - github: this.github,
126 - menu: this.menu,
127 - workspaces: this.workspaceStore.isConfigured() ? this.workspaceStore : null
128 - });
129 - this.cloudflare = new CloudflareService({
130 - token: env.CLOUDFLARE_API_TOKEN || '',
131 - accountId: env.CLOUDFLARE_ACCOUNT_ID || '',
132 - workerName: env.CLOUDFLARE_WORKER_NAME || 'nexa-dev-bot'
133 - });
134 - this.cloudflarePlugin = createCloudflarePlugin({ cloudflare: this.cloudflare });
135 - this.registry = new PluginRegistry([this.githubPlugin, this.cloudflarePlugin]);
136 - this.policy = new ActionPolicy();
137 - this.audit = new AuditLogger({
138 - secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.CLOUDFLARE_API_TOKEN, env.APPROVAL_SIGNING_SECRET]
139 - });
140 - this.router = new PluginRouter({ registry: this.registry, policy: this.policy, audit: this.audit });
141 - }
142 -
143 - async handleUpdate(update) {
144 - if (!update) return { ok: false, error: 'Empty update' };
145 - if (update.callback_query) return this.handleCallbackQuery(update.callback_query);
146 - if (update.message) return this.handleMessage(update.message);
147 - return { ok: true, ignored: true };
148 - }
1 +import { NexaDevBot as LegacyNexaDevBot } from './bot-legacy.js';
2
3 +export class NexaDevBot extends LegacyNexaDevBot {
4 async handleCallbackQuery(query) {
151 - const callbackId = query.id;
152 - const data = query.data || 'menu:main';
153 - const message = query.message;
154 - const chatId = message?.chat?.id;
155 - const messageId = message?.message_id;
156 - const ownerId = query.from?.id;
157 -
158 - let callbackAnswered = true;
159 - try { await this.telegram.answerCallbackQuery(callbackId); } catch { callbackAnswered = false; }
160 - if (!chatId || !messageId) return { ok: false, error: 'Missing message context for callback', callbackAnswered };
161 -
162 - try {
163 - if (data.startsWith('approve:')) {
164 - if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
165 - const token = data.slice('approve:'.length);
166 - let payload;
5 + const data = query?.data || 'menu:main';
6 + const ownerId = query?.from?.id;
7 + const chatId = query?.message?.chat?.id;
8 + const messageId = query?.message?.message_id;
9 + if (data.startsWith('approve:') && ownerId !== undefined && ownerId !== null) {
10 + const token = data.slice(8);
11 + let preview = null;
12 + try { preview = await this.approvals.verify(token, { ownerId: String(ownerId), pluginId: 'github' }); } catch {}
13 + if (preview?.actionId === 'github.pull_request.merge') {
14 + let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
15 try {
168 - payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'github', risk: 'WRITE' });
16 + const payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'github', actionId: 'github.pull_request.merge', risk: 'DESTRUCTIVE' });
17 + const input = payload.input || {}; const source = `mergepr:${Number(input.repoId).toString(36)}:${Number(input.prNumber).toString(36)}:${input.headSha}`;
18 + const routed = await this.router.dispatchCallback(source, { isOwner: true, ownerId: String(ownerId), approved: true });
19 + if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved merge could not be dispatched');
20 + const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
21 + return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
22 } catch (error) {
170 - this.audit.log({ event: 'approval_rejected', pluginId: 'github', risk: 'WRITE', outcome: 'rejected', error: error?.message || 'Approval rejected' });
171 - const view = approvalRejectedView(message, error);
172 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
173 - return { ok: false, approvalRejected: true, error: error?.message || 'Approval rejected', callbackAnswered, edited: true, res };
23 + const text = `⚠️ <b>Merge اجرا نشد</b>\nهیچ Merge تأییدنشده‌ای انجام نشد.\n\n${String(error?.message || 'Approval rejected').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;')}`;
24 + const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ بازگشت', callback_data: 'menu:repos' }]] });
25 + return { ok: false, approvalRejected: true, error: error?.message, callbackAnswered, edited: true, res };
26 }
175 -
176 - this.audit.log({ event: 'approval_verified', pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, outcome: 'verified' });
177 - const sourceCallback = approvalSourceCallback(payload);
178 - let routed;
179 - try {
180 - routed = await this.router.dispatchCallback(sourceCallback, {
181 - isOwner: true,
182 - ownerId: String(ownerId),
183 - approved: true
184 - });
185 - if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved action could not be dispatched');
186 - } catch (error) {
187 - const view = await buildApprovedActionFailedView({
188 - payload,
189 - error,
190 - ownerId,
191 - workspaces: this.workspaceStore
192 - });
193 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
194 - return { ok: false, approved: true, providerError: true, actionId: payload.actionId, error: error?.message || 'GitHub operation failed', callbackAnswered, edited: true, res };
195 - }
196 -
197 - const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
198 - return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
27 }
200 -
201 - const routed = await this.router.dispatchCallback(data, {
202 - isOwner: true,
203 - ownerId: ownerId === undefined || ownerId === null ? '' : String(ownerId)
204 - });
205 - if (routed?.requiresApproval) {
206 - const approval = routed.approval;
207 - const repoId = approval?.input?.repoId;
208 - if (!approval || !Number.isSafeInteger(Number(repoId))) throw new Error('Approval metadata is missing');
209 - const workspaceApproval = routed.actionId === 'github.workspace.commit_branch';
210 - const runId = approval?.input?.runId;
211 - const intentId = String(approval?.input?.intentId || '');
212 - if (workspaceApproval) {
213 - if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Approval metadata is missing');
214 - } else if (!Number.isSafeInteger(Number(runId))) {
215 - throw new Error('Approval metadata is missing');
216 - }
28 + }
29 + if (data.startsWith('mergepr:')) {
30 + let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
31 + try {
32 + const routed = await this.router.dispatchCallback(data, { isOwner: true, ownerId: String(ownerId ?? '') });
33 + if (!routed?.requiresApproval || routed.actionId !== 'github.pull_request.merge') throw new Error(routed?.reason || 'Merge approval route unavailable');
34 if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
218 - if (!this.approvals.isReplayProtected()) throw new Error('Durable approval replay protection is not configured');
219 -
220 - const token = await this.approvals.issue({
221 - pluginId: routed.pluginId,
222 - actionId: routed.actionId,
223 - risk: routed.risk,
224 - ownerId: String(ownerId),
225 - input: approval.input
226 - });
227 - this.audit.log({ event: 'approval_issued', pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, outcome: 'pending' });
228 - const cancelCallback = approval.cancelCallback || (Number.isSafeInteger(Number(runId)) ? `run:${repoId}:${runId}` : `repo:${repoId}`);
229 - const view = approvalView({ label: approval.label || routed.actionId, token, cancelCallback });
230 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
35 + const token = await this.approvals.issue({ pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, ownerId: String(ownerId), input: routed.approval.input });
36 + const callback = `approve:${token}`; if (callback.length > 64) throw new Error('Approval callback exceeds Telegram limit');
37 + const text = `⚠️ <b>تأیید نهایی Merge لازم است</b>\nPR #${routed.approval.input.prNumber}\nHead: <code>${routed.approval.input.headSha.slice(0,12)}</code>\n\nMerge فقط برای همین Head و فقط یک‌بار قابل اجراست.`;
38 + const markup = { inline_keyboard: [[{ text: '✅ تأیید و Merge', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: routed.approval.cancelCallback }]] };
39 + const res = await this.telegram.editMessageText(chatId, messageId, text, markup);
40 return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
41 + } catch (error) {
42 + const text = `⚠️ <b>Merge آماده نشد</b>\n${String(error?.message || 'Merge unavailable').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;')}`;
43 + const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ پروژه‌ها', callback_data: 'menu:repos' }]] });
44 + return { ok: false, error: error?.message, callbackAnswered, edited: true, res };
45 }
233 - if (routed?.denied) return { ok: false, denied: true, actionId: routed.actionId, reason: routed.reason, callbackAnswered };
234 -
235 - const view = routed || await this.menu.renderByCallback(data);
236 - if (data.startsWith('wtext:') && routed) {
237 - const res = await this.telegram.sendMessage(chatId, view.text, focusedCodeInputMarkup());
238 - return { ok: true, inputPrompt: true, callbackAnswered, sent: true, res };
239 - }
240 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
241 - return { ok: true, edited: true, callbackAnswered, res };
242 - } catch (err) {
243 - if (err.message && err.message.includes('message is not modified')) return { ok: true, unmodified: true, callbackAnswered };
244 - if (!data.startsWith('approve:')) {
245 - try {
246 - const view = await buildCallbackFailureView({ data, error: err, ownerId, workspaces: this.workspaceStore });
247 - const res = await this.telegram.editMessageText(chatId, messageId, view.text, view.reply_markup);
248 - return {
249 - ok: false,
250 - error: err.message,
251 - providerError: !view.validationError,
252 - validationError: Boolean(view.validationError),
253 - callbackAnswered,
254 - edited: true,
255 - res
256 - };
257 - } catch {
258 - // Preserve the original provider/navigation error when feedback delivery also fails.
259 - }
260 - }
261 - return { ok: false, error: err.message, callbackAnswered };
262 - }
263 - }
264 -
265 - async handleMessage(message) {
266 - const chatId = message.chat?.id;
267 - const rawText = typeof message.text === 'string' ? message.text : '';
268 - const text = rawText.trim();
269 - if (!chatId) return { ok: false, error: 'Missing chat_id' };
270 -
271 - if (text === '/start' || text === '/menu' || text.startsWith('/start')) {
272 - const quickMenuRes = await this.telegram.sendMessage(
273 - chatId,
274 - '⌨️ <b>منوی سریع Nexa Dev فعال شد</b>\nاین منو پایین صفحه می‌ماند و از هر بخش قابل استفاده است.',
275 - persistentQuickMenuMarkup()
276 - );
277 - const view = this.menu.getMainMenuView();
278 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
279 - return { ok: true, command: 'start', persistentMenu: true, quickMenuRes, res };
280 - }
281 -
282 - const quickMenu = QUICK_MENU[text];
283 - if (quickMenu) {
284 - let view;
285 - if (quickMenu === 'main') {
286 - view = this.menu.getMainMenuView();
287 - } else if (quickMenu === 'repos') {
288 - const routed = await this.router.dispatchCommand('/repos', { isOwner: true });
289 - if (routed?.requiresApproval || routed?.denied || !routed) {
290 - return { ok: false, quickMenu, error: routed?.reason || 'GitHub repository route unavailable' };
291 - }
292 - view = routed;
293 - } else if (quickMenu === 'status') {
294 - view = this.menu.getServiceStatusView();
295 - } else if (quickMenu === 'tools') {
296 - view = this.menu.getToolsView();
297 - } else {
298 - view = this.menu.getSecurityView();
299 - }
300 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
301 - return { ok: true, quickMenu, res };
302 - }
303 -
304 - if (text === '/repos') {
305 - const routed = await this.router.dispatchCommand(text, { isOwner: true });
306 - if (routed?.requiresApproval || routed?.denied || !routed) {
307 - return { ok: false, command: 'repos', error: routed?.reason || 'GitHub repository route unavailable' };
308 - }
309 - const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
310 - return { ok: true, command: 'repos', res };
311 - }
312 -
313 - if (text === '/status') {
314 - const view = this.menu.getServiceStatusView();
315 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
316 - return { ok: true, command: 'status', res };
46 }
318 -
319 - const ownerId = message.from?.id;
320 - if (ownerId !== undefined && ownerId !== null && this.workspaceStore.isConfigured()) {
321 - const pending = await this.workspaceStore.getPendingInput({ ownerId: String(ownerId) });
322 - if (pending) {
323 - let payload = { pending, text: rawText };
324 - if (pending.mode === 'draft_file') {
325 - const document = message.document;
326 - const maxUploadBytes = WORKSPACE_EDITOR_LIMITS.maxBytes;
327 - if (!document?.file_id) {
328 - const view = {
329 - text: `📎 <b>یک فایل متنی ارسال کنید</b>\nاین Workspace در حالت بارگذاری فایل است. فایل باید UTF-8 معتبر و حداکثر ${maxUploadBytes.toLocaleString('en-US')} بایت باشد.`,
330 - reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
331 - };
332 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
333 - return { ok: true, workspaceInput: true, inputRequired: 'document', res };
334 - }
335 - if (Number.isFinite(Number(document.file_size)) && Number(document.file_size) > maxUploadBytes) {
336 - const view = {
337 - text: `⚠️ <b>فایل پذیرفته نشد</b>\nحجم فایل بیشتر از سقف ${maxUploadBytes.toLocaleString('en-US')} بایت است. Draft تغییر نکرد؛ یک فایل کوچک‌تر ارسال کنید.`,
338 - reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
339 - };
340 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
341 - return { ok: false, workspaceInput: true, inputRejected: true, error: `Telegram file exceeds ${maxUploadBytes} byte size limit`, res };
342 - }
343 - let downloaded;
344 - try {
345 - downloaded = await this.telegram.downloadTextFile(document.file_id, { maxBytes: maxUploadBytes });
346 - } catch (error) {
347 - const view = {
348 - text: `⚠️ <b>فایل پذیرفته نشد</b>\n${escapeHtml(error?.message || 'Telegram file download failed')}\n\nDraft تغییر نکرد و می‌توانید فایل دیگری ارسال کنید.`,
349 - reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${pending.workspaceId}` }]] }
350 - };
351 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
352 - return { ok: false, workspaceInput: true, inputRejected: true, error: error?.message || 'Telegram file download failed', res };
353 - }
354 - payload = {
355 - pending,
356 - file: {
357 - name: String(document.file_name || 'uploaded.txt'),
358 - text: downloaded.text,
359 - byteLength: downloaded.byteLength
360 - }
361 - };
362 - }
363 -
364 - const routed = await this.router.dispatchMessage(
365 - payload,
366 - { isOwner: true, ownerId: String(ownerId) }
367 - );
368 - if (routed?.requiresApproval || routed?.denied || !routed) {
369 - return { ok: false, error: routed?.reason || 'Workspace input route unavailable' };
370 - }
371 - const res = await this.telegram.sendMessage(chatId, routed.text, routed.reply_markup);
372 - return { ok: true, workspaceInput: true, res };
373 - }
374 - }
375 -
376 - const defaultText = '💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:';
377 - const view = {
378 - text: defaultText,
379 - reply_markup: {
380 - inline_keyboard: [[{ text: '⚡ باز کردن منوی اصلی Nexa Dev', callback_data: 'menu:main' }]]
381 - }
382 - };
383 - const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
384 - return { ok: true, default: true, res };
47 + return super.handleCallbackQuery(query);
48 }
49 }
src/core/approval.js
+44 -261
@@ -1,276 +1,59 @@
1 const encoder = new TextEncoder();
2 const SIGNING_DOMAIN = 'nexa-approval-v1';
3 const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
4 -
4 +const FULL_SHA_PATTERN = /^[a-f0-9]{40}$/i;
5 const DEFAULT_CODECS = new Map([
6 - ['github.workflow.run.rerun_failed', {
7 - code: 'r',
8 - pluginId: 'github',
9 - risk: 'WRITE',
10 - target: 'run'
11 - }],
12 - ['github.workflow.run.cancel', {
13 - code: 'c',
14 - pluginId: 'github',
15 - risk: 'WRITE',
16 - target: 'run'
17 - }],
18 - ['github.workspace.commit_branch', {
19 - code: 'e',
20 - pluginId: 'github',
21 - risk: 'WRITE',
22 - target: 'intent'
23 - }]
6 + ['github.workflow.run.rerun_failed', { code: 'r', pluginId: 'github', risk: 'WRITE', target: 'run' }],
7 + ['github.workflow.run.cancel', { code: 'c', pluginId: 'github', risk: 'WRITE', target: 'run' }],
8 + ['github.workspace.commit_branch', { code: 'e', pluginId: 'github', risk: 'WRITE', target: 'intent' }]
9 ]);
25 -
26 -const bytesToBase64Url = bytes => {
27 - let binary = '';
28 - for (const byte of bytes) binary += String.fromCharCode(byte);
29 - return btoa(binary)
30 - .replace(/\+/g, '-')
31 - .replace(/\//g, '_')
32 - .replace(/=+$/g, '');
33 -};
34 -
35 -const base64UrlToBytes = value => {
36 - const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
37 - const padding = '='.repeat((4 - (normalized.length % 4)) % 4);
38 - const binary = atob(normalized + padding);
39 - return Uint8Array.from(binary, char => char.charCodeAt(0));
40 -};
41 -
10 +const bytesToBase64Url = bytes => { let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); };
11 +const base64UrlToBytes = value => { const normalized = value.replace(/-/g, '+').replace(/_/g, '/'); const padding = '='.repeat((4 - (normalized.length % 4)) % 4); const binary = atob(normalized + padding); return Uint8Array.from(binary, char => char.charCodeAt(0)); };
12 const textToBase64Url = value => bytesToBase64Url(encoder.encode(value));
13 const base64UrlToText = value => new TextDecoder().decode(base64UrlToBytes(value));
44 -
45 -const toBase36Int = value => {
46 - const number = Number(value);
47 - if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input');
48 - return number.toString(36);
49 -};
50 -
51 -const fromBase36Int = value => {
52 - if (!/^[0-9a-z]+$/i.test(value)) throw new Error('Invalid approval numeric input');
53 - const number = Number.parseInt(value, 36);
54 - if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input');
55 - return number;
56 -};
57 -
58 -const constantTimeEqual = (left, right) => {
59 - if (left.length !== right.length) return false;
60 - let mismatch = 0;
61 - for (let index = 0; index < left.length; index += 1) mismatch |= left[index] ^ right[index];
62 - return mismatch === 0;
63 -};
64 -
14 +const toBase36Int = value => { const number = Number(value); if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input'); return number.toString(36); };
15 +const fromBase36Int = value => { if (!/^[0-9a-z]+$/i.test(value)) throw new Error('Invalid approval numeric input'); const number = Number.parseInt(value, 36); if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input'); return number; };
16 +const constantTimeEqual = (left, right) => { if (left.length !== right.length) return false; let mismatch = 0; for (let i = 0; i < left.length; i += 1) mismatch |= left[i] ^ right[i]; return mismatch === 0; };
17 const compactCodecFor = actionId => DEFAULT_CODECS.get(actionId) || null;
66 -const compactCodecByCode = code => {
67 - for (const [actionId, codec] of DEFAULT_CODECS.entries()) {
68 - if (codec.code === code) return { actionId, ...codec };
69 - }
70 - return null;
71 -};
18 +const compactCodecByCode = code => { for (const [actionId, codec] of DEFAULT_CODECS.entries()) if (codec.code === code) return { actionId, ...codec }; return null; };
19
20 export class ApprovalService {
74 - constructor({
75 - secret = '',
76 - now = () => Date.now(),
77 - ttlMs = 120_000,
78 - maxTokenLength = 56,
79 - signatureBytes = 12,
80 - replayStore = null
81 - } = {}) {
82 - this.secret = String(secret || '');
83 - this.now = now;
84 - this.ttlMs = ttlMs;
85 - this.maxTokenLength = maxTokenLength;
86 - this.signatureBytes = signatureBytes;
87 - if (replayStore && typeof replayStore.consume !== 'function') {
88 - throw new Error('Approval replay store is invalid');
89 - }
90 - this.replayStore = replayStore;
91 - this.keyPromise = null;
92 - }
93 -
94 - isReplayProtected() {
95 - return Boolean(this.replayStore && typeof this.replayStore.consume === 'function');
96 - }
97 -
21 + constructor({ secret = '', now = () => Date.now(), ttlMs = 120_000, maxTokenLength = 56, signatureBytes = 12, replayStore = null } = {}) { this.secret = String(secret || ''); this.now = now; this.ttlMs = ttlMs; this.maxTokenLength = maxTokenLength; this.signatureBytes = signatureBytes; if (replayStore && typeof replayStore.consume !== 'function') throw new Error('Approval replay store is invalid'); this.replayStore = replayStore; this.keyPromise = null; }
22 + isReplayProtected() { return Boolean(this.replayStore && typeof this.replayStore.consume === 'function'); }
23 async issue(payload = {}) {
99 - this.#assertSecret();
100 - const issuedAt = this.now();
101 - const expiresAt = issuedAt + this.ttlMs;
102 - const nonce = this.#nonce();
103 - const normalized = {
104 - v: 1,
105 - pluginId: payload.pluginId,
106 - actionId: payload.actionId,
107 - risk: payload.risk,
108 - ownerId: String(payload.ownerId ?? ''),
109 - input: payload.input ?? {},
110 - issuedAt,
111 - expiresAt,
112 - nonce
113 - };
114 -
24 + this.#assertSecret(); const issuedAt = this.now(); const expiresAt = issuedAt + this.ttlMs; const nonce = this.#nonce();
25 + const normalized = { v: 1, pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, ownerId: String(payload.ownerId ?? ''), input: payload.input ?? {}, issuedAt, expiresAt, nonce };
26 if (!normalized.ownerId) throw new Error('Approval owner is required');
116 -
117 - const body = this.#encodeBody(normalized);
118 - const signature = await this.#sign(normalized.ownerId, body);
119 - const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
120 - if (token.length > this.maxTokenLength) throw new Error('Approval token too large for callback data');
121 - return token;
27 + let body;
28 + if (normalized.actionId === 'github.pull_request.merge') {
29 + const { repoId, prNumber, headSha } = normalized.input || {};
30 + if (normalized.pluginId !== 'github' || normalized.risk !== 'DESTRUCTIVE' || !Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(prNumber)) || !FULL_SHA_PATTERN.test(String(headSha || ''))) throw new Error('Invalid pull request approval target');
31 + if (!this.replayStore || typeof this.replayStore.put !== 'function' || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
32 + await this.replayStore.put({ ownerId: normalized.ownerId, nonce, expiresAt, payload: normalized });
33 + body = `s.m.${toBase36Int(expiresAt)}.${nonce}`;
34 + } else body = this.#encodeBody(normalized);
35 + const signature = await this.#sign(normalized.ownerId, body); const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
36 + if (token.length > this.maxTokenLength) throw new Error('Approval token too large for callback data'); return token;
37 }
123 -
38 async verify(token, expectations = {}) {
125 - this.#assertSecret();
126 - if (!token || typeof token !== 'string') throw new Error('Invalid approval token');
127 - const ownerId = String(expectations.ownerId ?? '');
128 - if (!ownerId) throw new Error('Approval owner is required');
129 -
130 - const parts = token.split('.');
131 - if (parts.length < 3) throw new Error('Invalid approval token');
132 - const signaturePart = parts.pop();
133 - const body = parts.join('.');
134 -
135 - let suppliedSignature;
136 - try {
137 - suppliedSignature = base64UrlToBytes(signaturePart);
138 - } catch {
139 - throw new Error('Invalid approval signature');
140 - }
141 -
142 - const expectedSignature = (await this.#sign(ownerId, body)).slice(0, this.signatureBytes);
143 - if (!constantTimeEqual(suppliedSignature, expectedSignature)) {
144 - throw new Error('Invalid approval signature or owner mismatch');
145 - }
146 -
147 - const payload = this.#decodeBody(body, ownerId);
148 - if (payload.expiresAt < this.now()) throw new Error('Approval token expired');
149 - if (expectations.pluginId && payload.pluginId !== expectations.pluginId) throw new Error('Approval plugin mismatch');
150 - if (expectations.actionId && payload.actionId !== expectations.actionId) throw new Error('Approval action mismatch');
151 - if (expectations.risk && payload.risk !== expectations.risk) throw new Error('Approval risk mismatch');
152 - return payload;
153 - }
154 -
155 - async consume(token, expectations = {}) {
156 - const payload = await this.verify(token, expectations);
157 - if (!this.isReplayProtected()) {
158 - throw new Error('Durable approval replay protection is not configured');
159 - }
160 -
161 - const accepted = await this.replayStore.consume({
162 - ownerId: payload.ownerId,
163 - nonce: payload.nonce,
164 - expiresAt: payload.expiresAt
165 - });
166 - if (!accepted) throw new Error('Approval token already used');
167 - return payload;
168 - }
169 -
170 - #encodeBody(payload) {
171 - const codec = compactCodecFor(payload.actionId);
172 - const repoId = payload.input?.repoId;
173 - if (
174 - codec &&
175 - codec.pluginId === payload.pluginId &&
176 - codec.risk === payload.risk &&
177 - Number.isSafeInteger(Number(repoId))
178 - ) {
179 - let target;
180 - if (codec.target === 'run') {
181 - const runId = payload.input?.runId;
182 - if (!Number.isSafeInteger(Number(runId))) return `j.${textToBase64Url(JSON.stringify(payload))}`;
183 - target = toBase36Int(runId);
184 - } else if (codec.target === 'intent') {
185 - const intentId = String(payload.input?.intentId || '');
186 - if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Invalid approval intent ID');
187 - target = intentId;
188 - } else {
189 - return `j.${textToBase64Url(JSON.stringify(payload))}`;
190 - }
191 - return [
192 - '1',
193 - codec.code,
194 - toBase36Int(repoId),
195 - target,
196 - toBase36Int(payload.expiresAt),
197 - payload.nonce
198 - ].join('.');
199 - }
200 -
201 - return `j.${textToBase64Url(JSON.stringify(payload))}`;
202 - }
203 -
204 - #decodeBody(body, ownerId) {
205 - if (body.startsWith('j.')) {
206 - let payload;
207 - try {
208 - payload = JSON.parse(base64UrlToText(body.slice(2)));
209 - } catch {
210 - throw new Error('Invalid approval payload');
211 - }
212 - if (String(payload.ownerId ?? '') !== ownerId) throw new Error('Approval owner mismatch');
213 - return payload;
214 - }
215 -
216 - const parts = body.split('.');
217 - if (parts.length !== 6 || parts[0] !== '1') throw new Error('Invalid approval payload');
218 - const [, code, repoPart, targetPart, expiryPart, nonce] = parts;
219 - const codec = compactCodecByCode(code);
220 - if (!codec) throw new Error('Invalid approval action');
221 - const expiresAt = fromBase36Int(expiryPart);
222 - const input = { repoId: fromBase36Int(repoPart) };
223 - if (codec.target === 'run') {
224 - input.runId = fromBase36Int(targetPart);
225 - } else if (codec.target === 'intent') {
226 - if (!INTENT_ID_PATTERN.test(targetPart)) throw new Error('Invalid approval intent ID');
227 - input.intentId = targetPart;
228 - } else {
229 - throw new Error('Invalid approval target');
230 - }
231 - return {
232 - v: 1,
233 - pluginId: codec.pluginId,
234 - actionId: codec.actionId,
235 - risk: codec.risk,
236 - ownerId,
237 - input,
238 - issuedAt: expiresAt - this.ttlMs,
239 - expiresAt,
240 - nonce
241 - };
242 - }
243 -
244 - async #sign(ownerId, body) {
245 - const key = await this.#key();
246 - const signature = await crypto.subtle.sign(
247 - 'HMAC',
248 - key,
249 - encoder.encode(`${SIGNING_DOMAIN}|${ownerId}|${body}`)
250 - );
251 - return new Uint8Array(signature);
252 - }
253 -
254 - async #key() {
255 - if (!this.keyPromise) {
256 - this.keyPromise = crypto.subtle.importKey(
257 - 'raw',
258 - encoder.encode(this.secret),
259 - { name: 'HMAC', hash: 'SHA-256' },
260 - false,
261 - ['sign']
262 - );
263 - }
264 - return this.keyPromise;
265 - }
266 -
267 - #nonce() {
268 - const bytes = new Uint8Array(6);
269 - crypto.getRandomValues(bytes);
270 - return bytesToBase64Url(bytes);
271 - }
272 -
273 - #assertSecret() {
274 - if (!this.secret) throw new Error('Approval signing secret is required');
275 - }
39 + this.#assertSecret(); if (!token || typeof token !== 'string') throw new Error('Invalid approval token'); const ownerId = String(expectations.ownerId ?? ''); if (!ownerId) throw new Error('Approval owner is required');
40 + const parts = token.split('.'); if (parts.length < 3) throw new Error('Invalid approval token'); const signaturePart = parts.pop(); const body = parts.join('.'); let suppliedSignature;
41 + try { suppliedSignature = base64UrlToBytes(signaturePart); } catch { throw new Error('Invalid approval signature'); }
42 + const expectedSignature = (await this.#sign(ownerId, body)).slice(0, this.signatureBytes); if (!constantTimeEqual(suppliedSignature, expectedSignature)) throw new Error('Invalid approval signature or owner mismatch');
43 + let payload;
44 + if (body.startsWith('s.m.')) {
45 + const state = body.split('.'); if (state.length !== 4) throw new Error('Invalid approval payload'); const expiresAt = fromBase36Int(state[2]); const nonce = state[3]; if (expiresAt < this.now()) throw new Error('Approval token expired');
46 + if (!this.replayStore || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
47 + payload = await this.replayStore.peek({ ownerId, nonce }); if (!payload) throw new Error('Approval context is unavailable');
48 + if (payload.expiresAt !== expiresAt || payload.nonce !== nonce || payload.ownerId !== ownerId || payload.actionId !== 'github.pull_request.merge') throw new Error('Approval context mismatch');
49 + } else payload = this.#decodeBody(body, ownerId);
50 + if (payload.expiresAt < this.now()) throw new Error('Approval token expired'); if (expectations.pluginId && payload.pluginId !== expectations.pluginId) throw new Error('Approval plugin mismatch'); if (expectations.actionId && payload.actionId !== expectations.actionId) throw new Error('Approval action mismatch'); if (expectations.risk && payload.risk !== expectations.risk) throw new Error('Approval risk mismatch'); return payload;
51 + }
52 + async consume(token, expectations = {}) { const payload = await this.verify(token, expectations); if (!this.isReplayProtected()) throw new Error('Durable approval replay protection is not configured'); const accepted = await this.replayStore.consume({ ownerId: payload.ownerId, nonce: payload.nonce, expiresAt: payload.expiresAt }); if (!accepted) throw new Error('Approval token already used'); return payload; }
53 + #encodeBody(payload) { const codec = compactCodecFor(payload.actionId); const repoId = payload.input?.repoId; if (codec && codec.pluginId === payload.pluginId && codec.risk === payload.risk && Number.isSafeInteger(Number(repoId))) { let target; if (codec.target === 'run') { const runId = payload.input?.runId; if (!Number.isSafeInteger(Number(runId))) return `j.${textToBase64Url(JSON.stringify(payload))}`; target = toBase36Int(runId); } else if (codec.target === 'intent') { const intentId = String(payload.input?.intentId || ''); if (!INTENT_ID_PATTERN.test(intentId)) throw new Error('Invalid approval intent ID'); target = intentId; } else return `j.${textToBase64Url(JSON.stringify(payload))}`; return ['1', codec.code, toBase36Int(repoId), target, toBase36Int(payload.expiresAt), payload.nonce].join('.'); } return `j.${textToBase64Url(JSON.stringify(payload))}`; }
54 + #decodeBody(body, ownerId) { if (body.startsWith('j.')) { let payload; try { payload = JSON.parse(base64UrlToText(body.slice(2))); } catch { throw new Error('Invalid approval payload'); } if (String(payload.ownerId ?? '') !== ownerId) throw new Error('Approval owner mismatch'); return payload; } const parts = body.split('.'); if (parts.length !== 6 || parts[0] !== '1') throw new Error('Invalid approval payload'); const [, code, repoPart, targetPart, expiryPart, nonce] = parts; const codec = compactCodecByCode(code); if (!codec) throw new Error('Invalid approval action'); const expiresAt = fromBase36Int(expiryPart); const input = { repoId: fromBase36Int(repoPart) }; if (codec.target === 'run') input.runId = fromBase36Int(targetPart); else if (codec.target === 'intent') { if (!INTENT_ID_PATTERN.test(targetPart)) throw new Error('Invalid approval intent ID'); input.intentId = targetPart; } return { v: 1, pluginId: codec.pluginId, actionId: codec.actionId, risk: codec.risk, ownerId, input, issuedAt: expiresAt - this.ttlMs, expiresAt, nonce }; }
55 + async #sign(ownerId, body) { const key = await this.#key(); const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(`${SIGNING_DOMAIN}|${ownerId}|${body}`)); return new Uint8Array(signature); }
56 + async #key() { if (!this.keyPromise) this.keyPromise = crypto.subtle.importKey('raw', encoder.encode(this.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); return this.keyPromise; }
57 + #nonce() { const bytes = new Uint8Array(6); crypto.getRandomValues(bytes); return bytesToBase64Url(bytes); }
58 + #assertSecret() { if (!this.secret) throw new Error('Approval signing secret is required'); }
59 }
src/core/durable-replay-store.js
+21 -39
@@ -1,47 +1,29 @@
1 export class DurableApprovalReplayStore {
2 - constructor({ namespace } = {}) {
3 - this.namespace = namespace || null;
2 + constructor({ namespace } = {}) { this.namespace = namespace || null; }
3 + isConfigured() { return Boolean(this.namespace && typeof this.namespace.idFromName === 'function' && typeof this.namespace.get === 'function'); }
4 + #stub(ownerId, nonce) {
5 + if (!this.isConfigured()) throw new Error('Durable approval replay protection is not configured');
6 + const owner = String(ownerId ?? ''); const nonceValue = String(nonce ?? '');
7 + if (!owner || !nonceValue) throw new Error('Invalid durable approval replay input');
8 + return this.namespace.get(this.namespace.idFromName(`${owner}:${nonceValue}`));
9 }
5 -
6 - isConfigured() {
7 - return Boolean(
8 - this.namespace &&
9 - typeof this.namespace.idFromName === 'function' &&
10 - typeof this.namespace.get === 'function'
11 - );
10 + async put({ ownerId, nonce, expiresAt, payload } = {}) {
11 + const expiry = Number(expiresAt); if (!Number.isFinite(expiry) || !payload) throw new Error('Invalid durable approval replay input');
12 + const response = await this.#stub(ownerId, nonce).fetch(new Request('https://approval-replay/prepare', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ expiresAt: expiry, payload }) }));
13 + if (!response.ok) throw new Error(`Durable approval preparation failed (${response.status})`);
14 + return true;
15 + }
16 + async peek({ ownerId, nonce } = {}) {
17 + const response = await this.#stub(ownerId, nonce).fetch(new Request('https://approval-replay/peek'));
18 + if (!response.ok) return null;
19 + const body = await response.json().catch(() => null); return body?.payload || null;
20 }
13 -
21 async consume({ ownerId, nonce, expiresAt } = {}) {
15 - if (!this.isConfigured()) {
16 - throw new Error('Durable approval replay protection is not configured');
17 - }
18 -
19 - const owner = String(ownerId ?? '');
20 - const nonceValue = String(nonce ?? '');
21 - const expiry = Number(expiresAt);
22 - if (!owner || !nonceValue || !Number.isFinite(expiry)) {
23 - throw new Error('Invalid durable approval replay input');
24 - }
25 -
26 - const id = this.namespace.idFromName(`${owner}:${nonceValue}`);
27 - const stub = this.namespace.get(id);
28 - const response = await stub.fetch(new Request('https://approval-replay/consume', {
29 - method: 'POST',
30 - headers: { 'content-type': 'application/json' },
31 - body: JSON.stringify({ expiresAt: expiry })
32 - }));
33 -
34 - let body = null;
35 - try {
36 - body = await response.json();
37 - } catch {
38 - body = null;
39 - }
40 -
22 + const expiry = Number(expiresAt); if (!Number.isFinite(expiry)) throw new Error('Invalid durable approval replay input');
23 + const response = await this.#stub(ownerId, nonce).fetch(new Request('https://approval-replay/consume', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ expiresAt: expiry }) }));
24 + const body = await response.json().catch(() => null);
25 if (response.status === 409 || response.status === 410) return false;
42 - if (!response.ok || body?.accepted !== true) {
43 - throw new Error(`Durable approval replay protection failed (${response.status})`);
44 - }
26 + if (!response.ok || body?.accepted !== true) throw new Error(`Durable approval replay protection failed (${response.status})`);
27 return true;
28 }
29 }
src/durable/approval-replay-guard.js
+24 -38
@@ -1,47 +1,33 @@
1 const json = (payload, status = 200) => Response.json(payload, { status });
2
3 export class ApprovalReplayGuard {
4 - constructor(state) {
5 - this.state = state;
6 - }
7 -
4 + constructor(state) { this.state = state; }
5 async fetch(request) {
6 const url = new URL(request.url);
10 - if (request.method !== 'POST' || url.pathname !== '/consume') {
11 - return new Response('Not Found', { status: 404 });
12 - }
13 -
14 - let payload;
15 - try {
16 - payload = await request.json();
17 - } catch {
18 - return json({ accepted: false, reason: 'invalid_payload' }, 400);
19 - }
20 -
21 - const expiresAt = Number(payload?.expiresAt);
22 - if (!Number.isFinite(expiresAt)) {
23 - return json({ accepted: false, reason: 'invalid_expiry' }, 400);
7 + if (request.method === 'POST' && url.pathname === '/prepare') {
8 + const payload = await request.json().catch(() => null); const expiresAt = Number(payload?.expiresAt);
9 + if (!Number.isFinite(expiresAt) || expiresAt < Date.now() || !payload?.payload) return json({ prepared: false }, 400);
10 + const prepared = await this.state.storage.transaction(async txn => {
11 + if (await txn.get('used')) return false;
12 + const existing = await txn.get('payload');
13 + if (existing) return JSON.stringify(existing) === JSON.stringify(payload.payload);
14 + await txn.put('payload', payload.payload); await txn.put('expiresAt', expiresAt); return true;
15 + });
16 + if (!prepared) return json({ prepared: false }, 409);
17 + await this.state.storage.setAlarm(expiresAt); return json({ prepared: true });
18 }
25 - if (expiresAt < Date.now()) {
26 - return json({ accepted: false, reason: 'expired' }, 410);
19 + if (request.method === 'GET' && url.pathname === '/peek') {
20 + const expiresAt = Number(await this.state.storage.get('expiresAt'));
21 + if (!Number.isFinite(expiresAt) || expiresAt < Date.now() || await this.state.storage.get('used')) return json({ payload: null }, 404);
22 + return json({ payload: await this.state.storage.get('payload') || null });
23 }
28 -
29 - const accepted = await this.state.storage.transaction(async txn => {
30 - const usedUntil = await txn.get('used');
31 - if (usedUntil) return false;
32 - await txn.put('used', expiresAt);
33 - return true;
34 - });
35 -
36 - if (!accepted) {
37 - return json({ accepted: false, reason: 'already_used' }, 409);
38 - }
39 -
40 - await this.state.storage.setAlarm(expiresAt);
41 - return json({ accepted: true });
42 - }
43 -
44 - async alarm() {
45 - await this.state.storage.deleteAll();
24 + if (request.method !== 'POST' || url.pathname !== '/consume') return new Response('Not Found', { status: 404 });
25 + const payload = await request.json().catch(() => null); const expiresAt = Number(payload?.expiresAt);
26 + if (!Number.isFinite(expiresAt)) return json({ accepted: false, reason: 'invalid_expiry' }, 400);
27 + if (expiresAt < Date.now()) return json({ accepted: false, reason: 'expired' }, 410);
28 + const accepted = await this.state.storage.transaction(async txn => { const usedUntil = await txn.get('used'); if (usedUntil) return false; await txn.put('used', expiresAt); return true; });
29 + if (!accepted) return json({ accepted: false, reason: 'already_used' }, 409);
30 + await this.state.storage.setAlarm(expiresAt); return json({ accepted: true });
31 }
32 + async alarm() { await this.state.storage.deleteAll(); }
33 }
src/github.js
+53 -485
@@ -3,493 +3,61 @@ import { DEFAULT_CONFIG } from './config.js';
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 -const gitBranch = value => {
17 - const branch = String(value || '');
18 - if (!branch || branch.includes('..') || branch.startsWith('/') || branch.endsWith('/') || branch.includes('\0')) {
19 - throw new Error('Invalid Git branch');
20 - }
21 - return branch;
22 -};
6 +const numericId = (value, label) => { const text = String(value ?? ''); if (!/^\d+$/.test(text)) throw new Error(`Invalid ${label} ID`); return text; };
7 +const fullSha = (value, label = 'Git commit') => { const text = String(value || ''); if (!/^[a-f0-9]{40}$/i.test(text)) throw new Error(`Invalid ${label} SHA`); return text; };
8 +const gitBranch = value => { const branch = String(value || ''); if (!branch || branch.includes('..') || branch.startsWith('/') || branch.endsWith('/') || branch.includes('\0')) throw new Error('Invalid Git branch'); return branch; };
9 const encodedBranch = value => gitBranch(value).split('/').map(encodeURIComponent).join('/');
10 const encodedPath = value => String(value || '').split('/').filter(Boolean).map(encodeURIComponent).join('/');
25 -const decodeBase64Utf8 = value => {
26 - let binary;
27 - try {
28 - binary = atob(String(value || '').replace(/\s/g, ''));
29 - } catch {
30 - throw new Error('GitHub file content is not valid base64');
31 - }
32 - const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
33 - try {
34 - return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
35 - } catch {
36 - throw new Error('GitHub file content is not valid UTF-8 text');
37 - }
38 -};
11 +const decodeBase64Utf8 = value => { let binary; try { binary = atob(String(value || '').replace(/\s/g, '')); } catch { throw new Error('GitHub file content is not valid base64'); } const bytes = Uint8Array.from(binary, char => char.charCodeAt(0)); try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { throw new Error('GitHub file content is not valid UTF-8 text'); } };
12
13 export class GitHubService {
41 - constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) {
42 - this.token = token;
43 - this.owner = owner;
44 - this.baseUrl = 'https://api.github.com';
45 - }
46 -
47 - requireToken() {
48 - if (!this.token) throw new Error('GITHUB_TOKEN is not configured');
49 - }
50 -
51 - getHeaders() {
52 - this.requireToken();
53 - return {
54 - 'User-Agent': 'Nexa-Dev-Bot-v1.1',
55 - 'Accept': 'application/vnd.github+json',
56 - 'Authorization': `Bearer ${this.token}`,
57 - 'X-GitHub-Api-Version': '2022-11-28'
58 - };
59 - }
60 -
61 - async requestJson(url, label, { method = 'GET', body, allowEmpty = false, allowNotFound = false } = {}) {
62 - const headers = this.getHeaders();
63 - const options = { method, headers };
64 - if (body !== undefined) {
65 - options.body = JSON.stringify(body);
66 - options.headers = { ...headers, 'Content-Type': 'application/json' };
67 - }
68 - const res = await fetch(url, options);
69 - const raw = await res.text();
70 - let parsed = null;
71 - if (raw) {
72 - try { parsed = JSON.parse(raw); } catch { parsed = null; }
73 - }
74 - if (!res.ok) {
75 - if (allowNotFound && res.status === 404) return null;
76 - const providerMessage = parsed?.message || raw.slice(0, 240);
77 - const detail = providerMessage ? ` ${providerMessage}` : '';
78 - const error = new Error(`${label} failed: ${res.status}${detail}`);
79 - error.status = res.status;
80 - throw error;
81 - }
82 - if (allowEmpty) return { accepted: true, status: res.status };
83 - if (!raw) return null;
84 - if (parsed === null) throw new Error(`${label} failed: invalid JSON response`);
85 - return parsed;
86 - }
87 -
88 - async requestText(url, label, { maxChars = 12000 } = {}) {
89 - const res = await fetch(url, { method: 'GET', headers: this.getHeaders() });
90 - const raw = await res.text();
91 - if (!res.ok) {
92 - const detail = raw ? ` ${raw.slice(0, 240)}` : '';
93 - throw new Error(`${label} failed: ${res.status}${detail}`);
94 - }
95 - const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000));
96 - return { text: raw.length > limit ? raw.slice(-limit) : raw, truncated: raw.length > limit };
97 - }
98 -
99 - repoUrl(repo, suffix = '') {
100 - return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`;
101 - }
102 -
103 - repositoryLookupUrl(repoRef) {
104 - const value = String(repoRef || '');
105 - return /^\d+$/.test(value) ? `${this.baseUrl}/repositories/${value}` : this.repoUrl(value);
106 - }
107 -
108 - repositoryApiBase(fullName) {
109 - const parts = String(fullName || '').split('/').filter(Boolean);
110 - if (parts.length !== 2) throw new Error('GitHub repository full_name is invalid');
111 - return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`;
112 - }
113 -
114 - async getRepositoryContext(repoRef) {
115 - const value = String(repoRef || '');
116 - try {
117 - const raw = await this.requestJson(this.repositoryLookupUrl(value), 'GitHub repository');
118 - return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
119 - } catch (error) {
120 - if (!/^\d+$/.test(value) || error?.status !== 404) throw error;
121 -
122 - const repositories = await this.listRepositories();
123 - const match = repositories.find(repo => repo.id === value);
124 - if (!match?.fullName) throw error;
125 -
126 - const apiBase = this.repositoryApiBase(match.fullName);
127 - const raw = await this.requestJson(apiBase, 'GitHub repository');
128 - return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
129 - }
130 - }
131 -
132 - mapRepository(r) {
133 - return {
134 - id: String(r.id ?? r.name), name: r.name, fullName: r.full_name, private: !!r.private,
135 - description: r.description || '', defaultBranch: r.default_branch || 'main', archived: !!r.archived,
136 - htmlUrl: r.html_url || '', stars: r.stargazers_count ?? 0, forks: r.forks_count ?? 0
137 - };
138 - }
139 -
140 - mapWorkflowRun(run = {}) {
141 - return {
142 - id: run.id, name: run.name || 'Workflow', status: run.status || '', conclusion: run.conclusion || null,
143 - event: run.event || '', branch: run.head_branch || '', sha: String(run.head_sha || '').slice(0, 7),
144 - runNumber: run.run_number ?? null, url: run.html_url || '', createdAt: run.created_at || '', updatedAt: run.updated_at || ''
145 - };
146 - }
147 -
148 - mapWorkflowJob(job = {}) {
149 - return {
150 - id: job.id, name: job.name || 'Job', status: job.status || '', conclusion: job.conclusion || null,
151 - startedAt: job.started_at || '', completedAt: job.completed_at || '', url: job.html_url || '',
152 - steps: (job.steps || []).slice(0, 30).map(step => ({
153 - number: step.number, name: step.name || 'Step', status: step.status || '', conclusion: step.conclusion || null
154 - }))
155 - };
156 - }
157 -
158 - mapPullRequestFile(file = {}) {
159 - return {
160 - filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0,
161 - deletions: file.deletions ?? 0, changes: file.changes ?? 0, patch: boundedPatch(file.patch)
162 - };
163 - }
164 -
165 - mapIssue(issue = {}) {
166 - return {
167 - number: issue.number,
168 - title: issue.title || '',
169 - state: issue.state || '',
170 - author: issue.user?.login || 'unknown',
171 - comments: issue.comments ?? 0,
172 - url: issue.html_url || ''
173 - };
174 - }
175 -
176 - async listRepositories() {
177 - const data = await this.requestJson(`${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`, 'GitHub repositories');
178 - return data.map(r => { const repo = this.mapRepository(r); return { ...repo, title: `${repo.name} ${repo.private ? '🔒' : '🌐'}` }; });
179 - }
180 -
181 - async getRepository(repoRef) {
182 - const { raw } = await this.getRepositoryContext(repoRef);
183 - return this.mapRepository(raw);
184 - }
185 -
186 - async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) {
187 - const count = clampPerPage(perPage, 10);
188 - const pageNumber = clampPage(page);
189 - const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
190 - const { apiBase } = await this.getRepositoryContext(repoRef);
191 - const data = await this.requestJson(`${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`, 'GitHub pull requests');
192 - return data.map(pr => ({
193 - number: pr.number, title: pr.title, author: pr.user?.login || 'unknown', state: pr.state,
194 - merged: !!pr.merged_at, createdAt: pr.created_at, url: pr.html_url
195 - }));
196 - }
197 -
198 - async getPullRequest(repoRef, prNumber) {
199 - const number = numericId(prNumber, 'pull request');
200 - const { apiBase } = await this.getRepositoryContext(repoRef);
201 - const pr = await this.requestJson(`${apiBase}/pulls/${number}`, 'GitHub pull request');
202 - return {
203 - number: pr.number, title: pr.title || '', author: pr.user?.login || 'unknown', state: pr.state || '',
204 - merged: !!(pr.merged ?? pr.merged_at), body: pr.body || '', url: pr.html_url || '', head: pr.head?.ref || '',
205 - headSha: pr.head?.sha || '', base: pr.base?.ref || '', additions: pr.additions ?? 0,
206 - deletions: pr.deletions ?? 0, changedFiles: pr.changed_files ?? 0
207 - };
208 - }
209 -
210 - async listPullRequestFiles(repoRef, prNumber, { perPage = 20, page = 1 } = {}) {
211 - const number = numericId(prNumber, 'pull request');
212 - const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
213 - const { apiBase } = await this.getRepositoryContext(repoRef);
214 - const data = await this.requestJson(`${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`, 'GitHub pull request files');
215 - return data.map(file => this.mapPullRequestFile(file));
216 - }
217 -
218 - async listCommits(repoRef) {
219 - const { apiBase } = await this.getRepositoryContext(repoRef);
220 - const data = await this.requestJson(`${apiBase}/commits?per_page=5`, 'GitHub commits');
221 - return data.map(c => ({
222 - sha: String(c.sha || '').slice(0, 7),
223 - fullSha: String(c.sha || ''),
224 - message: String(c.commit?.message || '').split('\n')[0],
225 - author: c.author?.login || c.commit?.author?.name || 'Unknown',
226 - date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : ''
227 - }));
228 - }
229 -
230 - async getCommit(repoRef, sha) {
231 - const commitSha = fullSha(sha);
232 - const { apiBase } = await this.getRepositoryContext(repoRef);
233 - const c = await this.requestJson(`${apiBase}/commits/${commitSha}`, 'GitHub commit');
234 - const files = (c.files || []).slice(0, 20).map(file => ({
235 - filename: file.filename || '',
236 - status: file.status || '',
237 - additions: file.additions ?? 0,
238 - deletions: file.deletions ?? 0,
239 - changes: file.changes ?? 0
240 - }));
241 - return {
242 - sha: commitSha,
243 - shortSha: commitSha.slice(0, 7),
244 - message: String(c.commit?.message || ''),
245 - author: c.author?.login || c.commit?.author?.name || 'Unknown',
246 - date: c.commit?.author?.date || '',
247 - additions: c.stats?.additions ?? 0,
248 - deletions: c.stats?.deletions ?? 0,
249 - changedFiles: files.length,
250 - files
251 - };
252 - }
253 -
254 - async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) {
255 - const commitSha = fullSha(sha); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
256 - const { apiBase } = await this.getRepositoryContext(repoRef);
257 - const data = await this.requestJson(`${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`, 'GitHub check runs');
258 - return (data.check_runs || []).map(check => ({ id: check.id, name: check.name || 'Check', status: check.status || '', conclusion: check.conclusion || null, url: check.html_url || '' }));
259 - }
260 -
261 - async listFiles(repoRef, path = '', { ref } = {}) {
262 - const { apiBase } = await this.getRepositoryContext(repoRef);
263 - const suffix = path ? `/contents/${encodedPath(path)}` : '/contents';
264 - const query = ref ? `?ref=${encodeURIComponent(String(ref))}` : '';
265 - const data = await this.requestJson(`${apiBase}${suffix}${query}`, 'GitHub contents');
266 - if (!Array.isArray(data)) throw new Error('GitHub contents response is not a directory listing');
267 - return data.map(item => ({ name: item.name, path: item.path, type: item.type === 'dir' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' }));
268 - }
269 -
270 - async getGitRef(repoRef, branch, { allowMissing = false } = {}) {
271 - const branchName = gitBranch(branch);
272 - const { apiBase } = await this.getRepositoryContext(repoRef);
273 - const data = await this.requestJson(
274 - `${apiBase}/git/ref/heads/${encodedBranch(branchName)}`,
275 - 'GitHub branch ref',
276 - { allowNotFound: allowMissing }
277 - );
278 - if (data === null) return null;
279 - return { branch: branchName, sha: fullSha(data?.object?.sha, 'Git branch head') };
280 - }
281 -
282 - async getBranchSnapshot(repoRef, branch) {
283 - const branchName = gitBranch(branch);
284 - const { apiBase } = await this.getRepositoryContext(repoRef);
285 - const ref = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref');
286 - const headSha = fullSha(ref?.object?.sha, 'Git branch head');
287 - const commit = await this.requestJson(`${apiBase}/git/commits/${headSha}`, 'GitHub branch commit');
288 - const treeSha = fullSha(commit?.tree?.sha, 'Git tree');
289 - return { branch: branchName, headSha, treeSha };
290 - }
291 -
292 - async getFileAtRef(repoRef, path, ref) {
293 - const filePath = String(path || '');
294 - if (!filePath || filePath.startsWith('/') || filePath.includes('\0')) throw new Error('Invalid GitHub file path');
295 - const commitRef = fullSha(ref);
296 - const { apiBase } = await this.getRepositoryContext(repoRef);
297 - const data = await this.requestJson(`${apiBase}/contents/${encodedPath(filePath)}?ref=${commitRef}`, 'GitHub file');
298 - if (!data || Array.isArray(data) || data.type !== 'file') throw new Error('GitHub contents response is not a file');
299 - if (data.encoding !== 'base64') throw new Error('GitHub file encoding is not supported');
300 - const content = decodeBase64Utf8(data.content || '');
301 - return {
302 - path: data.path || filePath,
303 - sha: String(data.sha || ''),
304 - size: Number(data.size) || 0,
305 - encoding: 'utf-8',
306 - content
307 - };
308 - }
309 -
310 - async createGitBlob(repoRef, text) {
311 - const { apiBase } = await this.getRepositoryContext(repoRef);
312 - const data = await this.requestJson(`${apiBase}/git/blobs`, 'GitHub create blob', {
313 - method: 'POST',
314 - body: { content: String(text ?? ''), encoding: 'utf-8' }
315 - });
316 - return { sha: fullSha(data?.sha, 'Git blob') };
317 - }
318 -
319 - async createGitTree(repoRef, { baseTreeSha, entries } = {}) {
320 - const base = fullSha(baseTreeSha, 'Git base tree');
321 - if (!Array.isArray(entries)) throw new Error('Git tree entries are required');
322 - const tree = entries.map(entry => {
323 - const path = String(entry?.path || '');
324 - if (!path || path.startsWith('/') || path.includes('\0')) throw new Error('Invalid Git tree path');
325 - if (entry?.mode !== '100644' || entry?.type !== 'blob') throw new Error('Unsupported Git tree entry');
326 - return { path, mode: '100644', type: 'blob', sha: fullSha(entry.sha, 'Git blob') };
327 - });
328 - const { apiBase } = await this.getRepositoryContext(repoRef);
329 - const data = await this.requestJson(`${apiBase}/git/trees`, 'GitHub create tree', {
330 - method: 'POST',
331 - body: { base_tree: base, tree }
332 - });
333 - return { sha: fullSha(data?.sha, 'Git tree') };
334 - }
335 -
336 - async createGitCommit(repoRef, { message, treeSha, parentSha, timestamp } = {}) {
337 - const commitMessage = String(message || '');
338 - if (!commitMessage) throw new Error('Git commit message is required');
339 - const tree = fullSha(treeSha, 'Git tree');
340 - const parent = fullSha(parentSha, 'Git parent commit');
341 - const date = new Date(String(timestamp || ''));
342 - if (Number.isNaN(date.getTime()) || date.toISOString() !== String(timestamp)) throw new Error('Invalid Git commit timestamp');
343 - const identity = { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: String(timestamp) };
344 - const { apiBase } = await this.getRepositoryContext(repoRef);
345 - const data = await this.requestJson(`${apiBase}/git/commits`, 'GitHub create commit', {
346 - method: 'POST',
347 - body: { message: commitMessage, tree, parents: [parent], author: identity, committer: identity }
348 - });
349 - return { sha: fullSha(data?.sha, 'Git commit') };
350 - }
351 -
352 - async createGitBranchRef(repoRef, { branch, sha } = {}) {
353 - const branchName = gitBranch(branch);
354 - const commitSha = fullSha(sha, 'Git commit');
355 - const { apiBase } = await this.getRepositoryContext(repoRef);
356 - const data = await this.requestJson(`${apiBase}/git/refs`, 'GitHub create branch ref', {
357 - method: 'POST',
358 - body: { ref: `refs/heads/${branchName}`, sha: commitSha }
359 - });
360 - return {
361 - ref: String(data?.ref || `refs/heads/${branchName}`),
362 - sha: fullSha(data?.object?.sha || commitSha, 'Git commit')
363 - };
364 - }
365 -
366 - async listTree(repoRef, sha) {
367 - if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git tree SHA');
368 - const { apiBase } = await this.getRepositoryContext(repoRef);
369 - const data = await this.requestJson(`${apiBase}/git/trees/${encodeURIComponent(sha)}`, 'GitHub tree');
370 - return (data.tree || []).filter(item => item.type === 'tree' || item.type === 'blob').map(item => ({
371 - name: item.path, path: item.path, type: item.type === 'tree' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || ''
372 - }));
373 - }
374 -
375 - async getBlob(repoRef, sha) {
376 - if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git blob SHA');
377 - const { apiBase } = await this.getRepositoryContext(repoRef);
378 - const data = await this.requestJson(`${apiBase}/git/blobs/${encodeURIComponent(sha)}`, 'GitHub blob');
379 - return { encoding: data.encoding || '', size: data.size ?? 0, content: data.content || '' };
380 - }
381 -
382 - async getRepoStatus(repoRef) {
383 - const { raw, apiBase } = await this.getRepositoryContext(repoRef);
384 - const runsData = await this.requestJson(`${apiBase}/actions/runs?per_page=3`, 'GitHub Actions runs');
385 - const runs = runsData.workflow_runs || [];
386 - return {
387 - repo: String(repoRef), repoName: raw.name, defaultBranch: raw.default_branch || 'main',
388 - 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 || '' }))
389 - };
390 - }
391 -
392 - async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) {
393 - const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page);
394 - const { apiBase } = await this.getRepositoryContext(repoRef);
395 - const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
396 - const data = await this.requestJson(`${apiBase}/actions/runs?per_page=${count}${pageQuery}`, 'GitHub workflow runs');
397 - return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run));
398 - }
399 -
400 - async getWorkflowRun(repoRef, runId) {
401 - const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
402 - return this.mapWorkflowRun(await this.requestJson(`${apiBase}/actions/runs/${id}`, 'GitHub workflow run'));
403 - }
404 -
405 - async listWorkflowJobs(repoRef, runId) {
406 - const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
407 - const data = await this.requestJson(`${apiBase}/actions/runs/${id}/jobs?per_page=20`, 'GitHub workflow jobs');
408 - return (data.jobs || []).map(job => this.mapWorkflowJob(job));
409 - }
410 -
411 - async getWorkflowJob(repoRef, jobId) {
412 - const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
413 - return this.mapWorkflowJob(await this.requestJson(`${apiBase}/actions/jobs/${id}`, 'GitHub workflow job'));
414 - }
415 -
416 - async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) {
417 - const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
418 - return this.requestText(`${apiBase}/actions/jobs/${id}/logs`, 'GitHub workflow job log', { maxChars });
419 - }
420 -
421 - async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) {
422 - const id = numericId(runId, 'workflow run'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
423 - const { apiBase } = await this.getRepositoryContext(repoRef);
424 - const data = await this.requestJson(`${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`, 'GitHub workflow artifacts');
425 - return (data.artifacts || []).map(artifact => ({
426 - id: artifact.id, name: artifact.name || 'Artifact', size: artifact.size_in_bytes ?? 0, expired: !!artifact.expired,
427 - createdAt: artifact.created_at || '', expiresAt: artifact.expires_at || '', downloadUrl: artifact.archive_download_url || ''
428 - }));
429 - }
430 -
431 - async listBranches(repoRef, { perPage = 20, page = 1 } = {}) {
432 - const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
433 - const data = await this.requestJson(`${apiBase}/branches?per_page=${count}&page=${pageNumber}`, 'GitHub branches');
434 - return data.map(branch => ({ name: branch.name || '', sha: branch.commit?.sha || '', protected: !!branch.protected }));
435 - }
436 -
437 - async compareWithDefault(repoRef, headSha) {
438 - const head = fullSha(headSha); const { raw, apiBase } = await this.getRepositoryContext(repoRef); const base = raw.default_branch || 'main';
439 - const data = await this.requestJson(`${apiBase}/compare/${encodeURIComponent(base)}...${head}`, 'GitHub compare');
440 - return {
441 - base, head, status: data.status || '', aheadBy: data.ahead_by ?? 0, behindBy: data.behind_by ?? 0,
442 - totalCommits: data.total_commits ?? 0, baseSha: data.base_commit?.sha || '', mergeBaseSha: data.merge_base_commit?.sha || '',
443 - files: (data.files || []).slice(0, 20).map(file => this.mapPullRequestFile(file))
444 - };
445 - }
446 -
447 - async listIssues(repoRef, { perPage = 10, page = 1 } = {}) {
448 - const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
449 - const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`, 'GitHub issues');
450 - return data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue));
451 - }
452 -
453 - async listIssuesPage(repoRef, { page = 1 } = {}) {
454 - const pageNumber = clampPage(page);
455 - const { apiBase } = await this.getRepositoryContext(repoRef);
456 - const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`, 'GitHub issues');
457 - return {
458 - items: data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)),
459 - hasMore: data.length === 20
460 - };
461 - }
462 -
463 - async getIssue(repoRef, issueNumber) {
464 - const number = numericId(issueNumber, 'issue');
465 - const { apiBase } = await this.getRepositoryContext(repoRef);
466 - const issue = await this.requestJson(apiBase + '/issues/' + number, 'GitHub issue');
467 - return { ...this.mapIssue(issue), body: issue.body || '', labels: (issue.labels || []).map(label => typeof label === 'string' ? label : label.name).filter(Boolean), assignees: (issue.assignees || []).map(user => user.login).filter(Boolean), createdAt: issue.created_at || '', updatedAt: issue.updated_at || '' };
468 - }
469 -
470 - async listReleases(repoRef, { perPage = 10, page = 1 } = {}) {
471 - const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
472 - const data = await this.requestJson(`${apiBase}/releases?per_page=${count}&page=${pageNumber}`, 'GitHub releases');
473 - return data.map(release => ({
474 - id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', draft: !!release.draft,
475 - prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', url: release.html_url || ''
476 - }));
477 - }
478 -
479 - async getRelease(repoRef, releaseId) {
480 - const id = numericId(releaseId, 'release');
481 - const { apiBase } = await this.getRepositoryContext(repoRef);
482 - const release = await this.requestJson(apiBase + '/releases/' + id, 'GitHub release');
483 - return { id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', body: release.body || '', draft: !!release.draft, prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', author: release.author?.login || 'unknown', target: release.target_commitish || '', url: release.html_url || '' };
484 - }
485 -
486 - async rerunFailedWorkflowRun(repoRef, runId) {
487 - const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
488 - return this.requestJson(`${apiBase}/actions/runs/${id}/rerun-failed-jobs`, 'GitHub rerun failed jobs', { method: 'POST', allowEmpty: true });
489 - }
490 -
491 - async cancelWorkflowRun(repoRef, runId) {
492 - const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
493 - return this.requestJson(`${apiBase}/actions/runs/${id}/cancel`, 'GitHub cancel workflow run', { method: 'POST', allowEmpty: true });
494 - }
14 + constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) { this.token = token; this.owner = owner; this.baseUrl = 'https://api.github.com'; }
15 + requireToken() { if (!this.token) throw new Error('GITHUB_TOKEN is not configured'); }
16 + getHeaders() { this.requireToken(); return { 'User-Agent': 'Nexa-Dev-Bot-v1.1', 'Accept': 'application/vnd.github+json', 'Authorization': `Bearer ${this.token}`, 'X-GitHub-Api-Version': '2022-11-28' }; }
17 + async requestJson(url, label, { method = 'GET', body, allowEmpty = false, allowNotFound = false } = {}) { const headers = this.getHeaders(); const options = { method, headers }; if (body !== undefined) { options.body = JSON.stringify(body); options.headers = { ...headers, 'Content-Type': 'application/json' }; } const res = await fetch(url, options); const raw = await res.text(); let parsed = null; if (raw) { try { parsed = JSON.parse(raw); } catch { parsed = null; } } if (!res.ok) { if (allowNotFound && res.status === 404) return null; const providerMessage = parsed?.message || raw.slice(0, 240); const detail = providerMessage ? ` ${providerMessage}` : ''; const error = new Error(`${label} failed: ${res.status}${detail}`); error.status = res.status; throw error; } if (allowEmpty) return { accepted: true, status: res.status }; if (!raw) return null; if (parsed === null) throw new Error(`${label} failed: invalid JSON response`); return parsed; }
18 + async requestText(url, label, { maxChars = 12000 } = {}) { const res = await fetch(url, { method: 'GET', headers: this.getHeaders() }); const raw = await res.text(); if (!res.ok) { const detail = raw ? ` ${raw.slice(0, 240)}` : ''; throw new Error(`${label} failed: ${res.status}${detail}`); } const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000)); return { text: raw.length > limit ? raw.slice(-limit) : raw, truncated: raw.length > limit }; }
19 + repoUrl(repo, suffix = '') { return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`; }
20 + repositoryLookupUrl(repoRef) { const value = String(repoRef || ''); return /^\d+$/.test(value) ? `${this.baseUrl}/repositories/${value}` : this.repoUrl(value); }
21 + repositoryApiBase(fullName) { const parts = String(fullName || '').split('/').filter(Boolean); if (parts.length !== 2) throw new Error('GitHub repository full_name is invalid'); return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`; }
22 + async getRepositoryContext(repoRef) { const value = String(repoRef || ''); try { const raw = await this.requestJson(this.repositoryLookupUrl(value), 'GitHub repository'); return { raw, apiBase: this.repositoryApiBase(raw.full_name) }; } catch (error) { if (!/^\d+$/.test(value) || error?.status !== 404) throw error; const repositories = await this.listRepositories(); const match = repositories.find(repo => repo.id === value); if (!match?.fullName) throw error; const apiBase = this.repositoryApiBase(match.fullName); const raw = await this.requestJson(apiBase, 'GitHub repository'); return { raw, apiBase: this.repositoryApiBase(raw.full_name) }; } }
23 + mapRepository(r) { return { id: String(r.id ?? r.name), name: r.name, fullName: r.full_name, private: !!r.private, description: r.description || '', defaultBranch: r.default_branch || 'main', archived: !!r.archived, htmlUrl: r.html_url || '', stars: r.stargazers_count ?? 0, forks: r.forks_count ?? 0 }; }
24 + mapWorkflowRun(run = {}) { return { id: run.id, name: run.name || 'Workflow', status: run.status || '', conclusion: run.conclusion || null, event: run.event || '', branch: run.head_branch || '', sha: String(run.head_sha || '').slice(0, 7), runNumber: run.run_number ?? null, url: run.html_url || '', createdAt: run.created_at || '', updatedAt: run.updated_at || '' }; }
25 + mapWorkflowJob(job = {}) { return { id: job.id, name: job.name || 'Job', status: job.status || '', conclusion: job.conclusion || null, startedAt: job.started_at || '', completedAt: job.completed_at || '', url: job.html_url || '', steps: (job.steps || []).slice(0, 30).map(step => ({ number: step.number, name: step.name || 'Step', status: step.status || '', conclusion: step.conclusion || null })) }; }
26 + mapPullRequestFile(file = {}) { return { filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0, deletions: file.deletions ?? 0, changes: file.changes ?? 0, patch: boundedPatch(file.patch) }; }
27 + mapIssue(issue = {}) { return { number: issue.number, title: issue.title || '', state: issue.state || '', author: issue.user?.login || 'unknown', comments: issue.comments ?? 0, url: issue.html_url || '' }; }
28 + async listRepositories() { const data = await this.requestJson(`${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`, 'GitHub repositories'); return data.map(r => { const repo = this.mapRepository(r); return { ...repo, title: `${repo.name} ${repo.private ? '🔒' : '🌐'}` }; }); }
29 + async getRepository(repoRef) { const { raw } = await this.getRepositoryContext(repoRef); return this.mapRepository(raw); }
30 + async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : ''; const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`, 'GitHub pull requests'); return data.map(pr => ({ number: pr.number, title: pr.title, author: pr.user?.login || 'unknown', state: pr.state, merged: !!pr.merged_at, createdAt: pr.created_at, url: pr.html_url })); }
31 + async getPullRequest(repoRef, prNumber) { const number = numericId(prNumber, 'pull request'); const { apiBase } = await this.getRepositoryContext(repoRef); const pr = await this.requestJson(`${apiBase}/pulls/${number}`, 'GitHub pull request'); return { number: pr.number, title: pr.title || '', author: pr.user?.login || 'unknown', state: pr.state || '', merged: !!(pr.merged ?? pr.merged_at), body: pr.body || '', url: pr.html_url || '', head: pr.head?.ref || '', headSha: pr.head?.sha || '', base: pr.base?.ref || '', additions: pr.additions ?? 0, deletions: pr.deletions ?? 0, changedFiles: pr.changed_files ?? 0 }; }
32 + async listPullRequestFiles(repoRef, prNumber, { perPage = 20, page = 1 } = {}) { const number = numericId(prNumber, 'pull request'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`, 'GitHub pull request files'); return data.map(file => this.mapPullRequestFile(file)); }
33 + async listCommits(repoRef) { const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/commits?per_page=5`, 'GitHub commits'); return data.map(c => ({ sha: String(c.sha || '').slice(0, 7), fullSha: String(c.sha || ''), message: String(c.commit?.message || '').split('\n')[0], author: c.author?.login || c.commit?.author?.name || 'Unknown', date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : '' })); }
34 + async getCommit(repoRef, sha) { const commitSha = fullSha(sha); const { apiBase } = await this.getRepositoryContext(repoRef); const c = await this.requestJson(`${apiBase}/commits/${commitSha}`, 'GitHub commit'); const files = (c.files || []).slice(0, 20).map(file => ({ filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0, deletions: file.deletions ?? 0, changes: file.changes ?? 0 })); return { sha: commitSha, shortSha: commitSha.slice(0, 7), message: String(c.commit?.message || ''), author: c.author?.login || c.commit?.author?.name || 'Unknown', date: c.commit?.author?.date || '', additions: c.stats?.additions ?? 0, deletions: c.stats?.deletions ?? 0, changedFiles: files.length, files }; }
35 + async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) { const commitSha = fullSha(sha); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`, 'GitHub check runs'); return (data.check_runs || []).map(check => ({ id: check.id, name: check.name || 'Check', status: check.status || '', conclusion: check.conclusion || null, url: check.html_url || '' })); }
36 + async listFiles(repoRef, path = '', { ref } = {}) { const { apiBase } = await this.getRepositoryContext(repoRef); const suffix = path ? `/contents/${encodedPath(path)}` : '/contents'; const query = ref ? `?ref=${encodeURIComponent(String(ref))}` : ''; const data = await this.requestJson(`${apiBase}${suffix}${query}`, 'GitHub contents'); if (!Array.isArray(data)) throw new Error('GitHub contents response is not a directory listing'); return data.map(item => ({ name: item.name, path: item.path, type: item.type === 'dir' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' })); }
37 + async getGitRef(repoRef, branch, { allowMissing = false } = {}) { const branchName = gitBranch(branch); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref', { allowNotFound: allowMissing }); if (data === null) return null; return { branch: branchName, sha: fullSha(data?.object?.sha, 'Git branch head') }; }
38 + async getBranchSnapshot(repoRef, branch) { const branchName = gitBranch(branch); const { apiBase } = await this.getRepositoryContext(repoRef); const ref = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref'); const headSha = fullSha(ref?.object?.sha, 'Git branch head'); const commit = await this.requestJson(`${apiBase}/git/commits/${headSha}`, 'GitHub branch commit'); const treeSha = fullSha(commit?.tree?.sha, 'Git tree'); return { branch: branchName, headSha, treeSha }; }
39 + async getFileAtRef(repoRef, path, ref) { const filePath = String(path || ''); if (!filePath || filePath.startsWith('/') || filePath.includes('\0')) throw new Error('Invalid GitHub file path'); const commitRef = fullSha(ref); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/contents/${encodedPath(filePath)}?ref=${commitRef}`, 'GitHub file'); if (!data || Array.isArray(data) || data.type !== 'file') throw new Error('GitHub contents response is not a file'); if (data.encoding !== 'base64') throw new Error('GitHub file encoding is not supported'); const content = decodeBase64Utf8(data.content || ''); return { path: data.path || filePath, sha: String(data.sha || ''), size: Number(data.size) || 0, encoding: 'utf-8', content }; }
40 + async createGitBlob(repoRef, text) { const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/blobs`, 'GitHub create blob', { method: 'POST', body: { content: String(text ?? ''), encoding: 'utf-8' } }); return { sha: fullSha(data?.sha, 'Git blob') }; }
41 + async createGitTree(repoRef, { baseTreeSha, entries } = {}) { const base = fullSha(baseTreeSha, 'Git base tree'); if (!Array.isArray(entries)) throw new Error('Git tree entries are required'); const tree = entries.map(entry => { const path = String(entry?.path || ''); if (!path || path.startsWith('/') || path.includes('\0')) throw new Error('Invalid Git tree path'); if (entry?.mode !== '100644' || entry?.type !== 'blob') throw new Error('Unsupported Git tree entry'); return { path, mode: '100644', type: 'blob', sha: fullSha(entry.sha, 'Git blob') }; }); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/trees`, 'GitHub create tree', { method: 'POST', body: { base_tree: base, tree } }); return { sha: fullSha(data?.sha, 'Git tree') }; }
42 + async createGitCommit(repoRef, { message, treeSha, parentSha, timestamp } = {}) { const commitMessage = String(message || ''); if (!commitMessage) throw new Error('Git commit message is required'); const tree = fullSha(treeSha, 'Git tree'); const parent = fullSha(parentSha, 'Git parent commit'); const date = new Date(String(timestamp || '')); if (Number.isNaN(date.getTime()) || date.toISOString() !== String(timestamp)) throw new Error('Invalid Git commit timestamp'); const identity = { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: String(timestamp) }; const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/commits`, 'GitHub create commit', { method: 'POST', body: { message: commitMessage, tree, parents: [parent], author: identity, committer: identity } }); return { sha: fullSha(data?.sha, 'Git commit') }; }
43 + async createGitBranchRef(repoRef, { branch, sha } = {}) { const branchName = gitBranch(branch); const commitSha = fullSha(sha, 'Git commit'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/refs`, 'GitHub create branch ref', { method: 'POST', body: { ref: `refs/heads/${branchName}`, sha: commitSha } }); return { ref: String(data?.ref || `refs/heads/${branchName}`), sha: fullSha(data?.object?.sha || commitSha, 'Git commit') }; }
44 + async listTree(repoRef, sha) { if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git tree SHA'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/trees/${encodeURIComponent(sha)}`, 'GitHub tree'); return (data.tree || []).filter(item => item.type === 'tree' || item.type === 'blob').map(item => ({ name: item.path, path: item.path, type: item.type === 'tree' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' })); }
45 + async getBlob(repoRef, sha) { if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git blob SHA'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/blobs/${encodeURIComponent(sha)}`, 'GitHub blob'); return { encoding: data.encoding || '', size: data.size ?? 0, content: data.content || '' }; }
46 + async getRepoStatus(repoRef) { const { raw, apiBase } = await this.getRepositoryContext(repoRef); const runsData = await this.requestJson(`${apiBase}/actions/runs?per_page=3`, 'GitHub Actions runs'); const runs = runsData.workflow_runs || []; return { repo: String(repoRef), repoName: raw.name, defaultBranch: raw.default_branch || 'main', 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 || '' })) }; }
47 + async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : ''; const data = await this.requestJson(`${apiBase}/actions/runs?per_page=${count}${pageQuery}`, 'GitHub workflow runs'); return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run)); }
48 + async getWorkflowRun(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.mapWorkflowRun(await this.requestJson(`${apiBase}/actions/runs/${id}`, 'GitHub workflow run')); }
49 + async listWorkflowJobs(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/actions/runs/${id}/jobs?per_page=20`, 'GitHub workflow jobs'); return (data.jobs || []).map(job => this.mapWorkflowJob(job)); }
50 + async getWorkflowJob(repoRef, jobId) { const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.mapWorkflowJob(await this.requestJson(`${apiBase}/actions/jobs/${id}`, 'GitHub workflow job')); }
51 + async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) { const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestText(`${apiBase}/actions/jobs/${id}/logs`, 'GitHub workflow job log', { maxChars }); }
52 + async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) { const id = numericId(runId, 'workflow run'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`, 'GitHub workflow artifacts'); return (data.artifacts || []).map(artifact => ({ id: artifact.id, name: artifact.name || 'Artifact', size: artifact.size_in_bytes ?? 0, expired: !!artifact.expired, createdAt: artifact.created_at || '', expiresAt: artifact.expires_at || '', downloadUrl: artifact.archive_download_url || '' })); }
53 + async listBranches(repoRef, { perPage = 20, page = 1 } = {}) { const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/branches?per_page=${count}&page=${pageNumber}`, 'GitHub branches'); return data.map(branch => ({ name: branch.name || '', sha: branch.commit?.sha || '', protected: !!branch.protected })); }
54 + async compareWithDefault(repoRef, headSha) { const head = fullSha(headSha); const { raw, apiBase } = await this.getRepositoryContext(repoRef); const base = raw.default_branch || 'main'; const data = await this.requestJson(`${apiBase}/compare/${encodeURIComponent(base)}...${head}`, 'GitHub compare'); return { base, head, status: data.status || '', aheadBy: data.ahead_by ?? 0, behindBy: data.behind_by ?? 0, totalCommits: data.total_commits ?? 0, baseSha: data.base_commit?.sha || '', mergeBaseSha: data.merge_base_commit?.sha || '', files: (data.files || []).slice(0, 20).map(file => this.mapPullRequestFile(file)) }; }
55 + async listIssues(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`, 'GitHub issues'); return data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)); }
56 + async listIssuesPage(repoRef, { page = 1 } = {}) { const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`, 'GitHub issues'); return { items: data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)), hasMore: data.length === 20 }; }
57 + async getIssue(repoRef, issueNumber) { const number = numericId(issueNumber, 'issue'); const { apiBase } = await this.getRepositoryContext(repoRef); const issue = await this.requestJson(apiBase + '/issues/' + number, 'GitHub issue'); return { ...this.mapIssue(issue), body: issue.body || '', labels: (issue.labels || []).map(label => typeof label === 'string' ? label : label.name).filter(Boolean), assignees: (issue.assignees || []).map(user => user.login).filter(Boolean), createdAt: issue.created_at || '', updatedAt: issue.updated_at || '' }; }
58 + async listReleases(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/releases?per_page=${count}&page=${pageNumber}`, 'GitHub releases'); return data.map(release => ({ id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', draft: !!release.draft, prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', url: release.html_url || '' })); }
59 + async getRelease(repoRef, releaseId) { const id = numericId(releaseId, 'release'); const { apiBase } = await this.getRepositoryContext(repoRef); const release = await this.requestJson(apiBase + '/releases/' + id, 'GitHub release'); return { id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', body: release.body || '', draft: !!release.draft, prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', author: release.author?.login || 'unknown', target: release.target_commitish || '', url: release.html_url || '' }; }
60 + async mergePullRequest(repoRef, prNumber, { expectedHeadSha, mergeMethod = 'squash' } = {}) { const number = numericId(prNumber, 'pull request'); const method = String(mergeMethod || 'squash'); if (!['merge', 'squash', 'rebase'].includes(method)) throw new Error('Unsupported merge method'); const expected = fullSha(expectedHeadSha, 'expected pull request head'); const { apiBase } = await this.getRepositoryContext(repoRef); const result = await this.requestJson(`${apiBase}/pulls/${number}/merge`, 'GitHub pull request merge', { method: 'PUT', body: { sha: expected, merge_method: method } }); if (!result?.merged) throw new Error(`GitHub pull request merge failed: ${String(result?.message || 'not merged').slice(0, 240)}`); return { merged: true, sha: String(result.sha || ''), message: String(result.message || '') }; }
61 + async rerunFailedWorkflowRun(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestJson(`${apiBase}/actions/runs/${id}/rerun-failed-jobs`, 'GitHub rerun failed jobs', { method: 'POST', allowEmpty: true }); }
62 + async cancelWorkflowRun(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestJson(`${apiBase}/actions/runs/${id}/cancel`, 'GitHub cancel workflow run', { method: 'POST', allowEmpty: true }); }
63 }
src/plugins/github/manifest.js
+3 -2
@@ -1,7 +1,7 @@
1 export const githubPluginManifest = Object.freeze({
2 id: 'github',
3 name: 'GitHub',
4 - version: 7,
4 + version: 8,
5 commands: Object.freeze(['/repos']),
6 actions: Object.freeze({
7 'github.repos.list': Object.freeze({ risk: 'READ' }),
@@ -39,6 +39,7 @@ export const githubPluginManifest = Object.freeze({
39 'github.workspace.cancel': Object.freeze({ risk: 'READ' }),
40 'github.workspace.commit_branch': Object.freeze({ risk: 'WRITE' }),
41 'github.workflow.run.rerun_failed': Object.freeze({ risk: 'WRITE' }),
42 - 'github.workflow.run.cancel': Object.freeze({ risk: 'WRITE' })
42 + 'github.workflow.run.cancel': Object.freeze({ risk: 'WRITE' }),
43 + 'github.pull_request.merge': Object.freeze({ risk: 'DESTRUCTIVE' })
44 })
45 });
src/plugins/github/plugin-legacy.js new
+541
@@ -0,0 +1,541 @@
1 +import { githubPluginManifest } from './manifest.js';
2 +import { createWorkspaceController } from './workspace.js';
3 +
4 +const CALLBACK_ACTIONS = Object.freeze([
5 + ['files:', 'github.files.list'],
6 + ['tree:', 'github.tree.read'],
7 + ['blob:', 'github.blob.read'],
8 + ['pr:', 'github.pr.list'],
9 + ['commits:', 'github.commits.list'],
10 + ['status:', 'github.status.read']
11 +]);
12 +
13 +const escapeHtml = value => String(value ?? '')
14 + .replaceAll('&', '&amp;')
15 + .replaceAll('<', '&lt;')
16 + .replaceAll('>', '&gt;')
17 + .replaceAll('"', '&quot;');
18 +
19 +const short = (value, max = 80) => {
20 + const text = String(value ?? '');
21 + return text.length > max ? `${text.slice(0, max - 1)}…` : text;
22 +};
23 +
24 +const numericPair = (value, prefix) => {
25 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)$`));
26 + if (!match) return null;
27 + return { repoId: Number(match[1]), runId: Number(match[2]) };
28 +};
29 +
30 +const numericTriple = (value, prefix) => {
31 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+):(\\d+)$`));
32 + if (!match) return null;
33 + return {
34 + repoId: Number(match[1]),
35 + itemId: Number(match[2]),
36 + page: Math.max(1, Math.min(100, Number(match[3]) || 1))
37 + };
38 +};
39 +
40 +const pagedPair = (value, prefix) => {
41 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)(?::(\\d+))?$`));
42 + if (!match) return null;
43 + return {
44 + repoId: Number(match[1]),
45 + itemId: Number(match[2]),
46 + page: Math.max(1, Math.min(100, Number(match[3]) || 1))
47 + };
48 +};
49 +
50 +const numericSingle = (value, prefix) => {
51 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)$`));
52 + return match ? Number(match[1]) : null;
53 +};
54 +
55 +const pagedSingle = (value, prefix) => {
56 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)(?::(\\d+))?$`));
57 + if (!match) return null;
58 + return {
59 + repoId: Number(match[1]),
60 + page: Math.max(1, Math.min(100, Number(match[2]) || 1))
61 + };
62 +};
63 +
64 +const compareRef = value => {
65 + const match = String(value || '').match(/^compare:(\d+):([a-f0-9]{40})$/i);
66 + if (!match) return null;
67 + return { repoId: Number(match[1]), sha: match[2] };
68 +};
69 +
70 +const commitDetailRef = value => {
71 + const match = String(value || '').match(/^commitdetail:(\d+):([a-f0-9]{40})$/i);
72 + if (!match) return null;
73 + return { repoId: Number(match[1]), sha: match[2] };
74 +};
75 +
76 +const workflowRunsPage = value => pagedSingle(value, 'runs');
77 +
78 +const runIcon = run => {
79 + if (run.conclusion === 'success') return '✅';
80 + if (run.conclusion === 'failure') return '❌';
81 + if (run.conclusion === 'cancelled') return '⏹';
82 + return run.status === 'in_progress' ? '🟡' : '⏳';
83 +};
84 +
85 +const stateIcon = value => {
86 + if (value === 'success' || value === 'completed') return '✅';
87 + if (value === 'failure') return '❌';
88 + if (value === 'cancelled') return '⏹';
89 + if (value === 'open') return '🟢';
90 + if (value === 'closed') return '⚫';
91 + return '•';
92 +};
93 +
94 +const addRepoAdvancedButtons = (view, repoId) => {
95 + const rows = [...(view?.reply_markup?.inline_keyboard || [])];
96 + const insertAt = Math.max(0, rows.length - 1);
97 + rows.splice(insertAt, 0,
98 + [{ text: '🌿 Branches', callback_data: `branches:${repoId}` }],
99 + [
100 + { text: '🐛 Issues', callback_data: `issues:${repoId}` },
101 + { text: '🏷 Releases', callback_data: `releases:${repoId}` }
102 + ]
103 + );
104 + return {
105 + ...view,
106 + reply_markup: { ...(view?.reply_markup || {}), inline_keyboard: rows }
107 + };
108 +};
109 +
110 +function listPagination(prefix, repoId, page, count, pageSize) {
111 + const row = [];
112 + if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
113 + if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
114 + return row.length ? [row] : [];
115 +}
116 +
117 +function explicitPagination(prefix, repoId, page, hasMore) {
118 + const row = [];
119 + if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
120 + if (hasMore && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
121 + return row.length ? [row] : [];
122 +}
123 +
124 +function pairPagination(prefix, repoId, itemId, page, count, pageSize) {
125 + const row = [];
126 + if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${itemId}:${page - 1}` });
127 + if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${itemId}:${page + 1}` });
128 + return row.length ? [row] : [];
129 +}
130 +
131 +async function commitsView(github, repoId) {
132 + const [repo, commits] = await Promise.all([github.getRepository(repoId), github.listCommits(repoId)]);
133 + const body = commits.length
134 + ? commits.slice(0, 10).map(commit => `• <code>${escapeHtml(commit.shortSha || commit.sha)}</code> — ${escapeHtml(short(commit.message, 110))}\n ${escapeHtml(commit.author || 'Unknown')}${commit.date ? ` · ${escapeHtml(commit.date)}` : ''}`).join('\n\n')
135 + : '<i>کامیتی در پاسخ GitHub یافت نشد.</i>';
136 + const detailRows = commits.slice(0, 10).map(commit => {
137 + const sha = String(commit.fullSha || commit.sha || '');
138 + return /^[a-f0-9]{40}$/i.test(sha)
139 + ? [{ text: `📝 ${short(commit.message || sha.slice(0, 7), 42)}`, callback_data: `commitdetail:${repoId}:${sha}` }]
140 + : null;
141 + }).filter(Boolean);
142 + return {
143 + text: `📝 <b>آخرین Commitهای ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
144 + reply_markup: { inline_keyboard: [
145 + ...detailRows,
146 + [{ text: '🔄 بروزرسانی', callback_data: `commits:${repoId}` }, { text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
147 + ] }
148 + };
149 +}
150 +
151 +async function commitDetailView(github, repoId, sha) {
152 + const [repo, commit] = await Promise.all([github.getRepository(repoId), github.getCommit(repoId, sha)]);
153 + const files = (commit.files || []).slice(0, 12)
154 + .map(file => `• <code>${escapeHtml(short(file.filename, 90))}</code> · ${escapeHtml(file.status || 'changed')} · +${file.additions ?? 0}/-${file.deletions ?? 0}`)
155 + .join('\n');
156 + return {
157 + text: `📝 <b>Commit — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(commit.shortSha || String(commit.sha).slice(0, 7))}</code> · ${escapeHtml(commit.author || 'Unknown')}\n${escapeHtml(commit.date || '-')}\n+${commit.additions ?? 0}/-${commit.deletions ?? 0} · ${commit.changedFiles ?? (commit.files || []).length} files\n➖➖➖➖➖➖➖➖➖➖\n${escapeHtml(short(commit.message || '', 1200)) || '<i>بدون پیام.</i>'}\n\n<b>فایل‌های تغییرکرده</b>\n${files || '<i>فایلی گزارش نشده است.</i>'}`,
158 + reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `commitdetail:${repoId}:${sha}` }, { text: '🔙 Commitها', callback_data: `commits:${repoId}` }], [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]] }
159 + };
160 +}
161 +
162 +async function workflowRunsView(github, repoId, page = 1) {
163 + const [repo, runs] = await Promise.all([
164 + github.getRepository(repoId),
165 + github.listWorkflowRuns(repoId, { perPage: 10, page })
166 + ]);
167 + const body = runs.length
168 + ? runs.slice(0, 10).map(run => `${runIcon(run)} <b>${escapeHtml(run.name)}</b> #${run.runNumber ?? '-'}\n └ ${escapeHtml(run.branch || '-')} · <code>${escapeHtml(run.sha || '-')}</code> · ${escapeHtml(run.conclusion || run.status || 'unknown')}`).join('\n\n')
169 + : '<i>Workflow runی یافت نشد.</i>';
170 + const refreshCallback = page === 1 ? `runs:${repoId}` : `runs:${repoId}:${page}`;
171 + return {
172 + text: `🧪 <b>CI / Actions — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
173 + reply_markup: {
174 + inline_keyboard: [
175 + ...runs.slice(0, 10).map(run => [{
176 + text: `${runIcon(run)} ${short(run.name, 32)} #${run.runNumber ?? run.id}`,
177 + callback_data: `run:${repoId}:${run.id}`
178 + }]),
179 + ...listPagination('runs', repoId, page, runs.length, 10),
180 + [
181 + { text: '🔄 بروزرسانی', callback_data: refreshCallback },
182 + { text: '🔙 پروژه', callback_data: `repo:${repoId}` }
183 + ]
184 + ]
185 + }
186 + };
187 +}
188 +
189 +async function workflowRunView(github, repoId, runId) {
190 + const [repo, run] = await Promise.all([
191 + github.getRepository(repoId),
192 + github.getWorkflowRun(repoId, runId)
193 + ]);
194 + const rows = [
195 + [
196 + { text: '👷 Jobها', callback_data: `jobs:${repoId}:${runId}` },
197 + { text: '📦 Artifacts', callback_data: `artifacts:${repoId}:${runId}` }
198 + ]
199 + ];
200 + if (run.conclusion === 'failure') rows.push([{ text: '🔁 اجرای مجدد jobهای ناموفق', callback_data: `rerun:${repoId}:${runId}` }]);
201 + if (run.status === 'in_progress' || run.status === 'queued') rows.push([{ text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }]);
202 + rows.push([
203 + { text: '🔄 بروزرسانی', callback_data: `run:${repoId}:${runId}` },
204 + { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
205 + ]);
206 + return {
207 + text: `🧪 <b>${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\nوضعیت: ${runIcon(run)} <b>${escapeHtml(run.conclusion || run.status || 'unknown')}</b>\nRun: <code>#${escapeHtml(run.runNumber ?? run.id)}</code>\nBranch: <code>${escapeHtml(run.branch || '-')}</code>\nSHA: <code>${escapeHtml(run.sha || '-')}</code>\nTrigger: <code>${escapeHtml(run.event || '-')}</code>`,
208 + reply_markup: { inline_keyboard: rows }
209 + };
210 +}
211 +
212 +async function workflowJobsView(github, repoId, runId) {
213 + const [repo, run, jobs] = await Promise.all([
214 + github.getRepository(repoId),
215 + github.getWorkflowRun(repoId, runId),
216 + github.listWorkflowJobs(repoId, runId)
217 + ]);
218 + const body = jobs.length
219 + ? jobs.slice(0, 20).map(job => {
220 + const jobState = job.conclusion || job.status || 'unknown';
221 + const steps = (job.steps || []).slice(0, 30)
222 + .map(step => ` ${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`)
223 + .join('\n');
224 + return `<b>${escapeHtml(job.name)}</b> — ${escapeHtml(jobState)}${steps ? `\n${steps}` : ''}`;
225 + }).join('\n\n')
226 + : '<i>Jobی در این Run یافت نشد.</i>';
227 + return {
228 + text: `👷 <b>Jobهای ${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
229 + reply_markup: {
230 + inline_keyboard: [
231 + ...jobs.slice(0, 20).map(job => [{ text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`, callback_data: `job:${repoId}:${job.id}` }]),
232 + [{ text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]
233 + ]
234 + }
235 + };
236 +}
237 +
238 +async function workflowJobView(github, repoId, jobId) {
239 + const [repo, job] = await Promise.all([github.getRepository(repoId), github.getWorkflowJob(repoId, jobId)]);
240 + const status = job.conclusion || job.status || 'unknown';
241 + const steps = (job.steps || []).slice(0, 30).map(step => `${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`).join('\n');
242 + const rows = [];
243 + if (job.conclusion === 'failure') rows.push([{ text: '📜 مشاهده log ناموفق', callback_data: `joblog:${repoId}:${jobId}` }]);
244 + rows.push([{ text: '🔄 بروزرسانی', callback_data: `job:${repoId}:${jobId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]);
245 + return {
246 + text: `👷 <b>${escapeHtml(job.name)} — ${escapeHtml(repo.name)}</b>\nوضعیت: ${stateIcon(status)} <b>${escapeHtml(status)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${steps || '<i>Stepی ثبت نشده.</i>'}`,
247 + reply_markup: { inline_keyboard: rows }
248 + };
249 +}
250 +
251 +async function workflowJobLogView(github, repoId, jobId) {
252 + const [job, log] = await Promise.all([
253 + github.getWorkflowJob(repoId, jobId),
254 + github.getWorkflowJobLog(repoId, jobId, { maxChars: 1800 })
255 + ]);
256 + const escaped = escapeHtml(log.text).slice(-3200);
257 + const note = log.truncated ? '⚠️ فقط بخش پایانی log نمایش داده شده است.\n\n' : '';
258 + return {
259 + text: `📜 <b>Log — ${escapeHtml(job.name)}</b>\n${note}<pre>${escaped || '(empty log)'}</pre>`,
260 + reply_markup: { inline_keyboard: [[{ text: '🔙 Job', callback_data: `job:${repoId}:${jobId}` }]] }
261 + };
262 +}
263 +
264 +async function workflowArtifactsView(github, repoId, runId, page = 1) {
265 + const [repo, artifacts] = await Promise.all([
266 + github.getRepository(repoId),
267 + github.listWorkflowArtifacts(repoId, runId, { perPage: 10, page })
268 + ]);
269 + const body = artifacts.length
270 + ? artifacts.slice(0, 10).map(item => `📦 <b>${escapeHtml(item.name)}</b>\n ${item.expired ? 'منقضی شده' : 'فعال'} · ${Number(item.size || 0).toLocaleString()} bytes\n expires: ${escapeHtml(item.expiresAt || '-')}`).join('\n\n')
271 + : '<i>Artifactی برای این Run یافت نشد.</i>';
272 + const refreshCallback = page === 1 ? `artifacts:${repoId}:${runId}` : `artifacts:${repoId}:${runId}:${page}`;
273 + return {
274 + text: `📦 <b>Artifacts — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
275 + reply_markup: { inline_keyboard: [...pairPagination('artifacts', repoId, runId, page, artifacts.length, 10), [{ text: '🔄 بروزرسانی', callback_data: refreshCallback }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]] }
276 + };
277 +}
278 +
279 +async function branchesView(github, repoId, page = 1) {
280 + const [repo, branches] = await Promise.all([github.getRepository(repoId), github.listBranches(repoId, { perPage: 20, page })]);
281 + const body = branches.length
282 + ? branches.slice(0, 20).map(branch => `🌿 <b>${escapeHtml(short(branch.name, 70))}</b>\n <code>${escapeHtml(String(branch.sha).slice(0, 10))}</code>${branch.protected ? ' · 🛡 protected' : ''}`).join('\n\n')
283 + : '<i>Branchی یافت نشد.</i>';
284 + return {
285 + text: `🌿 <b>Branches — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
286 + reply_markup: { inline_keyboard: [
287 + ...branches.slice(0, 20).filter(branch => /^[a-f0-9]{40}$/i.test(String(branch.sha))).map(branch => [{ text: `↔️ ${short(branch.name, 42)}`, callback_data: `compare:${repoId}:${branch.sha}` }]),
288 + ...listPagination('branches', repoId, page, branches.length, 20),
289 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
290 + ] }
291 + };
292 +}
293 +
294 +async function compareView(github, repoId, sha) {
295 + const [repo, compare] = await Promise.all([github.getRepository(repoId), github.compareWithDefault(repoId, sha)]);
296 + const files = (compare.files || []).slice(0, 12).map(file => `${stateIcon(file.status)} <code>${escapeHtml(short(file.filename, 90))}</code> · +${file.additions}/-${file.deletions}`).join('\n');
297 + return {
298 + text: `↔️ <b>Compare — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(compare.base)}</code> ← <code>${escapeHtml(String(compare.head).slice(0, 10))}</code>\nوضعیت: <b>${escapeHtml(compare.status || '-')}</b>\nAhead: <b>${compare.aheadBy ?? 0}</b> · Behind: <b>${compare.behindBy ?? 0}</b> · Commits: <b>${compare.totalCommits ?? 0}</b>\n➖➖➖➖➖➖➖➖➖➖\n${files || '<i>فایل تغییریافته‌ای نیست.</i>'}`,
299 + reply_markup: { inline_keyboard: [[{ text: '🔙 Branches', callback_data: `branches:${repoId}` }]] }
300 + };
301 +}
302 +
303 +async function pullRequestsView(github, repoId, page = 1) {
304 + const [repo, prs] = await Promise.all([github.getRepository(repoId), github.listPullRequests(repoId, { perPage: 10, page })]);
305 + const body = prs.length
306 + ? prs.slice(0, 10).map(pr => `${pr.merged ? '🟣' : stateIcon(pr.state)} <b>#${pr.number} ${escapeHtml(short(pr.title, 100))}</b>\n ${escapeHtml(pr.author)} · ${escapeHtml(pr.merged ? 'merged' : pr.state)}`).join('\n\n')
307 + : '<i>Pull Requestی یافت نشد.</i>';
308 + return {
309 + text: `🔎 <b>Pull Requests — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
310 + reply_markup: { inline_keyboard: [
311 + ...prs.slice(0, 10).map(pr => [{ text: `#${pr.number} ${short(pr.title, 42)}`, callback_data: `prdetail:${repoId}:${pr.number}` }]),
312 + ...listPagination('prs', repoId, page, prs.length, 10),
313 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
314 + ] }
315 + };
316 +}
317 +
318 +async function pullRequestDetailView(github, repoId, prNumber) {
319 + const [repo, pr] = await Promise.all([github.getRepository(repoId), github.getPullRequest(repoId, prNumber)]);
320 + const body = escapeHtml(short(pr.body || '', 600));
321 + return {
322 + text: `🔎 <b>PR #${pr.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(pr.title)}</b>\n${pr.merged ? '🟣 merged' : `${stateIcon(pr.state)} ${escapeHtml(pr.state)}`} · ${escapeHtml(pr.author)}\n<code>${escapeHtml(pr.head || '-')}</code> → <code>${escapeHtml(pr.base || '-')}</code>\n+${pr.additions}/-${pr.deletions} · ${pr.changedFiles} files\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
323 + reply_markup: { inline_keyboard: [[{ text: '🧩 فایل‌ها / Diff', callback_data: `prfiles:${repoId}:${prNumber}:1` }, { text: '✅ Checks', callback_data: `prchecks:${repoId}:${prNumber}:1` }], [{ text: '🔙 PRها', callback_data: `prs:${repoId}` }]] }
324 + };
325 +}
326 +
327 +async function pullRequestFilesView(github, repoId, prNumber, page = 1) {
328 + const files = await github.listPullRequestFiles(repoId, prNumber, { perPage: 8, page });
329 + const body = files.length ? files.slice(0, 8).map(file => {
330 + const patch = escapeHtml(short(file.patch || '', 220));
331 + return `🧩 <code>${escapeHtml(short(file.filename, 100))}</code> · ${escapeHtml(file.status)} · +${file.additions}/-${file.deletions}${patch ? `\n<pre>${patch}</pre>` : ''}`;
332 + }).join('\n\n') : '<i>فایل تغییریافته‌ای یافت نشد.</i>';
333 + return {
334 + text: `🧩 <b>PR #${prNumber} Files / Diff</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
335 + reply_markup: { inline_keyboard: [...pairPagination('prfiles', repoId, prNumber, page, files.length, 8), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
336 + };
337 +}
338 +
339 +async function pullRequestChecksView(github, repoId, prNumber, page = 1) {
340 + const pr = await github.getPullRequest(repoId, prNumber);
341 + const checks = await github.listCommitChecks(repoId, pr.headSha, { perPage: 20, page });
342 + const body = checks.length
343 + ? checks.slice(0, 20).map(check => `${stateIcon(check.conclusion || check.status)} <b>${escapeHtml(check.name)}</b> — ${escapeHtml(check.conclusion || check.status || 'unknown')}`).join('\n')
344 + : '<i>Checkی یافت نشد.</i>';
345 + return {
346 + text: `✅ <b>PR #${prNumber} Checks</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
347 + reply_markup: { inline_keyboard: [...pairPagination('prchecks', repoId, prNumber, page, checks.length, 20), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
348 + };
349 +}
350 +
351 +async function issuesView(github, repoId, page = 1) {
352 + const [repo, issuePage] = await Promise.all([github.getRepository(repoId), github.listIssuesPage(repoId, { page })]);
353 + const issues = issuePage.items || [];
354 + const body = issues.length
355 + ? issues.slice(0, 20).map(issue => `${stateIcon(issue.state)} <b>#${issue.number} ${escapeHtml(short(issue.title, 110))}</b>\n ${escapeHtml(issue.author)} · ${issue.comments} comments`).join('\n\n')
356 + : '<i>Issueی یافت نشد.</i>';
357 + return {
358 + text: `🐛 <b>Issues — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
359 + reply_markup: { inline_keyboard: [
360 + ...issues.slice(0, 20).map(issue => [{ text: `#${issue.number} ${short(issue.title, 42)}`, callback_data: `issuedetail:${repoId}:${issue.number}` }]),
361 + ...explicitPagination('issues', repoId, page, !!issuePage.hasMore),
362 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
363 + ] }
364 + };
365 +}
366 +
367 +async function issueDetailView(github, repoId, issueNumber) {
368 + const [repo, issue] = await Promise.all([github.getRepository(repoId), github.getIssue(repoId, issueNumber)]);
369 + const labels = (issue.labels || []).map(label => `#${escapeHtml(label)}`).join(' ');
370 + const assignees = (issue.assignees || []).map(name => `@${escapeHtml(name)}`).join(' ');
371 + const body = escapeHtml(short(issue.body || '', 1800));
372 + return {
373 + text: `🐛 <b>Issue #${issue.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(issue.title)}</b>\n${stateIcon(issue.state)} ${escapeHtml(issue.state || 'unknown')} · ${escapeHtml(issue.author)} · ${issue.comments ?? 0} comments\nLabels: ${labels || '-'}\nAssignees: ${assignees || '-'}\nUpdated: ${escapeHtml(issue.updatedAt || issue.createdAt || '-')}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
374 + reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `issuedetail:${repoId}:${issueNumber}` }, { text: '🔙 Issues', callback_data: `issues:${repoId}` }]] }
375 + };
376 +}
377 +
378 +async function releasesView(github, repoId, page = 1) {
379 + const [repo, releases] = await Promise.all([github.getRepository(repoId), github.listReleases(repoId, { perPage: 10, page })]);
380 + const body = releases.length
381 + ? releases.slice(0, 10).map(release => `🏷 <b>${escapeHtml(release.tag || release.name)}</b>${release.prerelease ? ' · pre-release' : ''}${release.draft ? ' · draft' : ''}\n ${escapeHtml(short(release.name, 110))}\n ${escapeHtml(release.publishedAt || '-')}`).join('\n\n')
382 + : '<i>هیچ Release منتشرشده‌ای برای این مخزن در GitHub وجود ندارد.</i>';
383 + return {
384 + text: `🏷 <b>Releases — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
385 + reply_markup: { inline_keyboard: [
386 + ...releases.slice(0, 10).map(release => [{ text: `🏷 ${short(release.tag || release.name, 42)}`, callback_data: `releasedetail:${repoId}:${release.id}` }]),
387 + ...listPagination('releases', repoId, page, releases.length, 10),
388 + [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
389 + ] }
390 + };
391 +}
392 +
393 +async function releaseDetailView(github, repoId, releaseId) {
394 + const [repo, release] = await Promise.all([github.getRepository(repoId), github.getRelease(repoId, releaseId)]);
395 + const body = escapeHtml(short(release.body || '', 1800));
396 + const flags = [release.draft ? 'draft' : '', release.prerelease ? 'pre-release' : ''].filter(Boolean).join(' · ');
397 + return {
398 + text: `🏷 <b>${escapeHtml(release.name)} — ${escapeHtml(repo.name)}</b>\nTag: <code>${escapeHtml(release.tag || '-')}</code>\nTarget: <code>${escapeHtml(release.target || '-')}</code>\nAuthor: ${escapeHtml(release.author || 'unknown')}\nPublished: ${escapeHtml(release.publishedAt || '-')}${flags ? `\nState: ${escapeHtml(flags)}` : ''}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون Release notes.</i>'}`,
399 + reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `releasedetail:${repoId}:${releaseId}` }, { text: '🔙 Releases', callback_data: `releases:${repoId}` }]] }
400 + };
401 +}
402 +
403 +function workflowActionResultView(repoId, runId, action) {
404 + const rerun = action === 'rerun_failed';
405 + return {
406 + text: rerun ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.' : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
407 + reply_markup: { inline_keyboard: [[{ text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]] }
408 + };
409 +}
410 +
411 +function resolveReadCallback(data) {
412 + const value = String(data || '');
413 + if (value === 'menu:repos') return { actionId: 'github.repos.list', kind: 'legacy' };
414 + const repoId = numericSingle(value, 'repo');
415 + if (repoId !== null) return { actionId: 'github.repo.detail', kind: 'repo', repoId };
416 + const commits = numericSingle(value, 'commits');
417 + if (commits !== null) return { actionId: 'github.commits.list', kind: 'commits', repoId: commits };
418 + const commitdetail = commitDetailRef(value);
419 + if (commitdetail) return { actionId: 'github.commit.detail', kind: 'commitdetail', ...commitdetail };
420 + const legacyStatus = numericSingle(value, 'status');
421 + if (legacyStatus !== null) return { actionId: 'github.workflow.runs.list', kind: 'runs', repoId: legacyStatus, page: 1 };
422 + const runs = workflowRunsPage(value);
423 + if (runs) return { actionId: 'github.workflow.runs.list', kind: 'runs', ...runs };
424 + const run = numericPair(value, 'run');
425 + if (run) return { actionId: 'github.workflow.run.detail', kind: 'run', ...run };
426 + const jobs = numericPair(value, 'jobs');
427 + if (jobs) return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
428 + const job = numericPair(value, 'job');
429 + if (job) return { actionId: 'github.workflow.job.detail', kind: 'job', repoId: job.repoId, jobId: job.runId };
430 + const joblog = numericPair(value, 'joblog');
431 + if (joblog) return { actionId: 'github.workflow.job.log', kind: 'joblog', repoId: joblog.repoId, jobId: joblog.runId };
432 + const artifacts = pagedPair(value, 'artifacts');
433 + if (artifacts) return { actionId: 'github.workflow.artifacts.list', kind: 'artifacts', repoId: artifacts.repoId, runId: artifacts.itemId, page: artifacts.page };
434 + const branches = pagedSingle(value, 'branches');
435 + if (branches) return { actionId: 'github.branches.list', kind: 'branches', ...branches };
436 + const compare = compareRef(value);
437 + if (compare) return { actionId: 'github.compare.read', kind: 'compare', ...compare };
438 + const legacyPr = numericSingle(value, 'pr');
439 + if (legacyPr !== null) return { actionId: 'github.pr.advanced.list', kind: 'prs', repoId: legacyPr, page: 1 };
440 + const prs = pagedSingle(value, 'prs');
441 + if (prs) return { actionId: 'github.pr.advanced.list', kind: 'prs', ...prs };
442 + const prdetail = numericPair(value, 'prdetail');
443 + if (prdetail) return { actionId: 'github.pr.detail', kind: 'prdetail', repoId: prdetail.repoId, prNumber: prdetail.runId };
444 + const prfiles = numericTriple(value, 'prfiles');
445 + if (prfiles) return { actionId: 'github.pr.files.list', kind: 'prfiles', repoId: prfiles.repoId, prNumber: prfiles.itemId, page: prfiles.page };
446 + const prchecks = numericTriple(value, 'prchecks');
447 + if (prchecks) return { actionId: 'github.pr.checks.list', kind: 'prchecks', repoId: prchecks.repoId, prNumber: prchecks.itemId, page: prchecks.page };
448 + const issues = pagedSingle(value, 'issues');
449 + if (issues) return { actionId: 'github.issues.list', kind: 'issues', ...issues };
450 + const issuedetail = numericPair(value, 'issuedetail');
451 + if (issuedetail) return { actionId: 'github.issue.detail', kind: 'issuedetail', repoId: issuedetail.repoId, issueNumber: issuedetail.runId };
452 + const releases = pagedSingle(value, 'releases');
453 + if (releases) return { actionId: 'github.releases.list', kind: 'releases', ...releases };
454 + const releasedetail = numericPair(value, 'releasedetail');
455 + if (releasedetail) return { actionId: 'github.release.detail', kind: 'releasedetail', repoId: releasedetail.repoId, releaseId: releasedetail.runId };
456 + for (const [prefix, actionId] of CALLBACK_ACTIONS) {
457 + if (value.startsWith(prefix)) return { actionId, kind: 'legacy' };
458 + }
459 + return null;
460 +}
461 +
462 +function resolveWriteCallback(data) {
463 + const rerun = numericPair(data, 'rerun');
464 + if (rerun) {
465 + return {
466 + actionId: 'github.workflow.run.rerun_failed',
467 + approval: { input: rerun, label: 'اجرای مجدد jobهای ناموفق' },
468 + execute: async github => {
469 + await github.rerunFailedWorkflowRun(rerun.repoId, rerun.runId);
470 + return workflowActionResultView(rerun.repoId, rerun.runId, 'rerun_failed');
471 + }
472 + };
473 + }
474 + const cancel = numericPair(data, 'cancelrun');
475 + if (cancel) {
476 + return {
477 + actionId: 'github.workflow.run.cancel',
478 + approval: { input: cancel, label: 'لغو Workflow در حال اجرا' },
479 + execute: async github => {
480 + await github.cancelWorkflowRun(cancel.repoId, cancel.runId);
481 + return workflowActionResultView(cancel.repoId, cancel.runId, 'cancel');
482 + }
483 + };
484 + }
485 + return null;
486 +}
487 +
488 +export function createGitHubPlugin({ github, menu, workspaces } = {}) {
489 + if (!github) throw new Error('GitHub plugin requires github service');
490 + if (!menu) throw new Error('GitHub plugin requires menu manager');
491 + const workspaceController = workspaces ? createWorkspaceController({ github, workspaces }) : null;
492 +
493 + return {
494 + manifest: githubPluginManifest,
495 +
496 + resolveCommand(command) {
497 + if (command !== '/repos') return null;
498 + return { actionId: 'github.repos.list', execute: () => menu.getReposListView() };
499 + },
500 +
501 + resolveMessage(payload, context = {}) {
502 + return workspaceController?.resolveMessage(payload, context) || null;
503 + },
504 +
505 + resolveCallback(data, context = {}) {
506 + const write = resolveWriteCallback(data);
507 + if (write) return { actionId: write.actionId, approval: write.approval, execute: () => write.execute(github) };
508 +
509 + const workspaceRoute = workspaceController?.resolveCallback(data, context);
510 + if (workspaceRoute) return workspaceRoute;
511 +
512 + const read = resolveReadCallback(data);
513 + if (!read) return null;
514 + return {
515 + actionId: read.actionId,
516 + execute: async () => {
517 + if (read.kind === 'repo') return addRepoAdvancedButtons(await menu.renderByCallback(data), read.repoId);
518 + if (read.kind === 'commits') return typeof github.listCommits === 'function' ? commitsView(github, read.repoId) : menu.renderByCallback(data);
519 + if (read.kind === 'commitdetail') return commitDetailView(github, read.repoId, read.sha);
520 + if (read.kind === 'runs') return workflowRunsView(github, read.repoId, read.page);
521 + if (read.kind === 'run') return workflowRunView(github, read.repoId, read.runId);
522 + if (read.kind === 'jobs') return workflowJobsView(github, read.repoId, read.runId);
523 + if (read.kind === 'job') return workflowJobView(github, read.repoId, read.jobId);
524 + if (read.kind === 'joblog') return workflowJobLogView(github, read.repoId, read.jobId);
525 + if (read.kind === 'artifacts') return workflowArtifactsView(github, read.repoId, read.runId, read.page);
526 + if (read.kind === 'branches') return branchesView(github, read.repoId, read.page);
527 + if (read.kind === 'compare') return compareView(github, read.repoId, read.sha);
528 + if (read.kind === 'prs') return pullRequestsView(github, read.repoId, read.page);
529 + if (read.kind === 'prdetail') return pullRequestDetailView(github, read.repoId, read.prNumber);
530 + if (read.kind === 'prfiles') return pullRequestFilesView(github, read.repoId, read.prNumber, read.page);
531 + if (read.kind === 'prchecks') return pullRequestChecksView(github, read.repoId, read.prNumber, read.page);
532 + if (read.kind === 'issues') return issuesView(github, read.repoId, read.page);
533 + if (read.kind === 'issuedetail') return issueDetailView(github, read.repoId, read.issueNumber);
534 + if (read.kind === 'releases') return releasesView(github, read.repoId, read.page);
535 + if (read.kind === 'releasedetail') return releaseDetailView(github, read.repoId, read.releaseId);
536 + return menu.renderByCallback(data);
537 + }
538 + };
539 + }
540 + };
541 +}
src/plugins/github/plugin.js
+20 -540
@@ -1,541 +1,21 @@
1 -import { githubPluginManifest } from './manifest.js';
2 -import { createWorkspaceController } from './workspace.js';
3 -
4 -const CALLBACK_ACTIONS = Object.freeze([
5 - ['files:', 'github.files.list'],
6 - ['tree:', 'github.tree.read'],
7 - ['blob:', 'github.blob.read'],
8 - ['pr:', 'github.pr.list'],
9 - ['commits:', 'github.commits.list'],
10 - ['status:', 'github.status.read']
11 -]);
12 -
13 -const escapeHtml = value => String(value ?? '')
14 - .replaceAll('&', '&amp;')
15 - .replaceAll('<', '&lt;')
16 - .replaceAll('>', '&gt;')
17 - .replaceAll('"', '&quot;');
18 -
19 -const short = (value, max = 80) => {
20 - const text = String(value ?? '');
21 - return text.length > max ? `${text.slice(0, max - 1)}…` : text;
22 -};
23 -
24 -const numericPair = (value, prefix) => {
25 - const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)$`));
26 - if (!match) return null;
27 - return { repoId: Number(match[1]), runId: Number(match[2]) };
28 -};
29 -
30 -const numericTriple = (value, prefix) => {
31 - const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+):(\\d+)$`));
32 - if (!match) return null;
33 - return {
34 - repoId: Number(match[1]),
35 - itemId: Number(match[2]),
36 - page: Math.max(1, Math.min(100, Number(match[3]) || 1))
37 - };
38 -};
39 -
40 -const pagedPair = (value, prefix) => {
41 - const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)(?::(\\d+))?$`));
42 - if (!match) return null;
43 - return {
44 - repoId: Number(match[1]),
45 - itemId: Number(match[2]),
46 - page: Math.max(1, Math.min(100, Number(match[3]) || 1))
47 - };
48 -};
49 -
50 -const numericSingle = (value, prefix) => {
51 - const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)$`));
52 - return match ? Number(match[1]) : null;
53 -};
54 -
55 -const pagedSingle = (value, prefix) => {
56 - const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)(?::(\\d+))?$`));
57 - if (!match) return null;
58 - return {
59 - repoId: Number(match[1]),
60 - page: Math.max(1, Math.min(100, Number(match[2]) || 1))
61 - };
62 -};
63 -
64 -const compareRef = value => {
65 - const match = String(value || '').match(/^compare:(\d+):([a-f0-9]{40})$/i);
66 - if (!match) return null;
67 - return { repoId: Number(match[1]), sha: match[2] };
68 -};
69 -
70 -const commitDetailRef = value => {
71 - const match = String(value || '').match(/^commitdetail:(\d+):([a-f0-9]{40})$/i);
72 - if (!match) return null;
73 - return { repoId: Number(match[1]), sha: match[2] };
74 -};
75 -
76 -const workflowRunsPage = value => pagedSingle(value, 'runs');
77 -
78 -const runIcon = run => {
79 - if (run.conclusion === 'success') return '✅';
80 - if (run.conclusion === 'failure') return '❌';
81 - if (run.conclusion === 'cancelled') return '⏹';
82 - return run.status === 'in_progress' ? '🟡' : '⏳';
83 -};
84 -
85 -const stateIcon = value => {
86 - if (value === 'success' || value === 'completed') return '✅';
87 - if (value === 'failure') return '❌';
88 - if (value === 'cancelled') return '⏹';
89 - if (value === 'open') return '🟢';
90 - if (value === 'closed') return '⚫';
91 - return '•';
92 -};
93 -
94 -const addRepoAdvancedButtons = (view, repoId) => {
95 - const rows = [...(view?.reply_markup?.inline_keyboard || [])];
96 - const insertAt = Math.max(0, rows.length - 1);
97 - rows.splice(insertAt, 0,
98 - [{ text: '🌿 Branches', callback_data: `branches:${repoId}` }],
99 - [
100 - { text: '🐛 Issues', callback_data: `issues:${repoId}` },
101 - { text: '🏷 Releases', callback_data: `releases:${repoId}` }
102 - ]
103 - );
104 - return {
105 - ...view,
106 - reply_markup: { ...(view?.reply_markup || {}), inline_keyboard: rows }
107 - };
108 -};
109 -
110 -function listPagination(prefix, repoId, page, count, pageSize) {
111 - const row = [];
112 - if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
113 - if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
114 - return row.length ? [row] : [];
115 -}
116 -
117 -function explicitPagination(prefix, repoId, page, hasMore) {
118 - const row = [];
119 - if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${page - 1}` });
120 - if (hasMore && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${page + 1}` });
121 - return row.length ? [row] : [];
122 -}
123 -
124 -function pairPagination(prefix, repoId, itemId, page, count, pageSize) {
125 - const row = [];
126 - if (page > 1) row.push({ text: '⬅️ جدیدتر', callback_data: `${prefix}:${repoId}:${itemId}:${page - 1}` });
127 - if (count === pageSize && page < 100) row.push({ text: 'قدیمی‌تر ➡️', callback_data: `${prefix}:${repoId}:${itemId}:${page + 1}` });
128 - return row.length ? [row] : [];
129 -}
130 -
131 -async function commitsView(github, repoId) {
132 - const [repo, commits] = await Promise.all([github.getRepository(repoId), github.listCommits(repoId)]);
133 - const body = commits.length
134 - ? commits.slice(0, 10).map(commit => `• <code>${escapeHtml(commit.shortSha || commit.sha)}</code> — ${escapeHtml(short(commit.message, 110))}\n ${escapeHtml(commit.author || 'Unknown')}${commit.date ? ` · ${escapeHtml(commit.date)}` : ''}`).join('\n\n')
135 - : '<i>کامیتی در پاسخ GitHub یافت نشد.</i>';
136 - const detailRows = commits.slice(0, 10).map(commit => {
137 - const sha = String(commit.fullSha || commit.sha || '');
138 - return /^[a-f0-9]{40}$/i.test(sha)
139 - ? [{ text: `📝 ${short(commit.message || sha.slice(0, 7), 42)}`, callback_data: `commitdetail:${repoId}:${sha}` }]
140 - : null;
141 - }).filter(Boolean);
142 - return {
143 - text: `📝 <b>آخرین Commitهای ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
144 - reply_markup: { inline_keyboard: [
145 - ...detailRows,
146 - [{ text: '🔄 بروزرسانی', callback_data: `commits:${repoId}` }, { text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
147 - ] }
148 - };
149 -}
150 -
151 -async function commitDetailView(github, repoId, sha) {
152 - const [repo, commit] = await Promise.all([github.getRepository(repoId), github.getCommit(repoId, sha)]);
153 - const files = (commit.files || []).slice(0, 12)
154 - .map(file => `• <code>${escapeHtml(short(file.filename, 90))}</code> · ${escapeHtml(file.status || 'changed')} · +${file.additions ?? 0}/-${file.deletions ?? 0}`)
155 - .join('\n');
156 - return {
157 - text: `📝 <b>Commit — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(commit.shortSha || String(commit.sha).slice(0, 7))}</code> · ${escapeHtml(commit.author || 'Unknown')}\n${escapeHtml(commit.date || '-')}\n+${commit.additions ?? 0}/-${commit.deletions ?? 0} · ${commit.changedFiles ?? (commit.files || []).length} files\n➖➖➖➖➖➖➖➖➖➖\n${escapeHtml(short(commit.message || '', 1200)) || '<i>بدون پیام.</i>'}\n\n<b>فایل‌های تغییرکرده</b>\n${files || '<i>فایلی گزارش نشده است.</i>'}`,
158 - reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `commitdetail:${repoId}:${sha}` }, { text: '🔙 Commitها', callback_data: `commits:${repoId}` }], [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]] }
159 - };
160 -}
161 -
162 -async function workflowRunsView(github, repoId, page = 1) {
163 - const [repo, runs] = await Promise.all([
164 - github.getRepository(repoId),
165 - github.listWorkflowRuns(repoId, { perPage: 10, page })
166 - ]);
167 - const body = runs.length
168 - ? runs.slice(0, 10).map(run => `${runIcon(run)} <b>${escapeHtml(run.name)}</b> #${run.runNumber ?? '-'}\n └ ${escapeHtml(run.branch || '-')} · <code>${escapeHtml(run.sha || '-')}</code> · ${escapeHtml(run.conclusion || run.status || 'unknown')}`).join('\n\n')
169 - : '<i>Workflow runی یافت نشد.</i>';
170 - const refreshCallback = page === 1 ? `runs:${repoId}` : `runs:${repoId}:${page}`;
171 - return {
172 - text: `🧪 <b>CI / Actions — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
173 - reply_markup: {
174 - inline_keyboard: [
175 - ...runs.slice(0, 10).map(run => [{
176 - text: `${runIcon(run)} ${short(run.name, 32)} #${run.runNumber ?? run.id}`,
177 - callback_data: `run:${repoId}:${run.id}`
178 - }]),
179 - ...listPagination('runs', repoId, page, runs.length, 10),
180 - [
181 - { text: '🔄 بروزرسانی', callback_data: refreshCallback },
182 - { text: '🔙 پروژه', callback_data: `repo:${repoId}` }
183 - ]
184 - ]
185 - }
186 - };
187 -}
188 -
189 -async function workflowRunView(github, repoId, runId) {
190 - const [repo, run] = await Promise.all([
191 - github.getRepository(repoId),
192 - github.getWorkflowRun(repoId, runId)
193 - ]);
194 - const rows = [
195 - [
196 - { text: '👷 Jobها', callback_data: `jobs:${repoId}:${runId}` },
197 - { text: '📦 Artifacts', callback_data: `artifacts:${repoId}:${runId}` }
198 - ]
199 - ];
200 - if (run.conclusion === 'failure') rows.push([{ text: '🔁 اجرای مجدد jobهای ناموفق', callback_data: `rerun:${repoId}:${runId}` }]);
201 - if (run.status === 'in_progress' || run.status === 'queued') rows.push([{ text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }]);
202 - rows.push([
203 - { text: '🔄 بروزرسانی', callback_data: `run:${repoId}:${runId}` },
204 - { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
205 - ]);
206 - return {
207 - text: `🧪 <b>${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\nوضعیت: ${runIcon(run)} <b>${escapeHtml(run.conclusion || run.status || 'unknown')}</b>\nRun: <code>#${escapeHtml(run.runNumber ?? run.id)}</code>\nBranch: <code>${escapeHtml(run.branch || '-')}</code>\nSHA: <code>${escapeHtml(run.sha || '-')}</code>\nTrigger: <code>${escapeHtml(run.event || '-')}</code>`,
208 - reply_markup: { inline_keyboard: rows }
209 - };
210 -}
211 -
212 -async function workflowJobsView(github, repoId, runId) {
213 - const [repo, run, jobs] = await Promise.all([
214 - github.getRepository(repoId),
215 - github.getWorkflowRun(repoId, runId),
216 - github.listWorkflowJobs(repoId, runId)
217 - ]);
218 - const body = jobs.length
219 - ? jobs.slice(0, 20).map(job => {
220 - const jobState = job.conclusion || job.status || 'unknown';
221 - const steps = (job.steps || []).slice(0, 30)
222 - .map(step => ` ${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`)
223 - .join('\n');
224 - return `<b>${escapeHtml(job.name)}</b> — ${escapeHtml(jobState)}${steps ? `\n${steps}` : ''}`;
225 - }).join('\n\n')
226 - : '<i>Jobی در این Run یافت نشد.</i>';
227 - return {
228 - text: `👷 <b>Jobهای ${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
229 - reply_markup: {
230 - inline_keyboard: [
231 - ...jobs.slice(0, 20).map(job => [{ text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`, callback_data: `job:${repoId}:${job.id}` }]),
232 - [{ text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]
233 - ]
234 - }
235 - };
236 -}
237 -
238 -async function workflowJobView(github, repoId, jobId) {
239 - const [repo, job] = await Promise.all([github.getRepository(repoId), github.getWorkflowJob(repoId, jobId)]);
240 - const status = job.conclusion || job.status || 'unknown';
241 - const steps = (job.steps || []).slice(0, 30).map(step => `${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`).join('\n');
242 - const rows = [];
243 - if (job.conclusion === 'failure') rows.push([{ text: '📜 مشاهده log ناموفق', callback_data: `joblog:${repoId}:${jobId}` }]);
244 - rows.push([{ text: '🔄 بروزرسانی', callback_data: `job:${repoId}:${jobId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]);
245 - return {
246 - text: `👷 <b>${escapeHtml(job.name)} — ${escapeHtml(repo.name)}</b>\nوضعیت: ${stateIcon(status)} <b>${escapeHtml(status)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${steps || '<i>Stepی ثبت نشده.</i>'}`,
247 - reply_markup: { inline_keyboard: rows }
248 - };
249 -}
250 -
251 -async function workflowJobLogView(github, repoId, jobId) {
252 - const [job, log] = await Promise.all([
253 - github.getWorkflowJob(repoId, jobId),
254 - github.getWorkflowJobLog(repoId, jobId, { maxChars: 1800 })
255 - ]);
256 - const escaped = escapeHtml(log.text).slice(-3200);
257 - const note = log.truncated ? '⚠️ فقط بخش پایانی log نمایش داده شده است.\n\n' : '';
258 - return {
259 - text: `📜 <b>Log — ${escapeHtml(job.name)}</b>\n${note}<pre>${escaped || '(empty log)'}</pre>`,
260 - reply_markup: { inline_keyboard: [[{ text: '🔙 Job', callback_data: `job:${repoId}:${jobId}` }]] }
261 - };
262 -}
263 -
264 -async function workflowArtifactsView(github, repoId, runId, page = 1) {
265 - const [repo, artifacts] = await Promise.all([
266 - github.getRepository(repoId),
267 - github.listWorkflowArtifacts(repoId, runId, { perPage: 10, page })
268 - ]);
269 - const body = artifacts.length
270 - ? artifacts.slice(0, 10).map(item => `📦 <b>${escapeHtml(item.name)}</b>\n ${item.expired ? 'منقضی شده' : 'فعال'} · ${Number(item.size || 0).toLocaleString()} bytes\n expires: ${escapeHtml(item.expiresAt || '-')}`).join('\n\n')
271 - : '<i>Artifactی برای این Run یافت نشد.</i>';
272 - const refreshCallback = page === 1 ? `artifacts:${repoId}:${runId}` : `artifacts:${repoId}:${runId}:${page}`;
273 - return {
274 - text: `📦 <b>Artifacts — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
275 - reply_markup: { inline_keyboard: [...pairPagination('artifacts', repoId, runId, page, artifacts.length, 10), [{ text: '🔄 بروزرسانی', callback_data: refreshCallback }, { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }]] }
276 - };
277 -}
278 -
279 -async function branchesView(github, repoId, page = 1) {
280 - const [repo, branches] = await Promise.all([github.getRepository(repoId), github.listBranches(repoId, { perPage: 20, page })]);
281 - const body = branches.length
282 - ? branches.slice(0, 20).map(branch => `🌿 <b>${escapeHtml(short(branch.name, 70))}</b>\n <code>${escapeHtml(String(branch.sha).slice(0, 10))}</code>${branch.protected ? ' · 🛡 protected' : ''}`).join('\n\n')
283 - : '<i>Branchی یافت نشد.</i>';
284 - return {
285 - text: `🌿 <b>Branches — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
286 - reply_markup: { inline_keyboard: [
287 - ...branches.slice(0, 20).filter(branch => /^[a-f0-9]{40}$/i.test(String(branch.sha))).map(branch => [{ text: `↔️ ${short(branch.name, 42)}`, callback_data: `compare:${repoId}:${branch.sha}` }]),
288 - ...listPagination('branches', repoId, page, branches.length, 20),
289 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
290 - ] }
291 - };
292 -}
293 -
294 -async function compareView(github, repoId, sha) {
295 - const [repo, compare] = await Promise.all([github.getRepository(repoId), github.compareWithDefault(repoId, sha)]);
296 - const files = (compare.files || []).slice(0, 12).map(file => `${stateIcon(file.status)} <code>${escapeHtml(short(file.filename, 90))}</code> · +${file.additions}/-${file.deletions}`).join('\n');
297 - return {
298 - text: `↔️ <b>Compare — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(compare.base)}</code> ← <code>${escapeHtml(String(compare.head).slice(0, 10))}</code>\nوضعیت: <b>${escapeHtml(compare.status || '-')}</b>\nAhead: <b>${compare.aheadBy ?? 0}</b> · Behind: <b>${compare.behindBy ?? 0}</b> · Commits: <b>${compare.totalCommits ?? 0}</b>\n➖➖➖➖➖➖➖➖➖➖\n${files || '<i>فایل تغییریافته‌ای نیست.</i>'}`,
299 - reply_markup: { inline_keyboard: [[{ text: '🔙 Branches', callback_data: `branches:${repoId}` }]] }
300 - };
301 -}
302 -
303 -async function pullRequestsView(github, repoId, page = 1) {
304 - const [repo, prs] = await Promise.all([github.getRepository(repoId), github.listPullRequests(repoId, { perPage: 10, page })]);
305 - const body = prs.length
306 - ? prs.slice(0, 10).map(pr => `${pr.merged ? '🟣' : stateIcon(pr.state)} <b>#${pr.number} ${escapeHtml(short(pr.title, 100))}</b>\n ${escapeHtml(pr.author)} · ${escapeHtml(pr.merged ? 'merged' : pr.state)}`).join('\n\n')
307 - : '<i>Pull Requestی یافت نشد.</i>';
308 - return {
309 - text: `🔎 <b>Pull Requests — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
310 - reply_markup: { inline_keyboard: [
311 - ...prs.slice(0, 10).map(pr => [{ text: `#${pr.number} ${short(pr.title, 42)}`, callback_data: `prdetail:${repoId}:${pr.number}` }]),
312 - ...listPagination('prs', repoId, page, prs.length, 10),
313 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
314 - ] }
315 - };
316 -}
317 -
318 -async function pullRequestDetailView(github, repoId, prNumber) {
319 - const [repo, pr] = await Promise.all([github.getRepository(repoId), github.getPullRequest(repoId, prNumber)]);
320 - const body = escapeHtml(short(pr.body || '', 600));
321 - return {
322 - text: `🔎 <b>PR #${pr.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(pr.title)}</b>\n${pr.merged ? '🟣 merged' : `${stateIcon(pr.state)} ${escapeHtml(pr.state)}`} · ${escapeHtml(pr.author)}\n<code>${escapeHtml(pr.head || '-')}</code> → <code>${escapeHtml(pr.base || '-')}</code>\n+${pr.additions}/-${pr.deletions} · ${pr.changedFiles} files\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
323 - reply_markup: { inline_keyboard: [[{ text: '🧩 فایل‌ها / Diff', callback_data: `prfiles:${repoId}:${prNumber}:1` }, { text: '✅ Checks', callback_data: `prchecks:${repoId}:${prNumber}:1` }], [{ text: '🔙 PRها', callback_data: `prs:${repoId}` }]] }
324 - };
325 -}
326 -
327 -async function pullRequestFilesView(github, repoId, prNumber, page = 1) {
328 - const files = await github.listPullRequestFiles(repoId, prNumber, { perPage: 8, page });
329 - const body = files.length ? files.slice(0, 8).map(file => {
330 - const patch = escapeHtml(short(file.patch || '', 220));
331 - return `🧩 <code>${escapeHtml(short(file.filename, 100))}</code> · ${escapeHtml(file.status)} · +${file.additions}/-${file.deletions}${patch ? `\n<pre>${patch}</pre>` : ''}`;
332 - }).join('\n\n') : '<i>فایل تغییریافته‌ای یافت نشد.</i>';
333 - return {
334 - text: `🧩 <b>PR #${prNumber} Files / Diff</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
335 - reply_markup: { inline_keyboard: [...pairPagination('prfiles', repoId, prNumber, page, files.length, 8), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
336 - };
337 -}
338 -
339 -async function pullRequestChecksView(github, repoId, prNumber, page = 1) {
340 - const pr = await github.getPullRequest(repoId, prNumber);
341 - const checks = await github.listCommitChecks(repoId, pr.headSha, { perPage: 20, page });
342 - const body = checks.length
343 - ? checks.slice(0, 20).map(check => `${stateIcon(check.conclusion || check.status)} <b>${escapeHtml(check.name)}</b> — ${escapeHtml(check.conclusion || check.status || 'unknown')}`).join('\n')
344 - : '<i>Checkی یافت نشد.</i>';
345 - return {
346 - text: `✅ <b>PR #${prNumber} Checks</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
347 - reply_markup: { inline_keyboard: [...pairPagination('prchecks', repoId, prNumber, page, checks.length, 20), [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]] }
348 - };
349 -}
350 -
351 -async function issuesView(github, repoId, page = 1) {
352 - const [repo, issuePage] = await Promise.all([github.getRepository(repoId), github.listIssuesPage(repoId, { page })]);
353 - const issues = issuePage.items || [];
354 - const body = issues.length
355 - ? issues.slice(0, 20).map(issue => `${stateIcon(issue.state)} <b>#${issue.number} ${escapeHtml(short(issue.title, 110))}</b>\n ${escapeHtml(issue.author)} · ${issue.comments} comments`).join('\n\n')
356 - : '<i>Issueی یافت نشد.</i>';
357 - return {
358 - text: `🐛 <b>Issues — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
359 - reply_markup: { inline_keyboard: [
360 - ...issues.slice(0, 20).map(issue => [{ text: `#${issue.number} ${short(issue.title, 42)}`, callback_data: `issuedetail:${repoId}:${issue.number}` }]),
361 - ...explicitPagination('issues', repoId, page, !!issuePage.hasMore),
362 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
363 - ] }
364 - };
365 -}
366 -
367 -async function issueDetailView(github, repoId, issueNumber) {
368 - const [repo, issue] = await Promise.all([github.getRepository(repoId), github.getIssue(repoId, issueNumber)]);
369 - const labels = (issue.labels || []).map(label => `#${escapeHtml(label)}`).join(' ');
370 - const assignees = (issue.assignees || []).map(name => `@${escapeHtml(name)}`).join(' ');
371 - const body = escapeHtml(short(issue.body || '', 1800));
372 - return {
373 - text: `🐛 <b>Issue #${issue.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(issue.title)}</b>\n${stateIcon(issue.state)} ${escapeHtml(issue.state || 'unknown')} · ${escapeHtml(issue.author)} · ${issue.comments ?? 0} comments\nLabels: ${labels || '-'}\nAssignees: ${assignees || '-'}\nUpdated: ${escapeHtml(issue.updatedAt || issue.createdAt || '-')}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
374 - reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `issuedetail:${repoId}:${issueNumber}` }, { text: '🔙 Issues', callback_data: `issues:${repoId}` }]] }
375 - };
376 -}
377 -
378 -async function releasesView(github, repoId, page = 1) {
379 - const [repo, releases] = await Promise.all([github.getRepository(repoId), github.listReleases(repoId, { perPage: 10, page })]);
380 - const body = releases.length
381 - ? releases.slice(0, 10).map(release => `🏷 <b>${escapeHtml(release.tag || release.name)}</b>${release.prerelease ? ' · pre-release' : ''}${release.draft ? ' · draft' : ''}\n ${escapeHtml(short(release.name, 110))}\n ${escapeHtml(release.publishedAt || '-')}`).join('\n\n')
382 - : '<i>هیچ Release منتشرشده‌ای برای این مخزن در GitHub وجود ندارد.</i>';
383 - return {
384 - text: `🏷 <b>Releases — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
385 - reply_markup: { inline_keyboard: [
386 - ...releases.slice(0, 10).map(release => [{ text: `🏷 ${short(release.tag || release.name, 42)}`, callback_data: `releasedetail:${repoId}:${release.id}` }]),
387 - ...listPagination('releases', repoId, page, releases.length, 10),
388 - [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
389 - ] }
390 - };
391 -}
392 -
393 -async function releaseDetailView(github, repoId, releaseId) {
394 - const [repo, release] = await Promise.all([github.getRepository(repoId), github.getRelease(repoId, releaseId)]);
395 - const body = escapeHtml(short(release.body || '', 1800));
396 - const flags = [release.draft ? 'draft' : '', release.prerelease ? 'pre-release' : ''].filter(Boolean).join(' · ');
397 - return {
398 - text: `🏷 <b>${escapeHtml(release.name)} — ${escapeHtml(repo.name)}</b>\nTag: <code>${escapeHtml(release.tag || '-')}</code>\nTarget: <code>${escapeHtml(release.target || '-')}</code>\nAuthor: ${escapeHtml(release.author || 'unknown')}\nPublished: ${escapeHtml(release.publishedAt || '-')}${flags ? `\nState: ${escapeHtml(flags)}` : ''}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون Release notes.</i>'}`,
399 - reply_markup: { inline_keyboard: [[{ text: '🔄 بروزرسانی', callback_data: `releasedetail:${repoId}:${releaseId}` }, { text: '🔙 Releases', callback_data: `releases:${repoId}` }]] }
400 - };
401 -}
402 -
403 -function workflowActionResultView(repoId, runId, action) {
404 - const rerun = action === 'rerun_failed';
405 - return {
406 - text: rerun ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.' : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
407 - reply_markup: { inline_keyboard: [[{ text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` }, { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }]] }
408 - };
409 -}
410 -
411 -function resolveReadCallback(data) {
412 - const value = String(data || '');
413 - if (value === 'menu:repos') return { actionId: 'github.repos.list', kind: 'legacy' };
414 - const repoId = numericSingle(value, 'repo');
415 - if (repoId !== null) return { actionId: 'github.repo.detail', kind: 'repo', repoId };
416 - const commits = numericSingle(value, 'commits');
417 - if (commits !== null) return { actionId: 'github.commits.list', kind: 'commits', repoId: commits };
418 - const commitdetail = commitDetailRef(value);
419 - if (commitdetail) return { actionId: 'github.commit.detail', kind: 'commitdetail', ...commitdetail };
420 - const legacyStatus = numericSingle(value, 'status');
421 - if (legacyStatus !== null) return { actionId: 'github.workflow.runs.list', kind: 'runs', repoId: legacyStatus, page: 1 };
422 - const runs = workflowRunsPage(value);
423 - if (runs) return { actionId: 'github.workflow.runs.list', kind: 'runs', ...runs };
424 - const run = numericPair(value, 'run');
425 - if (run) return { actionId: 'github.workflow.run.detail', kind: 'run', ...run };
426 - const jobs = numericPair(value, 'jobs');
427 - if (jobs) return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
428 - const job = numericPair(value, 'job');
429 - if (job) return { actionId: 'github.workflow.job.detail', kind: 'job', repoId: job.repoId, jobId: job.runId };
430 - const joblog = numericPair(value, 'joblog');
431 - if (joblog) return { actionId: 'github.workflow.job.log', kind: 'joblog', repoId: joblog.repoId, jobId: joblog.runId };
432 - const artifacts = pagedPair(value, 'artifacts');
433 - if (artifacts) return { actionId: 'github.workflow.artifacts.list', kind: 'artifacts', repoId: artifacts.repoId, runId: artifacts.itemId, page: artifacts.page };
434 - const branches = pagedSingle(value, 'branches');
435 - if (branches) return { actionId: 'github.branches.list', kind: 'branches', ...branches };
436 - const compare = compareRef(value);
437 - if (compare) return { actionId: 'github.compare.read', kind: 'compare', ...compare };
438 - const legacyPr = numericSingle(value, 'pr');
439 - if (legacyPr !== null) return { actionId: 'github.pr.advanced.list', kind: 'prs', repoId: legacyPr, page: 1 };
440 - const prs = pagedSingle(value, 'prs');
441 - if (prs) return { actionId: 'github.pr.advanced.list', kind: 'prs', ...prs };
442 - const prdetail = numericPair(value, 'prdetail');
443 - if (prdetail) return { actionId: 'github.pr.detail', kind: 'prdetail', repoId: prdetail.repoId, prNumber: prdetail.runId };
444 - const prfiles = numericTriple(value, 'prfiles');
445 - if (prfiles) return { actionId: 'github.pr.files.list', kind: 'prfiles', repoId: prfiles.repoId, prNumber: prfiles.itemId, page: prfiles.page };
446 - const prchecks = numericTriple(value, 'prchecks');
447 - if (prchecks) return { actionId: 'github.pr.checks.list', kind: 'prchecks', repoId: prchecks.repoId, prNumber: prchecks.itemId, page: prchecks.page };
448 - const issues = pagedSingle(value, 'issues');
449 - if (issues) return { actionId: 'github.issues.list', kind: 'issues', ...issues };
450 - const issuedetail = numericPair(value, 'issuedetail');
451 - if (issuedetail) return { actionId: 'github.issue.detail', kind: 'issuedetail', repoId: issuedetail.repoId, issueNumber: issuedetail.runId };
452 - const releases = pagedSingle(value, 'releases');
453 - if (releases) return { actionId: 'github.releases.list', kind: 'releases', ...releases };
454 - const releasedetail = numericPair(value, 'releasedetail');
455 - if (releasedetail) return { actionId: 'github.release.detail', kind: 'releasedetail', repoId: releasedetail.repoId, releaseId: releasedetail.runId };
456 - for (const [prefix, actionId] of CALLBACK_ACTIONS) {
457 - if (value.startsWith(prefix)) return { actionId, kind: 'legacy' };
458 - }
459 - return null;
460 -}
461 -
462 -function resolveWriteCallback(data) {
463 - const rerun = numericPair(data, 'rerun');
464 - if (rerun) {
465 - return {
466 - actionId: 'github.workflow.run.rerun_failed',
467 - approval: { input: rerun, label: 'اجرای مجدد jobهای ناموفق' },
468 - execute: async github => {
469 - await github.rerunFailedWorkflowRun(rerun.repoId, rerun.runId);
470 - return workflowActionResultView(rerun.repoId, rerun.runId, 'rerun_failed');
471 - }
472 - };
473 - }
474 - const cancel = numericPair(data, 'cancelrun');
475 - if (cancel) {
476 - return {
477 - actionId: 'github.workflow.run.cancel',
478 - approval: { input: cancel, label: 'لغو Workflow در حال اجرا' },
479 - execute: async github => {
480 - await github.cancelWorkflowRun(cancel.repoId, cancel.runId);
481 - return workflowActionResultView(cancel.repoId, cancel.runId, 'cancel');
482 - }
483 - };
484 - }
485 - return null;
486 -}
487 -
488 -export function createGitHubPlugin({ github, menu, workspaces } = {}) {
489 - if (!github) throw new Error('GitHub plugin requires github service');
490 - if (!menu) throw new Error('GitHub plugin requires menu manager');
491 - const workspaceController = workspaces ? createWorkspaceController({ github, workspaces }) : null;
492 -
493 - return {
494 - manifest: githubPluginManifest,
495 -
496 - resolveCommand(command) {
497 - if (command !== '/repos') return null;
498 - return { actionId: 'github.repos.list', execute: () => menu.getReposListView() };
499 - },
500 -
501 - resolveMessage(payload, context = {}) {
502 - return workspaceController?.resolveMessage(payload, context) || null;
503 - },
504 -
505 - resolveCallback(data, context = {}) {
506 - const write = resolveWriteCallback(data);
507 - if (write) return { actionId: write.actionId, approval: write.approval, execute: () => write.execute(github) };
508 -
509 - const workspaceRoute = workspaceController?.resolveCallback(data, context);
510 - if (workspaceRoute) return workspaceRoute;
511 -
512 - const read = resolveReadCallback(data);
513 - if (!read) return null;
514 - return {
515 - actionId: read.actionId,
516 - execute: async () => {
517 - if (read.kind === 'repo') return addRepoAdvancedButtons(await menu.renderByCallback(data), read.repoId);
518 - if (read.kind === 'commits') return typeof github.listCommits === 'function' ? commitsView(github, read.repoId) : menu.renderByCallback(data);
519 - if (read.kind === 'commitdetail') return commitDetailView(github, read.repoId, read.sha);
520 - if (read.kind === 'runs') return workflowRunsView(github, read.repoId, read.page);
521 - if (read.kind === 'run') return workflowRunView(github, read.repoId, read.runId);
522 - if (read.kind === 'jobs') return workflowJobsView(github, read.repoId, read.runId);
523 - if (read.kind === 'job') return workflowJobView(github, read.repoId, read.jobId);
524 - if (read.kind === 'joblog') return workflowJobLogView(github, read.repoId, read.jobId);
525 - if (read.kind === 'artifacts') return workflowArtifactsView(github, read.repoId, read.runId, read.page);
526 - if (read.kind === 'branches') return branchesView(github, read.repoId, read.page);
527 - if (read.kind === 'compare') return compareView(github, read.repoId, read.sha);
528 - if (read.kind === 'prs') return pullRequestsView(github, read.repoId, read.page);
529 - if (read.kind === 'prdetail') return pullRequestDetailView(github, read.repoId, read.prNumber);
530 - if (read.kind === 'prfiles') return pullRequestFilesView(github, read.repoId, read.prNumber, read.page);
531 - if (read.kind === 'prchecks') return pullRequestChecksView(github, read.repoId, read.prNumber, read.page);
532 - if (read.kind === 'issues') return issuesView(github, read.repoId, read.page);
533 - if (read.kind === 'issuedetail') return issueDetailView(github, read.repoId, read.issueNumber);
534 - if (read.kind === 'releases') return releasesView(github, read.repoId, read.page);
535 - if (read.kind === 'releasedetail') return releaseDetailView(github, read.repoId, read.releaseId);
536 - return menu.renderByCallback(data);
537 - }
538 - };
539 - }
540 - };
1 +import { createGitHubPlugin as createLegacyGitHubPlugin } from './plugin-legacy.js';
2 +const FULL_SHA = /^[a-f0-9]{40}$/i;
3 +const from36 = value => /^[0-9a-z]+$/i.test(String(value || '')) ? Number.parseInt(value, 36) : NaN;
4 +const mergeRef = value => { const m = String(value || '').match(/^mergepr:([0-9a-z]+):([0-9a-z]+):([a-f0-9]{40})$/i); if (!m) return null; const repoId = from36(m[1]); const prNumber = from36(m[2]); return Number.isSafeInteger(repoId) && Number.isSafeInteger(prNumber) && prNumber > 0 ? { repoId, prNumber, headSha: m[3].toLowerCase() } : null; };
5 +export function createGitHubPlugin(options = {}) {
6 + const { github } = options; const base = createLegacyGitHubPlugin(options);
7 + return { ...base, resolveCallback(data, context = {}) {
8 + const merge = mergeRef(data);
9 + if (merge) return { actionId: 'github.pull_request.merge', approval: { input: merge, label: `Merge PR #${merge.prNumber}`, cancelCallback: `prdetail:${merge.repoId}:${merge.prNumber}` }, execute: async () => {
10 + const current = await github.getPullRequest(merge.repoId, merge.prNumber);
11 + if (current.merged || current.state !== 'open' || current.draft) throw new Error('Pull request is not mergeable');
12 + if (!FULL_SHA.test(String(current.headSha || '')) || String(current.headSha).toLowerCase() !== merge.headSha) throw new Error('Pull request head changed; fresh approval is required');
13 + const result = await github.mergePullRequest(merge.repoId, merge.prNumber, { expectedHeadSha: merge.headSha, mergeMethod: 'squash' });
14 + if (!result?.merged) throw new Error(result?.message || 'GitHub did not merge the pull request');
15 + return { text: `✅ <b>PR #${merge.prNumber} با موفقیت Merge شد.</b>`, reply_markup: { inline_keyboard: [[{ text: '🔙 PRها', callback_data: `prs:${merge.repoId}` }]] } };
16 + } };
17 + const route = base.resolveCallback(data, context); const detail = String(data || '').match(/^prdetail:(\d+):(\d+)$/); if (!route || !detail || typeof route.execute !== 'function') return route;
18 + const repoId = Number(detail[1]); const prNumber = Number(detail[2]);
19 + return { ...route, execute: async () => { const view = await route.execute(); const pr = await github.getPullRequest(repoId, prNumber); if (pr?.state !== 'open' || pr?.merged || pr?.draft || !FULL_SHA.test(String(pr?.headSha || ''))) return view; const callback = `mergepr:${repoId.toString(36)}:${prNumber.toString(36)}:${String(pr.headSha).toLowerCase()}`; if (callback.length > 64) return view; const rows = [...(view?.reply_markup?.inline_keyboard || [])]; rows.splice(Math.max(0, rows.length - 1), 0, [{ text: '🔀 Merge امن (Squash)', callback_data: callback }]); return { ...view, reply_markup: { ...(view.reply_markup || {}), inline_keyboard: rows } }; } };
20 + } };
21 }
test/github-pr-merge.test.js new
+26
@@ -0,0 +1,26 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { GitHubService } from '../src/github.js';
4 +import { githubPluginManifest } from '../src/plugins/github/manifest.js';
5 +import { ApprovalService } from '../src/core/approval.js';
6 +const HEAD_SHA = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
7 +function replayStore() {
8 + const used = new Set(); const payloads = new Map();
9 + return {
10 + async put({ ownerId, nonce, payload }) { payloads.set(`${ownerId}:${nonce}`, payload); return true; },
11 + async peek({ ownerId, nonce }) { return payloads.get(`${ownerId}:${nonce}`) || null; },
12 + async consume({ ownerId, nonce }) { const key = `${ownerId}:${nonce}`; if (used.has(key)) return false; used.add(key); return true; }
13 + };
14 +}
15 +test('PR merge is a DESTRUCTIVE GitHub action', () => { assert.deepEqual(githubPluginManifest.actions['github.pull_request.merge'], { risk: 'DESTRUCTIVE' }); });
16 +test('mergePullRequest requires an exact full PR head SHA', async () => { const github = new GitHubService('token', 'owner'); await assert.rejects(github.mergePullRequest('repo', 42, { expectedHeadSha: 'abc123', mergeMethod: 'squash' }), /head sha|required|expected|invalid/i); });
17 +test('mergePullRequest rejects missing exact-head binding before provider mutation', async () => { const github = new GitHubService('token', 'owner'); await assert.rejects(github.mergePullRequest('repo', 42, { mergeMethod: 'squash' }), /head sha|required|expected/i); });
18 +test('mergePullRequest only accepts supported merge methods', async () => { const github = new GitHubService('token', 'owner'); await assert.rejects(github.mergePullRequest('repo', 42, { expectedHeadSha: HEAD_SHA, mergeMethod: 'octopus' }), /merge method|unsupported/i); });
19 +test('destructive merge approval is owner/action/risk/repo/PR/head bound and replay-safe', async () => {
20 + const service = new ApprovalService({ secret: 'test-secret', now: () => 1700000000000, replayStore: replayStore() });
21 + const token = await service.issue({ pluginId: 'github', actionId: 'github.pull_request.merge', risk: 'DESTRUCTIVE', ownerId: '42', input: { repoId: 7, prNumber: 39, headSha: HEAD_SHA } });
22 + assert.ok(`approve:${token}`.length <= 64);
23 + const payload = await service.consume(token, { ownerId: '42', pluginId: 'github', actionId: 'github.pull_request.merge', risk: 'DESTRUCTIVE' });
24 + assert.deepEqual(payload.input, { repoId: 7, prNumber: 39, headSha: HEAD_SHA });
25 + await assert.rejects(() => service.consume(token, { ownerId: '42' }), /already used/i);
26 +});