/** @jest-environment node */ import { NextRequest } from 'next/server' import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { Readable } from 'node:stream' import AdmZip from 'adm-zip' import { GET } from '@/app/api/external/download/route' import { isTokenExpired, verifyDownloadToken } from '@/lib/download-token' import { prisma } from '@/lib/prisma' import { getS3ObjectStream } from '@/lib/s3' jest.mock('@/lib/s3', () => ({ getS3ObjectStream: jest.fn(), })) jest.mock('@/lib/download-token', () => ({ isTokenExpired: jest.fn(), verifyDownloadToken: jest.fn(), })) jest.mock('@/lib/prisma', () => ({ prisma: { material: { findUnique: jest.fn(), }, deliveryRevision: { findFirst: jest.fn() }, revisionAsset: { findFirst: jest.fn() }, }, })) const originalFetch = global.fetch const fileUrl = 'https://s3.example.test/materials/task-page.bin' const localPayload = Buffer.from( Array.from({ length: 4096 }, (_, index) => index % 256), ) let localTempDir: string let localFilePath: string function makeMaterial(assetFileUrl = fileUrl) { return { id: 'material-1', materialType: '任务-详情', createdAt: new Date('2025-01-01T00:00:00.000Z'), taskNo: 'TASK-001', assets: [ { id: 'asset-1', assetType: 'main', fileUrl: assetFileUrl, fileName: 'task-page.bin', }, ], } } function makeNonProductMaterial(overrides: Record = {}) { return { id: 'material-1', materialType: '任务-页面', createdAt: new Date('2025-01-01T00:00:00.000Z'), zipFilePath: '', zipFileName: '', productModel: 'MODEL-001', categoryName: '分类', sceneName: '场景', productCategoryName: '品类', assets: [], ...overrides, } } function makeUpstreamResponse(status: number, size: number, headers: Record) { const body = new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array(size)) controller.close() }, }) return new Response(body, { status, headers: { 'Content-Type': 'application/octet-stream', 'Content-Length': String(size), ...headers, }, }) } function makeRequest(range?: string) { return new NextRequest('http://localhost/api/external/download?token=download-token', { headers: range ? { Range: range } : undefined, }) } describe('external single-file S3 download range forwarding', () => { beforeAll(async () => { localTempDir = await mkdtemp(join(tmpdir(), 'external-download-range-')) localFilePath = join(localTempDir, 'task-page.bin') await writeFile(localFilePath, localPayload) }) beforeEach(() => { jest.clearAllMocks() global.fetch = jest.fn() as unknown as typeof fetch ;(isTokenExpired as jest.Mock).mockReturnValue(false) ;(verifyDownloadToken as jest.Mock).mockReturnValue({ materialId: 'material-1', downloadType: 'single', assetId: 'asset-1', }) ;(prisma.material.findUnique as jest.Mock).mockResolvedValue(makeMaterial()) }) afterEach(() => { global.fetch = originalFetch }) afterAll(async () => { await rm(localTempDir, { recursive: true, force: true }) }) test.each([ [['1440x1440/001-A.jpg'], ['sku/001-A.jpg']], [ ['800x800/001-A.jpg', '1440x1920/001-A.jpg', '1440x1920/001-B.jpg'], ['sku/800x800/001-A.jpg', 'sku/1440x1920/001-A.jpg', 'sku/1440x1920/001-B.jpg'], ], [ ['800x800/001-A.jpg', '800x800/001-A.jpg', '1440x1920/001-A.jpg', '800x800/001-B.jpg'], ['sku/800x800/01/001-A.jpg', 'sku/800x800/02/001-A.jpg', 'sku/1440x1920/001-A.jpg', 'sku/800x800/001-B.jpg'], ], ])('小壹 ZIP 按分辨率组织 SKU 并保留单分辨率的历史目录(%j)', async (paths, expected) => { jest.mocked(verifyDownloadToken).mockReturnValue({ materialId: 'material-1', downloadType: 'all' }) const assets = await Promise.all(paths.map(async (relative, sortOrder) => { const [resolution, fileName] = relative.split('/') const fileUrl = join(localTempDir, 'xiaoyi-deliveries', 'owner', 'project', 'request', 'sku', resolution, `hash-${sortOrder}`, fileName) await mkdir(dirname(fileUrl), { recursive: true }) await writeFile(fileUrl, `${relative}#${sortOrder}`) return { assetType: 'sku', fileUrl, fileName, sortOrder } })) jest.mocked(prisma.material.findUnique).mockResolvedValue({ ...makeMaterial(), materialType: '自动上架-详情', assets, } as any) const response = await GET(makeRequest()) expect(response.status).toBe(200) const zip = new AdmZip(Buffer.from(await response.arrayBuffer())) expect(zip.getEntries().map(entry => entry.entryName).sort()).toEqual([...expected].sort()) expected.forEach((entry, index) => expect(zip.readAsText(entry)).toBe(`${paths[index]}#${index}`)) }) test.each([{ accessScope: 'operations_g' }, { taskDetailPrivate: true }])( '小壹成图的下载 Token 仍会核对当前素材权限(%j)', async restrictions => { jest.mocked(prisma.material.findUnique).mockResolvedValue({ ...makeMaterial(), materialType: '自动上架-详情', ...restrictions, } as any) const response = await GET(makeRequest()) expect(response.status).toBe(404) expect(prisma.material.findUnique).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 'material-1', accessScope: 'general', taskDetailPrivate: false, deletedAt: null }, })) expect(global.fetch).not.toHaveBeenCalled() }, ) test('forwards Range to S3 and preserves a 206 streaming response', async () => { ;(global.fetch as jest.Mock).mockResolvedValueOnce( makeUpstreamResponse(206, 1024, { 'Content-Range': 'bytes 0-1023/4096', }), ) const response = await GET(makeRequest('bytes=0-1023')) expect(response.status).toBe(206) expect(response.headers.get('Content-Range')).toBe('bytes 0-1023/4096') expect(response.headers.get('Content-Length')).toBe('1024') expect(response.body).toBeInstanceOf(ReadableStream) expect(global.fetch).toHaveBeenCalledTimes(1) const [requestedUrl, requestInit] = (global.fetch as jest.Mock).mock.calls[0] expect(requestedUrl).toBe(fileUrl) expect(new Headers(requestInit?.headers).get('range')).toBe('bytes=0-1023') }) test('without Range keeps the full upstream 200 streaming response', async () => { ;(global.fetch as jest.Mock).mockResolvedValueOnce( makeUpstreamResponse(200, 4096, {}), ) const response = await GET(makeRequest()) expect(response.status).toBe(200) expect(response.headers.get('Content-Range')).toBeNull() expect(response.headers.get('Content-Length')).toBe('4096') expect(response.body).toBeInstanceOf(ReadableStream) expect(global.fetch).toHaveBeenCalledTimes(1) const [, requestInit] = (global.fetch as jest.Mock).mock.calls[0] expect(new Headers(requestInit?.headers).get('range')).toBeNull() }) test.each(['all', 'sku'])('相同 Token 重复下载 %s:重新解析最新文件和内容,不缓存旧版本', async (downloadType) => { ;(verifyDownloadToken as jest.Mock).mockReturnValue({ materialId: 'material-1', downloadType }) for (const revision of [1, 2, 3]) { const latestUrl = `https://s3.example.test/materials/${downloadType}-v${revision}.zip` const payload = Uint8Array.from([revision, revision + 1, revision + 2]) ;(prisma.material.findUnique as jest.Mock).mockResolvedValue({ ...makeMaterial(), taskStatus: 'fetched', assets: [{ id: `asset-${downloadType}`, assetType: downloadType, fileUrl: latestUrl, fileName: `${downloadType}.zip` }], }) ;(global.fetch as jest.Mock).mockResolvedValueOnce(new Response(payload, { headers: { 'Content-Type': 'application/zip', 'Content-Length': String(payload.length), 'Cache-Control': 'public, max-age=31536000' }, })) const response = await GET(makeRequest()) expect(response.status).toBe(200) expect(response.headers.get('Cache-Control')).toBe('private, no-store') expect(Buffer.from(await response.arrayBuffer())).toEqual(Buffer.from(payload)) expect(global.fetch).toHaveBeenLastCalledWith(latestUrl, expect.objectContaining({ cache: 'no-store' })) } expect(prisma.material.findUnique).toHaveBeenCalledTimes(3) }) describe('local file ranges', () => { beforeEach(() => { ;(prisma.material.findUnique as jest.Mock).mockResolvedValue(makeMaterial(localFilePath)) }) test('returns the first 1024 bytes for bytes=0-1023', async () => { const response = await GET(makeRequest('bytes=0-1023')) expect(response.status).toBe(206) expect(response.headers.get('Content-Range')).toBe('bytes 0-1023/4096') expect(response.headers.get('Content-Length')).toBe('1024') expect(Buffer.from(await response.arrayBuffer())).toEqual(localPayload.subarray(0, 1024)) expect(global.fetch).not.toHaveBeenCalled() }) test('clamps an end beyond the file to the final byte', async () => { const response = await GET(makeRequest('bytes=0-999999')) expect(response.status).toBe(206) expect(response.headers.get('Content-Range')).toBe('bytes 0-4095/4096') expect(response.headers.get('Content-Length')).toBe('4096') expect(Buffer.from(await response.arrayBuffer())).toEqual(localPayload) expect(global.fetch).not.toHaveBeenCalled() }) test('returns the final 500 bytes for a suffix range', async () => { const response = await GET(makeRequest('bytes=-500')) expect(response.status).toBe(206) expect(response.headers.get('Content-Range')).toBe('bytes 3596-4095/4096') expect(response.headers.get('Content-Length')).toBe('500') expect(Buffer.from(await response.arrayBuffer())).toEqual(localPayload.subarray(-500)) expect(global.fetch).not.toHaveBeenCalled() }) test.each(['bytes=4096-', 'bytes=0-1,2-3'])( 'rejects a true out-of-bounds or multi-range request (%s)', async (range) => { const response = await GET(makeRequest(range)) expect(response.status).toBe(416) expect(response.headers.get('Content-Range')).toBe('bytes */4096') expect(global.fetch).not.toHaveBeenCalled() }, ) }) describe('non-product package source ranges', () => { test('forwards Range to a historical task-page local ZIP and returns the requested bytes', async () => { ;(prisma.material.findUnique as jest.Mock).mockResolvedValue( makeNonProductMaterial({ zipFilePath: localFilePath, zipFileName: 'task-page.zip', }), ) const response = await GET(makeRequest('bytes=0-1023')) expect(response.status).toBe(206) expect(response.headers.get('Content-Range')).toBe('bytes 0-1023/4096') expect(response.headers.get('Content-Length')).toBe('1024') expect(Buffer.from(await response.arrayBuffer())).toEqual(localPayload.subarray(0, 1024)) expect(global.fetch).not.toHaveBeenCalled() }) test('forwards Range for a zipFileName S3 URL when zipFilePath is empty', async () => { const s3ZipUrl = 'https://s3.example.test/materials/task-page.zip' ;(prisma.material.findUnique as jest.Mock).mockResolvedValue( makeNonProductMaterial({ zipFileName: s3ZipUrl }), ) ;(global.fetch as jest.Mock).mockResolvedValueOnce( makeUpstreamResponse(206, 1024, { 'Content-Range': 'bytes 0-1023/4096', 'Accept-Ranges': 'bytes', }), ) const response = await GET(makeRequest('bytes=0-1023')) expect(response.status).toBe(206) expect(response.headers.get('Content-Range')).toBe('bytes 0-1023/4096') expect(response.headers.get('Content-Length')).toBe('1024') expect(response.body).toBeInstanceOf(ReadableStream) expect(Buffer.from(await response.arrayBuffer())).toEqual(new Uint8Array(1024)) expect(global.fetch).toHaveBeenCalledTimes(1) const [requestedUrl, requestInit] = (global.fetch as jest.Mock).mock.calls[0] expect(requestedUrl).toBe(s3ZipUrl) expect(new Headers(requestInit?.headers).get('range')).toBe('bytes=0-1023') }) test('forwards Range for an old HTTP zipFilePath and preserves 206 headers', async () => { const legacyZipUrl = 'http://103.118.245.6/materials/task-page.zip' ;(prisma.material.findUnique as jest.Mock).mockResolvedValue( makeNonProductMaterial({ zipFilePath: legacyZipUrl }), ) ;(global.fetch as jest.Mock).mockResolvedValueOnce( makeUpstreamResponse(206, 1024, { 'Content-Range': 'bytes 0-1023/4096', 'Accept-Ranges': 'bytes', }), ) const response = await GET(makeRequest('bytes=0-1023')) expect(response.status).toBe(206) expect(response.headers.get('Content-Range')).toBe('bytes 0-1023/4096') expect(response.headers.get('Content-Length')).toBe('1024') expect(response.body).toBeInstanceOf(ReadableStream) expect(global.fetch).toHaveBeenCalledTimes(1) const [requestedUrl, requestInit] = (global.fetch as jest.Mock).mock.calls[0] expect(requestedUrl).toBe(legacyZipUrl) expect(new Headers(requestInit?.headers).get('range')).toBe('bytes=0-1023') }) test('propagates an upstream 416 Content-Range for a S3 zip URL', async () => { const s3ZipUrl = 'https://s3.example.test/materials/task-page.zip' ;(prisma.material.findUnique as jest.Mock).mockResolvedValue( makeNonProductMaterial({ zipFileName: s3ZipUrl }), ) const upstreamResponse = makeUpstreamResponse(416, 0, { 'Content-Range': 'bytes */4096', 'Accept-Ranges': 'bytes', }) ;(global.fetch as jest.Mock).mockResolvedValueOnce(upstreamResponse) const response = await GET(makeRequest('bytes=9999-')) expect(response.status).toBe(416) expect(response.headers.get('Content-Range')).toBe('bytes */4096') expect(global.fetch).toHaveBeenCalledTimes(1) const [, requestInit] = (global.fetch as jest.Mock).mock.calls[0] expect(new Headers(requestInit?.headers).get('range')).toBe('bytes=9999-') }) test('keeps a 200 full response when an upstream ignores Range', async () => { const s3ZipUrl = 'https://s3.example.test/materials/task-page.zip' ;(prisma.material.findUnique as jest.Mock).mockResolvedValue( makeNonProductMaterial({ zipFileName: s3ZipUrl }), ) ;(global.fetch as jest.Mock).mockResolvedValueOnce( makeUpstreamResponse(200, 4096, { 'Accept-Ranges': 'bytes', }), ) const response = await GET(makeRequest('bytes=0-1023')) expect(response.status).toBe(200) expect(response.headers.get('Content-Range')).toBeNull() expect(response.headers.get('Content-Length')).toBe('4096') expect(response.body).toBeInstanceOf(ReadableStream) expect(Buffer.from(await response.arrayBuffer())).toHaveLength(4096) expect(global.fetch).toHaveBeenCalledTimes(1) const [, requestInit] = (global.fetch as jest.Mock).mock.calls[0] expect(new Headers(requestInit?.headers).get('range')).toBe('bytes=0-1023') }) }) describe('xiaoyi delivery remote S3 fallback', () => { const prevBucket = process.env.S3_BUCKET const prevPrefix = process.env.S3_FILE_PATH beforeEach(() => { process.env.S3_BUCKET = 'gongxiangpan' process.env.S3_FILE_PATH = 'xiaoyi/' }) afterEach(() => { if (prevBucket === undefined) delete process.env.S3_BUCKET else process.env.S3_BUCKET = prevBucket if (prevPrefix === undefined) delete process.env.S3_FILE_PATH else process.env.S3_FILE_PATH = prevPrefix }) test('falls back to S3 stream for Xiaoyi ZIP when local upload file is missing', async () => { ;(verifyDownloadToken as jest.Mock).mockReturnValue({ materialId: 'material-1', downloadType: 'all', }) ;(prisma.material.findUnique as jest.Mock).mockResolvedValue({ id: 'material-1', materialType: '自动上架-详情', createdAt: new Date('2026-12-01T00:00:00.000Z'), assets: [ { id: 'asset-main', assetType: 'main', fileUrl: 'uploads/xiaoyi-deliveries/owner/proj/req/0000-main.jpg', fileName: '0000-main.jpg', sortOrder: 0, }, ], }) ;(getS3ObjectStream as jest.Mock).mockResolvedValueOnce({ body: Readable.from([Buffer.from('remote-main-bytes')]), contentLength: 17, }) const response = await GET(makeRequest()) expect(response.status).toBe(200) expect(getS3ObjectStream).toHaveBeenCalledWith('xiaoyi/uploads/xiaoyi-deliveries/owner/proj/req/0000-main.jpg', expect.anything()) const zip = new AdmZip(Buffer.from(await response.arrayBuffer())) expect(zip.readAsText('main/0000-main.jpg')).toBe('remote-main-bytes') }) test('falls back to S3 stream for Xiaoyi single file when local upload file is missing', async () => { ;(verifyDownloadToken as jest.Mock).mockReturnValue({ materialId: 'material-1', downloadType: 'single', assetId: 'asset-main', }) ;(prisma.material.findUnique as jest.Mock).mockResolvedValue({ id: 'material-1', materialType: '自动上架-详情', createdAt: new Date('2026-12-01T00:00:00.000Z'), assets: [ { id: 'asset-main', assetType: 'main', fileUrl: 'uploads/xiaoyi-deliveries/owner/proj/req/0000-main.jpg', fileName: '0000-main.jpg', sortOrder: 0, }, ], }) ;(getS3ObjectStream as jest.Mock).mockResolvedValueOnce({ body: Readable.from([Buffer.from('remote-single-bytes')]), contentLength: 19, }) const response = await GET(makeRequest()) expect(response.status).toBe(200) expect(response.headers.get('Content-Length')).toBe('19') expect(Buffer.from(await response.arrayBuffer()).toString()).toBe('remote-single-bytes') }) test('旧单图和固定版本整包继续读取该次交付的字节', async () => { const oldAsset = { id: 'previous-main', assetType: 'main', fileName: 'old.jpg', barcodes: [], fileUrl: 'uploads/xiaoyi-deliveries/owner/proj/old/0000-main.jpg', } jest.mocked(prisma.material.findUnique).mockResolvedValue({ id: 'material-1', materialType: '自动上架-详情', currentRevisionId: 'new-revision', createdAt: new Date('2026-12-01T00:00:00.000Z'), assets: [], } as any) jest.mocked(prisma.revisionAsset.findFirst).mockResolvedValue(oldAsset as any) jest.mocked(prisma.deliveryRevision.findFirst).mockResolvedValue({ assets: [oldAsset] } as any) jest.mocked(getS3ObjectStream).mockImplementation(async () => ({ body: Readable.from([Buffer.from('old-version-bytes')]), contentLength: 17, })) jest.mocked(verifyDownloadToken).mockReturnValue({ materialId: 'material-1', downloadType: 'single', assetId: oldAsset.id }) const single = await GET(makeRequest()) expect(single.status).toBe(200) expect(Buffer.from(await single.arrayBuffer()).toString()).toBe('old-version-bytes') expect(prisma.revisionAsset.findFirst).toHaveBeenCalledWith({ where: { id: oldAsset.id, revision: { materialId: 'material-1' } }, }) jest.mocked(verifyDownloadToken).mockReturnValue({ materialId: 'material-1', downloadType: 'all', revisionId: 'old-revision' }) const archive = await GET(makeRequest()) expect(prisma.deliveryRevision.findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 'old-revision', materialId: 'material-1' }, })) expect(new AdmZip(Buffer.from(await archive.arrayBuffer())).readAsText('main/old.jpg')).toBe('old-version-bytes') }) test('returns 503 when both local and S3 objects are missing for Xiaoyi ZIP', async () => { ;(verifyDownloadToken as jest.Mock).mockReturnValue({ materialId: 'material-1', downloadType: 'all', }) ;(prisma.material.findUnique as jest.Mock).mockResolvedValue({ id: 'material-1', materialType: '自动上架-详情', createdAt: new Date('2026-12-01T00:00:00.000Z'), assets: [ { id: 'asset-main', assetType: 'main', fileUrl: 'uploads/xiaoyi-deliveries/owner/proj/req/missing.jpg', fileName: 'missing.jpg', sortOrder: 0, }, ], }) ;(getS3ObjectStream as jest.Mock).mockRejectedValue(new Error('NoSuchKey')) const response = await GET(makeRequest()) expect(response.status).toBe(503) }) }) })