/** @jest-environment node */ import { createHmac, randomBytes } from 'node:crypto' import { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS } from '@/app/api/desktop/knowledge/proxy/[[...path]]/route' 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', () => ({})) const proxyUrl = 'https://platform.test/api/desktop/knowledge/proxy' const current = '/api/xiaoyi/v1/templates/key-check/current' const bundle = '/api/xiaoyi/v1/templates/SFY-CHAIR-001/releases/2026-11-28.1/bundle' const origin = 'https://knowledge.test:8443' const secret = randomBytes(32).toString('hex') const desktopAuth = 'Bearer dcs_' + randomBytes(48).toString('base64url') const expiresAt = new Date(Date.now() + 20 * 86400_000) const account = { username: 'owner', status: 'active', isActive: true, archivedAt: null, isSuperAdmin: false } const querySession = prisma.$queryRawUnsafe as jest.Mock const executeSession = prisma.$executeRawUnsafe as jest.Mock const findUser = prisma.user.findUnique as jest.Mock const originalEnv = process.env let upstream: jest.SpyInstance, Parameters> function request(path = current, method = 'GET', extraHeaders?: HeadersInit) { const headers = new Headers(extraHeaders) headers.set('authorization', desktopAuth) return new Request(proxyUrl + path, { method, headers }) } beforeEach(() => { process.env = { ...originalEnv, DETAIL_GENERATOR_ENABLED: 'true', XIAOYI_KNOWLEDGE_UPSTREAM_ORIGIN: origin, XIAOYI_KNOWLEDGE_SESSION_SECRET: secret } querySession.mockReset().mockResolvedValue([{ id: 'device', ownerId: 'owner-id', expiresAt }]) executeSession.mockReset().mockResolvedValue(1) findUser.mockReset().mockResolvedValue(account) upstream = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}', { headers: { 'Content-Type': 'application/json' } })) }) afterEach(() => { process.env = originalEnv jest.restoreAllMocks() jest.useRealTimers() }) test('requires authorization and rejects revoked sessions before contacting the upstream', async () => { const anonymous = await GET(new Request(proxyUrl + current)) expect(anonymous.status).toBe(401) expect(await anonymous.json()).toHaveProperty('code', 'unauthenticated') expect(querySession).not.toHaveBeenCalled() querySession.mockResolvedValueOnce([]) const revoked = await GET(request()) expect(revoked.status).toBe(401) expect(await revoked.json()).toHaveProperty('code', 'session_expired') expect(String(querySession.mock.calls[0][0])).toContain('revoked_at IS NULL') expect(upstream.mock.calls.length).toBe(0) }) test.each([{ isActive: false }, { archivedAt: new Date() }])('rejects unavailable accounts (%o)', async (changes) => { findUser.mockResolvedValueOnce({ ...account, ...changes }) const response = await GET(request(current, 'GET', { 'If-None-Match': '"release"' })) expect(response.status).toBe(403) expect(await response.json()).toHaveProperty('code', 'account_inactive') expect(upstream.mock.calls.length).toBe(0) }) test.each([undefined, 'ftp://knowledge.test', 'https://knowledge.test/path', 'https://knowledge.test?query', 'https://knowledge.test:99999'])('rejects missing or invalid upstream origin (%s)', async (configured) => { if (configured === undefined) delete process.env.XIAOYI_KNOWLEDGE_UPSTREAM_ORIGIN else process.env.XIAOYI_KNOWLEDGE_UPSTREAM_ORIGIN = configured const response = await GET(request()) expect(response.status).toBe(503) expect(await response.json()).toHaveProperty('code', 'knowledge_upstream_misconfigured') expect(upstream.mock.calls.length).toBe(0) }) test('rejects a missing signing secret', async () => { delete process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET const response = await GET(request()) expect(response.status).toBe(503) expect(await response.json()).toHaveProperty('code', 'knowledge_session_misconfigured') expect(upstream.mock.calls.length).toBe(0) }) test.each([ '', '/healthz', '/api/xiaoyi/v1/admin', '//other.test/api/xiaoyi/v1/templates', '/api/xiaoyi/v1/templates/../templates', '/api/xiaoyi/v1/templates/%2e%2e/templates', '/api/xiaoyi/v1/templates/with..dots/current', '/api/xiaoyi/v1/templates/%252e%252e/current', '/api/xiaoyi/v1/templates/bad\\path/current', '/api/xiaoyi/v1/templates/bad%2fpath/current', '/api/xiaoyi/v1/templates/bad%00path/current', '/api/xiaoyi/v1/templates/a/current\n', ])('rejects paths outside the published read endpoints (%s)', async (path) => { const incoming = request() // URL parsers may normalize dot segments before the route sees them. Object.defineProperty(incoming, 'url', { value: proxyUrl + path }) const response = await GET(incoming) expect(response.status).toBe(400) expect(await response.json()).toHaveProperty('code', 'invalid_knowledge_path') expect(upstream.mock.calls.length).toBe(0) }) test.each([['POST', POST], ['PUT', PUT], ['PATCH', PATCH], ['DELETE', DELETE], ['OPTIONS', OPTIONS]] as const)('rejects %s requests', async (method, handler) => { const response = await handler(request(current, method)) expect(response.status).toBe(405) expect(response.headers.get('allow')).toBe('GET, HEAD') expect(upstream.mock.calls.length).toBe(0) }) test.each([true, false])('forwards the query unchanged and signs the database isSuperAdmin=%s', async isSuperAdmin => { findUser.mockResolvedValueOnce({ ...account, isSuperAdmin }) const query = `?a=%2f+%20&a=%25&flag&isSuperAdmin=${!isSuperAdmin}` const incoming = request(current + query, 'GET', { Accept: 'application/json', 'If-None-Match': '"v1"', 'X-EKB-Client-Version': '1.0', Cookie: 'example=test', 'X-API-Key': 'ignored', }) const response = await GET(incoming) expect(response.status).toBe(200) expect(await response.json()).toEqual({}) const [target, init] = upstream.mock.calls[0] expect(target).toBe(origin + current + query) expect([init?.method, init?.cache, init?.redirect]).toEqual(['GET', 'no-store', 'manual']) const headers = new Headers(init?.headers) expect(headers.get('accept')).toBe('application/json') expect(headers.get('if-none-match')).toBe('"v1"') expect(headers.get('x-ekb-client-version')).toBe('1.0') expect(headers.has('cookie')).toBe(false) expect(headers.has('x-api-key')).toBe(false) const signed = /^Bearer ekb_xiaoyi_session_([\w-]+)\.([\w-]+)$/.exec(headers.get('authorization') ?? '') expect(Boolean(signed)).toBe(true) const [, payload, signature] = signed! const claims = JSON.parse(Buffer.from(payload, 'base64url').toString()) expect(claims).toMatchObject({ sub: 'owner-id', aud: 'xiaoyi-knowledge', isSuperAdmin }) const { iat, exp } = claims expect(exp - iat).toBe(300) expect(exp - iat).toBeGreaterThan(0) expect(exp - iat).toBeLessThanOrEqual(300) expect(createHmac('sha256', secret).update(payload).digest('base64url') === signature).toBe(true) }) test('returns the upstream stream before the bundle finishes and preserves range metadata', async () => { let producer!: ReadableStreamDefaultController const stream = new ReadableStream({ start(controller) { producer = controller } }) const content = new Uint8Array([0, 129, 254, 255]) upstream.mockResolvedValueOnce(new Response(stream, { status: 206, headers: { 'Content-Type': 'application/octet-stream', 'Content-Length': '4', 'Content-Range': 'bytes 10-13/500', 'Accept-Ranges': 'bytes', ETag: '"bundle"', 'Last-Modified': 'Mon, 30 Nov 2026 01:00:00 GMT', 'Cache-Control': 'public, s-maxage=600', 'Set-Cookie': 'ignored=test', 'X-Upstream-Trace': 'ignored', } })) const response = await GET(request(bundle, 'GET', { Range: 'bytes=10-13', 'If-Range': '"bundle"' })) expect(response.body === stream).toBe(true) expect(response.status).toBe(206) expect(Object.fromEntries(response.headers)).toMatchObject({ 'content-type': 'application/octet-stream', 'content-length': '4', 'content-range': 'bytes 10-13/500', 'accept-ranges': 'bytes', etag: '"bundle"', 'last-modified': 'Mon, 30 Nov 2026 01:00:00 GMT', 'cache-control': 'private, no-store, no-transform', }) expect(response.headers.has('set-cookie') || response.headers.has('x-upstream-trace')).toBe(false) const headers = new Headers(upstream.mock.calls[0][1]?.headers) expect(headers.get('range')).toBe('bytes=10-13') expect(headers.get('if-range')).toBe('"bundle"') producer.enqueue(content.subarray(0, 2)) const reader = response.body!.getReader() expect((await reader.read()).value).toEqual(content.subarray(0, 2)) producer.enqueue(content.subarray(2)) producer.close() expect((await reader.read()).value).toEqual(content.subarray(2)) expect((await reader.read()).done).toBe(true) }) test('preserves bodyless HEAD and 304 and checks authorization on both', async () => { upstream.mockResolvedValueOnce(new Response(null, { status: 200, headers: { 'Content-Length': '88', ETag: '"bundle"' } })) .mockResolvedValueOnce(new Response(null, { status: 304, headers: { ETag: '"bundle"' } })) const head = await HEAD(request(bundle, 'HEAD')) expect(head.status).toBe(200) expect(head.body).toBeNull() expect(head.headers.get('content-length')).toBe('88') expect(upstream.mock.calls[0][1]?.method).toBe('HEAD') const unchanged = await GET(request(bundle, 'GET', { 'If-None-Match': '"bundle"' })) expect(unchanged.status).toBe(304) expect(unchanged.body).toBeNull() expect(unchanged.headers.get('etag')).toBe('"bundle"') expect(findUser).toHaveBeenCalledTimes(2) }) test.each([[404, 404], [302, 502], [500, 502], [504, 504]])('sanitizes upstream status %d as %d', async (status, expected) => { upstream.mockResolvedValueOnce(new Response('internal-placeholder', { status, headers: { Location: 'https://other.test/' } })) const response = await GET(request()) expect(response.status).toBe(expected) expect(response.headers.has('location')).toBe(false) expect(await response.text()).not.toContain('internal-placeholder') expect(upstream).toHaveBeenCalledTimes(1) }) test.each([ ['not_found', 'not_found', '企业知识库资源不存在'], ['not_published', 'not_published', '企业知识库模板尚未发布'], ['channel_unavailable', 'knowledge_upstream_rejected', '企业知识库资源不存在'], ])('sanitizes a JSON 404 with code %s', async (upstreamCode, code, error) => { upstream.mockResolvedValueOnce(new Response(JSON.stringify({ status: 404, code: upstreamCode, error: 'internal-placeholder', }), { status: 404, headers: { 'Content-Type': 'Application/JSON; charset=utf-8' } })) const response = await GET(request()) expect(response.status).toBe(404) const body = await response.text() expect(JSON.parse(body)).toMatchObject({ code, error }) expect(body).not.toContain('internal-placeholder') }) test.each([ ['text/html', '

