Skip to content

A full-featured download manager.

6.1 KB
Raw Blame
import {
  chmod,
  mkdir,
  mkdtemp,
  readFile,
  rm,
  writeFile,
} from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
  assertPacmanMetadata,
  expectedPacmanName,
  verifyPacmanArtifact,
} from '../../scripts/verify-pacman-artifact.mjs'

const directories: string[] = []
const config = JSON.parse(await readFile('electron-builder.json', 'utf8'))
const version = '2.0.0-beta.34'
const depends: string[] = config.pacman.depends

afterEach(async () => {
  await Promise.all(
    directories
      .splice(0)
      .map((dir) => rm(dir, { recursive: true, force: true }))
  )
})

function metadata(arch = 'x86_64', pkgver = '2.0.0_beta.34-1') {
  return [
    '# Generated by fpm',
    'pkgname = motrix',
    `pkgver = ${pkgver}`,
    `arch = ${arch}`,
    'url = https://motrix.app',
    'license = MIT',
    ...depends.map((dependency) => `depend = ${dependency}`),
    'conflict = motrix-bin',
    'conflict = motrix-git',
    'conflict = motrix-beta-bin',
  ].join('\n')
}

describe('Arch package metadata', () => {
  it.each([
    ['x64', 'x86_64'],
    ['arm64', 'aarch64'],
  ])(
    'maps %s to pacman architecture %s and normalizes prereleases',
    (arch, nativeArch) => {
      expect(expectedPacmanName(version, arch)).toBe(
        `Motrix-${version}-${arch === 'arm64' ? 'aarch64' : 'x64'}.pacman`
      )
      expect(() =>
        assertPacmanMetadata(metadata(nativeArch), { version, arch, depends })
      ).not.toThrow()
    }
  )

  it('accepts stable versions with the fixed package release', () => {
    expect(() =>
      assertPacmanMetadata(metadata('x86_64', '2.0.0-1'), {
        version: '2.0.0',
        arch: 'x64',
        depends,
      })
    ).not.toThrow()
  })

  it.each([
    ['arch = x86_64', 'arch = aarch64', 'arch must be x86_64'],
    ['pkgver = 2.0.0_beta.34-1', 'pkgver = 2.0.0-beta.34-1', 'pkgver must be'],
    ['pkgname = motrix', 'pkgname = motrix-turbo', 'pkgname must be motrix'],
    [
      'depend = libsecret',
      'optdepend = libsecret',
      'missing dependency: libsecret',
    ],
    ['conflict = motrix-bin', '# omitted', 'missing conflict: motrix-bin'],
    [
      'license = MIT',
      'pkgdesc = Summary\n Long description\nlicense = MIT',
      'Invalid .PKGINFO line',
    ],
    ['arch = x86_64', 'arch = x86_64\narch = aarch64', 'arch must be x86_64'],
  ])('rejects invalid metadata: %s', (before, after, message) => {
    expect(() =>
      assertPacmanMetadata(metadata().replace(before, after), {
        version,
        arch: 'x64',
        depends,
      })
    ).toThrow(message)
  })

  it('rejects unsupported architectures and malformed versions', () => {
    expect(() => expectedPacmanName(version, 'ia32')).toThrow(
      'Unsupported pacman architecture'
    )
    expect(() => expectedPacmanName('../2.0.0', 'x64')).toThrow('strict SemVer')
  })
})

async function fixture() {
  const directory = await mkdtemp(path.join(tmpdir(), 'motrix-pacman-test-'))
  directories.push(directory)
  await writeFile(
    path.join(directory, expectedPacmanName(version, 'x64')),
    Buffer.from('28b52ffd', 'hex')
  )
  const extractArchive = async (_file: string, destination: string) => {
    const files = {
      '.PKGINFO': metadata(),
      '.MTREE': 'mtree',
      'opt/Motrix/resources/package-type': 'pacman',
      'opt/Motrix/motrix': 'executable payload',
      'usr/share/applications/motrix.desktop': [
        '[Desktop Entry]',
        'Exec="/opt/Motrix/motrix" %U',
        'MimeType=application/x-bittorrent;x-scheme-handler/magnet;x-scheme-handler/motrix;',
      ].join('\n'),
    }
    for (const [name, content] of Object.entries(files)) {
      const file = path.join(destination, name)
      await mkdir(path.dirname(file), { recursive: true })
      await writeFile(file, content)
    }
    await chmod(path.join(destination, 'opt/Motrix/motrix'), 0o755)
  }
  return {
    directory,
    version,
    arch: 'x64',
    extractArchive,
    verifyPayload: vi.fn(async () => ({
      passed: true,
      errors: [] as string[],
    })),
  }
}

describe('pacman final archive verification', () => {
  it('verifies the extracted Electron payload with the target architecture', async () => {
    const input = await fixture()
    await expect(verifyPacmanArtifact(input)).resolves.toEqual({
      artifact: expectedPacmanName(version, 'x64'),
      version,
      arch: 'x64',
    })
    expect(input.verifyPayload).toHaveBeenCalledWith(
      expect.objectContaining({
        platform: 'linux',
        arch: 'x64',
        appDir: expect.stringContaining('/opt/Motrix'),
      })
    )
  })

  it('rejects archives with the wrong compression or architecture filename', async () => {
    const input = await fixture()
    await writeFile(
      path.join(input.directory, expectedPacmanName(version, 'x64')),
      'not zstd'
    )
    await expect(verifyPacmanArtifact(input)).rejects.toThrow(
      'Zstandard compression'
    )
    await expect(
      verifyPacmanArtifact({ ...input, arch: 'arm64' })
    ).rejects.toThrow('Expected exactly one')
    expect(input.verifyPayload).not.toHaveBeenCalled()
  })

  it.each([
    ['opt/Motrix/resources/package-type', 'rpm', 'pacman updater'],
    [
      'usr/share/applications/motrix.desktop',
      '[Desktop Entry]\nExec=/opt/Motrix/motrix %U',
      'missing application/x-bittorrent',
    ],
  ])('rejects broken integration in %s', async (name, content, error) => {
    const input = await fixture()
    const extract = input.extractArchive
    input.extractArchive = async (file, destination) => {
      await extract(file, destination)
      await writeFile(path.join(destination, name), content)
    }
    await expect(verifyPacmanArtifact(input)).rejects.toThrow(error)
    expect(input.verifyPayload).not.toHaveBeenCalled()
  })

  it('propagates native payload failures instead of accepting correct metadata alone', async () => {
    const input = await fixture()
    input.verifyPayload.mockResolvedValue({
      passed: false,
      errors: ['wrong native architecture'],
    })
    await expect(verifyPacmanArtifact(input)).rejects.toThrow(
      'wrong native architecture'
    )
  })
})