118 lines
6.4 KiB
TypeScript
118 lines
6.4 KiB
TypeScript
/** @jest-environment node */
|
|
import { createHmac } from 'node:crypto'
|
|
import { GET } from '@/app/api/desktop/[...path]/route'
|
|
import { issueKnowledgeSession } from '@/lib/desktop-client/knowledge-session'
|
|
import { prisma } from '@/lib/prisma'
|
|
|
|
jest.mock('@/lib/prisma', () => ({ prisma: { $queryRawUnsafe: jest.fn(), $executeRawUnsafe: 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 = (claimedSuperAdmin = false) => new Request(`https://platform.test/api/desktop/knowledge/session?isSuperAdmin=${claimedSuperAdmin}`, {
|
|
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, isSuperAdmin: false }
|
|
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.$executeRawUnsafe).mockResolvedValue(1)
|
|
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.each([true, false])('signs the database isSuperAdmin=%s and limits the lifetime', async isSuperAdmin => {
|
|
jest.mocked(prisma.user.findUnique).mockResolvedValue({ ...user, isSuperAdmin } as any)
|
|
const response = await GET(request(!isSuperAdmin), 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 === createHmac('sha256', secret).update(encoded).digest('base64url')).toBe(true)
|
|
expect(prisma.user.findUnique).toHaveBeenCalledWith({
|
|
where: { id: session.ownerId }, select: expect.objectContaining({ isSuperAdmin: true }),
|
|
})
|
|
expect(JSON.parse(Buffer.from(encoded, 'base64url').toString())).toEqual({
|
|
sub: 'test-account', aud: 'xiaoyi-knowledge', iat: 1796112000, exp: 1796112300, isSuperAdmin,
|
|
})
|
|
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:05:00.000Z')
|
|
expect(prisma.$executeRawUnsafe).toHaveBeenCalledWith(
|
|
expect.stringContaining('UPDATE desktop_client_sessions SET expires_at=$2'),
|
|
session.id,
|
|
expect.any(Date),
|
|
)
|
|
expect(issueKnowledgeSession(session.ownerId, new Date('2026-12-01T08:00:45Z'), isSuperAdmin).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)
|
|
})
|
|
|
|
test('renews an expired knowledge session using the current desktop role', async () => {
|
|
jest.mocked(prisma.user.findUnique).mockResolvedValueOnce({ ...user, isSuperAdmin: true } as any)
|
|
const readClaims = async () => {
|
|
const response = await GET(request(), context)
|
|
expect(response.status).toBe(200)
|
|
const { token } = await response.json()
|
|
const payload = token.slice('ekb_xiaoyi_session_'.length).split('.')[0]
|
|
return JSON.parse(Buffer.from(payload, 'base64url').toString())
|
|
}
|
|
const first = await readClaims()
|
|
jest.setSystemTime(new Date((first.exp + 1) * 1000))
|
|
const renewed = await readClaims()
|
|
expect(first.isSuperAdmin).toBe(true)
|
|
expect(renewed).toMatchObject({ iat: first.exp + 1, exp: first.exp + 301, isSuperAdmin: false })
|
|
expect(prisma.user.findUnique).toHaveBeenCalledTimes(2)
|
|
})
|
|
})
|