/** @jest-environment node */ import { createHash } from 'node:crypto' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { GetObjectCommand, HeadObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' import { GET as latest } from '@/app/api/desktop/client-release/route' import { GET as download } from '@/app/api/desktop/client-release/download/route' import { requireDesktop } from '@/lib/desktop-client/service' import { DesktopClientError } from '@/lib/desktop-client/contract.mjs' import { s3Client } from '@/lib/s3' import { publishXiaoyiClient } from '@/scripts/publish-xiaoyi-client' jest.mock('@/lib/desktop-client/service', () => ({ requireDesktop: jest.fn() })) jest.mock('@/lib/s3', () => ({ s3Client: { send: jest.fn() } })) jest.mock('@aws-sdk/s3-request-presigner', () => ({ getSignedUrl: jest.fn() })) const send = s3Client.send as jest.Mock const authorize = requireDesktop as jest.Mock const sign = getSignedUrl as jest.Mock const prefix = 'xiaoyi-client/stable' const base = 'https://platform.test/api/desktop/client-release' const zip = Buffer.from('mock installer') const manifest = { version: '1.2.0', channel: 'stable', commit: 'internal-sha', builtAt: '2026-11-30T00:00:00Z', publishedAt: '2026-11-30T01:00:00Z', minimumVersion: '1.0.0', notes: '修复客户端问题', file: { name: '小壹-1.2.0-win-x64.zip', size: zip.length, sha256: createHash('sha256').update(zip).digest('hex') }, } const objects = new Map() beforeEach(() => { jest.resetAllMocks() objects.clear() send.mockImplementation(async (command) => { const value = objects.get(command.input.Key) if (command instanceof HeadObjectCommand && value) return { ContentLength: manifest.file.size } if (command instanceof GetObjectCommand && value) return { Body: { transformToString: async () => JSON.stringify(value) } } if (command instanceof PutObjectCommand) return {} throw Object.assign(new Error('missing object'), { name: 'NoSuchKey' }) }) }) function published() { objects.set(`${prefix}/latest.json`, { version: manifest.version }) objects.set(`${prefix}/${manifest.version}/release.json`, manifest) objects.set(`${prefix}/${manifest.version}/${manifest.file.name}`, zip) } test.each([ ['1.1.0', true, false], ['1.2.0+local', false, false], ['1.3.0', false, false], ['1.0.0-rc.1', true, true], ])('从 %s 查询版本', async (current, updateAvailable, mandatory) => { published() const response = await latest(new Request(`${base}?channel=stable¤t=${encodeURIComponent(current)}`)) expect(response.status).toBe(200) const { commit, ...metadata } = manifest expect(await response.json()).toEqual({ latest: metadata, updateAvailable, mandatory }) }) test('通道尚未发布', async () => { const response = await latest(new Request(`${base}?current=1.0.0`)) expect(await response.json()).toEqual({ latest: null, updateAvailable: false }) expect(response.headers.get('etag')).toBeTruthy() }) test.each(['../stable', 'Stable', 'a'.repeat(33), 'stable%0A'])('拒绝无效通道 %s', async (channel) => { const response = await latest(new Request(`${base}?channel=${channel}¤t=1.0.0`)) expect(response.status).toBe(400) expect(await response.json()).toMatchObject({ code: 'invalid_request' }) expect(send).not.toHaveBeenCalled() }) test('ETag 命中仍检查桌面登录', async () => { published() const url = `${base}?current=1.0.0` const first = await latest(new Request(url)) const request = new Request(url, { headers: { 'If-None-Match': first.headers.get('etag')! } }) const hit = await latest(request) expect(hit.status).toBe(304) expect(hit.headers.get('cache-control')).toBe('private, no-store') authorize.mockRejectedValueOnce(new DesktopClientError('无权访问', 401, 'unauthorized')) expect((await latest(request)).status).toBe(401) }) test('下载跳转到有效期 600 秒的签名地址', async () => { published() sign.mockResolvedValue('https://minio.test/installer?signature=fixture') const response = await download(new Request(`${base}/download?channel=stable&version=1.2.0`)) expect(response.status).toBe(302) expect(response.headers.get('location')).toBe('https://minio.test/installer?signature=fixture') expect(sign.mock.calls[0][1].input.Key).toBe(`${prefix}/1.2.0/${manifest.file.name}`) expect(sign.mock.calls[0][2]).toEqual({ expiresIn: 600 }) }) test('未发布版本返回桌面接口的 404 错误体', async () => { const response = await download(new Request(`${base}/download?channel=stable&version=1.3.0`)) expect(response.status).toBe(404) expect(await response.json()).toEqual({ error: '客户端版本不存在', code: 'not_found' }) expect(sign).not.toHaveBeenCalled() }) describe('发布脚本', () => { let directory: string let args: string[] let releasePath: string beforeEach(async () => { directory = await mkdtemp(join(tmpdir(), 'xiaoyi-release-')) const zipPath = join(directory, manifest.file.name) releasePath = join(directory, 'release.json') await writeFile(zipPath, zip) await writeFile(releasePath, JSON.stringify(manifest)) args = ['--zip', zipPath, '--release', releasePath, '--channel', 'stable'] }) afterEach(async () => { await rm(directory, { recursive: true, force: true }) }) test('哈希不符时在访问存储前拒绝', async () => { await writeFile(releasePath, JSON.stringify({ ...manifest, file: { ...manifest.file, sha256: '0'.repeat(64) } })) await expect(publishXiaoyiClient([...args, '--apply'])).rejects.toThrow('SHA-256') expect(send).not.toHaveBeenCalled() }) test('默认预演,验证本地文件后结束', async () => { await expect(publishXiaoyiClient(args)).resolves.toMatchObject({ applied: false }) expect(send).not.toHaveBeenCalled() }) test('先上传安装包和清单,再切换最新版本', async () => { await publishXiaoyiClient([...args, '--apply']) const writes = send.mock.calls.map(([command]) => command).filter(command => command instanceof PutObjectCommand) expect(writes.map(command => command.input.Key)).toEqual([ `${prefix}/1.2.0/${manifest.file.name}`, `${prefix}/1.2.0/release.json`, `${prefix}/latest.json`, ]) expect(JSON.parse(writes[2].input.Body as string)).toEqual({ version: '1.2.0' }) }) test('清单写入失败时不切换指针', async () => { send.mockRejectedValueOnce(Object.assign(new Error(), { name: 'NoSuchKey' })) .mockResolvedValueOnce({}).mockRejectedValueOnce(new Error('write failed')) await expect(publishXiaoyiClient([...args, '--apply'])).rejects.toThrow('write failed') expect(send).toHaveBeenCalledTimes(3) }) test('回滚核对旧安装包后只写最新版本指针', async () => { published() await publishXiaoyiClient(['--set-latest', '1.2.0', '--apply']) expect(send.mock.calls.map(([command]) => command.input.Key)).toEqual([ `${prefix}/1.2.0/release.json`, `${prefix}/1.2.0/${manifest.file.name}`, `${prefix}/latest.json`, ]) }) })