@zhin.js/adapter-github 3.0.1 → 3.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +624 -0
  2. package/README.md +38 -190
  3. package/adapters/github.ts +51 -0
  4. package/{skills/github/SKILL.md → agent/skills/github.md} +22 -5
  5. package/agent/tools/bind.ts +12 -0
  6. package/agent/tools/create_pr.ts +19 -0
  7. package/agent/tools/install.ts +12 -0
  8. package/agent/tools/patch_file.ts +18 -0
  9. package/agent/tools/prepare_workspace.ts +14 -0
  10. package/agent/tools/push_branch.ts +17 -0
  11. package/agent/tools/star.ts +15 -0
  12. package/agent/tools/subscribe.ts +16 -0
  13. package/agent/tools/subscriptions.ts +13 -0
  14. package/agent/tools/unbind.ts +12 -0
  15. package/agent/tools/unsubscribe.ts +15 -0
  16. package/agent/tools/whoami.ts +12 -0
  17. package/lib/agent-prompt.d.ts +0 -1
  18. package/lib/agent-prompt.js +10 -9
  19. package/lib/endpoint.d.ts +46 -24
  20. package/lib/endpoint.js +144 -144
  21. package/lib/gh-client.d.ts +73 -1
  22. package/lib/gh-client.js +99 -1
  23. package/lib/github-agent-deps.d.ts +47 -0
  24. package/lib/github-agent-deps.js +43 -0
  25. package/lib/github-bot-handlers.d.ts +26 -0
  26. package/lib/github-bot-handlers.js +77 -0
  27. package/lib/github-channel-context.d.ts +16 -0
  28. package/lib/github-channel-context.js +31 -0
  29. package/lib/github-tool-handlers.d.ts +17 -0
  30. package/lib/github-tool-handlers.js +221 -0
  31. package/lib/index.d.ts +7 -32
  32. package/lib/index.js +7 -386
  33. package/lib/oauth-users.d.ts +33 -0
  34. package/lib/oauth-users.js +38 -0
  35. package/lib/protocol.d.ts +87 -0
  36. package/lib/protocol.js +241 -0
  37. package/lib/types.d.ts +6 -1
  38. package/lib/types.js +0 -1
  39. package/lib/webhook.d.ts +13 -0
  40. package/lib/webhook.js +87 -0
  41. package/lib/workspace-manager.d.ts +21 -0
  42. package/lib/workspace-manager.js +145 -0
  43. package/package.json +60 -23
  44. package/plugin.ts +52 -0
  45. package/schema.json +65 -0
  46. package/src/agent-prompt.ts +11 -10
  47. package/src/endpoint.ts +169 -150
  48. package/src/gh-client.ts +131 -0
  49. package/src/github-agent-deps.ts +82 -0
  50. package/src/github-bot-handlers.ts +109 -0
  51. package/src/github-channel-context.ts +46 -0
  52. package/src/github-tool-handlers.ts +257 -0
  53. package/src/index.ts +55 -431
  54. package/src/oauth-users.ts +47 -0
  55. package/src/protocol.ts +367 -0
  56. package/src/types.ts +6 -0
  57. package/src/webhook.ts +125 -0
  58. package/src/workspace-manager.ts +158 -0
  59. package/lib/adapter.d.ts +0 -66
  60. package/lib/adapter.d.ts.map +0 -1
  61. package/lib/adapter.js +0 -418
  62. package/lib/adapter.js.map +0 -1
  63. package/lib/agent-prompt.d.ts.map +0 -1
  64. package/lib/agent-prompt.js.map +0 -1
  65. package/lib/endpoint.d.ts.map +0 -1
  66. package/lib/endpoint.js.map +0 -1
  67. package/lib/gh-client.d.ts.map +0 -1
  68. package/lib/gh-client.js.map +0 -1
  69. package/lib/index.d.ts.map +0 -1
  70. package/lib/index.js.map +0 -1
  71. package/lib/register-github-mcp.d.ts +0 -7
  72. package/lib/register-github-mcp.d.ts.map +0 -1
  73. package/lib/register-github-mcp.js +0 -36
  74. package/lib/register-github-mcp.js.map +0 -1
  75. package/lib/segment-mapper.d.ts +0 -2
  76. package/lib/segment-mapper.d.ts.map +0 -1
  77. package/lib/segment-mapper.js +0 -2
  78. package/lib/segment-mapper.js.map +0 -1
  79. package/lib/types.d.ts.map +0 -1
  80. package/lib/types.js.map +0 -1
  81. package/plugin.yml +0 -3
  82. package/src/adapter.ts +0 -450
  83. package/src/register-github-mcp.ts +0 -62
  84. package/src/segment-mapper.ts +0 -1
