import type { EndpointProfileConfiguration } from 'zhin.js/adapter'; /** * GitHub webhook / comment helpers — no legacy Adapter/Endpoint / segment-mapper. * Canonicalization is owned by gateway/core before endpoint.send. */ import { createHmac, timingSafeEqual } from 'node:crypto'; import { isMediaRef, type ConversationRef } from '@zhin.js/im-contract'; import { formatCompact, getLogger } from '@zhin.js/logger'; const logger = getLogger('github'); import { buildChannelId, type GenericWebhookPayload, type IssueCommentPayload, type PRReviewCommentPayload, type PRReviewPayload, } from './types.js'; export type { EventType, GenericWebhookPayload, GitHubComment, GitHubIssue, GitHubOAuthUser, GitHubPR, GitHubRepo, GitHubUser, IssueCommentPayload, ParsedChannel, PRReviewCommentPayload, PRReviewPayload, Subscription, } from './types.js'; export { buildChannelId, parseChannelId } from './types.js'; /** One expanded GitHub endpoint configuration produced by AdapterIndex. */ export interface GithubEndpointConfig extends EndpointProfileConfiguration { readonly id: string; readonly host?: string; readonly app_id: string | number; readonly private_key: string; readonly webhook_secret?: string; readonly webhook_path?: string; readonly auto_reply_repos?: readonly string[]; readonly bot_login?: string; readonly workspace_root?: string; } export interface ResolvedGithubConfig { readonly context: 'github'; readonly id: string; readonly host?: string; readonly appId: string | number; readonly privateKey: string; readonly webhookSecret?: string; readonly webhookPath: string; readonly autoReplyRepos: readonly string[]; readonly botLogin?: string; readonly workspaceRoot: string; } export interface GithubWireSegment { readonly type: string; readonly data?: Record; } export interface GithubInboundComment { readonly id: string; readonly channelId: string; readonly sender: string; readonly content: string; readonly repo: string; readonly kind: 'issue_comment' | 'pr_review_comment' | 'pr_review'; readonly createdAt: number; } /** * 入站归一化 → ConversationRef:Issue/PR 评论区即仓库容器内的 channel 会话, * 仓库(owner/repo)进 `parent`。出站侧用 `parseChannelId(conversation.id)` * 在平台边界还原 repo/type/number。 */ export function githubInboundConversation( endpointKey: string, comment: GithubInboundComment, ): ConversationRef { return { endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey }, kind: 'channel', id: comment.channelId, parent: { kind: 'channel', id: comment.repo }, }; } export function resolveGithubConfig(config: GithubEndpointConfig): ResolvedGithubConfig { const id = typeof config.id === 'string' ? config.id.trim() : ''; if (!id) throw new TypeError('GitHub endpoint requires a non-empty id'); const appIdRaw = config.app_id != null ? String(config.app_id).trim() : ''; const appId = appIdRaw ? (Number(appIdRaw) || appIdRaw) : undefined; const privateKey = typeof config.private_key === 'string' ? config.private_key.trim() : ''; if (!appId || !privateKey) { throw new TypeError('GitHub endpoint requires app_id and private_key'); } const webhookSecret = config.webhook_secret; const host = config.host; const webhookPath = normalizeWebhookPath(config.webhook_path ?? '/github/webhook'); const autoReplyRepos = [...(config.auto_reply_repos ?? [])]; const botLogin = config.bot_login; const workspaceRoot = config.workspace_root ?? 'data/github-workspaces'; return { context: 'github', id, ...(host ? { host } : {}), appId, privateKey, ...(webhookSecret ? { webhookSecret } : {}), webhookPath, autoReplyRepos, ...(botLogin ? { botLogin } : {}), workspaceRoot, }; } export function normalizeWebhookPath(path: string): string { const trimmed = path.trim() || '/github/webhook'; return trimmed.startsWith('/') ? trimmed : `/${trimmed}`; } export function shouldAutoReplyRepo( config: Pick, repo: string, ): boolean { const list = config.autoReplyRepos; if (!list.length) return false; const key = repo.toLowerCase(); return list.some((r) => r.toLowerCase() === key); } /** Prepend synthetic @bot for auto_reply repos (gateway text path). */ export function enrichInboundContent( content: string, config: Pick, botLogin: string | undefined, repo: string, ): string { const login = config.botLogin || botLogin; if (!login || !shouldAutoReplyRepo(config, repo)) return content; if (content.includes(`@${login}`)) return content; return `@${login} ${content}`; } /** Build inbound text for OutboundMessageService.receive from markdown/comment body. */ export function formatInboundContent(body: string): string { return body; } /** Build markdown body for Issue/PR comment send. */ export function formatOutboundBody(payload: unknown): string { if (typeof payload === 'string') return payload; if (payload == null) return ''; if (!Array.isArray(payload)) { if (typeof payload === 'object' && payload !== null && 'text' in payload) { return String((payload as { text?: unknown }).text ?? ''); } return String(payload); } // Issue / PR comments are GitHub Flavored Markdown: a `markdown` segment is delivered as its source, // as a block of its own (separated from neighbouring inline text by a blank line). let body = ''; let afterBlock = false; const append = (part: string, block: boolean) => { if (!part) return; // A single newline is no block boundary: text after `- item\n` or `> quote\n` would continue that block. if (body && (block || afterBlock)) { let newlines = 0; for (let i = body.length - 1; i >= 0 && body[i] === '\n' && newlines < 2; i -= 1) newlines += 1; for (let i = 0; i < part.length && part[i] === '\n' && newlines < 2; i += 1) newlines += 1; if (newlines < 2) body += '\n'.repeat(2 - newlines); } body += part; afterBlock = block; }; for (const seg of payload) { const item = seg as GithubWireSegment; if (typeof seg !== 'string' && item?.type === 'markdown') { append(String(item.data?.content ?? item.data?.text ?? ''), true); } else { append(formatInlineSegment(seg), false); } } return body; } function formatInlineSegment(seg: unknown): string { if (typeof seg === 'string') return seg; const item = seg as GithubWireSegment; switch (item.type) { case 'text': return String(item.data?.text ?? ''); case 'mention': case 'at': return `@${item.data?.name || item.data?.id || item.data?.target || ''}`; case 'image': case 'audio': case 'video': case 'file': return formatMediaSegment(item); case 'link': return `[${item.data?.text || item.data?.url || ''}](${item.data?.url || ''})`; default: return String(item.data?.text ?? `[${item.type}]`); } } /** * 媒体段 → GitHub markdown(canonical MediaRef 唯一来源)。 * GitHub 评论只能消费远程 URL(无上传面),kind=url 直发; * base64 / path / file 不可投递,warn + 丢弃。 */ function formatMediaSegment(seg: GithubWireSegment): string { const media = seg.data?.media; if (!isMediaRef(media)) { logger.warn(formatCompact({ op: 'github_outbound_media_dropped', type: seg.type, reason: 'missing_media_ref', })); return ''; } if (media.kind !== 'url') { logger.warn(formatCompact({ op: 'github_outbound_media_dropped', type: seg.type, reason: `unsupported_kind:${media.kind}`, })); return ''; } if (seg.type === 'image') { const alt = typeof seg.data?.alt === 'string' && seg.data.alt ? seg.data.alt : media.file_name || 'image'; return `![${alt}](${media.value})`; } const label = media.file_name || seg.type; return `[${label}](${media.value})`; } export function verifyWebhookSignature( secret: string, rawBody: string, signatureHeader: string | undefined, ): boolean { if (!signatureHeader?.startsWith('sha256=')) return false; const expected = `sha256=${createHmac('sha256', secret).update(rawBody).digest('hex')}`; try { const a = Buffer.from(signatureHeader); const b = Buffer.from(expected); if (a.length !== b.length) return false; return timingSafeEqual(a, b); } catch { return false; } } export function headerValue( headers: Headers, name: string, ): string { return headers.get(name) ?? ''; } export function parseIssueCommentInbound(payload: IssueCommentPayload): GithubInboundComment | null { if (payload.action !== 'created' || !payload.comment) return null; const repo = payload.repository.full_name; const isPR = 'pull_request' in (payload.issue as object); return { id: String(payload.comment.id), channelId: buildChannelId(repo, isPR ? 'pr' : 'issue', payload.issue.number), sender: payload.sender.login, content: payload.comment.body, repo, kind: 'issue_comment', createdAt: new Date(payload.comment.created_at).getTime(), }; } export function parsePrReviewCommentInbound(payload: PRReviewCommentPayload): GithubInboundComment | null { if (payload.action !== 'created' || !payload.comment) return null; const repo = payload.repository.full_name; const body = payload.comment.path ? `**${payload.comment.path}**\n${payload.comment.diff_hunk ? `\`\`\`diff\n${payload.comment.diff_hunk}\n\`\`\`\n` : ''}${payload.comment.body}` : payload.comment.body; return { id: String(payload.comment.id), channelId: buildChannelId(repo, 'pr', payload.pull_request.number), sender: payload.sender.login, content: body, repo, kind: 'pr_review_comment', createdAt: new Date(payload.comment.created_at).getTime(), }; } export function parsePrReviewInbound(payload: PRReviewPayload): GithubInboundComment | null { if (payload.action !== 'submitted' || !payload.review.body) return null; const repo = payload.repository.full_name; const stateLabel: Record = { approved: '✅ APPROVED', changes_requested: '🔄 CHANGES REQUESTED', commented: '💬 COMMENTED', dismissed: '❌ DISMISSED', }; const body = `**[${stateLabel[payload.review.state] || payload.review.state}]**\n${payload.review.body}`; return { id: String(payload.review.id), channelId: buildChannelId(repo, 'pr', payload.pull_request.number), sender: payload.sender.login, content: body, repo, kind: 'pr_review', createdAt: new Date(payload.review.submitted_at).getTime(), }; } export function formatNotification(event: string, p: GenericWebhookPayload): string { const repo = p.repository.full_name; const sender = p.sender.login; const repoUrl = p.repository.html_url; switch (event) { case 'push': { const branch = p.ref?.replace('refs/heads/', '') || '?'; const commits = p.commits || []; const compareUrl = commits.length >= 2 ? `${repoUrl}/compare/${commits[0].id.substring(0, 12)}...${commits[commits.length - 1].id.substring(0, 12)}` : commits.length === 1 ? `${repoUrl}/commit/${commits[0].id}` : ''; let msg = `📦 ${repo}\n🌿 ${sender} pushed ${commits.length} commit(s) to \`${branch}\`\n`; if (commits.length) { msg += '\n'; msg += commits.slice(0, 5).map((c) => ` • [\`${c.id.substring(0, 7)}\`](${repoUrl}/commit/${c.id}) ${c.message.split('\n')[0]}`, ).join('\n'); if (commits.length > 5) msg += `\n ... +${commits.length - 5} more`; } if (compareUrl) msg += `\n\n🔗 ${compareUrl}`; return msg; } case 'issues': { const i = p.issue!; const act = p.action === 'opened' ? '📝 opened' : p.action === 'closed' ? '✅ closed' : `🔄 ${p.action || 'updated'}`; return `🐛 ${repo}\n👤 ${sender} ${act} issue #${i.number}\n📌 ${i.title}\n🔗 ${i.html_url}`; } case 'star': { const starred = p.action !== 'deleted'; return `${starred ? '⭐' : '💔'} ${repo}\n👤 ${sender} ${starred ? 'starred' : 'unstarred'}\n🔗 ${repoUrl}`; } case 'fork': return `🍴 ${repo}\n👤 ${sender} forked → ${p.forkee!.full_name}\n🔗 ${p.forkee!.html_url}`; case 'pull_request': { const pr = p.pull_request!; const act = p.action === 'opened' ? '📝 opened' : p.action === 'closed' ? (pr.state === 'closed' ? '❌ closed' : '✅ merged') : `🔄 ${p.action || 'updated'}`; return `🔀 ${repo}\n👤 ${sender} ${act} PR #${pr.number}\n📌 ${pr.title}\n🌿 ${pr.head.ref} → ${pr.base.ref}\n🔗 ${pr.html_url}`; } default: return `📬 ${repo}\n📡 ${event}${p.action ? ` (${p.action})` : ''} by ${sender}\n🔗 ${repoUrl}`; } }