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

156 lines
8.4 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() },
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' })
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}$`),
}))
})
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 })
})
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()
})
})
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 }],
])('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', 'DEPT_ADMIN'] as const)('returns a real 403 to another %s and checks only metadata', async role => {
jest.mocked(getServerSession).mockResolvedValue({ user: { id: 'another', role: 'ADMIN' } })
userStore.findUnique.mockResolvedValue({ ...active, role } 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)
})
})