226 lines
12 KiB
TypeScript
226 lines
12 KiB
TypeScript
/** @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()
|
||
})
|
||
})
|
||
|
||
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 ['<b>导出失败</b>', '提交人甲', 'project-01', 'task-01', 'req-01', '<script>unsafe</script>']) {
|
||
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)
|
||
})
|
||
})
|