/** @jest-environment node */ import { createHmac } from 'node:crypto' import { GET } from '@/app/api/desktop/[...path]/route' import { prisma } from '@/lib/prisma' jest.mock('@/lib/prisma', () => ({ prisma: { $queryRawUnsafe: jest.fn(), user: { findUnique: jest.fn() } } })) jest.mock('@/lib/detail-generator/repository', () => ({})) jest.mock('@/lib/detail-generator/storage', () => ({})) jest.mock('@/lib/desktop-client/project-lifecycle', () => ({})) jest.mock('@/lib/auth', () => ({ authOptions: {} })) jest.mock('next-auth', () => ({ getServerSession: jest.fn() })) const context = { params: { path: ['knowledge', 'session'] } } const request = () => new Request('https://platform.test/api/desktop/knowledge/session', { headers: { authorization: 'Bearer dcs_' + 'a'.repeat(64) }, }) const originalSecret = process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET const originalEnabled = process.env.DETAIL_GENERATOR_ENABLED const secret = 'knowledge-session-test-secret-123456789' const user = { username: 'account', realName: '当前账号', isActive: true, status: 'active', archivedAt: null } const session = { id: 'session-id', ownerId: 'test-account', expiresAt: new Date('2026-12-01T09:00:00Z') } describe('desktop knowledge session', () => { beforeEach(() => { jest.clearAllMocks() jest.useFakeTimers().setSystemTime(new Date('2026-12-01T08:00:00Z')) process.env.DETAIL_GENERATOR_ENABLED = 'true' process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET = secret jest.mocked(prisma.$queryRawUnsafe).mockResolvedValue([session]) jest.mocked(prisma.user.findUnique).mockResolvedValue(user as any) }) afterEach(() => { jest.useRealTimers() if (originalSecret === undefined) delete process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET else process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET = originalSecret if (originalEnabled === undefined) delete process.env.DETAIL_GENERATOR_ENABLED else process.env.DETAIL_GENERATOR_ENABLED = originalEnabled }) test.each([{ isActive: false }, { archivedAt: new Date() }, { status: 'pending' }, { status: '' }])('checks account state on every request (%j)', async patch => { expect((await GET(request(), context)).status).toBe(200) jest.mocked(prisma.user.findUnique).mockResolvedValueOnce({ ...user, ...patch } as any) const response = await GET(request(), context) expect(response.status).toBe(403) expect(response.headers.get('cache-control')).toBe('private, no-store') expect(await response.json()).toEqual({ code: 'account_inactive', error: expect.any(String) }) }) test('refuses to sign immediately after desktop authorization is revoked', async () => { expect((await GET(request(), context)).status).toBe(200) jest.mocked(prisma.$queryRawUnsafe).mockResolvedValueOnce([]) const response = await GET(request(), context) expect(response.status).toBe(401) expect(await response.json()).toEqual({ code: 'session_expired', error: expect.any(String) }) expect(prisma.$queryRawUnsafe).toHaveBeenLastCalledWith(expect.stringContaining('revoked_at IS NULL AND expires_at>NOW()'), expect.any(String)) expect(prisma.user.findUnique).toHaveBeenCalledTimes(1) }) test('signs the account identity with the configured key and limits the lifetime', async () => { const response = await GET(request(), context) expect(response.status).toBe(200) expect(response.headers.get('cache-control')).toBe('private, no-store') const result = await response.json() const [encoded, signature] = result.token.replace('ekb_xiaoyi_session_', '').split('.') expect(signature).toBe(createHmac('sha256', secret).update(encoded).digest('base64url')) expect(JSON.parse(Buffer.from(encoded, 'base64url').toString())).toEqual({ sub: 'test-account', aud: 'xiaoyi-knowledge', iat: 1796112000, exp: 1796112300, }) expect(result.expiresAt).toBe('2026-12-01T08:05:00.000Z') jest.mocked(prisma.$queryRawUnsafe).mockResolvedValueOnce([{ ...session, expiresAt: new Date('2026-12-01T08:00:45Z') }]) expect((await (await GET(request(), context)).json()).expiresAt).toBe('2026-12-01T08:00:45.000Z') }) test.each([undefined, '汉'.repeat(10) + 'a'])('reports missing or sub-32-byte key (%s)', async value => { if (value === undefined) delete process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET else process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET = value const response = await GET(request(), context) expect(response.status).toBe(503) expect(await response.json()).toEqual({ error: '小壹知识库自动授权配置错误,请联系管理员', code: 'knowledge_session_misconfigured' }) }) test('accepts exactly 32 UTF-8 bytes', async () => { process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET = '汉'.repeat(10) + 'ab' expect((await GET(request(), context)).status).toBe(200) }) })