197 lines
9.8 KiB
TypeScript
197 lines
9.8 KiB
TypeScript
/** @jest-environment node */
|
|
|
|
import { createWriteStream } from 'node:fs'
|
|
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
|
import { tmpdir } from 'node:os'
|
|
import path from 'node:path'
|
|
import archiver from 'archiver'
|
|
import jwt from 'jsonwebtoken'
|
|
import { NextRequest } from 'next/server'
|
|
import { GET } from '@/app/api/external/task-details/route'
|
|
import { GET as download } from '@/app/api/external/download/route'
|
|
import { prisma } from '@/lib/prisma'
|
|
|
|
jest.mock('@/lib/prisma', () => ({
|
|
prisma: { material: { findUnique: jest.fn(), update: jest.fn(), updateMany: jest.fn() } },
|
|
}))
|
|
jest.mock('@/lib/public-app-url', () => ({ getPublicAppOrigin: () => 'https://materials.example.test' }))
|
|
|
|
const findUnique = jest.mocked(prisma.material.findUnique) as jest.Mock
|
|
const materialId = '02000000-0000-4000-8000-000000000001'
|
|
const key = 'task-detail-test-key'
|
|
const updatedAt = new Date('2026-11-25T08:00:00Z')
|
|
const rawImage = Buffer.from('original-image-data '.repeat(4096))
|
|
const zipEntryName = '详情-原始图.webp'
|
|
let uploadDir: string
|
|
let assets: ReturnType<typeof asset>[]
|
|
const environment = { ...process.env }
|
|
|
|
function asset(id: string, assetType: string, fileName: string, extra: Record<string, unknown> = {}) {
|
|
return {
|
|
id, assetType, fileName, fileUrl: `uploads/materials/${fileName}`, sortOrder: 0, fileSize: BigInt(0),
|
|
skuCode: null, barcodes: [], createdAt: updatedAt, updatedAt, ...extra,
|
|
}
|
|
}
|
|
|
|
function material(extra: Record<string, unknown> = {}) {
|
|
return {
|
|
id: materialId, materialType: '任务-详情', accessScope: 'general', taskDetailPrivate: false,
|
|
deletedAt: null, isIncompleteShell: false, taskStatus: 'completed',
|
|
productModel: 'SPU-0001', categoryName: '店铺', taskNo: null, dingtalkApprovalNo: 'AP-1',
|
|
platformName: '天猫', taskDetailSourceType: 'render', taskDetailRequesterName: '需求人',
|
|
taskDetailDemandType: '上新', createdAt: updatedAt, updatedAt, assets,
|
|
previewUrl: 'uploads/materials/detail-001.webp', displayImages: ['uploads/materials/cover.webp'],
|
|
zipFilePath: 'uploads/materials/all.zip', zipFileName: 'all.zip', zipFileSize: BigInt(42),
|
|
...extra,
|
|
}
|
|
}
|
|
|
|
function stubMaterial(row: ReturnType<typeof material>) {
|
|
findUnique.mockImplementation(async ({ where, select }) => {
|
|
if (where.materialType !== row.materialType || where.id !== row.id || where.accessScope !== row.accessScope ||
|
|
where.taskDetailPrivate !== row.taskDetailPrivate || where.deletedAt !== row.deletedAt ||
|
|
where.isIncompleteShell !== row.isIncompleteShell || !where.taskStatus.in.includes(row.taskStatus)) return null
|
|
const assetIds = select.assets.where.id
|
|
const selected = row.assets.filter(file => select.assets.where.assetType.in.includes(file.assetType) &&
|
|
(assetIds === undefined || assetIds === file.id))
|
|
return Object.fromEntries(Object.keys(select).map(field => [
|
|
field, field === 'assets' ? selected : row[field as keyof typeof row],
|
|
]))
|
|
})
|
|
}
|
|
|
|
function query(id = materialId, requestKey = key) {
|
|
return new NextRequest(`https://materials.example.test/api/external/task-details?materialId=${id}`, {
|
|
headers: requestKey ? { 'X-API-Key': requestKey } : {},
|
|
})
|
|
}
|
|
|
|
async function writeZip(name: string, files: Array<{ name: string; buffer: Buffer }>, store: boolean) {
|
|
const archive = archiver('zip', { store })
|
|
const output = createWriteStream(path.join(uploadDir, 'materials', name))
|
|
const finished = new Promise<void>((resolve, reject) => {
|
|
output.once('close', resolve)
|
|
output.once('error', reject)
|
|
archive.once('error', reject)
|
|
})
|
|
archive.pipe(output)
|
|
for (const file of files) archive.append(file.buffer, { name: file.name })
|
|
await archive.finalize()
|
|
await finished
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
uploadDir = await mkdtemp(path.join(tmpdir(), 'external-task-details-'))
|
|
await mkdir(path.join(uploadDir, 'materials'))
|
|
await writeFile(path.join(uploadDir, 'materials', 'detail-001.webp'), 'preview-slice-one')
|
|
await writeFile(path.join(uploadDir, 'materials', 'cover.webp'), 'cover-preview')
|
|
await writeFile(path.join(uploadDir, 'materials', 'design.psd'), 'source-design')
|
|
await writeZip('detail.zip', [{ name: zipEntryName, buffer: rawImage }], false)
|
|
await writeZip('main.zip', [{ name: '主图.png', buffer: rawImage }], true)
|
|
await writeZip('legacy.zip', [{ name: '详情/原图.webp', buffer: rawImage }], false)
|
|
await writeZip('all.zip', [
|
|
{ name: '详情图.zip', buffer: await readFile(path.join(uploadDir, 'materials', 'detail.zip')) },
|
|
{ name: '主图.zip', buffer: await readFile(path.join(uploadDir, 'materials', 'main.zip')) },
|
|
], true)
|
|
})
|
|
|
|
beforeEach(() => {
|
|
jest.clearAllMocks()
|
|
process.env.EXTERNAL_TASK_DETAIL_API_KEY = key
|
|
process.env.DOWNLOAD_TOKEN_SECRET = 'test-signing-secret'
|
|
process.env.UPLOAD_DIR = uploadDir
|
|
assets = [
|
|
asset('sku-preview', 'sku-preview', 'sku.webp', { skuCode: '特殊-编号', barcodes: [{ barcode: '0123' }] }),
|
|
asset('slice-1', 'detail-preview', 'detail-001.webp'),
|
|
asset('slice-2', 'detail-preview', 'detail-002.webp'),
|
|
asset('detail-zip', 'detail', 'detail.zip'),
|
|
asset('main-zip', 'main', 'main.zip'),
|
|
asset('all-zip', 'all', 'all.zip'),
|
|
asset('design', 'psd', 'design.psd'),
|
|
]
|
|
stubMaterial(material())
|
|
})
|
|
|
|
afterAll(async () => {
|
|
process.env = environment
|
|
await rm(uploadDir, { recursive: true, force: true })
|
|
})
|
|
|
|
test('authenticates before lookup and accepts exactly the dedicated header credential', async () => {
|
|
for (const request of [query(materialId, 'generic-key'), query(`${materialId}&apiKey=${key}`, '')]) {
|
|
expect((await GET(request)).status).toBe(401)
|
|
}
|
|
expect((await GET(query('invalid-id'))).status).toBe(400)
|
|
delete process.env.EXTERNAL_TASK_DETAIL_API_KEY
|
|
expect((await GET(query())).status).toBe(401)
|
|
expect(findUnique).not.toHaveBeenCalled()
|
|
})
|
|
|
|
test('returns business fields, all preview slices, archive entries and unchanged archive bytes', async () => {
|
|
const response = await GET(query())
|
|
expect(response.status).toBe(200)
|
|
expect(response.headers.get('Cache-Control')).toBe('private, no-store')
|
|
const { data } = await response.json()
|
|
expect(data).toMatchObject({
|
|
materialId, productModel: 'SPU-0001', dingtalkApprovalNo: 'AP-1', taskStatus: 'completed',
|
|
taskDetailRequesterName: '需求人', downloadExpiresInSeconds: 1800, isFullSet: true,
|
|
})
|
|
expect(data.previews).toHaveLength(3)
|
|
expect(data.previews[0]).toMatchObject({ group: 'sku', skuCode: '特殊-编号', barcodes: ['0123'] })
|
|
expect(data.originals.map(({ group, fileName }: { group: string; fileName: string }) => [group, fileName])).toEqual([
|
|
['detail', zipEntryName], ['main', '主图.png'],
|
|
])
|
|
expect(data.archives.map((file: { group: string }) => file.group)).toEqual(['detail', 'main', 'all'])
|
|
expect(data.sourceFiles.map((file: { fileName: string }) => file.fileName)).toEqual(['design.psd'])
|
|
expect(data.issues).toContainEqual({ group: 'sku', code: 'ORIGINALS_UNAVAILABLE' })
|
|
expect(JSON.stringify(data)).not.toContain('uploads/')
|
|
expect(prisma.material.update).not.toHaveBeenCalled()
|
|
expect(prisma.material.updateMany).not.toHaveBeenCalled()
|
|
|
|
for (const image of data.originals) {
|
|
const file = await download(new NextRequest(image.downloadUrl))
|
|
expect(file.status).toBe(200)
|
|
expect(file.headers.get('Content-Length')).toBe(String(rawImage.length))
|
|
expect(Buffer.from(await file.arrayBuffer())).toEqual(rawImage)
|
|
const token = jwt.decode(new URL(image.downloadUrl).searchParams.get('token')!) as jwt.JwtPayload
|
|
expect(token.exp! - token.iat!).toBe(1800)
|
|
}
|
|
const preview = await download(new NextRequest(data.previewUrl))
|
|
expect(preview.headers.get('Content-Disposition')).toMatch(/^inline/)
|
|
expect(await preview.text()).toBe('preview-slice-one')
|
|
expect(await (await download(new NextRequest(data.displayImages[0]))).text()).toBe('cover-preview')
|
|
expect(await (await download(new NextRequest(data.sourceFiles[0].downloadUrl))).text()).toBe('source-design')
|
|
const zip = await download(new NextRequest(data.archives[2].downloadUrl, { headers: { Range: 'bytes=0-3' } }))
|
|
expect(zip.status).toBe(206)
|
|
expect(Buffer.from(await zip.arrayBuffer())).toEqual(Buffer.from([0x50, 0x4b, 0x03, 0x04]))
|
|
})
|
|
|
|
test.each([
|
|
{ taskDetailPrivate: true }, { accessScope: 'operations_g' }, { deletedAt: updatedAt },
|
|
{ materialType: '任务-页面' }, { isIncompleteShell: true }, { taskStatus: 'uploading' }, { taskStatus: 'failed' },
|
|
])('rechecks access when queried and when a previously issued link is downloaded (%j)', async (restriction) => {
|
|
const { data } = await (await GET(query())).json()
|
|
stubMaterial(material(restriction))
|
|
expect((await GET(query())).status).toBe(404)
|
|
expect((await download(new NextRequest(data.originals[0].downloadUrl))).status).toBe(404)
|
|
expect((await download(new NextRequest(data.previews[0].downloadUrl))).status).toBe(404)
|
|
})
|
|
|
|
test('a regenerated ZIP cannot serve a different entry through a previously issued link', async () => {
|
|
const { data } = await (await GET(query())).json()
|
|
assets[3] = asset('detail-zip', 'detail', 'main.zip', { updatedAt: new Date(updatedAt.getTime() + 1000) })
|
|
stubMaterial(material({ taskStatus: 'fetched' }))
|
|
expect((await download(new NextRequest(data.originals[0].downloadUrl))).status).toBe(404)
|
|
const { data: refreshed } = await (await GET(query())).json()
|
|
expect(refreshed.originals[0].fileName).toBe('主图.png')
|
|
})
|
|
|
|
test('finds originals in a legacy flat archive referenced directly by the material', async () => {
|
|
stubMaterial(material({ zipFilePath: 'uploads/materials/legacy.zip', zipFileName: 'legacy.zip', assets: [] }))
|
|
const { data } = await (await GET(query())).json()
|
|
expect(data.archives).toHaveLength(1)
|
|
expect(data.originals[0]).toMatchObject({ archiveAssetId: null, group: 'all', entryName: '详情/原图.webp' })
|
|
const response = await download(new NextRequest(data.originals[0].downloadUrl))
|
|
expect(Buffer.from(await response.arrayBuffer())).toEqual(rawImage)
|
|
})
|