gongxiangp2/app/feedback/[id]/feedback.integration.test.ts

441 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** @jest-environment node */
import { getServerSession } from 'next-auth'
import { POST } from '@/app/api/desktop/[...path]/route'
import { DesktopClientError } from '@/lib/desktop-client/contract.mjs'
import { requireDesktop } from '@/lib/desktop-client/service'
import { prisma } from '@/lib/prisma'
import { submitYouyidianNotification } from '@/lib/youyidian-notification-center'
import { GET } from './route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/desktop-client/service', () => ({ requireDesktop: jest.fn() }))
jest.mock('@/lib/youyidian-notification-center', () => ({ submitYouyidianNotification: jest.fn() }))
jest.mock('@/lib/prisma', () => ({ prisma: {
user: { findUnique: jest.fn(), findMany: jest.fn() },
desktopClientFeedback: { createMany: jest.fn(), findFirst: jest.fn(), findUnique: jest.fn() },
} }))
const id = '5acdddaa-6c85-4d20-9783-17de944b2e8a'
const ownerId = 'submitter'
const createdAt = new Date('2026-12-01T10:00:00.000Z')
const active = { role: 'USER', isSuperAdmin: false, isActive: true, status: 'active', archivedAt: null } as const
const record = {
feedbackId: id, ownerId, createdAt, status: 'submitted', summary: '<b>导出失败</b>',
projectId: 'project-01', taskId: 'task-01', requestId: 'req-01', snapshot: { message: '<script>unsafe</script>' },
owner: { username: 'submitter', realName: '提交人甲' },
}
const feedbackStore = jest.mocked(prisma.desktopClientFeedback)
const userStore = jest.mocked(prisma.user)
function post(input: object | string = { feedbackId: id, summary: ' 导出失败 ' }, path = ['feedback']) {
const request = new Request('https://example.invalid/api/desktop/feedback', {
method: 'POST', body: typeof input === 'string' ? input : JSON.stringify(input),
})
return POST(request, { params: { path } })
}
function get(idParam = id) {
return GET(new Request(`https://example.invalid/feedback/${idParam}`), { params: { id: idParam } })
}
beforeEach(() => {
jest.resetAllMocks()
jest.replaceProperty(process, 'env', {
...process.env, YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID: 'recipient-test', YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS: '',
})
jest.mocked(requireDesktop).mockResolvedValue({ id: 'session-01', account: { id: ownerId, name: '提交人甲' }, isSuperAdmin: false, expiresAt: createdAt })
jest.mocked(submitYouyidianNotification).mockResolvedValue({ id: 'notice-01', projectCode: 'test', status: 'pending', recipientUserId: 'recipient-test', title: '小壹问题反馈' })
})
afterEach(() => jest.restoreAllMocks())
describe('POST /api/desktop/feedback', () => {
it('passes through desktop session authentication and rejects extra path segments', async () => {
jest.mocked(requireDesktop).mockRejectedValueOnce(new DesktopClientError('请先登录', 401, 'unauthenticated'))
expect((await post()).status).toBe(401)
expect((await post({}, ['feedback', 'extra'])).status).toBe(404)
expect(feedbackStore.createMany).not.toHaveBeenCalled()
})
it('handles concurrent repeats with one insert and one notification', async () => {
feedbackStore.createMany.mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 })
feedbackStore.findFirst.mockResolvedValue(record)
const responses = await Promise.all([post(), post({ feedbackId: id.toUpperCase(), summary: '新的说明' })])
const receipt = { feedback: { feedbackId: id, status: 'submitted', createdAt: createdAt.toISOString(), detailPath: `/feedback/${id}` } }
for (const response of responses) {
expect(response.status).toBe(200)
expect(await response.json()).toEqual(receipt)
}
expect(feedbackStore.createMany).toHaveBeenCalledWith({ data: expect.objectContaining({ ownerId, feedbackId: id, summary: '导出失败' }), skipDuplicates: true })
expect(jest.mocked(submitYouyidianNotification)).toHaveBeenCalledTimes(1)
expect(jest.mocked(submitYouyidianNotification)).toHaveBeenCalledWith(expect.objectContaining({
recipientUserId: 'recipient-test', idempotencyKey: `desktop-feedback:${id}`, actionUrl: expect.stringMatching(`/feedback/${id}$`),
}))
expect(userStore.findMany).not.toHaveBeenCalled()
})
it('deduplicates configured DingTalk IDs and delivers to each recipient independently', async () => {
const warning = jest.spyOn(console, 'warn').mockImplementation(() => {})
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS = ' ding-second, , recipient-test, ding-second, ding-third '
feedbackStore.createMany.mockResolvedValue({ count: 1 })
feedbackStore.findFirst.mockResolvedValue(record)
jest.mocked(submitYouyidianNotification)
.mockRejectedValueOnce(new Error('opaque details'))
.mockResolvedValueOnce({ id: 'notice-02', projectCode: 'test', status: 'failed', recipientUserId: 'ding-second', title: '小壹问题反馈' })
expect((await post()).status).toBe(200)
expect(jest.mocked(submitYouyidianNotification).mock.calls.map(([input]) => [input.recipientUserId, input.idempotencyKey])).toEqual(
['recipient-test', 'ding-second', 'ding-third'].map(recipient => [recipient, `desktop-feedback:${id}:${recipient}`]),
)
expect(userStore.findMany).not.toHaveBeenCalled()
expect(warning.mock.calls).toEqual([
['[desktop-feedback] 通知投递失败', { feedbackId: id, recipientUserId: 'recipient-test', errorCode: 'notification_request_failed' }],
['[desktop-feedback] 通知投递失败', { feedbackId: id, recipientUserId: 'ding-second', errorCode: 'delivery_failed' }],
])
})
it('uses active super-admin DingTalk IDs and sends a bounded, sanitized summary with the feedback link', async () => {
delete process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS = ' , '
feedbackStore.createMany.mockResolvedValue({ count: 1 })
feedbackStore.findFirst.mockResolvedValue(record)
userStore.findMany.mockResolvedValue([
{ id: 'app-admin-id', dingtalkUserId: 'ding-admin', username: 'admin', realName: '管理员' },
] as Awaited<ReturnType<typeof prisma.user.findMany>>)
const summary = '🛋'.repeat(125)
const response = await post({ feedbackId: id, summary, context: {
project: { name: '森屿布艺沙发', cookie: 'private' }, clientVersion: '1.2612.107', errors: ['Bearer fake-secret'],
} })
expect(response.status).toBe(200)
expect(userStore.findMany).toHaveBeenCalledWith({
where: {
isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true,
dingtalkUserId: { not: null }, NOT: { dingtalkUserId: '' },
},
select: { id: true, dingtalkUserId: true, realName: true, username: true },
})
expect(submitYouyidianNotification).toHaveBeenCalledWith({
recipientUserId: 'ding-admin', idempotencyKey: `desktop-feedback:${id}`, title: '小壹问题反馈',
content: `反馈人:提交人甲\n项目:森屿布艺沙发\n客户端版本:1.2612.107\n摘要:${'🛋'.repeat(120)}\n反馈编号:${id}`,
actionTitle: '查看反馈', actionUrl: expect.stringMatching(`^https?://[^/]+/feedback/${id}$`),
})
})
it('warns without attempting delivery when no eligible recipient exists', async () => {
const warning = jest.spyOn(console, 'warn').mockImplementation(() => {})
delete process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID
userStore.findMany.mockResolvedValue([])
feedbackStore.createMany.mockResolvedValue({ count: 1 })
feedbackStore.findFirst.mockResolvedValue(record)
expect((await post()).status).toBe(200)
expect(submitYouyidianNotification).not.toHaveBeenCalled()
expect(warning).toHaveBeenCalledWith('[desktop-feedback] 没有可用的钉钉收件人', { feedbackId: id })
})
it('validates before writing and enforces the body size limit', async () => {
expect((await post({ feedbackId: id, summary: '字'.repeat(2001) })).status).toBe(400)
expect((await post('{')).status).toBe(400)
expect((await post('a'.repeat(262145))).status).toBe(413)
expect(feedbackStore.createMany).not.toHaveBeenCalled()
})
it('returns a successful receipt when notification fails and persists only the sanitized snapshot', async () => {
const warning = jest.spyOn(console, 'warn').mockImplementation(() => {})
feedbackStore.createMany.mockResolvedValue({ count: 1 })
feedbackStore.findFirst.mockResolvedValue(record)
jest.mocked(submitYouyidianNotification).mockRejectedValue(new Error('opaque details'))
const response = await post({ feedbackId: id, summary: '问题描述', context: { cookie: 'raw-cookie', errors: ['Bearer fake-secret', 'data:image/png;base64,raw-data'] } })
expect(response.status).toBe(200)
expect(feedbackStore.createMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({
snapshot: { errors: ['[敏感信息已移除]', '[图片已移除]'] },
}) }))
expect(warning).toHaveBeenCalledWith('[desktop-feedback] 通知投递失败', {
feedbackId: id, recipientUserId: 'recipient-test', errorCode: 'notification_request_failed',
})
})
it('does not expose another account’s receipt for a reused UUID', async () => {
feedbackStore.createMany.mockResolvedValue({ count: 0 })
feedbackStore.findFirst.mockResolvedValue(null)
const response = await post()
expect(response.status).toBe(409)
expect(await response.json()).toMatchObject({ code: 'feedback_id_conflict' })
expect(feedbackStore.findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: { feedbackId: id, ownerId } }))
expect(submitYouyidianNotification).not.toHaveBeenCalled()
})
it('includes short commit hash and trimmed currentError or daemon stderrSummary in DingTalk notifications', async () => {
feedbackStore.createMany.mockResolvedValue({ count: 1 })
feedbackStore.findFirst.mockResolvedValue(record)
const longError = '渲染队列超时 '.repeat(25)
expect((await post({
feedbackId: id,
summary: '画布导出卡死',
context: {
clientVersion: '1.2612.112',
commit: 'abc123456789',
currentError: longError,
agentDaemon: { stderrSummary: 'should not override currentError' },
},
})).status).toBe(200)
const firstCall = jest.mocked(submitYouyidianNotification).mock.calls[0][0]
expect(firstCall.content).toContain('客户端版本:1.2612.112 (abc1234)')
expect(firstCall.content).toContain(`当前报错:${Array.from(longError.replace(/\s+/g, ' ').trim()).slice(0, 120).join('')}`)
jest.mocked(submitYouyidianNotification).mockClear()
expect((await post({
feedbackId: id,
summary: '本机服务异常',
context: {
clientVersion: '1.2612.112',
commit: ' ',
agentDaemon: { available: false, stderrSummary: 'Bearer leaked-token' },
},
})).status).toBe(200)
const secondCall = jest.mocked(submitYouyidianNotification).mock.calls[0][0]
expect(secondCall.content).toContain('客户端版本:1.2612.112\n')
expect(secondCall.content).toContain('当前报错:\\[敏感信息已移除\\]')
})
})
describe('GET /feedback/[id]', () => {
it('redirects to login and preserves the feedback path', async () => {
const response = await get()
expect(response.status).toBe(307)
expect(response.headers.get('location')).toBe(`/login?redirect=%2Ffeedback%2F${id}`)
expect(feedbackStore.findFirst).not.toHaveBeenCalled()
})
it.each([
[ownerId, active],
['admin', { ...active, role: 'ADMIN' as const }],
['system-admin', { ...active, role: 'SYSTEM_ADMIN' as const }],
['super-admin', { ...active, isSuperAdmin: true }],
['configured-recipient', { ...active, dingtalkUserId: 'recipient-test' }],
])('serves escaped, private HTML to %s', async (viewerId, identity) => {
jest.mocked(getServerSession).mockResolvedValue({ user: { id: viewerId } })
userStore.findUnique.mockResolvedValue(identity as never)
feedbackStore.findFirst.mockResolvedValue(record)
const response = await get()
expect(response.status).toBe(200)
expect(response.headers.get('cache-control')).toBe('private, no-store')
const html = await response.text()
for (const expected of ['&lt;b&gt;导出失败&lt;/b&gt;', '提交人甲', 'project-01', 'task-01', 'req-01', '&lt;script&gt;unsafe&lt;/script&gt;']) {
expect(html).toContain(expected)
}
expect(html).not.toContain('<script>')
expect(feedbackStore.findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: viewerId === ownerId ? { feedbackId: id, ownerId } : { feedbackId: id } }))
})
it.each([
['USER', undefined],
['DEPT_ADMIN', undefined],
['USER', 'other-ding-user'],
] as const)('returns a real 403 to another %s (%s) and checks only metadata', async (role, dingtalkUserId) => {
jest.mocked(getServerSession).mockResolvedValue({ user: { id: 'another', role: 'ADMIN' } })
userStore.findUnique.mockResolvedValue({ ...active, role, dingtalkUserId } as never)
feedbackStore.findFirst.mockResolvedValue(null)
feedbackStore.findUnique.mockResolvedValue({ feedbackId: id } as never)
const response = await get()
expect(response.status).toBe(403)
expect(await response.text()).not.toContain('导出失败')
expect(feedbackStore.findUnique).toHaveBeenCalledWith({ where: { feedbackId: id }, select: { feedbackId: true } })
})
it('returns 404 for missing or invalid IDs and 403 for an inactive account', async () => {
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
expect((await get('not-a-uuid')).status).toBe(404)
userStore.findUnique.mockResolvedValueOnce(active as never).mockResolvedValueOnce({ ...active, isActive: false } as never)
feedbackStore.findFirst.mockResolvedValue(null)
feedbackStore.findUnique.mockResolvedValue(null)
expect((await get()).status).toBe(404)
expect((await get()).status).toBe(403)
})
it('renders rich v2 triage cards, highlights WARN/ERROR logs, preserves strict CSP and collapses raw JSON by default', async () => {
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
userStore.findUnique.mockResolvedValue(active as never)
feedbackStore.findFirst.mockResolvedValue({
...record,
summary: 'GPU 渲染降级导致导出模糊',
snapshot: {
clientVersion: '1.2612.112',
commit: 'abc1234',
channel: 'stable',
builtAt: '2026-12-03T01:00:00Z',
os: 'Windows 11',
arch: 'x86_64',
page: 'workspace',
view: 'detail-editor',
online: false,
capturedAt: '2026-12-03T01:25:00Z',
currentError: 'WebGPU adapter lost',
project: { name: '森屿布艺沙发' },
agentDaemon: {
available: false,
ready: false,
spawnCount: 3,
activeRuns: ['run-a', 'run-b'],
heartbeatAgeMs: 4200,
exitCode: 137,
lastError: 'process killed',
stderrSummary: 'fatal: daemon exited',
},
models: {
chatModel: 'chat-pro',
copyModel: 'copy-v2',
imageModel: 'img-hd',
hasPersonalKey: true,
knowledgeMode: 'cloud',
},
canvas: {
renderPath: 'cpu',
gpuFallback: true,
gpuFallbackKind: 'deviceLost',
documentWidth: 750,
documentHeight: 1200,
layerCount: 18,
activeOutput: { id: 'out-1', name: '主图 01' },
outputId: 'out-1',
variantId: 'var-2',
templateHash: 'tpl-abc123',
revision: 9,
dirty: true,
professionalMode: true,
},
multiProject: { runningCount: 1, queuedCount: 2, pausedCount: 1 },
storage: { usingCustomRoot: true, migrationPhase: 'completed', freeBytes: 2147483648 },
notices: [{ kind: 'warning', message: '存储空间低于阈值' }],
recentErrors: [{ errorCode: 'E_RENDER', message: '切换软件渲染' }],
recentLogs: [
'10:00:01 INFO canvas ready',
'10:00:02 WARN memory pressure high',
'10:00:03 ERROR device lost during export',
],
},
})
const response = await get()
expect(response.status).toBe(200)
expect(response.headers.get('content-security-policy')).toBe("default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'")
const html = await response.text()
for (const expected of [
'问题说明',
'核心故障摘要',
'提交与关联信息',
'运行环境与状态速览',
'近期通知与告警',
'近期客户端日志摘要',
'完整诊断 JSON',
'本机服务状态',
'模型配置',
'画布与渲染状态',
'多项目与存储状态',
'1.2612.112',
'abc1234',
'Windows 11 / x86_64',
'workspace / detail-editor',
'离线',
'WebGPU adapter lost',
'fatal: daemon exited',
'750 × 1200 px',
'2 GB',
'class="log-line"',
'class="log-line log-warn"',
'class="log-line log-error"',
'<details class="json-details">',
]) {
expect(html).toContain(expected)
}
expect(html).not.toContain('<details class="json-details" open>')
expect(html).not.toContain('<script>')
expect(html).not.toMatch(/\bPi\b|PhotoCraft/i)
})
it('escapes HTML and XSS payloads in every v2 triage field', async () => {
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
userStore.findUnique.mockResolvedValue(active as never)
const xss = '<img src=x onerror=alert(1)>'
const scriptXss = '<script>alert("xss")</script>'
feedbackStore.findFirst.mockResolvedValue({
...record,
snapshot: {
clientVersion: xss,
commit: scriptXss,
channel: xss,
os: xss,
arch: scriptXss,
page: xss,
currentError: scriptXss,
agentDaemon: { available: false, lastError: xss, stderrSummary: scriptXss, activeRuns: [xss] },
models: { chatModel: xss, knowledgeMode: scriptXss },
canvas: { renderPath: xss, gpuFallback: scriptXss, templateHash: xss },
notices: [xss],
recentErrors: [{ message: scriptXss }],
recentLogs: [`ERROR ${scriptXss}`],
},
})
const html = await (await get()).text()
expect(html).not.toContain('<script>')
expect(html).not.toContain('<img ')
expect(html).toContain('&lt;img src=x onerror=alert(1)&gt;')
expect(html).toContain('&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;')
})
it('renders only matching overview cards for partial v2 snapshots and ignores gpuFallback=false', async () => {
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
userStore.findUnique.mockResolvedValue(active as never)
feedbackStore.findFirst.mockResolvedValue({
...record,
snapshot: {
models: { chatModel: 'model-a' },
canvas: { renderPath: 'gpu', gpuFallback: false },
},
})
const html = await (await get()).text()
expect(html).toContain('模型配置')
expect(html).toContain('画布与渲染状态')
expect(html).toContain('未降级')
expect(html).not.toContain('核心故障摘要')
expect(html).not.toContain('本机服务状态')
expect(html).not.toContain('多项目与存储状态')
expect(html).not.toContain('近期通知与告警')
expect(html).not.toContain('近期客户端日志摘要')
})
it('degrades gracefully for v1 and empty snapshots with expanded JSON fallback', async () => {
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
userStore.findUnique.mockResolvedValue(active as never)
feedbackStore.findFirst.mockResolvedValueOnce({
...record,
snapshot: { clientVersion: '1.0.5', os: 'Windows', project: { name: '老项目' }, message: 'v1报错' },
}).mockResolvedValueOnce({
...record,
snapshot: {},
})
const v1Html = await (await get()).text()
expect(v1Html).toContain('老项目')
expect(v1Html).toContain('1.0.5')
expect(v1Html).toContain('<details class="json-details" open>')
expect(v1Html).not.toContain('核心故障摘要')
expect(v1Html).not.toContain('运行环境与状态速览')
expect(v1Html).not.toContain('近期通知与告警')
expect(v1Html).not.toContain('近期客户端日志摘要')
const emptyHtml = await (await get()).text()
expect(emptyHtml).toContain('没有记录诊断信息。')
expect(emptyHtml).not.toContain('<details')
})
})