@@ -0,0 +1,367 @@
1
+ /**
2
+ * GitHub webhook / comment helpers — no legacy Adapter/Endpoint / segment-mapper.
3
+ * Canonicalization is owned by gateway/core before endpoint.send.
4
+ */
5
+
6
+ import { createHmac, timingSafeEqual } from 'node:crypto';
7
+ import type { IncomingMessage } from 'node:http';
8
+ import { pickCredential } from '@zhin.js/adapter';
9
+ import {
10
+ buildChannelId,
11
+ type GenericWebhookPayload,
12
+ type IssueCommentPayload,
13
+ type PRReviewCommentPayload,
14
+ type PRReviewPayload,
15
+ } from './types.js';
16
+
17
+ export type {
18
+ EventType,
19
+ GenericWebhookPayload,
20
+ GitHubComment,
21
+ GitHubEndpointConfig,
22
+ GitHubIssue,
23
+ GitHubOAuthUser,
24
+ GitHubPR,
25
+ GitHubRepo,
26
+ GitHubUser,
27
+ IssueCommentPayload,
28
+ ParsedChannel,
29
+ PRReviewCommentPayload,
30
+ PRReviewPayload,
31
+ Subscription,
32
+ } from './types.js';
33
+
34
+ export { buildChannelId, parseChannelId } from './types.js';
35
+
36
+ /** Plugin Runtime owner config (`plugins.<instanceKey>` / schema.json). */
37
+ export interface GithubAdapterConfig {
38
+ readonly name?: string;
39
+ readonly host?: string;
40
+ readonly app_id?: string | number;
41
+ readonly appId?: string | number;
42
+ readonly private_key?: string;
43
+ readonly privateKey?: string;
44
+ readonly webhook_secret?: string;
45
+ readonly webhookSecret?: string;
46
+ readonly webhook_path?: string;
47
+ readonly webhookPath?: string;
48
+ readonly poll_interval?: number;
49
+ readonly pollInterval?: number;
50
+ readonly auto_reply_repos?: readonly string[];
51
+ readonly autoReplyRepos?: readonly string[];
52
+ readonly bot_login?: string;
53
+ readonly botLogin?: string;
54
+ readonly workspace_root?: string;
55
+ readonly workspaceRoot?: string;
56
+ /** Transitional: legacy root `endpoints[]` with `context: github`. */
57
+ readonly endpoints?: ReadonlyArray<Partial<ResolvedGithubConfig> & {
58
+ readonly context?: string;
59
+ readonly app_id?: string | number;
60
+ readonly private_key?: string;
61
+ readonly webhook_secret?: string;
62
+ readonly webhook_path?: string;
63
+ readonly poll_interval?: number;
64
+ readonly auto_reply_repos?: readonly string[];
65
+ readonly bot_login?: string;
66
+ readonly workspace_root?: string;
67
+ }>;
68
+ }
69
+
70
+ export interface ResolvedGithubConfig {
71
+ readonly context: 'github';
72
+ readonly name: string;
73
+ readonly host?: string;
74
+ readonly appId?: string | number;
75
+ readonly privateKey?: string;
76
+ readonly webhookSecret?: string;
77
+ readonly webhookPath: string;
78
+ readonly pollInterval: number;
79
+ readonly autoReplyRepos: readonly string[];
80
+ readonly botLogin?: string;
81
+ readonly workspaceRoot?: string;
82
+ }
83
+
84
+ export interface GithubWireSegment {
85
+ readonly type: string;
86
+ readonly data?: Record<string, unknown>;
87
+ }
88
+
89
+ export interface GithubInboundComment {
90
+ readonly id: string;
91
+ readonly channelId: string;
92
+ readonly sender: string;
93
+ readonly content: string;
94
+ readonly repo: string;
95
+ readonly kind: 'issue_comment' | 'pr_review_comment' | 'pr_review';
96
+ readonly createdAt: number;
97
+ }
98
+
99
+ export function resolveGithubConfig(config: GithubAdapterConfig = {}): ResolvedGithubConfig {
100
+ const entry = config.endpoints?.find((item) => item.context === 'github');
101
+ const appIdRaw = pickCredential(
102
+ config.appId != null ? String(config.appId) : undefined,
103
+ config.app_id != null ? String(config.app_id) : undefined,
104
+ entry?.appId != null ? String(entry.appId) : undefined,
105
+ entry?.app_id != null ? String(entry.app_id) : undefined,
106
+ process.env.GITHUB_APP_ID,
107
+ );
108
+ const appId = appIdRaw ? (Number(appIdRaw) || appIdRaw) : undefined;
109
+ const privateKey = pickCredential(
110
+ config.privateKey,
111
+ config.private_key,
112
+ entry?.privateKey,
113
+ entry?.private_key,
114
+ ) || undefined;
115
+ if (!appId || !privateKey) {
116
+ throw new TypeError(
117
+ 'GitHub adapter requires app_id + private_key (plugins.<key> or GITHUB_APP_ID)',
118
+ );
119
+ }
120
+ const name = (typeof config.name === 'string' && config.name)
121
+ || (typeof entry?.name === 'string' && entry.name)
122
+ || process.env.GITHUB_BOT_NAME
123
+ || 'github-bot';
124
+ const webhookSecret = config.webhookSecret ?? config.webhook_secret
125
+ ?? entry?.webhookSecret ?? entry?.webhook_secret
126
+ ?? process.env.GITHUB_WEBHOOK_SECRET
127
+ ?? undefined;
128
+ const host = config.host ?? entry?.host;
129
+ const webhookPath = normalizeWebhookPath(
130
+ config.webhookPath ?? config.webhook_path ?? entry?.webhookPath ?? entry?.webhook_path
131
+ ?? '/github/webhook',
132
+ );
133
+ const pollInterval = Number(
134
+ config.pollInterval ?? config.poll_interval ?? entry?.pollInterval ?? entry?.poll_interval ?? 60,
135
+ ) || 60;
136
+ const autoReplyRepos = [
137
+ ...(config.autoReplyRepos ?? config.auto_reply_repos
138
+ ?? entry?.autoReplyRepos ?? entry?.auto_reply_repos ?? []),
139
+ ];
140
+ const botLogin = config.botLogin ?? config.bot_login ?? entry?.botLogin ?? entry?.bot_login;
141
+ const workspaceRoot = config.workspaceRoot ?? config.workspace_root
142
+ ?? entry?.workspaceRoot ?? entry?.workspace_root;
143
+
144
+ return {
145
+ context: 'github',
146
+ name,
147
+ ...(host ? { host } : {}),
148
+ ...(appId != null ? { appId } : {}),
149
+ ...(privateKey ? { privateKey } : {}),
150
+ ...(webhookSecret ? { webhookSecret } : {}),
151
+ webhookPath,
152
+ pollInterval,
153
+ autoReplyRepos,
154
+ ...(botLogin ? { botLogin } : {}),
155
+ ...(workspaceRoot ? { workspaceRoot } : {}),
156
+ };
157
+ }
158
+
159
+ export function normalizeWebhookPath(path: string): string {
160
+ const trimmed = path.trim() || '/github/webhook';
161
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
162
+ }
163
+
164
+ export function shouldAutoReplyRepo(
165
+ config: Pick<ResolvedGithubConfig, 'autoReplyRepos'>,
166
+ repo: string,
167
+ ): boolean {
168
+ const list = config.autoReplyRepos;
169
+ if (!list.length) return false;
170
+ const key = repo.toLowerCase();
171
+ return list.some((r) => r.toLowerCase() === key);
172
+ }
173
+
174
+ /** Prepend synthetic @bot for auto_reply repos (gateway text path). */
175
+ export function enrichInboundContent(
176
+ content: string,
177
+ config: Pick<ResolvedGithubConfig, 'autoReplyRepos' | 'botLogin'>,
178
+ botLogin: string | undefined,
179
+ repo: string,
180
+ ): string {
181
+ const login = config.botLogin || botLogin;
182
+ if (!login || !shouldAutoReplyRepo(config, repo)) return content;
183
+ if (content.includes(`@${login}`)) return content;
184
+ return `@${login} ${content}`;
185
+ }
186
+
187
+ /** Build inbound text for MessageGateway.receive from markdown/comment body. */
188
+ export function formatInboundContent(body: string): string {
189
+ return body;
190
+ }
191
+
192
+ /** Build markdown body for Issue/PR comment send. */
193
+ export function formatOutboundBody(payload: unknown): string {
194
+ if (typeof payload === 'string') return payload;
195
+ if (payload == null) return '';
196
+ if (!Array.isArray(payload)) {
197
+ if (typeof payload === 'object' && payload !== null && 'text' in payload) {
198
+ return String((payload as { text?: unknown }).text ?? '');
199
+ }
200
+ return String(payload);
201
+ }
202
+ return payload.map((seg) => {
203
+ if (typeof seg === 'string') return seg;
204
+ const item = seg as GithubWireSegment;
205
+ switch (item.type) {
206
+ case 'text':
207
+ return String(item.data?.text ?? '');
208
+ case 'mention':
209
+ case 'at':
210
+ return `@${item.data?.name || item.data?.id || item.data?.target || ''}`;
211
+ case 'image':
212
+ return item.data?.url ? `![image](${item.data.url})` : '[image]';
213
+ case 'link':
214
+ return `[${item.data?.text || item.data?.url || ''}](${item.data?.url || ''})`;
215
+ default:
216
+ return String(item.data?.text ?? `[${item.type}]`);
217
+ }
218
+ }).join('');
219
+ }
220
+
221
+ export function verifyWebhookSignature(
222
+ secret: string,
223
+ rawBody: string,
224
+ signatureHeader: string | undefined,
225
+ ): boolean {
226
+ if (!signatureHeader?.startsWith('sha256=')) return false;
227
+ const expected = `sha256=${createHmac('sha256', secret).update(rawBody).digest('hex')}`;
228
+ try {
229
+ const a = Buffer.from(signatureHeader);
230
+ const b = Buffer.from(expected);
231
+ if (a.length !== b.length) return false;
232
+ return timingSafeEqual(a, b);
233
+ } catch {
234
+ return false;
235
+ }
236
+ }
237
+
238
+ export function headerValue(
239
+ headers: IncomingMessage['headers'],
240
+ name: string,
241
+ ): string {
242
+ const raw = headers[name] ?? headers[name.toLowerCase()];
243
+ if (Array.isArray(raw)) return raw[0] ?? '';
244
+ return raw ?? '';
245
+ }
246
+
247
+ export async function readTextBody(
248
+ request: IncomingMessage,
249
+ options: { readonly limit?: number } = {},
250
+ ): Promise<string> {
251
+ const limit = options.limit ?? 1_048_576;
252
+ const chunks: Buffer[] = [];
253
+ let size = 0;
254
+ for await (const chunk of request) {
255
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
256
+ size += buffer.length;
257
+ if (size > limit) {
258
+ request.destroy();
259
+ throw new Error(`Request body exceeds ${limit} bytes`);
260
+ }
261
+ chunks.push(buffer);
262
+ }
263
+ return Buffer.concat(chunks).toString('utf8');
264
+ }
265
+
266
+ export function parseIssueCommentInbound(payload: IssueCommentPayload): GithubInboundComment | null {
267
+ if (payload.action !== 'created' || !payload.comment) return null;
268
+ const repo = payload.repository.full_name;
269
+ const isPR = 'pull_request' in (payload.issue as object);
270
+ return {
271
+ id: String(payload.comment.id),
272
+ channelId: buildChannelId(repo, isPR ? 'pr' : 'issue', payload.issue.number),
273
+ sender: payload.sender.login,
274
+ content: payload.comment.body,
275
+ repo,
276
+ kind: 'issue_comment',
277
+ createdAt: new Date(payload.comment.created_at).getTime(),
278
+ };
279
+ }
280
+
281
+ export function parsePrReviewCommentInbound(payload: PRReviewCommentPayload): GithubInboundComment | null {
282
+ if (payload.action !== 'created' || !payload.comment) return null;
283
+ const repo = payload.repository.full_name;
284
+ const body = payload.comment.path
285
+ ? `**${payload.comment.path}**\n${payload.comment.diff_hunk ? `\`\`\`diff\n${payload.comment.diff_hunk}\n\`\`\`\n` : ''}${payload.comment.body}`
286
+ : payload.comment.body;
287
+ return {
288
+ id: String(payload.comment.id),
289
+ channelId: buildChannelId(repo, 'pr', payload.pull_request.number),
290
+ sender: payload.sender.login,
291
+ content: body,
292
+ repo,
293
+ kind: 'pr_review_comment',
294
+ createdAt: new Date(payload.comment.created_at).getTime(),
295
+ };
296
+ }
297
+
298
+ export function parsePrReviewInbound(payload: PRReviewPayload): GithubInboundComment | null {
299
+ if (payload.action !== 'submitted' || !payload.review.body) return null;
300
+ const repo = payload.repository.full_name;
301
+ const stateLabel: Record<string, string> = {
302
+ approved: '✅ APPROVED',
303
+ changes_requested: '🔄 CHANGES REQUESTED',
304
+ commented: '💬 COMMENTED',
305
+ dismissed: '❌ DISMISSED',
306
+ };
307
+ const body = `**[${stateLabel[payload.review.state] || payload.review.state}]**\n${payload.review.body}`;
308
+ return {
309
+ id: String(payload.review.id),
310
+ channelId: buildChannelId(repo, 'pr', payload.pull_request.number),
311
+ sender: payload.sender.login,
312
+ content: body,
313
+ repo,
314
+ kind: 'pr_review',
315
+ createdAt: new Date(payload.review.submitted_at).getTime(),
316
+ };
317
+ }
318
+
319
+ export function formatNotification(event: string, p: GenericWebhookPayload): string {
320
+ const repo = p.repository.full_name;
321
+ const sender = p.sender.login;
322
+ const repoUrl = p.repository.html_url;
323
+ switch (event) {
324
+ case 'push': {
325
+ const branch = p.ref?.replace('refs/heads/', '') || '?';
326
+ const commits = p.commits || [];
327
+ const compareUrl = commits.length >= 2
328
+ ? `${repoUrl}/compare/${commits[0].id.substring(0, 12)}...${commits[commits.length - 1].id.substring(0, 12)}`
329
+ : commits.length === 1 ? `${repoUrl}/commit/${commits[0].id}` : '';
330
+ let msg = `📦 ${repo}\n🌿 ${sender} pushed ${commits.length} commit(s) to \`${branch}\`\n`;
331
+ if (commits.length) {
332
+ msg += '\n';
333
+ msg += commits.slice(0, 5).map((c) =>
334
+ ` • [\`${c.id.substring(0, 7)}\`](${repoUrl}/commit/${c.id}) ${c.message.split('\n')[0]}`,
335
+ ).join('\n');
336
+ if (commits.length > 5) msg += `\n ... +${commits.length - 5} more`;
337
+ }
338
+ if (compareUrl) msg += `\n\n🔗 ${compareUrl}`;
339
+ return msg;
340
+ }
341
+ case 'issues': {
342
+ const i = p.issue!;
343
+ const act = p.action === 'opened' ? '📝 opened' : p.action === 'closed' ? '✅ closed' : `🔄 ${p.action || 'updated'}`;
344
+ return `🐛 ${repo}\n👤 ${sender} ${act} issue #${i.number}\n📌 ${i.title}\n🔗 ${i.html_url}`;
345
+ }
346
+ case 'star': {
347
+ const starred = p.action !== 'deleted';
348
+ return `${starred ? '⭐' : '💔'} ${repo}\n👤 ${sender} ${starred ? 'starred' : 'unstarred'}\n🔗 ${repoUrl}`;
349
+ }
350
+ case 'fork':
351
+ return `🍴 ${repo}\n👤 ${sender} forked → ${p.forkee!.full_name}\n🔗 ${p.forkee!.html_url}`;
352
+ case 'pull_request': {
353
+ const pr = p.pull_request!;
354
+ const act = p.action === 'opened' ? '📝 opened'
355
+ : p.action === 'closed' ? (pr.state === 'closed' ? '❌ closed' : '✅ merged')
356
+ : `🔄 ${p.action || 'updated'}`;
357
+ return `🔀 ${repo}\n👤 ${sender} ${act} PR #${pr.number}\n📌 ${pr.title}\n🌿 ${pr.head.ref} → ${pr.base.ref}\n🔗 ${pr.html_url}`;
358
+ }
359
+ default:
360
+ return `📬 ${repo}\n📡 ${event}${p.action ? ` (${p.action})` : ''} by ${sender}\n🔗 ${repoUrl}`;
361
+ }
362
+ }
363
+
364
+ /** Parse @mentions in markdown into a flat display string (gateway text path). */
365
+ export function parseMarkdownMentions(md: string): string {
366
+ return md;
367
+ }
package/src/types.ts CHANGED
@@ -18,6 +18,12 @@ export interface GitHubEndpointConfig {
18
18
  webhook_path?: string;
19
19
  /** 事件轮询间隔(秒,默认 60,Webhook 模式下作为降级备选) */
20
20
  poll_interval?: number;
21
+ /** 这些仓库的人类 Issue/PR 评论自动触发 AI(无需 @bot) */
22
+ auto_reply_repos?: string[];
23
+ /** 覆盖 App bot 登录名(默认 {slug}[bot]) */
24
+ bot_login?: string;
25
+ /** 托管 git 工作区根目录(默认 {cwd}/data/github-workspaces) */
26
+ workspace_root?: string;
21
27
  }