internal-placeholder

'], ['application/json', '{"code":"not_found","error":"internal-placeholder"'], ['application/json', '{"error":"internal-placeholder"}'], ])('sanitizes an unrecognized %s 404 body', async (contentType, body) => { upstream.mockResolvedValueOnce(new Response(body, { status: 404, headers: { 'Content-Type': contentType } })) const response = await GET(request()) expect(response.status).toBe(404) const responseBody = await response.text() expect(JSON.parse(responseBody)).toMatchObject({ code: 'knowledge_upstream_rejected', error: '企业知识库资源不存在' }) expect(responseBody).not.toContain('internal-placeholder') }) test('cancels a JSON 404 stream when it exceeds 8192 bytes', async () => { const cancel = jest.fn() const encoder = new TextEncoder() const body = new ReadableStream({ start(controller) { controller.enqueue(encoder.encode('{"code":"not_found"}'.padEnd(8192, ' '))) controller.enqueue(encoder.encode(' ')) }, cancel, }) upstream.mockResolvedValueOnce(new Response(body, { status: 404, headers: { 'Content-Type': 'application/json' } })) const response = await GET(request()) expect(response.status).toBe(404) expect(await response.json()).toHaveProperty('code', 'knowledge_upstream_rejected') expect(cancel).toHaveBeenCalledTimes(1) }) test('returns a bodyless HEAD for a not_found 404', async () => { upstream.mockResolvedValueOnce(new Response('{"code":"not_found"}', { status: 404, headers: { 'Content-Type': 'application/json' }, })) const head = await HEAD(request(current, 'HEAD')) expect(head.status).toBe(404) expect(head.body).toBeNull() }) test('maps upstream connection failures and header timeouts to JSON errors', async () => { upstream.mockRejectedValueOnce(new TypeError('internal-placeholder')) const failed = await GET(request()) expect(failed.status).toBe(502) expect(await failed.json()).toHaveProperty('code', 'knowledge_upstream_unreachable') jest.useFakeTimers() upstream.mockImplementationOnce((_, init) => new Promise((_, reject) => { init!.signal!.addEventListener('abort', () => reject(init!.signal!.reason), { once: true }) })) const pending = GET(request()) await jest.advanceTimersByTimeAsync(15_001) const timedOut = await pending expect(timedOut.status).toBe(504) expect(await timedOut.json()).toHaveProperty('code', 'knowledge_upstream_timeout') })