196 lines
9.7 KiB
TypeScript
196 lines
9.7 KiB
TypeScript
/** @jest-environment node */
|
||
|
||
import { randomUUID } from 'node:crypto'
|
||
import { submitYouyidianNotification } from '@/lib/youyidian-notification-center'
|
||
import { parseDesktopFeedback } from './feedback-contract'
|
||
import { dispatchDesktopFeedback } from './feedback-dispatch'
|
||
|
||
jest.mock('@/lib/youyidian-notification-center', () => ({
|
||
...jest.requireActual('@/lib/youyidian-notification-center'),
|
||
submitYouyidianNotification: jest.fn(),
|
||
}))
|
||
|
||
const feedbackId = randomUUID()
|
||
const createdAt = new Date('2026-12-04T10:00:00.000Z')
|
||
const owner = 'ding-owner'
|
||
const labels = ['feedback', 'status:triage']
|
||
const appOrigin = ['https:', '', 'app.invalid'].join('/')
|
||
const webhookUrl = new URL('/incoming', ['https:', '', 'harness.invalid'].join('/'))
|
||
const detailPath = `/feedback/${feedbackId}`
|
||
const adminUrl = new URL(detailPath, appOrigin).href
|
||
const envKeys = [
|
||
'FEEDBACK_GITHUB_TOKEN', 'FEEDBACK_GITHUB_REPO', 'FEEDBACK_DINGTALK_OWNER_USER_ID',
|
||
'FEEDBACK_AGENT_WEBHOOK_URL', 'FEEDBACK_AGENT_WEBHOOK_SECRET', 'YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID',
|
||
'YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS', 'YYD_NOTIFICATION_CENTER_URL', 'YYD_NOTIFICATION_CENTER_PROJECT_CODE',
|
||
'YYD_NOTIFICATION_CENTER_PROJECT_SECRET',
|
||
]
|
||
const reporter = { name: '同事甲', department: '运营部' }
|
||
const data = {
|
||
feedbackId, createdAt, detailPath, reporter, summary: '导出时闪退',
|
||
snapshot: {
|
||
type: 'crash', clientVersion: '1.2612.120', commit: 'abc123456789',
|
||
os: 'windows', arch: 'x86_64', updateState: { channel: 'stable' }, recentErrors: ['一条原始诊断'],
|
||
},
|
||
}
|
||
const sendDingTalk = jest.mocked(submitYouyidianNotification)
|
||
let fetchMock: jest.SpiedFunction<typeof fetch>
|
||
let info: jest.SpiedFunction<typeof console.info>
|
||
let warn: jest.SpiedFunction<typeof console.warn>
|
||
|
||
function issueResponse() {
|
||
return Response.json({ number: 43, labels: labels.map(name => ({ name })) }, { status: 201 })
|
||
}
|
||
|
||
function configureDingTalk() {
|
||
process.env.FEEDBACK_DINGTALK_OWNER_USER_ID = owner
|
||
process.env.YYD_NOTIFICATION_CENTER_URL = new URL('/notify', appOrigin).href
|
||
process.env.YYD_NOTIFICATION_CENTER_PROJECT_CODE = 'test-project'
|
||
process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET = randomUUID()
|
||
}
|
||
|
||
beforeEach(() => {
|
||
jest.replaceProperty(process, 'env', { ...process.env, NEXT_PUBLIC_APP_PUBLIC_URL: appOrigin })
|
||
for (const name of envKeys) delete process.env[name]
|
||
fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 204 }))
|
||
info = jest.spyOn(console, 'info').mockImplementation(() => {})
|
||
warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||
sendDingTalk.mockReset().mockResolvedValue({
|
||
id: 'notice', projectCode: 'test-project', recipientUserId: owner, status: 'pending', title: '小壹问题反馈',
|
||
})
|
||
})
|
||
|
||
afterEach(() => jest.restoreAllMocks())
|
||
|
||
it('creates a labeled Issue, then shares the link with the personal DingTalk recipient and the Agent', async () => {
|
||
const token = randomUUID()
|
||
const webhookSecret = randomUUID()
|
||
process.env.FEEDBACK_GITHUB_TOKEN = token
|
||
process.env.FEEDBACK_AGENT_WEBHOOK_URL = webhookUrl.href
|
||
process.env.FEEDBACK_AGENT_WEBHOOK_SECRET = webhookSecret
|
||
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID = 'legacy-recipient'
|
||
configureDingTalk()
|
||
fetchMock.mockResolvedValueOnce(issueResponse())
|
||
|
||
await dispatchDesktopFeedback({ ...data, summary: 'detail-agent-pi 导出时闪退' })
|
||
|
||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||
const [[gitUrl, gitRequest], [webhookTarget, webhookRequest]] = fetchMock.mock.calls
|
||
expect(gitUrl).toEqual(expect.objectContaining({
|
||
protocol: 'https:', hostname: 'api.github.com', pathname: '/repos/wuyongjie1990-coder/gongxiangp2/issues',
|
||
}))
|
||
expect(gitRequest).toMatchObject({
|
||
method: 'POST', signal: expect.any(AbortSignal), redirect: 'error', headers: { Authorization: `Bearer ${token}` },
|
||
})
|
||
const issue = JSON.parse(String(gitRequest?.body))
|
||
expect(issue).toEqual({
|
||
title: '[小壹崩溃反馈 · 1.2612.120] 小壹 导出时闪退',
|
||
labels,
|
||
body: expect.stringMatching(/反馈人:同事甲[\s\S]*部门:运营部[\s\S]*提交号:abc123456789[\s\S]*问题描述[\s\S]*导出时闪退/),
|
||
})
|
||
expect(issue.body).toContain(feedbackId)
|
||
expect(issue.body).toContain(adminUrl)
|
||
expect(issue.body).toContain('最近错误 1 条,工具失败 0 条')
|
||
expect(issue.body).not.toContain('一条原始诊断')
|
||
const issueUrl = new URL('/wuyongjie1990-coder/gongxiangp2/issues/43', ['https:', '', 'github.com'].join('/')).href
|
||
expect(sendDingTalk).toHaveBeenCalledTimes(1)
|
||
expect(sendDingTalk).toHaveBeenCalledWith({
|
||
idempotencyKey: `desktop-feedback:${feedbackId}`, recipientUserId: owner, title: '小壹问题反馈',
|
||
actionTitle: '查看反馈', actionUrl: adminUrl,
|
||
content: expect.stringContaining(`[查看 GitHub Issue](${issueUrl})`),
|
||
})
|
||
expect(webhookTarget).toEqual(webhookUrl)
|
||
expect(webhookRequest).toMatchObject({
|
||
method: 'POST', signal: expect.any(AbortSignal), redirect: 'error',
|
||
headers: { 'Content-Type': 'application/json', 'X-Feedback-Webhook-Token': webhookSecret },
|
||
})
|
||
expect(JSON.parse(String(webhookRequest?.body))).toEqual({
|
||
event: 'xiaoyi.feedback.created', feedbackId, reporter, clientVersion: '1.2612.120', commit: 'abc123456789',
|
||
summary: '小壹 导出时闪退', githubIssueUrl: issueUrl, githubIssueNumber: 43, adminUrl, createdAt: createdAt.toISOString(),
|
||
})
|
||
expect(info).toHaveBeenCalledWith(expect.any(String), {
|
||
feedbackId, channel: 'github', outcome: 'created', githubIssueUrl: issueUrl, githubIssueNumber: 43,
|
||
})
|
||
expect(warn).not.toHaveBeenCalled()
|
||
})
|
||
|
||
it('only dispatches configured channels and sends a webhook without an optional secret', async () => {
|
||
process.env.FEEDBACK_DINGTALK_OWNER_USER_ID = owner
|
||
process.env.FEEDBACK_AGENT_WEBHOOK_URL = webhookUrl.href
|
||
|
||
await dispatchDesktopFeedback(data)
|
||
|
||
expect(sendDingTalk).not.toHaveBeenCalled()
|
||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||
expect(fetchMock.mock.calls[0][1]?.headers).toEqual({ 'Content-Type': 'application/json' })
|
||
expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toMatchObject({ githubIssueUrl: null, githubIssueNumber: null })
|
||
expect(info.mock.calls.map(([, fields]) => fields)).toEqual([
|
||
{ feedbackId, channel: 'github', outcome: 'skipped', missing: ['FEEDBACK_GITHUB_TOKEN'] },
|
||
{ feedbackId, channel: 'dingtalk', outcome: 'skipped', missing: [
|
||
'YYD_NOTIFICATION_CENTER_URL', 'YYD_NOTIFICATION_CENTER_PROJECT_CODE', 'YYD_NOTIFICATION_CENTER_PROJECT_SECRET',
|
||
] },
|
||
])
|
||
})
|
||
|
||
it.each(['github', 'agent_webhook'] as const)('uses an 8 second abort signal and isolates a %s timeout', async channel => {
|
||
process.env.FEEDBACK_GITHUB_TOKEN = randomUUID()
|
||
process.env.FEEDBACK_GITHUB_REPO = 'example-owner/private-test'
|
||
process.env.FEEDBACK_AGENT_WEBHOOK_URL = webhookUrl.href
|
||
configureDingTalk()
|
||
const controller = new AbortController()
|
||
const timeout = jest.spyOn(AbortSignal, 'timeout').mockReturnValueOnce(controller.signal)
|
||
const started = Promise.withResolvers<void>()
|
||
const slow = (_url: Parameters<typeof fetch>[0], init?: RequestInit) => {
|
||
const response = Promise.withResolvers<Response>()
|
||
init?.signal?.addEventListener('abort', () => response.reject(init.signal?.reason), { once: true })
|
||
started.resolve()
|
||
return response.promise
|
||
}
|
||
if (channel === 'github') {
|
||
fetchMock.mockImplementationOnce(slow)
|
||
} else {
|
||
fetchMock.mockResolvedValueOnce(issueResponse()).mockImplementationOnce(slow)
|
||
timeout.mockReset().mockReturnValueOnce(new AbortController().signal).mockReturnValueOnce(controller.signal)
|
||
}
|
||
|
||
const dispatch = dispatchDesktopFeedback(data)
|
||
await started.promise
|
||
controller.abort(new DOMException('request expired', 'TimeoutError'))
|
||
await dispatch
|
||
|
||
expect(timeout.mock.calls).toEqual([[8000], [8000]])
|
||
expect(fetchMock.mock.calls[0][0]).toMatchObject({ pathname: '/repos/example-owner/private-test/issues' })
|
||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||
expect(sendDingTalk).toHaveBeenCalledTimes(1)
|
||
expect(warn).toHaveBeenCalledWith(expect.any(String), { feedbackId, channel, outcome: 'failed', errorCode: 'timeout' })
|
||
})
|
||
|
||
it('sends no private fields or internal names and logs no raw upstream error data', async () => {
|
||
const raw = randomUUID()
|
||
const token = randomUUID()
|
||
process.env.FEEDBACK_GITHUB_TOKEN = token
|
||
process.env.FEEDBACK_AGENT_WEBHOOK_URL = webhookUrl.href
|
||
configureDingTalk()
|
||
fetchMock.mockResolvedValueOnce(new Response(raw, { status: 500 })).mockResolvedValueOnce(new Response(raw, { status: 500 }))
|
||
const parsed = parseDesktopFeedback(JSON.stringify({
|
||
feedbackId, summary: `PhotoCraft Pi 无法启动 ${token}`,
|
||
context: { schemaVersion: 3, cookie: raw, commit: `Bearer ${raw}`, clientVersion: `key is ${raw}`,
|
||
currentError: `Cookie: sid=${raw}`, recentErrors: [`Cookie: sid=${raw}`],
|
||
screenshot: `data:image/png;base64,${raw}`, os: raw },
|
||
}))
|
||
|
||
await dispatchDesktopFeedback({ ...data, ...parsed, reporter: { name: `https://${raw}.invalid`, department: `secret=${raw}` } })
|
||
|
||
const bodiesAndLogs = JSON.stringify([
|
||
fetchMock.mock.calls.map(([, init]) => init?.body), sendDingTalk.mock.calls, info.mock.calls, warn.mock.calls,
|
||
])
|
||
for (const forbidden of [raw, token, 'PhotoCraft', 'screenshot', 'sid=']) expect(bodiesAndLogs).not.toContain(forbidden)
|
||
const webhook = JSON.parse(String(fetchMock.mock.calls[1][1]?.body))
|
||
expect(webhook).toMatchObject({
|
||
summary: '[敏感信息已移除]', clientVersion: null, commit: null, githubIssueNumber: null, githubIssueUrl: null,
|
||
})
|
||
expect(warn.mock.calls.map(([, fields]) => fields)).toEqual([
|
||
{ feedbackId, channel: 'github', outcome: 'failed', errorCode: 'http_error', status: 500 },
|
||
{ feedbackId, channel: 'agent_webhook', outcome: 'failed', errorCode: 'http_error', status: 500 },
|
||
])
|
||
})
|