22
28
 
23
29
  // ── Channel ID ───────────────────────────────────────────────────────
package/src/webhook.ts ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * GitHub webhook HTTP: verify → parse → admit inbound comments.
3
+ */
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
6
+ import { formatCompact, getLogger } from '@zhin.js/logger';
7
+ import {
8
+ headerValue,
9
+ parseIssueCommentInbound,
10
+ parsePrReviewCommentInbound,
11
+ parsePrReviewInbound,
12
+ readTextBody,
13
+ verifyWebhookSignature,
14
+ type GithubInboundComment,
15
+ type IssueCommentPayload,
16
+ type PRReviewCommentPayload,
17
+ type PRReviewPayload,
18
+ type ResolvedGithubConfig,
19
+ } from './protocol.js';
20
+
21
+ const logger = getLogger('github');
22
+
23
+ export interface GithubWebhookHandler {
24
+ readonly config: ResolvedGithubConfig;
25
+ admit(comment: GithubInboundComment): void;
26
+ }
27
+
28
+ export function registerGithubWebhookRoutes(
29
+ http: HttpHost,
30
+ handler: GithubWebhookHandler,
31
+ ): HttpRouteRegistration[] {
32
+ const routePath = handler.config.webhookPath;
33
+ return [
34
+ http.route('POST', routePath, async (request, response) => {
35
+ await handleGithubWebhookRequest(request, response, handler);
36
+ }, { summary: 'GitHub webhook', tags: ['github'] }),
37
+ ];
38
+ }
39
+
40
+ export async function handleGithubWebhookRequest(
41
+ request: IncomingMessage,
42
+ response: ServerResponse,
43
+ handler: GithubWebhookHandler,
44
+ ): Promise<void> {
45
+ const secret = handler.config.webhookSecret;
46
+ if (!secret) {
47
+ response.writeHead(503, { 'Content-Type': 'application/json' });
48
+ response.end(JSON.stringify({ error: 'Webhook not configured' }));
49
+ return;
50
+ }
51
+
52
+ const signature = headerValue(request.headers, 'x-hub-signature-256');
53
+ const event = headerValue(request.headers, 'x-github-event');
54
+ const deliveryId = headerValue(request.headers, 'x-github-delivery');
55
+
56
+ if (!signature || !event) {
57
+ response.writeHead(400, { 'Content-Type': 'application/json' });
58
+ response.end(JSON.stringify({ error: 'Missing signature or event header' }));
59
+ return;
60
+ }
61
+
62
+ try {
63
+ const rawBody = await readTextBody(request);
64
+ if (!verifyWebhookSignature(secret, rawBody, signature)) {
65
+ logger.warn(formatCompact({
66
+ op: 'webhook',
67
+ ok: false,
68
+ error: 'invalid signature',
69
+ delivery: deliveryId,
70
+ }));
71
+ response.writeHead(401, { 'Content-Type': 'application/json' });
72
+ response.end(JSON.stringify({ error: 'Invalid signature' }));
73
+ return;
74
+ }
75
+
76
+ let payload: unknown;
77
+ try {
78
+ payload = rawBody ? JSON.parse(rawBody) : {};
79
+ } catch {
80
+ response.writeHead(400, { 'Content-Type': 'application/json' });
81
+ response.end(JSON.stringify({ error: 'Invalid JSON' }));
82
+ return;
83
+ }
84
+
85
+ response.writeHead(200, { 'Content-Type': 'application/json' });
86
+ response.end(JSON.stringify({ ok: true }));
87
+
88
+ void dispatchGithubWebhookPayload(event, payload, handler).catch((e) => {
89
+ logger.error(`Webhook 事件处理失败 (${event}):`, e);
90
+ });
91
+ } catch (error) {
92
+ logger.error('Webhook error:', error);
93
+ if (!response.headersSent) {
94
+ response.writeHead(500, { 'Content-Type': 'application/json' });
95
+ response.end(JSON.stringify({ error: 'Internal Server Error' }));
96
+ }
97
+ }
98
+ }
99
+
100
+ export async function dispatchGithubWebhookPayload(
101
+ event: string,
102
+ payload: unknown,
103
+ handler: GithubWebhookHandler,
104
+ ): Promise<void> {
105
+ if (!payload || typeof payload !== 'object') return;
106
+ const body = payload as Record<string, unknown>;
107
+ const repo = (body.repository as { full_name?: string } | undefined)?.full_name;
108
+ logger.debug(`Webhook: ${event}${(body.action as string) ? `.${body.action}` : ''} ${repo || ''}`);
109
+
110
+ if (event === 'issue_comment') {
111
+ const inbound = parseIssueCommentInbound(payload as IssueCommentPayload);
112
+ if (inbound) handler.admit(inbound);
113
+ return;
114
+ }
115
+ if (event === 'pull_request_review_comment') {
116
+ const inbound = parsePrReviewCommentInbound(payload as PRReviewCommentPayload);
117
+ if (inbound) handler.admit(inbound);
118
+ return;
119
+ }
120
+ if (event === 'pull_request_review') {
121
+ const inbound = parsePrReviewInbound(payload as PRReviewPayload);
122
+ if (inbound) handler.admit(inbound);
123
+ }
124
+ // Cross-adapter subscription fan-out deferred (needs multi-adapter send in Runtime).
125
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Managed git workspaces for GitHub App Bot development flow.
3
+ */
4
+ import { spawn } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import type { GhClient, GitHubBotIdentity } from './gh-client.js';
8
+
9
+ const REPO_FULL_NAME_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
10
+ const GIT_REF_ILLEGAL_RE = /[\s\x00-\x1f\x7f~^:?*[\\`;]/;
11
+
12
+ /**
13
+ * 校验 GitHub "owner/name" 全名,防止路径穿越与 git 选项注入。
14
+ * 返回通过校验的原值,便于调用方直接使用「已消毒」的变量。
15
+ */
16
+ export function assertRepoFullName(repo: string): string {
17
+ if (
18
+ typeof repo !== 'string' ||
19
+ !REPO_FULL_NAME_RE.test(repo) ||
20
+ repo.split('/').some((seg) => seg === '' || seg.startsWith('-') || /^\.+$/.test(seg))
21
+ ) {
22
+ throw new TypeError(`非法的仓库全名: ${JSON.stringify(repo)}`);
23
+ }
24
+ return repo;
25
+ }
26
+
27
+ /**
28
+ * 校验 git ref 名称,拒绝选项注入(`-` 前缀)与 git 非法字符。
29
+ */
30
+ export function assertGitRefName(ref: string): string {
31
+ if (typeof ref !== 'string' || ref.length === 0) {
32
+ throw new TypeError(`非法的 git ref: ${JSON.stringify(ref)}`);
33
+ }
34
+ if (
35
+ ref.startsWith('-') ||
36
+ ref.includes('..') ||
37
+ GIT_REF_ILLEGAL_RE.test(ref) ||
38
+ ref.endsWith('/') ||
39
+ ref.endsWith('.')
40
+ ) {
41
+ throw new TypeError(`非法的 git ref: ${JSON.stringify(ref)}`);
42
+ }
43
+ return ref;
44
+ }
45
+
46
+ export class WorkspaceManager {
47
+ constructor(
48
+ private readonly gh: GhClient,
49
+ private readonly rootDir: string,
50
+ ) {}
51
+
52
+ getRepoPath(repo: string): string {
53
+ repo = assertRepoFullName(repo);
54
+ const [owner, name] = repo.split('/');
55
+ return path.join(this.rootDir, owner, name);
56
+ }
57
+
58
+ private runGit(cwd: string, args: string[], env?: NodeJS.ProcessEnv): Promise<string> {
59
+ return new Promise((resolve, reject) => {
60
+ const proc = spawn('git', args, {
61
+ cwd,
62
+ stdio: ['ignore', 'pipe', 'pipe'],
63
+ env: { ...process.env, ...env },
64
+ });
65
+ let stdout = '';
66
+ let stderr = '';
67
+ proc.stdout.on('data', (d: Buffer) => { stdout += d.toString(); });
68
+ proc.stderr.on('data', (d: Buffer) => { stderr += d.toString(); });
69
+ proc.on('error', (err: NodeJS.ErrnoException) => {
70
+ if (err.code === 'ENOENT') reject(new Error('git 未安装'));
71
+ else reject(err);
72
+ });
73
+ proc.on('close', (code) => {
74
+ if (code === 0) resolve(stdout);
75
+ else reject(new Error(stderr.trim() || `git ${args.join(' ')} failed (${code})`));
76
+ });
77
+ });
78
+ }
79
+
80
+ configureBotGit(repoPath: string, identity: GitHubBotIdentity): Promise<void> {
81
+ return Promise.all([
82
+ this.runGit(repoPath, ['config', 'user.name', identity.login]),
83
+ this.runGit(repoPath, ['config', 'user.email', identity.email]),
84
+ ]).then(() => undefined);
85
+ }
86
+
87
+ async ensureRepo(repo: string): Promise<string> {
88
+ repo = assertRepoFullName(repo);
89
+ if (!this.gh.isAppAuth) {
90
+ throw new Error('GitHub App 认证未配置,无法托管工作区');
91
+ }
92
+ const token = await this.gh.ensureInstallationTokenForRepo(repo);
93
+ if (!token) throw new Error(`无法获取 ${repo} 的 Installation Token`);
94
+
95
+ const repoPath = this.getRepoPath(repo);
96
+ fs.mkdirSync(path.dirname(repoPath), { recursive: true });
97
+
98
+ const identity = await this.gh.getBotIdentity();
99
+ if (!identity) throw new Error('无法解析 GitHub App Bot 身份');
100
+
101
+ const cloneUrl = this.gh.buildCloneUrl(repo, token);
102
+ if (!fs.existsSync(path.join(repoPath, '.git'))) {
103
+ await this.runGit(path.dirname(repoPath), ['clone', cloneUrl, path.basename(repoPath)]);
104
+ } else {
105
+ await this.runGit(repoPath, ['remote', 'set-url', 'origin', cloneUrl]);
106
+ await this.runGit(repoPath, ['fetch', 'origin', '--prune']);
107
+ }
108
+
109
+ await this.configureBotGit(repoPath, identity);
110
+ return repoPath;
111
+ }
112
+
113
+ async checkoutBranch(repo: string, branch: string, baseRef: string): Promise<string> {
114
+ repo = assertRepoFullName(repo);
115
+ branch = assertGitRefName(branch);
116
+ baseRef = assertGitRefName(baseRef);
117
+ const repoPath = await this.ensureRepo(repo);
118
+ const localBranches = await this.runGit(repoPath, ['branch', '--list', branch]);
119
+ if (localBranches.trim()) {
120
+ await this.runGit(repoPath, ['checkout', branch]);
121
+ await this.runGit(repoPath, ['pull', '--rebase', 'origin', branch]).catch(async () => {
122
+ await this.runGit(repoPath, ['fetch', 'origin', branch]);
123
+ });
124
+ return repoPath;
125
+ }
126
+
127
+ const remoteBranch = await this.runGit(repoPath, ['ls-remote', '--heads', 'origin', branch]);
128
+ if (remoteBranch.trim()) {
129
+ await this.runGit(repoPath, ['checkout', '-B', branch, `origin/${branch}`]);
130
+ return repoPath;
131
+ }
132
+
133
+ await this.runGit(repoPath, ['fetch', 'origin', baseRef]);
134
+ await this.runGit(repoPath, ['checkout', '-B', branch, `origin/${baseRef}`]);
135
+ return repoPath;
136
+ }
137
+
138
+ async commitAndPush(repo: string, branch: string, message: string): Promise<string> {
139
+ repo = assertRepoFullName(repo);
140
+ branch = assertGitRefName(branch);
141
+ const repoPath = this.getRepoPath(repo);
142
+ if (!fs.existsSync(repoPath)) {
143
+ throw new Error(`工作区不存在: ${repoPath},请先 github_prepare_workspace`);
144
+ }
145
+
146
+ const token = await this.gh.ensureInstallationTokenForRepo(repo);
147
+ if (!token) throw new Error('Installation Token 不可用');
148
+ await this.runGit(repoPath, ['remote', 'set-url', 'origin', this.gh.buildCloneUrl(repo, token)]);
149
+
150
+ const status = await this.runGit(repoPath, ['status', '--porcelain']);
151
+ if (!status.trim()) return '没有可提交的变更';
152
+
153
+ await this.runGit(repoPath, ['add', '-A']);
154
+ await this.runGit(repoPath, ['commit', '-m', message]);
155
+ await this.runGit(repoPath, ['push', '-u', 'origin', branch]);
156
+ return `已 push 到 origin/${branch}`;
157
+ }
158
+ }