import { createEndpointHarness, createTestEventGateway } from '../../test-utils/endpoint.js'; import { createHmac } from 'node:crypto'; import { describe, expect, it, vi, afterEach } from 'vitest'; import { capabilityId, featureId, rootPluginId } from 'zhin.js'; import { createHttpHost } from '@zhin.js/host-http/node'; import { projectOutboundPayload, type OutboundMessageService } from '@zhin.js/core/runtime'; import type { ConversationRef } from '@zhin.js/im-contract'; import defineGithubAdapter from '../adapters/github/index.js'; import { GithubEndpoint } from '../src/endpoint.js'; import { GhClient } from '../src/gh-client.js'; import { enrichInboundContent, formatOutboundBody, resolveGithubConfig, shouldAutoReplyRepo, verifyWebhookSignature, type GithubEndpointConfig, } from '../src/protocol.js'; const adapterFeature = featureId('zhin.adapter'); const hosts: ReturnType[] = []; const WEBHOOK_SECRET = 'test-webhook-secret'; const baseConfig = resolveGithubConfig({ id: 'test-github-bot', app_id: 1, private_key: '-----BEGIN RSA PRIVATE KEY-----\nMIIB\n-----END RSA PRIVATE KEY-----', webhook_secret: WEBHOOK_SECRET, webhook_path: '/github/webhook', }); function signBody(body: string, secret = WEBHOOK_SECRET): string { return `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`; } function mockGhClient(overrides: Partial = {}): GhClient { const transport = { verifyAuth: vi.fn(async () => ({ ok: true, user: 'bot[bot]', message: 'ok' })), authenticatedUser: 'bot[bot]', getBotLogin: () => 'bot[bot]', clientId: 'client-1', appSlug: 'bot', installations: [], createIssueComment: vi.fn(async () => ({ ok: true, status: 200, data: { id: 99 } })), createPRComment: vi.fn(async () => ({ ok: true, status: 200, data: { id: 100 } })), ...overrides, }; for (const [name, value] of Object.entries(transport)) { const descriptor = Object.getOwnPropertyDescriptor(GhClient.prototype, name); if (descriptor?.get) vi.spyOn(GhClient.prototype, name as never, 'get').mockReturnValue(value as never); else if (typeof value === 'function') vi.spyOn(GhClient.prototype, name as never).mockImplementation(value as never); } return transport as unknown as GhClient; } afterEach(async () => { vi.unstubAllEnvs(); vi.restoreAllMocks(); await Promise.all(hosts.splice(0).map((host) => host.close())); }); describe('github protocol helpers', () => { it('resolves plugin config with defaults', () => { const config: GithubEndpointConfig = { id: 'github-bot', app_id: 42, private_key: 'key', }; const resolved = resolveGithubConfig(config); expect(resolved.webhookPath).toBe('/github/webhook'); expect(resolved.id).toBe('github-bot'); expect(resolved.appId).toBe(42); expect(resolved.workspaceRoot).toBe('data/github-workspaces'); }); it('does not infer credentials or identity from process state and compatibility shapes', () => { vi.stubEnv('GITHUB_APP_ID', '42'); vi.stubEnv('GITHUB_BOT_NAME', 'github-bot'); vi.stubEnv('GITHUB_WEBHOOK_SECRET', 'secret'); const resolve = resolveGithubConfig as (config: unknown) => unknown; expect(() => resolve({ private_key: 'key' })).toThrow(/non-empty id/); expect(() => resolve({ id: 'github-bot', private_key: 'key' })) .toThrow(/app_id and private_key/); expect(() => resolve({ endpoints: [{ context: 'github', id: 'github-bot', app_id: 42, private_key: 'key' }], })).toThrow(/non-empty id/); expect(() => resolve({ id: 'github-bot', appId: 42, privateKey: 'key', })).toThrow(/app_id and private_key/); }); it('verifies HMAC-SHA256 webhook signatures', () => { const body = '{"ok":true}'; const sig = signBody(body); expect(verifyWebhookSignature(WEBHOOK_SECRET, body, sig)).toBe(true); expect(verifyWebhookSignature(WEBHOOK_SECRET, body, 'sha256=bad')).toBe(false); }); it('formats outbound string and segment payloads', () => { expect(formatOutboundBody('pong')).toBe('pong'); expect(formatOutboundBody([ { type: 'text', data: { text: 'hi' } }, { type: 'at', data: { id: 'alice', name: 'alice' } }, ])).toBe('hi@alice'); }); it('keeps Markdown segments as GitHub Flavored Markdown blocks (ADR 0064 F2)', () => { expect(formatOutboundBody([ { type: 'markdown', data: { content: '## 结果\n\n- **通过**\n- `lint`' } }, ])).toBe('## 结果\n\n- **通过**\n- `lint`'); expect(formatOutboundBody([ { type: 'text', data: { text: '总结:' } }, { type: 'markdown', data: { content: '| a | b |\n|---|---|\n| 1 | 2 |' } }, { type: 'text', data: { text: '完毕' } }, ])).toBe('总结:\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n完毕'); expect(formatOutboundBody([{ type: 'markdown', data: { content: '' } }, { type: 'text', data: { text: 'x' } }])).toBe('x'); }); it('separates a Markdown block ending in one newline so the next text does not continue it', () => { // GFM lazy continuation: `- item\n谢谢` puts 谢谢 inside the list item, `> 引用\n谢谢` inside the quote. expect(formatOutboundBody([ { type: 'markdown', data: { content: '- 条目\n' } }, { type: 'text', data: { text: '谢谢' } }, ])).toBe('- 条目\n\n谢谢'); expect(formatOutboundBody([ { type: 'text', data: { text: '说明\n' } }, { type: 'markdown', data: { content: '> 引用' } }, ])).toBe('说明\n\n> 引用'); expect(formatOutboundBody([ { type: 'markdown', data: { content: '> 引用\n\n' } }, { type: 'text', data: { text: '\n谢谢' } }, ])).toBe('> 引用\n\n\n谢谢'); }); it('declares native Markdown so the core projection keeps the formatting (ADR 0064 F2)', async () => { expect(defineGithubAdapter.segments?.markdown).toBe('native'); const snapshot = { root: 'root', tree: new Map(), capabilities: new Map([['adapter:github', { id: 'adapter:github', definition: defineGithubAdapter }]]), resources: new Map([['root', new Map()]]), } as unknown as Parameters[2]; const conversation = { endpoint: { id: 'adapter:github', adapter: 'github' }, kind: 'channel', id: 'owner/repo/issues/7', } as ConversationRef; const projected = await projectOutboundPayload( [{ type: 'markdown', data: { content: '**粗体** 与 [链接](https://example.org)' } }], conversation, snapshot, ); expect(projected.rendering.fallbacks).toEqual([]); expect(formatOutboundBody(projected.payload)).toBe('**粗体** 与 [链接](https://example.org)'); }); it('formats outbound media segments from canonical data.media only', () => { expect(formatOutboundBody([ { type: 'image', data: { media: { kind: 'url', value: 'https://example.com/a.png' } } }, ])).toBe('![image](https://example.com/a.png)'); expect(formatOutboundBody([ { type: 'image', data: { media: { kind: 'url', value: 'https://example.com/a.png', file_name: 'a.png' }, alt: 'shot' } }, ])).toBe('![shot](https://example.com/a.png)'); expect(formatOutboundBody([ { type: 'file', data: { media: { kind: 'url', value: 'https://example.com/a.zip', file_name: 'a.zip' } } }, ])).toBe('[a.zip](https://example.com/a.zip)'); // 非 url kind(GitHub 评论无上传面)与缺失 media 的段一律丢弃 expect(formatOutboundBody([ { type: 'image', data: { media: { kind: 'base64', value: 'Zm9v' } } }, ])).toBe(''); expect(formatOutboundBody([ { type: 'image', data: { url: 'https://example.com/legacy.png' } }, ])).toBe(''); }); it('shouldAutoReplyRepo matches case-insensitive', () => { expect(shouldAutoReplyRepo({ autoReplyRepos: ['Owner/Repo'] }, 'owner/repo')).toBe(true); expect(shouldAutoReplyRepo({ autoReplyRepos: ['other/x'] }, 'owner/repo')).toBe(false); }); it('enrichInboundContent prepends @bot for auto_reply repos', () => { expect(enrichInboundContent( 'hello', { autoReplyRepos: ['owner/repo'], botLogin: 'bot[bot]' }, 'bot[bot]', 'owner/repo', )).toBe('@bot[bot] hello'); }); }); describe('github plugin runtime adapter', () => { it('POST webhook with valid signature admits via OutboundMessageService when open', async () => { const http = createHttpHost({ host: '127.0.0.1', port: 0 }); hosts.push(http); const receive = vi.fn(async () => Object.freeze({ matched: true, value: 'ok' })); const gateway: OutboundMessageService = { receive, send: vi.fn(async () => 'sent') }; const gh = mockGhClient(); const endpoint = await createEndpointHarness(() => new GithubEndpoint({ id: capabilityId(rootPluginId(), adapterFeature, 'github'), gateway, http, config: baseConfig, }), { gateway: createTestEventGateway(gateway, undefined), capabilities: ['inbound', 'outbound'] }); await endpoint.start(); endpoint.open(); const { port } = await http.listen(); const payload = { action: 'created', comment: { id: 1, body: 'hello from issue', user: { login: 'alice', id: 1, html_url: '' }, created_at: '2024-01-01T00:00:00Z', updated_at: '2024-01-01T00:00:00Z', html_url: '', }, issue: { number: 42, title: 't', html_url: '', state: 'open', user: { login: 'alice', id: 1, html_url: '' } }, repository: { full_name: 'owner/repo', html_url: 'https://github.com/owner/repo' }, sender: { login: 'alice', id: 1, html_url: '' }, }; const body = JSON.stringify(payload); const res = await fetch(`http://127.0.0.1:${port}/github/webhook`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-hub-signature-256': signBody(body), 'x-github-event': 'issue_comment', 'x-github-delivery': 'd1', }, body, }); expect(res.status).toBe(200); await vi.waitFor(() => expect(receive).toHaveBeenCalled()); expect(receive).toHaveBeenCalledWith(expect.objectContaining({ conversation: expect.objectContaining({ kind: 'channel', id: 'owner/repo/issues/42', parent: { kind: 'channel', id: 'owner/repo' }, }), message: expect.objectContaining({ id: '1' }), content: 'hello from issue', sender: expect.objectContaining({ id: 'alice' }), })); await endpoint.stop(); }); it('rejects webhook with invalid signature', async () => { mockGhClient(); const http = createHttpHost({ host: '127.0.0.1', port: 0 }); hosts.push(http); const receive = vi.fn(async () => Object.freeze({ matched: false })); const endpoint = await createEndpointHarness(() => new GithubEndpoint({ id: capabilityId(rootPluginId(), adapterFeature, 'github'), gateway: { receive, send: vi.fn(async () => 'sent') }, http, config: baseConfig, }), { gateway: createTestEventGateway({ receive, send: vi.fn(async () => 'sent') }, undefined), capabilities: ['inbound', 'outbound'] }); await endpoint.start(); endpoint.open(); const { port } = await http.listen(); const res = await fetch(`http://127.0.0.1:${port}/github/webhook`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-hub-signature-256': 'sha256=invalid', 'x-github-event': 'issue_comment', }, body: JSON.stringify({ action: 'created' }), }); expect(res.status).toBe(401); expect(receive).not.toHaveBeenCalled(); await endpoint.stop(); }); it('does not admit inbound while closed', async () => { mockGhClient(); const receive = vi.fn(async () => Object.freeze({ matched: false })); const endpoint = await createEndpointHarness(() => new GithubEndpoint({ id: capabilityId(rootPluginId(), adapterFeature, 'github'), gateway: { receive, send: vi.fn(async () => 'sent') }, config: resolveGithubConfig({ id: 'api-only', app_id: 1, private_key: 'k' }), }), { gateway: createTestEventGateway({ receive, send: vi.fn(async () => 'sent') }, undefined), capabilities: ['inbound', 'outbound'] }); await endpoint.start(); endpoint.endpoint.admit({ id: '1', channelId: 'o/r/issues/1', sender: expect.objectContaining({ id: 'alice' }), content: 'hi', repo: 'o/r', kind: 'issue_comment', createdAt: 1, }); expect(receive).not.toHaveBeenCalled(); await endpoint.stop(); }); it('send posts issue comment via GhClient', async () => { const gh = mockGhClient(); const endpoint = await createEndpointHarness(() => new GithubEndpoint({ id: capabilityId(rootPluginId(), adapterFeature, 'github'), gateway: { receive: vi.fn(), send: vi.fn(async () => 'sent') }, config: resolveGithubConfig({ id: 'api-only', app_id: 1, private_key: 'k' }), }), { gateway: createTestEventGateway({ receive: vi.fn(), send: vi.fn(async () => 'sent') }, undefined), capabilities: ['inbound', 'outbound'] }); await endpoint.start(); endpoint.open(); const id = await endpoint.send({ conversation: { endpoint: { id: 'test-endpoint', adapter: 'test' }, kind: 'channel', id: 'owner/repo/issues/7', parent: { kind: 'channel', id: 'owner/repo' }, }, payload: 'reply text', }); expect(id).toBe('99'); expect(gh.createIssueComment).toHaveBeenCalledWith({ repo: 'owner/repo', number: 7, body: 'reply text', signal: expect.any(AbortSignal) }); await endpoint.stop(); }); it('send posts a Markdown segment as the comment body unchanged', async () => { const gh = mockGhClient(); const endpoint = await createEndpointHarness(() => new GithubEndpoint({ id: capabilityId(rootPluginId(), adapterFeature, 'github'), gateway: { receive: vi.fn(), send: vi.fn(async () => 'sent') }, config: resolveGithubConfig({ id: 'api-only', app_id: 1, private_key: 'k' }), }), { gateway: createTestEventGateway({ receive: vi.fn(), send: vi.fn(async () => 'sent') }, undefined), capabilities: ['inbound', 'outbound'] }); await endpoint.start(); endpoint.open(); await endpoint.send({ conversation: { endpoint: { id: 'test-endpoint', adapter: 'test' }, kind: 'channel', id: 'owner/repo/issues/7', parent: { kind: 'channel', id: 'owner/repo' }, }, payload: [{ type: 'markdown', data: { content: '### 构建\n\n- [x] **通过**' } }], }); expect(gh.createIssueComment).toHaveBeenCalledWith({ repo: 'owner/repo', number: 7, body: '### 构建\n\n- [x] **通过**', signal: expect.any(AbortSignal) }); await endpoint.stop(); }); it('projects the actual Endpoint through the owning AdapterIndex', async () => { mockGhClient(); const endpoint = await createEndpointHarness(() => new GithubEndpoint({ id: capabilityId(rootPluginId(), adapterFeature, 'github'), gateway: { receive: vi.fn(), send: vi.fn(async () => 'sent') }, config: resolveGithubConfig({ id: 'agent-bot', app_id: 1, private_key: 'k' }), }), { gateway: createTestEventGateway({ receive: vi.fn(), send: vi.fn(async () => 'sent') }, undefined), capabilities: ['inbound', 'outbound'] }); await endpoint.start(); expect(endpoint.index.client('test-endpoint', endpoint.canonicalId)).toBe(endpoint.endpoint); await endpoint.stop(); }); it('defineAdapter exports frozen definition', () => { expect(defineGithubAdapter.$feature).toBe('zhin.adapter/1'); expect(defineGithubAdapter.capabilities).toEqual(['inbound', 'outbound']); }); });