A full-featured download manager.
fix(linux): modernize AppImage distribution (#1933)
Dr_rOot1877b28d61f8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 75e39fd2..c97b3d60 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -137,6 +137,7 @@ jobs:src/main/bridge/native-messaging-extensions.test.tssrc/main/bridge/snap-environment.test.tstests/scripts/assemble-release-artifacts.test.ts+ tests/scripts/appimage-artifact.test.tstests/scripts/before-pack-verify.test.tstests/scripts/compose-server.test.tstests/scripts/container-platform-metadata.test.ts@@ -145,6 +146,7 @@ jobs:tests/scripts/docker-server-docs.test.tstests/scripts/electron-package-contract.test.tstests/scripts/flatpak-native-host.test.ts+ tests/scripts/finalize-appimage-artifact.test.tstests/scripts/native-binary-target.test.tstests/scripts/obsidian-docs.test.tstests/scripts/release-metadata.test.ts@@ -161,6 +163,7 @@ jobs:tests/scripts/smoke-server-package.test.tstests/scripts/stage-server-app.test.tstests/scripts/verify-electron-package.test.ts+ tests/scripts/verify-appimage-artifact.test.tstests/scripts/verify-container-publication.test.tstests/scripts/verify-server-package.test.tstests/scripts/verify-update-artifacts.test.tsdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 5eed6e0a..0271179e 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -11,7 +11,8 @@# - a native GitHub-hosted runner;# - a packages/native-host/build.mjs Rust target.#-# The Linux AppImage is published for x64 and arm64. It self-integrates its+# The Linux AppImage is published for x64 and arm64 with the static AppImage+# runtime and per-architecture native zsync metadata. It self-integrates its# desktop entry and URL-scheme handlers at runtime under the user's XDG data# tree (src/main/platform/appimage-integration.ts). Snap has its own# strict-confinement build and Store promotion workflows. 32-bit targets remain@@ -191,8 +192,8 @@ jobs:sudo apt-get update# squashfs-tools provides `unsquashfs`, used by# verify-appimage-artifact.mjs to read the AppImage's embedded- # desktop entry.- sudo apt-get install --yes rpm squashfs-tools+ # desktop entry. zsync provides the canonical `zsyncmake` generator.+ sudo apt-get install --yes rpm squashfs-tools zsync- name: Setup Rustuses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable@@ -379,6 +380,47 @@ jobs:--version "${{ needs.preflight.outputs.version }}"--arch ${{ matrix.arch }}+ - name: Smoke test AppImage without system FUSE2+ if: matrix.platform == 'linux'+ shell: bash+ env:+ RELEASE_CHANNEL: ${{ needs.preflight.outputs.channel }}+ RELEASE_VERSION: ${{ needs.preflight.outputs.version }}+ TARGET_ARCH: ${{ matrix.arch }}+ run: |+ set -euo pipefail+ case "$TARGET_ARCH" in+ x64) artifact_arch='x86_64' ;;+ arm64) artifact_arch='arm64' ;;+ *) echo "Unsupported AppImage arch: $TARGET_ARCH" >&2; exit 1 ;;+ esac+ case "$RELEASE_CHANNEL" in+ stable) native_release='latest' ;;+ beta) native_release='latest-pre' ;;+ *) echo "Unsupported release channel: $RELEASE_CHANNEL" >&2; exit 1 ;;+ esac+ appimage="Motrix-${RELEASE_VERSION}-${artifact_arch}.AppImage"+ update_info="gh-releases-zsync|agalwood|Motrix|${native_release}|Motrix-*-${artifact_arch}.AppImage.zsync"+ docker run --rm --network none \+ --mount "type=bind,src=$PWD/release,dst=/artifacts,readonly" \+ --workdir /tmp \+ --env "APPIMAGE_FILE=/artifacts/${appimage}" \+ --env "EXPECTED_UPDATE=${update_info}" \+ ubuntu:24.04 \+ bash -eu -o pipefail -c '+ [[ ! -e /dev/fuse ]]+ if find /lib /usr/lib -name "libfuse.so.2*" -print -quit |+ grep -q .; then+ echo "Clean container unexpectedly contains libfuse.so.2" >&2+ exit 1+ fi+ actual="$($APPIMAGE_FILE --appimage-updateinformation)"+ [[ "$actual" == "$EXPECTED_UPDATE" ]]+ "$APPIMAGE_FILE" --appimage-extract \+ app.motrix.native.desktop >/tmp/appimage-extract.log+ test -f squashfs-root/app.motrix.native.desktop+ '+- name: Package Flatpak native host companionif: matrix.platform == 'linux'env:@@ -448,6 +490,7 @@ jobs:name: release-input-${{ matrix.target }}path: |release/*.AppImage+ release/*.AppImage.zsyncrelease/*.blockmaprelease/beta*.ymlrelease/*.deb@@ -2434,3 +2477,51 @@ jobs:exit 1fidone++ - name: Verify native AppImage update metadata distribution+ shell: bash+ run: |+ set -euo pipefail+ shopt -s nullglob+ endpoint="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com"+ zsyncs=(release/*.AppImage.zsync)+ if (( ${#zsyncs[@]} != 2 )); then+ echo "Expected two architecture-specific zsync assets" >&2+ exit 1+ fi+ for zsync in "${zsyncs[@]}"; do+ name="$(basename "$zsync")"+ expected="$(sha256sum "$zsync" | cut -d ' ' -f 1)"+ aws s3api head-object \+ --bucket "$R2_BUCKET" \+ --key "$name" \+ --endpoint-url "$endpoint" \+ > /dev/null+ for provider in generic github; do+ downloaded="${RUNNER_TEMP}/${provider}-${name}"+ matched='false'+ for attempt in {1..12}; do+ case "$provider" in+ generic)+ url="https://dl.motrix.app/releases/${name}?release=${GITHUB_SHA}&attempt=${attempt}"+ ;;+ github)+ url="https://github.com/agalwood/Motrix/releases/download/${GITHUB_REF_NAME}/${name}?attempt=${attempt}"+ ;;+ esac+ if curl --fail --location --silent --show-error \+ "$url" --output "$downloaded"; then+ actual="$(sha256sum "$downloaded" | cut -d ' ' -f 1)"+ if [[ "$actual" == "$expected" ]]; then+ matched='true'+ break+ fi+ fi+ sleep 5+ done+ if [[ "$matched" != 'true' ]]; then+ echo "Published zsync did not converge via ${provider}: ${name}" >&2+ exit 1+ fi+ done+ donediff --git a/electron-builder.json b/electron-builder.jsonindex 9a0f4e6d..36abec9a 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -3,6 +3,9 @@"appId": "app.motrix.native","productName": "Motrix","copyright": "Copyright © 2026 Dr_rOot",+ "toolsets": {+ "appimage": "1.0.3"+ },"asar": true,"asarUnpack": ["**/node_modules/{better-sqlite3,bindings,file-uri-to-path}/**",@@ -227,6 +230,7 @@},"beforePack": "./scripts/before-pack-verify.mjs","beforeBuild": "./scripts/before-build-use-staged-dependencies.mjs",+ "artifactBuildCompleted": "./scripts/finalize-appimage-artifact.mjs","detectUpdateChannel": true,"generateUpdatesFilesForAllChannels": true,"publish": {diff --git a/package.json b/package.jsonindex fbd5ee01..633b0f14 100644--- a/package.json+++ b/package.json@@ -94,7 +94,7 @@"@types/yauzl": "^3.4.0","@vitest/coverage-v8": "^4.1.10","electron": "43.4.0",- "electron-builder": "^26.15.7",+ "electron-builder": "26.15.7","esbuild": "^0.28.2","js-yaml": "^5.3.0","jsdom": "^30.0.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1430b076..cc44d66b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -211,7 +211,7 @@ importers:specifier: 43.4.0version: 43.4.0([email protected])electron-builder:- specifier: ^26.15.7+ specifier: 26.15.7version: 26.15.7([email protected])([email protected])esbuild:specifier: ^0.28.2diff --git a/scripts/appimage-artifact.mjs b/scripts/appimage-artifact.mjsnew file mode 100644index 00000000..080fe6e8--- /dev/null+++ b/scripts/appimage-artifact.mjs@@ -0,0 +1,474 @@+import { createHash } from 'node:crypto'+import { createReadStream } from 'node:fs'+import { open, readFile, stat, truncate } from 'node:fs/promises'+import path from 'node:path'+import { inflateRawSync } from 'node:zlib'++import { parseStrictSemVer } from './release-metadata.mjs'++export const APPIMAGE_TOOLSET_VERSION = '1.0.3'+export const ELECTRON_BUILDER_VERSION = '26.15.7'++const APPIMAGE_ARCH = Object.freeze({+ x64: { artifact: 'x86_64', machine: 0x3e },+ arm64: { artifact: 'arm64', machine: 0xb7 },+})++const ELF64_HEADER_BYTES = 64+const ELF64_PROGRAM_HEADER_BYTES = 56+const ELF64_SECTION_HEADER_BYTES = 64+const MAX_RUNTIME_BYTES = 8 * 1024 * 1024+const MAX_BLOCKMAP_BYTES = 32 * 1024 * 1024+const MAX_ZSYNC_BYTES = 32 * 1024 * 1024++export function expectedAppImageName(version, arch) {+ const architecture = APPIMAGE_ARCH[arch]+ if (!architecture) throw new Error(`Unsupported AppImage arch: ${arch}`)+ return `Motrix-${version}-${architecture.artifact}.AppImage`+}++export function expectedZsyncName(version, arch) {+ return `${expectedAppImageName(version, arch)}.zsync`+}++export function nativeUpdateInformation(version, arch) {+ const metadata = parseStrictSemVer(version, 'AppImage version')+ if (metadata.channel !== 'stable' && metadata.channel !== 'beta') {+ throw new Error(+ `Unsupported AppImage update channel ${metadata.channel}: ${version}`+ )+ }+ const architecture = APPIMAGE_ARCH[arch]+ if (!architecture) throw new Error(`Unsupported AppImage arch: ${arch}`)+ const release = metadata.channel === 'stable' ? 'latest' : 'latest-pre'+ return (+ `gh-releases-zsync|agalwood|Motrix|${release}|` ++ `Motrix-*-${architecture.artifact}.AppImage.zsync`+ )+}++export function appImageArchFromBuilder(arch) {+ if (arch === 1 || arch === 'x64') return 'x64'+ if (arch === 3 || arch === 'arm64') return 'arm64'+ throw new Error(`Unsupported electron-builder AppImage arch: ${arch}`)+}++export function parseAppImageRuntime(runtime, arch) {+ const architecture = APPIMAGE_ARCH[arch]+ if (!architecture) throw new Error(`Unsupported AppImage arch: ${arch}`)+ assertRange(runtime, 0, ELF64_HEADER_BYTES, 'ELF header')+ if (!runtime.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))) {+ throw new Error('Artifact is not an ELF (not an AppImage)')+ }+ if (runtime[4] !== 2 || runtime[5] !== 1) {+ throw new Error('AppImage runtime must be a 64-bit little-endian ELF')+ }+ if (runtime[8] !== 0x41 || runtime[9] !== 0x49 || runtime[10] !== 0x02) {+ throw new Error('Missing AppImage type-2 magic (AI\\x02) at offset 8')+ }+ const machine = runtime.readUInt16LE(18)+ if (machine !== architecture.machine) {+ throw new Error(+ `AppImage ELF machine 0x${machine.toString(16)} does not match ${arch} ` ++ `(expected 0x${architecture.machine.toString(16)})`+ )+ }++ const programHeaderOffset = safeUInt64(runtime, 0x20, 'e_phoff')+ const sectionHeaderOffset = safeUInt64(runtime, 0x28, 'e_shoff')+ const programHeaderSize = runtime.readUInt16LE(0x36)+ const programHeaderCount = runtime.readUInt16LE(0x38)+ const sectionHeaderSize = runtime.readUInt16LE(0x3a)+ const sectionHeaderCount = runtime.readUInt16LE(0x3c)+ const sectionNameIndex = runtime.readUInt16LE(0x3e)+ if (+ sectionHeaderOffset === 0 ||+ sectionHeaderSize !== ELF64_SECTION_HEADER_BYTES ||+ sectionHeaderCount < 2 ||+ sectionNameIndex === 0 ||+ sectionNameIndex >= sectionHeaderCount+ ) {+ throw new Error('AppImage runtime has an unsupported ELF section table')+ }+ if (+ programHeaderCount > 0 &&+ programHeaderSize !== ELF64_PROGRAM_HEADER_BYTES+ ) {+ throw new Error('AppImage runtime has an unsupported ELF program table')+ }++ const runtimeBytes =+ sectionHeaderOffset + sectionHeaderSize * sectionHeaderCount+ if (runtimeBytes > MAX_RUNTIME_BYTES) {+ throw new Error(`AppImage runtime is unexpectedly large: ${runtimeBytes}`)+ }+ assertRange(runtime, 0, runtimeBytes, 'complete AppImage runtime')+ assertRange(+ runtime,+ programHeaderOffset,+ programHeaderSize * programHeaderCount,+ 'ELF program headers'+ )++ for (let index = 0; index < programHeaderCount; index += 1) {+ const offset = programHeaderOffset + index * programHeaderSize+ if (runtime.readUInt32LE(offset) === 3) {+ throw new Error(+ 'AppImage runtime contains PT_INTERP and is not statically linked'+ )+ }+ }++ const rawSections = []+ for (let index = 0; index < sectionHeaderCount; index += 1) {+ const offset = sectionHeaderOffset + index * sectionHeaderSize+ rawSections.push({+ nameOffset: runtime.readUInt32LE(offset),+ type: runtime.readUInt32LE(offset + 4),+ offset: safeUInt64(runtime, offset + 24, `section ${index} offset`),+ size: safeUInt64(runtime, offset + 32, `section ${index} size`),+ })+ }+ const sectionNameTable = rawSections[sectionNameIndex]+ assertRange(+ runtime,+ sectionNameTable.offset,+ sectionNameTable.size,+ 'ELF section-name table'+ )+ const names = runtime.subarray(+ sectionNameTable.offset,+ sectionNameTable.offset + sectionNameTable.size+ )+ const sections = new Map()+ for (const [index, section] of rawSections.entries()) {+ const name = readCString(names, section.nameOffset, `section ${index} name`)+ if (!name) continue+ if (sections.has(name)) throw new Error(`Duplicate ELF section ${name}`)+ if (section.type !== 8) {+ assertRange(runtime, section.offset, section.size, `ELF section ${name}`)+ }+ sections.set(name, section)+ }++ const staticMarker = requiredSection(sections, '.static')+ if (+ runtime+ .subarray(staticMarker.offset, staticMarker.offset + staticMarker.size)+ .toString('utf8') !== 'static'+ ) {+ throw new Error('AppImage runtime is missing the static-runtime marker')+ }++ const dynamic = requiredSection(sections, '.dynamic')+ if (dynamic.size % 16 !== 0) {+ throw new Error('AppImage runtime has a malformed dynamic section')+ }+ for (+ let offset = dynamic.offset;+ offset < dynamic.offset + dynamic.size;+ offset += 16+ ) {+ const tag = runtime.readBigInt64LE(offset)+ if (tag === 0n) break+ if (tag === 1n) {+ throw new Error(+ 'AppImage runtime contains a DT_NEEDED dependency and is not static'+ )+ }+ }++ const legacyFuse = runtime.indexOf(Buffer.from('libfuse.so.2'))+ if (legacyFuse >= 0) {+ throw new Error(+ 'AppImage runtime still contains legacy libfuse.so.2 loading logic'+ )+ }+ for (const capability of [+ '--appimage-mount',+ '--appimage-extract',+ '--appimage-extract-and-run',+ 'TARGET_APPIMAGE',+ ]) {+ if (runtime.indexOf(Buffer.from(capability)) < 0) {+ throw new Error(+ `AppImage static runtime is missing required capability ${capability}`+ )+ }+ }++ return { runtimeBytes, sections }+}++export function readSectionValue(runtime, section, label) {+ const bytes = runtime.subarray(section.offset, section.offset + section.size)+ const nul = bytes.indexOf(0)+ const end = nul < 0 ? bytes.length : nul+ if (nul >= 0 && bytes.subarray(nul).some((value) => value !== 0)) {+ throw new Error(`${label} has non-zero bytes after its terminator`)+ }+ return bytes.subarray(0, end).toString('utf8')+}++export async function inspectAppImageRuntime(file, arch) {+ const handle = await open(file, 'r')+ try {+ const head = Buffer.alloc(ELF64_HEADER_BYTES)+ const { bytesRead } = await handle.read(head, 0, head.length, 0)+ if (bytesRead !== head.length) throw new Error('AppImage header too short')+ const sectionHeaderOffset = safeUInt64(head, 0x28, 'e_shoff')+ const sectionHeaderSize = head.readUInt16LE(0x3a)+ const sectionHeaderCount = head.readUInt16LE(0x3c)+ const runtimeBytes =+ sectionHeaderOffset + sectionHeaderSize * sectionHeaderCount+ if (+ !Number.isSafeInteger(runtimeBytes) ||+ runtimeBytes < ELF64_HEADER_BYTES ||+ runtimeBytes > MAX_RUNTIME_BYTES+ ) {+ throw new Error(`Invalid AppImage runtime size: ${runtimeBytes}`)+ }+ const runtime = Buffer.alloc(runtimeBytes)+ const result = await handle.read(runtime, 0, runtime.length, 0)+ if (result.bytesRead !== runtime.length) {+ throw new Error('AppImage runtime is truncated')+ }+ return { runtime, ...parseAppImageRuntime(runtime, arch) }+ } finally {+ await handle.close()+ }+}++export function assertAppImageRuntimeMetadata(+ inspection,+ { updateInformation, requireUnsigned = true }+) {+ const updateSection = requiredSection(inspection.sections, '.upd_info')+ const actual = readSectionValue(+ inspection.runtime,+ updateSection,+ 'AppImage .upd_info'+ )+ if (actual !== updateInformation) {+ throw new Error(+ `AppImage update information does not match: expected ${updateInformation || '<empty>'}, got ${actual || '<empty>'}`+ )+ }+ if (requireUnsigned) {+ const signature = requiredSection(inspection.sections, '.sha256_sig')+ const bytes = inspection.runtime.subarray(+ signature.offset,+ signature.offset + signature.size+ )+ if (bytes.some((value) => value !== 0)) {+ throw new Error(+ 'AppImage native signature is populated; update information must be embedded before native signing'+ )+ }+ }+}++export async function writeAppImageUpdateInformation(file, arch, value) {+ if (value.includes('\0')) {+ throw new Error('AppImage update information must not contain NUL bytes')+ }+ const inspection = await inspectAppImageRuntime(file, arch)+ const section = requiredSection(inspection.sections, '.upd_info')+ const encoded = Buffer.from(value, 'utf8')+ if (encoded.length >= section.size) {+ throw new Error(+ `AppImage update information exceeds .upd_info capacity ${section.size}`+ )+ }+ const padded = Buffer.alloc(section.size)+ encoded.copy(padded)+ const handle = await open(file, 'r+')+ try {+ const { bytesWritten } = await handle.write(+ padded,+ 0,+ padded.length,+ section.offset+ )+ if (bytesWritten !== padded.length) {+ throw new Error(+ 'Failed to write the complete AppImage update information'+ )+ }+ } finally {+ await handle.close()+ }+}++export async function inspectEmbeddedBlockmap(file) {+ const info = await stat(file)+ if (!info.isFile() || info.size < 5) {+ throw new Error('AppImage is too short to contain an embedded blockmap')+ }+ const footer = await readRange(file, info.size - 4, 4)+ const blockMapSize = footer.readUInt32BE(0)+ if (blockMapSize <= 0 || blockMapSize > MAX_BLOCKMAP_BYTES) {+ throw new Error(`Invalid embedded AppImage blockmap size: ${blockMapSize}`)+ }+ const baseSize = info.size - blockMapSize - 4+ if (baseSize <= 0)+ throw new Error('Embedded AppImage blockmap overlaps artifact')+ const compressed = await readRange(file, baseSize, blockMapSize)+ let document+ try {+ document = JSON.parse(inflateRawSync(compressed).toString('utf8'))+ } catch (error) {+ throw new Error(`Invalid embedded AppImage blockmap: ${error.message}`, {+ cause: error,+ })+ }+ const blockFile = document?.files?.[0]+ if (+ document?.version !== '2' ||+ !Array.isArray(document.files) ||+ document.files.length !== 1 ||+ blockFile?.name !== 'file' ||+ blockFile.offset !== 0 ||+ !Array.isArray(blockFile.sizes) ||+ !Array.isArray(blockFile.checksums) ||+ blockFile.sizes.length === 0 ||+ blockFile.sizes.length !== blockFile.checksums.length ||+ !blockFile.sizes.every((size) => Number.isSafeInteger(size) && size > 0) ||+ blockFile.sizes.reduce((sum, size) => sum + size, 0) !== baseSize+ ) {+ throw new Error('Embedded AppImage blockmap has invalid contents')+ }+ return { baseSize, blockMapSize, size: info.size }+}++export async function stripEmbeddedBlockmap(file, expectedBlockMapSize) {+ const blockmap = await inspectEmbeddedBlockmap(file)+ if (+ expectedBlockMapSize !== undefined &&+ blockmap.blockMapSize !== expectedBlockMapSize+ ) {+ throw new Error(+ `Embedded AppImage blockmap size ${blockmap.blockMapSize} does not match electron-builder metadata ${expectedBlockMapSize}`+ )+ }+ await truncate(file, blockmap.baseSize)+ return blockmap+}++export async function verifyZsyncFile({ appImagePath, zsyncPath }) {+ const [appImageInfo, zsyncInfo] = await Promise.all([+ stat(appImagePath),+ stat(zsyncPath).catch(() => null),+ ])+ if (!zsyncInfo?.isFile()) {+ throw new Error(`${path.basename(zsyncPath)} is missing`)+ }+ if (zsyncInfo.size <= 0 || zsyncInfo.size > MAX_ZSYNC_BYTES) {+ throw new Error(`${path.basename(zsyncPath)} has an invalid size`)+ }+ const content = await readFile(zsyncPath)+ const separator = content.indexOf(Buffer.from('\n\n'))+ if (separator < 0 || separator + 2 >= content.length) {+ throw new Error(`${path.basename(zsyncPath)} has no checksum payload`)+ }+ const headers = parseHeaders(content.subarray(0, separator).toString('utf8'))+ const expectedName = path.basename(appImagePath)+ if (headers.get('Filename') !== expectedName) {+ throw new Error(+ `${path.basename(zsyncPath)} Filename must be ${expectedName}`+ )+ }+ if (headers.get('URL') !== expectedName) {+ throw new Error(`${path.basename(zsyncPath)} URL must be ${expectedName}`)+ }+ if (headers.get('Length') !== String(appImageInfo.size)) {+ throw new Error(+ `${path.basename(zsyncPath)} Length does not match AppImage`+ )+ }+ const expectedSha1 = await hashFile(appImagePath, 'sha1', 'hex')+ const legacySha1 = headers.get('SHA-1')?.toLowerCase()+ const fileHash = /^sha-?1:([0-9a-f]{40})$/iu.exec(+ headers.get('File-Hash') ?? ''+ )?.[1]+ if (legacySha1 !== expectedSha1 && fileHash?.toLowerCase() !== expectedSha1) {+ throw new Error(`${path.basename(zsyncPath)} SHA-1 does not match AppImage`)+ }+ for (const required of ['zsync', 'Blocksize', 'Hash-Lengths']) {+ if (!headers.get(required)) {+ throw new Error(`${path.basename(zsyncPath)} is missing ${required}`)+ }+ }+ return { zsync: path.basename(zsyncPath) }+}++function parseHeaders(value) {+ const headers = new Map()+ for (const line of value.split(/\r?\n/)) {+ const separator = line.indexOf(':')+ if (separator <= 0) throw new Error(`Malformed zsync header: ${line}`)+ const name = line.slice(0, separator)+ const headerValue = line.slice(separator + 1).trim()+ if (headers.has(name)) throw new Error(`Duplicate zsync header: ${name}`)+ headers.set(name, headerValue)+ }+ return headers+}++function requiredSection(sections, name) {+ const section = sections.get(name)+ if (!section) throw new Error(`AppImage runtime is missing ${name}`)+ return section+}++function safeUInt64(buffer, offset, label) {+ assertRange(buffer, offset, 8, label)+ const value = buffer.readBigUInt64LE(offset)+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) {+ throw new Error(`${label} exceeds JavaScript's safe integer range`)+ }+ return Number(value)+}++function assertRange(buffer, offset, size, label) {+ if (+ !Number.isSafeInteger(offset) ||+ !Number.isSafeInteger(size) ||+ offset < 0 ||+ size < 0 ||+ offset + size > buffer.length+ ) {+ throw new Error(`${label} is outside the AppImage runtime`)+ }+}++function readCString(buffer, offset, label) {+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= buffer.length) {+ throw new Error(`${label} offset is invalid`)+ }+ const end = buffer.indexOf(0, offset)+ if (end < 0) throw new Error(`${label} is not NUL-terminated`)+ return buffer.subarray(offset, end).toString('utf8')+}++async function readRange(file, position, size) {+ const handle = await open(file, 'r')+ try {+ const output = Buffer.alloc(size)+ const { bytesRead } = await handle.read(output, 0, size, position)+ if (bytesRead !== size) throw new Error(`Short read from ${file}`)+ return output+ } finally {+ await handle.close()+ }+}++function hashFile(file, algorithm, encoding) {+ return new Promise((resolve, reject) => {+ const hash = createHash(algorithm)+ const input = createReadStream(file)+ input.on('error', reject)+ input.on('data', (chunk) => hash.update(chunk))+ input.on('end', () => resolve(hash.digest(encoding)))+ })+}diff --git a/scripts/assemble-release-artifacts.mjs b/scripts/assemble-release-artifacts.mjsindex e76c6110..395a5a0c 100644--- a/scripts/assemble-release-artifacts.mjs+++ b/scripts/assemble-release-artifacts.mjs@@ -54,6 +54,7 @@ export const RELEASE_TARGETS = [`Motrix_${version}_amd64.deb`,`Motrix-${version}.x86_64.rpm`,`Motrix-${version}-x86_64.AppImage`,+ `Motrix-${version}-x86_64.AppImage.zsync`,flatpakCompanionArchiveName(version, 'x64'),],manifestAssetNames: (version) => [@@ -71,6 +72,7 @@ export const RELEASE_TARGETS = [`Motrix_${version}_arm64.deb`,`Motrix-${version}.aarch64.rpm`,`Motrix-${version}-arm64.AppImage`,+ `Motrix-${version}-arm64.AppImage.zsync`,flatpakCompanionArchiveName(version, 'arm64'),],manifestAssetNames: (version) => [@@ -103,6 +105,7 @@ const RELEASE_ASSET_EXTENSIONS = ['.snap','.tar.gz','.zip',+ '.zsync',]export async function assembleReleaseArtifacts({@@ -280,7 +283,7 @@ async function collectTargetFiles(directory, target, version, manifestNames) {const requiredAssets = new Set(target.assetNames(version))const optionalBlockmaps = new Set([...requiredAssets]- .filter((name) => !name.endsWith('.tar.gz'))+ .filter((name) => /\.(?:dmg|exe|zip)$/u.test(name)).map((name) => `${name}.blockmap`))for (const source of candidates) {diff --git a/scripts/finalize-appimage-artifact.mjs b/scripts/finalize-appimage-artifact.mjsnew file mode 100644index 00000000..161d9a92--- /dev/null+++ b/scripts/finalize-appimage-artifact.mjs@@ -0,0 +1,142 @@+import { execFile } from 'node:child_process'+import { rename, rm } from 'node:fs/promises'+import { createRequire } from 'node:module'+import path from 'node:path'+import { promisify } from 'node:util'++import {+ APPIMAGE_TOOLSET_VERSION,+ appImageArchFromBuilder,+ assertAppImageRuntimeMetadata,+ ELECTRON_BUILDER_VERSION,+ expectedAppImageName,+ expectedZsyncName,+ inspectAppImageRuntime,+ inspectEmbeddedBlockmap,+ nativeUpdateInformation,+ stripEmbeddedBlockmap,+ verifyZsyncFile,+ writeAppImageUpdateInformation,+} from './appimage-artifact.mjs'++const require = createRequire(import.meta.url)+const execFileAsync = promisify(execFile)++function defaultAppendBlockmap(file) {+ const {+ appendBlockmap,+ } = require('app-builder-lib/out/targets/differentialUpdateInfoBuilder.js')+ return appendBlockmap(file)+}++function installedElectronBuilderVersion() {+ return require('electron-builder/package.json').version+}++export async function generateZsync(appImagePath, zsyncPath) {+ const temporary = `${zsyncPath}.tmp-${process.pid}`+ await rm(temporary, { force: true })+ try {+ const name = path.basename(appImagePath)+ await execFileAsync(+ 'zsyncmake',+ ['-e', '-f', name, '-u', name, '-o', temporary, appImagePath],+ { maxBuffer: 16 * 1024 * 1024 }+ )+ await rename(temporary, zsyncPath)+ } catch (error) {+ throw new Error(+ `Failed to generate ${path.basename(zsyncPath)} with zsyncmake: ${error.message}`,+ { cause: error }+ )+ } finally {+ await rm(temporary, { force: true }).catch(() => {})+ }+}++export async function finalizeAppImageArtifact(event, dependencies = {}) {+ if (event?.target?.name !== 'appImage') return+ if (typeof event.file !== 'string' || !event.file.endsWith('.AppImage')) {+ throw new Error('AppImage artifact hook received an unexpected file')+ }++ const version = event.packager?.appInfo?.version+ if (typeof version !== 'string' || version.length === 0) {+ throw new Error('AppImage artifact hook could not determine the version')+ }+ const arch = appImageArchFromBuilder(event.arch)+ const expectedName = expectedAppImageName(version, arch)+ if (path.basename(event.file) !== expectedName) {+ throw new Error(+ `Unexpected AppImage artifact ${path.basename(event.file)}; expected ${expectedName}`+ )+ }+ const configuredToolset = event.packager?.config?.toolsets?.appimage+ if (configuredToolset !== APPIMAGE_TOOLSET_VERSION) {+ throw new Error(+ `AppImage toolset must be ${APPIMAGE_TOOLSET_VERSION}, got ${configuredToolset ?? '<unset>'}`+ )+ }++ const getBuilderVersion =+ dependencies.getBuilderVersion ?? installedElectronBuilderVersion+ const builderVersion = getBuilderVersion()+ if (builderVersion !== ELECTRON_BUILDER_VERSION) {+ throw new Error(+ `AppImage finalization requires electron-builder ${ELECTRON_BUILDER_VERSION}, got ${builderVersion}`+ )+ }+ if (+ !event.updateInfo ||+ !Number.isSafeInteger(event.updateInfo.blockMapSize) ||+ event.updateInfo.blockMapSize <= 0+ ) {+ throw new Error('electron-builder did not provide an embedded blockmap')+ }++ const inspectRuntime = dependencies.inspectRuntime ?? inspectAppImageRuntime+ const assertMetadata =+ dependencies.assertMetadata ?? assertAppImageRuntimeMetadata+ const stripBlockmap = dependencies.stripBlockmap ?? stripEmbeddedBlockmap+ const writeUpdateInformation =+ dependencies.writeUpdateInformation ?? writeAppImageUpdateInformation+ const appendBlockmap = dependencies.appendBlockmap ?? defaultAppendBlockmap+ const inspectBlockmap =+ dependencies.inspectBlockmap ?? inspectEmbeddedBlockmap+ const createZsync = dependencies.generateZsync ?? generateZsync+ const checkZsync = dependencies.verifyZsync ?? verifyZsyncFile++ const initialRuntime = await inspectRuntime(event.file, arch)+ assertMetadata(initialRuntime, {+ updateInformation: '',+ requireUnsigned: true,+ })+ await stripBlockmap(event.file, event.updateInfo.blockMapSize)++ const updateInformation = nativeUpdateInformation(version, arch)+ await writeUpdateInformation(event.file, arch, updateInformation)++ // electron-updater hashes and downloads the complete AppImage including its+ // embedded blockmap. Rebuild it after mutating .upd_info, then replace the+ // event metadata before PublishManager creates latest/beta-linux*.yml.+ event.updateInfo = await appendBlockmap(event.file)+ const rebuilt = await inspectBlockmap(event.file)+ if (rebuilt.blockMapSize !== event.updateInfo.blockMapSize) {+ throw new Error('Rebuilt AppImage blockmap metadata does not match footer')+ }++ const finalRuntime = await inspectRuntime(event.file, arch)+ assertMetadata(finalRuntime, {+ updateInformation,+ requireUnsigned: true,+ })++ const zsyncPath = path.join(+ path.dirname(event.file),+ expectedZsyncName(version, arch)+ )+ await createZsync(event.file, zsyncPath)+ await checkZsync({ appImagePath: event.file, zsyncPath })+}++export default finalizeAppImageArtifactdiff --git a/scripts/verify-appimage-artifact.mjs b/scripts/verify-appimage-artifact.mjsindex 887945b1..a10e1875 100644--- a/scripts/verify-appimage-artifact.mjs+++ b/scripts/verify-appimage-artifact.mjs@@ -5,6 +5,16 @@ import path from 'node:path'import { pathToFileURL } from 'node:url'import { promisify } from 'node:util'+import {+ assertAppImageRuntimeMetadata,+ expectedAppImageName,+ expectedZsyncName,+ inspectAppImageRuntime,+ inspectEmbeddedBlockmap,+ nativeUpdateInformation,+ verifyZsyncFile,+} from './appimage-artifact.mjs'+// Release-time verification for the Linux AppImage target. Unlike a config-only// check, this inspects the BUILT artifact itself:// 1. Exactly one AppImage exists for the built architecture, named per the@@ -13,7 +23,11 @@ import { promisify } from 'node:util'// 3. Its header is an ELF carrying the AppImage type-2 magic, and its ELF// machine matches the target architecture (a wrong-arch or non-AppImage// file with the right name is rejected).-// 4. The desktop entry embedded INSIDE the AppImage declares all three+// 4. Its runtime is static, has no legacy libfuse.so.2 dependency/loading+// logic, and preserves a valid electron-updater embedded blockmap.+// 5. Its native AppImage update information selects stable `latest` or beta+// `latest-pre`, and the matching per-architecture zsync is valid.+// 6. The desktop entry embedded INSIDE the AppImage declares all three// handler MimeTypes a browser needs (bittorrent, magnet, motrix:) — read// out of the artifact, not from the source config.// The runtime self-integration (src/main/platform/appimage-integration.ts) is a@@ -27,24 +41,13 @@ export const REQUIRED_MIME_TYPES = ['x-scheme-handler/motrix',]-// electron-builder's `${arch}` macro for the AppImage target (builder-util-// getArtifactArchName): x64 -> x86_64, arm64 -> arm64.-const APPIMAGE_ARCH = {- x64: 'x86_64',- arm64: 'arm64',-}-// ELF e_machine values (offset 18, little-endian u16).const ELF_MACHINE = {x64: 0x3e, // EM_X86_64arm64: 0xb7, // EM_AARCH64}-export function expectedAppImageName(version, arch) {- const archName = APPIMAGE_ARCH[arch]- if (!archName) throw new Error(`Unsupported AppImage arch: ${arch}`)- return `Motrix-${version}-${archName}.AppImage`-}+export { expectedAppImageName }export function assertDesktopMimeTypes(mimeValue) {const mime = typeof mimeValue === 'string' ? mimeValue : ''@@ -153,11 +156,15 @@ export async function verifyAppimageArtifact({statFile = stat,readArtifactHead = readHead,extractMimeType = defaultExtractMimeType,+ inspectRuntime = inspectAppImageRuntime,+ assertRuntimeMetadata = assertAppImageRuntimeMetadata,+ inspectBlockmap = inspectEmbeddedBlockmap,+ verifyZsync = verifyZsyncFile,}) {if (!version) throw new Error('Expected release version')if (!arch) throw new Error('Expected target architecture')- if (!APPIMAGE_ARCH[arch])- throw new Error(`Unsupported AppImage arch: ${arch}`)+ // expectedAppImageName owns the supported-architecture contract.+ expectedAppImageName(version, arch)const entries = await readdir(directory)const appImages = entries.filter((name) => name.endsWith('.AppImage'))@@ -174,7 +181,21 @@ export async function verifyAppimageArtifact({)}+ const zsyncs = entries.filter((name) => name.endsWith('.AppImage.zsync'))+ if (zsyncs.length !== 1) {+ throw new Error(+ `Expected exactly one AppImage zsync for ${arch}, found ${zsyncs.length}: ${zsyncs.join(', ')}`+ )+ }+ const expectedZsync = expectedZsyncName(version, arch)+ if (zsyncs[0] !== expectedZsync) {+ throw new Error(+ `Unexpected AppImage zsync name ${zsyncs[0]}; expected ${expectedZsync}`+ )+ }+const artifactPath = path.join(directory, expected)+ const zsyncPath = path.join(directory, expectedZsync)const info = await statFile(artifactPath)if (!info.isFile()) throw new Error(`${expected} is not a regular file`)@@ -188,10 +209,18 @@ export async function verifyAppimageArtifact({const head = await readArtifactHead(artifactPath, 64)assertAppImageHeader(head, arch)+ const runtime = await inspectRuntime(artifactPath, arch)+ assertRuntimeMetadata(runtime, {+ updateInformation: nativeUpdateInformation(version, arch),+ requireUnsigned: true,+ })+ await inspectBlockmap(artifactPath)+ await verifyZsync({ appImagePath: artifactPath, zsyncPath })+const mime = await extractMimeType(artifactPath)assertDesktopMimeTypes(mime)- return { appImage: expected }+ return { appImage: expected, zsync: expectedZsync }}function readArg(name) {@@ -206,5 +235,5 @@ if (import.meta.url === pathToFileURL(process.argv[1]).href) {readArg('--version') ?? process.env.GITHUB_REF_NAME?.replace(/^v/, ''),arch: readArg('--arch'),})- console.log(`Verified AppImage ${result.appImage}`)+ console.log(`Verified AppImage ${result.appImage} and ${result.zsync}`)}diff --git a/scripts/verify-update-artifacts.mjs b/scripts/verify-update-artifacts.mjsindex 9616dadc..742944e7 100644--- a/scripts/verify-update-artifacts.mjs+++ b/scripts/verify-update-artifacts.mjs@@ -4,6 +4,7 @@ import { access, readdir, readFile, stat } from 'node:fs/promises'import path from 'node:path'import { pathToFileURL } from 'node:url'import { load } from 'js-yaml'+import { verifyZsyncFile } from './appimage-artifact.mjs'import { parseStrictSemVer } from './release-metadata.mjs'const MANIFEST_PLATFORMS = [@@ -96,9 +97,20 @@ export async function verifyUpdateArtifacts({}}+ const zsyncAssets = []+ for (const name of verified.keys()) {+ if (!name.endsWith('.AppImage')) continue+ const zsync = `${name}.zsync`+ await verifyZsyncFile({+ appImagePath: path.join(directory, name),+ zsyncPath: path.join(directory, zsync),+ })+ zsyncAssets.push(zsync)+ }+return {manifests: manifests.map((manifest) => manifest.name),- assets: [...verified.keys()],+ assets: [...verified.keys(), ...zsyncAssets],}}diff --git a/tests/scripts/appimage-artifact.test.ts b/tests/scripts/appimage-artifact.test.tsnew file mode 100644index 00000000..861fba89--- /dev/null+++ b/tests/scripts/appimage-artifact.test.ts@@ -0,0 +1,292 @@+import { createHash } from 'node:crypto'+import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { deflateRawSync } from 'node:zlib'+import { afterEach, describe, expect, it } from 'vitest'+// @ts-expect-error -- JavaScript release script intentionally has no declarations+import {+ assertAppImageRuntimeMetadata,+ expectedAppImageName,+ expectedZsyncName,+ inspectAppImageRuntime,+ inspectEmbeddedBlockmap,+ nativeUpdateInformation,+ parseAppImageRuntime,+ stripEmbeddedBlockmap,+ verifyZsyncFile,+ writeAppImageUpdateInformation,+} from '../../scripts/appimage-artifact.mjs'++const tempDirs: string[] = []++afterEach(async () => {+ await Promise.all(+ tempDirs+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true }))+ )+})++describe('AppImage native update metadata', () => {+ it('uses latest for stable and latest-pre for beta, per architecture', () => {+ expect(nativeUpdateInformation('2.0.0', 'x64')).toBe(+ 'gh-releases-zsync|agalwood|Motrix|latest|Motrix-*-x86_64.AppImage.zsync'+ )+ expect(nativeUpdateInformation('2.0.0-beta.23', 'arm64')).toBe(+ 'gh-releases-zsync|agalwood|Motrix|latest-pre|Motrix-*-arm64.AppImage.zsync'+ )+ expect(expectedAppImageName('2.0.0', 'x64')).toBe(+ 'Motrix-2.0.0-x86_64.AppImage'+ )+ expect(expectedZsyncName('2.0.0', 'arm64')).toBe(+ 'Motrix-2.0.0-arm64.AppImage.zsync'+ )+ })++ it('rejects unsupported release channels and architectures', () => {+ expect(() => nativeUpdateInformation('2.0.0-rc.1', 'x64')).toThrow(+ 'Unsupported AppImage update channel'+ )+ expect(() => nativeUpdateInformation('2.0.0', 'armv7l')).toThrow(+ 'Unsupported AppImage arch'+ )+ })+})++describe('static AppImage runtime inspection', () => {+ it('accepts a static runtime and reads empty update/signature sections', () => {+ const runtime = makeRuntime()+ const inspection = parseAppImageRuntime(runtime, 'x64')+ expect(inspection.runtimeBytes).toBe(runtime.length)+ expect(() =>+ assertAppImageRuntimeMetadata(+ { runtime, ...inspection },+ { updateInformation: '', requireUnsigned: true }+ )+ ).not.toThrow()+ })++ it('rejects an interpreter, dynamic dependency, and FUSE2 loader string', () => {+ const interpreted = makeRuntime()+ interpreted.writeUInt32LE(3, 64)+ expect(() => parseAppImageRuntime(interpreted, 'x64')).toThrow('PT_INTERP')++ const needed = makeRuntime()+ needed.writeBigInt64LE(1n, RUNTIME_OFFSETS.dynamic)+ expect(() => parseAppImageRuntime(needed, 'x64')).toThrow('DT_NEEDED')++ const fuse2 = makeRuntime()+ fuse2.write('libfuse.so.2', RUNTIME_OFFSETS.padding, 'utf8')+ expect(() => parseAppImageRuntime(fuse2, 'x64')).toThrow('libfuse.so.2')+ })++ it('rejects populated native signature bytes', () => {+ const runtime = makeRuntime()+ runtime[RUNTIME_OFFSETS.signature] = 1+ const inspection = parseAppImageRuntime(runtime, 'x64')+ expect(() =>+ assertAppImageRuntimeMetadata(+ { runtime, ...inspection },+ { updateInformation: '', requireUnsigned: true }+ )+ ).toThrow('native signature is populated')+ })++ it('writes update information into the fixed ELF section', async () => {+ const directory = await makeTempDir()+ const file = path.join(directory, 'Motrix-2.0.0-x86_64.AppImage')+ await writeFile(file, makeRuntime())+ await chmod(file, 0o755)+ const update = nativeUpdateInformation('2.0.0', 'x64')++ await writeAppImageUpdateInformation(file, 'x64', update)++ const inspection = await inspectAppImageRuntime(file, 'x64')+ expect(() =>+ assertAppImageRuntimeMetadata(inspection, {+ updateInformation: update,+ requireUnsigned: true,+ })+ ).not.toThrow()+ })+})++describe('embedded blockmap inspection', () => {+ it('validates and strips the electron-updater blockmap footer', async () => {+ const directory = await makeTempDir()+ const file = path.join(directory, 'Motrix.AppImage')+ const base = Buffer.from('complete AppImage bytes')+ const document = {+ version: '2',+ files: [+ {+ name: 'file',+ offset: 0,+ checksums: ['fixture-checksum'],+ sizes: [base.length],+ },+ ],+ }+ const compressed = deflateRawSync(Buffer.from(JSON.stringify(document)))+ const footer = Buffer.alloc(4)+ footer.writeUInt32BE(compressed.length)+ await writeFile(file, Buffer.concat([base, compressed, footer]))++ await expect(inspectEmbeddedBlockmap(file)).resolves.toMatchObject({+ baseSize: base.length,+ blockMapSize: compressed.length,+ })+ await stripEmbeddedBlockmap(file, compressed.length)+ await expect(readFile(file)).resolves.toEqual(base)+ })++ it('rejects malformed blockmap metadata', async () => {+ const directory = await makeTempDir()+ const file = path.join(directory, 'Motrix.AppImage')+ await writeFile(file, Buffer.from('not a blockmap\0\0\0\0'))+ await expect(inspectEmbeddedBlockmap(file)).rejects.toThrow(+ 'Invalid embedded AppImage blockmap size'+ )+ })+})++describe('zsync verification', () => {+ it('binds Filename, URL, Length, and SHA-1 to the final AppImage', async () => {+ const directory = await makeTempDir()+ const appImagePath = path.join(directory, 'Motrix-2.0.0-x86_64.AppImage')+ const zsyncPath = `${appImagePath}.zsync`+ const content = Buffer.from('final AppImage including embedded blockmap')+ await writeFile(appImagePath, content)+ await writeFile(zsyncPath, makeZsync(path.basename(appImagePath), content))++ await expect(verifyZsyncFile({ appImagePath, zsyncPath })).resolves.toEqual(+ { zsync: path.basename(zsyncPath) }+ )++ const changed = Buffer.from('changed AppImage')+ await writeFile(appImagePath, changed)+ await expect(verifyZsyncFile({ appImagePath, zsyncPath })).rejects.toThrow(+ 'Length does not match AppImage'+ )+ })++ it('accepts the current File-Hash form as well as legacy SHA-1', async () => {+ const directory = await makeTempDir()+ const appImagePath = path.join(directory, 'Motrix-2.0.0-arm64.AppImage')+ const zsyncPath = `${appImagePath}.zsync`+ const content = Buffer.from('arm64 AppImage')+ await writeFile(appImagePath, content)+ await writeFile(+ zsyncPath,+ makeZsync(path.basename(appImagePath), content).replace(+ /SHA-1: ([0-9a-f]{40})/u,+ 'File-Hash: SHA-1:$1'+ )+ )+ await expect(+ verifyZsyncFile({ appImagePath, zsyncPath })+ ).resolves.toMatchObject({ zsync: path.basename(zsyncPath) })+ })+})++const RUNTIME_OFFSETS = {+ names: 128,+ static: 256,+ padding: 300,+ update: 512,+ signature: 1536,+ dynamic: 2560,+ sections: 4096,+}++function makeRuntime() {+ const names = Buffer.from(+ '\0.shstrtab\0.static\0.upd_info\0.sha256_sig\0.dynamic\0'+ )+ const sectionCount = 6+ const runtime = Buffer.alloc(RUNTIME_OFFSETS.sections + sectionCount * 64)+ Buffer.from([0x7f, 0x45, 0x4c, 0x46]).copy(runtime)+ runtime[4] = 2+ runtime[5] = 1+ runtime[6] = 1+ runtime[8] = 0x41+ runtime[9] = 0x49+ runtime[10] = 0x02+ runtime.writeUInt16LE(2, 16)+ runtime.writeUInt16LE(0x3e, 18)+ runtime.writeUInt32LE(1, 20)+ runtime.writeBigUInt64LE(64n, 0x20)+ runtime.writeBigUInt64LE(BigInt(RUNTIME_OFFSETS.sections), 0x28)+ runtime.writeUInt16LE(64, 0x34)+ runtime.writeUInt16LE(56, 0x36)+ runtime.writeUInt16LE(1, 0x38)+ runtime.writeUInt16LE(64, 0x3a)+ runtime.writeUInt16LE(sectionCount, 0x3c)+ runtime.writeUInt16LE(1, 0x3e)+ runtime.writeUInt32LE(1, 64)+ names.copy(runtime, RUNTIME_OFFSETS.names)+ runtime.write('static', RUNTIME_OFFSETS.static, 'utf8')+ Buffer.from(+ '--appimage-mount\0--appimage-extract\0--appimage-extract-and-run\0TARGET_APPIMAGE'+ ).copy(runtime, RUNTIME_OFFSETS.padding)++ writeSection(+ runtime,+ 1,+ names,+ '.shstrtab',+ 3,+ RUNTIME_OFFSETS.names,+ names.length+ )+ writeSection(runtime, 2, names, '.static', 1, RUNTIME_OFFSETS.static, 6)+ writeSection(runtime, 3, names, '.upd_info', 1, RUNTIME_OFFSETS.update, 1024)+ writeSection(+ runtime,+ 4,+ names,+ '.sha256_sig',+ 1,+ RUNTIME_OFFSETS.signature,+ 1024+ )+ writeSection(runtime, 5, names, '.dynamic', 6, RUNTIME_OFFSETS.dynamic, 16)+ return runtime+}++function writeSection(+ runtime: Buffer,+ index: number,+ names: Buffer,+ name: string,+ type: number,+ offset: number,+ size: number+) {+ const header = RUNTIME_OFFSETS.sections + index * 64+ runtime.writeUInt32LE(names.indexOf(Buffer.from(`${name}\0`)), header)+ runtime.writeUInt32LE(type, header + 4)+ runtime.writeBigUInt64LE(BigInt(offset), header + 24)+ runtime.writeBigUInt64LE(BigInt(size), header + 32)+}++function makeZsync(name: string, appImage: Buffer) {+ const sha1 = createHash('sha1').update(appImage).digest('hex')+ return (+ `zsync: 0.6.2\n` ++ `Filename: ${name}\n` ++ `Blocksize: 2048\n` ++ `Length: ${appImage.length}\n` ++ `Hash-Lengths: 1,2,4\n` ++ `URL: ${name}\n` ++ `SHA-1: ${sha1}\n\n` ++ 'checksum-payload'+ )+}++async function makeTempDir() {+ const directory = await mkdtemp(path.join(os.tmpdir(), 'motrix-appimage-'))+ tempDirs.push(directory)+ return directory+}diff --git a/tests/scripts/assemble-release-artifacts.test.ts b/tests/scripts/assemble-release-artifacts.test.tsindex 2ceba768..51649ecb 100644--- a/tests/scripts/assemble-release-artifacts.test.ts+++ b/tests/scripts/assemble-release-artifacts.test.ts@@ -47,7 +47,9 @@ describe('assembleReleaseArtifacts', () => {expect(await readdir(fixture.output)).toEqual(expect.arrayContaining(['Motrix-2.0.0-arm64.AppImage',+ 'Motrix-2.0.0-arm64.AppImage.zsync','Motrix-2.0.0-x86_64.AppImage',+ 'Motrix-2.0.0-x86_64.AppImage.zsync','Motrix-2.0.0.aarch64.rpm','Motrix-2.0.0.x86_64.rpm','Motrix-Native-Host-2.0.0-linux-arm64.tar.gz',@@ -445,10 +447,7 @@ describe('assembleReleaseArtifacts', () => {const rejected = await createFixture()await writeFile(- path.join(- path.dirname(rejected.paths.linuxX64Deb),- 'Motrix-2.0.0-x64.AppImage.blockmap'- ),+ `${rejected.paths.linuxX64AppImage}.blockmap`,'orphaned AppImage blockmap')await expect(@@ -458,7 +457,22 @@ describe('assembleReleaseArtifacts', () => {version: VERSION,})).rejects.toThrow(- 'linux-x64: unexpected release asset Motrix-2.0.0-x64.AppImage.blockmap'+ 'linux-x64: unexpected release asset Motrix-2.0.0-x86_64.AppImage.blockmap'+ )++ const zsyncBlockmap = await createFixture()+ await writeFile(+ `${zsyncBlockmap.paths.linuxX64Zsync}.blockmap`,+ 'orphaned zsync blockmap'+ )+ await expect(+ assembleReleaseArtifacts({+ inputDirectory: zsyncBlockmap.input,+ outputDirectory: zsyncBlockmap.output,+ version: VERSION,+ })+ ).rejects.toThrow(+ 'linux-x64: unexpected release asset Motrix-2.0.0-x86_64.AppImage.zsync.blockmap')const companionBlockmap = await createFixture()@@ -477,7 +491,7 @@ describe('assembleReleaseArtifacts', () => {)})- it('flattens the AppImage asset and records it in both Linux manifests', async () => {+ it('flattens AppImage/zsync assets but keeps zsync out of updater manifests', async () => {const fixture = await createFixture()await assembleReleaseArtifacts({@@ -491,7 +505,9 @@ describe('assembleReleaseArtifacts', () => {expect(output).toEqual(expect.arrayContaining(['Motrix-2.0.0-x86_64.AppImage',+ 'Motrix-2.0.0-x86_64.AppImage.zsync','Motrix-2.0.0-arm64.AppImage',+ 'Motrix-2.0.0-arm64.AppImage.zsync',]))@@ -504,9 +520,26 @@ describe('assembleReleaseArtifacts', () => {await readFile(path.join(fixture.output, manifestName), 'utf8')) as { files: Array<{ url: string }> }expect(manifest.files.map((file) => file.url)).toContain(appImage)+ expect(manifest.files.some((file) => file.url.endsWith('.zsync'))).toBe(+ false+ )}})+ it('requires a zsync sidecar for every Linux AppImage', async () => {+ const fixture = await createFixture()+ await unlink(fixture.paths.linuxX64Zsync)+ await expect(+ assembleReleaseArtifacts({+ inputDirectory: fixture.input,+ outputDirectory: fixture.output,+ version: VERSION,+ })+ ).rejects.toThrow(+ 'required release asset Motrix-2.0.0-x86_64.AppImage.zsync is missing'+ )+ })+it('rejects Linux artifacts swapped between x64 and arm64 inputs', async () => {const fixture = await createFixture()await rename(@@ -577,25 +610,34 @@ async function createFixture(version = VERSION) {linuxArm64Companion: `Motrix-Native-Host-${version}-linux-arm64.tar.gz`,linuxArm64Rpm: `Motrix-${version}.aarch64.rpm`,linuxArm64AppImage: `Motrix-${version}-arm64.AppImage`,+ linuxArm64Zsync: `Motrix-${version}-arm64.AppImage.zsync`,linuxX64Deb: `Motrix_${version}_amd64.deb`,linuxX64Companion: `Motrix-Native-Host-${version}-linux-x64.tar.gz`,linuxX64Rpm: `Motrix-${version}.x86_64.rpm`,linuxX64AppImage: `Motrix-${version}-x86_64.AppImage`,+ linuxX64Zsync: `Motrix-${version}-x86_64.AppImage.zsync`,macArm64Dmg: `Motrix-${version}-arm64.dmg`,macArm64Zip: `Motrix-${version}-arm64.zip`,macX64Dmg: `Motrix-${version}-x64.dmg`,macX64Zip: `Motrix-${version}-x64.zip`,windowsExe: `Motrix-Setup-${version}.exe`,}+ const linuxArm64AppImageContent = Buffer.from('Linux arm64 AppImage')+ const linuxX64AppImageContent = Buffer.from('Linux x64 AppImage')const contents = {linuxArm64Deb: Buffer.from('Linux arm64 deb'),linuxArm64Companion: Buffer.from('Linux arm64 Flatpak companion'),linuxArm64Rpm: Buffer.from('Linux arm64 rpm'),- linuxArm64AppImage: Buffer.from('Linux arm64 AppImage'),+ linuxArm64AppImage: linuxArm64AppImageContent,+ linuxArm64Zsync: makeZsync(+ names.linuxArm64AppImage,+ linuxArm64AppImageContent+ ),linuxX64Deb: Buffer.from('Linux x64 deb'),linuxX64Companion: Buffer.from('Linux x64 Flatpak companion'),linuxX64Rpm: Buffer.from('Linux x64 rpm'),- linuxX64AppImage: Buffer.from('Linux x64 AppImage'),+ linuxX64AppImage: linuxX64AppImageContent,+ linuxX64Zsync: makeZsync(names.linuxX64AppImage, linuxX64AppImageContent),macArm64Dmg: Buffer.from('macOS arm64 DMG'),macArm64Zip: Buffer.from('macOS arm64 ZIP'),macX64Dmg: Buffer.from('macOS x64 DMG'),@@ -673,6 +715,11 @@ async function createFixture(version = VERSION) {names.linuxX64AppImage,contents.linuxX64AppImage)+ const linuxX64Zsync = await writeAsset(+ linuxX64,+ names.linuxX64Zsync,+ contents.linuxX64Zsync+ )const linuxX64Manifest = path.join(linuxX64, 'latest-linux.yml')const linuxX64BetaManifest = path.join(linuxX64, 'beta-linux.yml')await writeManifest(@@ -719,6 +766,11 @@ async function createFixture(version = VERSION) {names.linuxArm64AppImage,contents.linuxArm64AppImage)+ const linuxArm64Zsync = await writeAsset(+ linuxArm64,+ names.linuxArm64Zsync,+ contents.linuxArm64Zsync+ )const linuxArm64Manifest = path.join(linuxArm64, 'latest-linux-arm64.yml')await writeManifest(linuxArm64Manifest,@@ -771,9 +823,11 @@ async function createFixture(version = VERSION) {linuxArm64Manifest,linuxArm64Rpm: linuxArm64Rpm.path,linuxArm64AppImage: linuxArm64AppImage.path,+ linuxArm64Zsync: linuxArm64Zsync.path,linuxX64Deb: linuxX64Deb.path,linuxX64Companion: linuxX64Companion.path,linuxX64AppImage: linuxX64AppImage.path,+ linuxX64Zsync: linuxX64Zsync.path,linuxX64BetaManifest,linuxX64Manifest,macArm64Manifest,@@ -829,3 +883,16 @@ async function writeManifest(function sha512(content: Buffer) {return createHash('sha512').update(content).digest('base64')}++function makeZsync(name: string, content: Buffer) {+ return Buffer.from(+ 'zsync: 0.6.2\n' ++ `Filename: ${name}\n` ++ 'Blocksize: 2048\n' ++ `Length: ${content.length}\n` ++ 'Hash-Lengths: 1,2,4\n' ++ `URL: ${name}\n` ++ `SHA-1: ${createHash('sha1').update(content).digest('hex')}\n\n` ++ 'checksum-payload'+ )+}diff --git a/tests/scripts/finalize-appimage-artifact.test.ts b/tests/scripts/finalize-appimage-artifact.test.tsnew file mode 100644index 00000000..8c162bbe--- /dev/null+++ b/tests/scripts/finalize-appimage-artifact.test.ts@@ -0,0 +1,127 @@+import path from 'node:path'+import { describe, expect, it, vi } from 'vitest'+// @ts-expect-error -- JavaScript electron-builder hook has no declarations+import { finalizeAppImageArtifact } from '../../scripts/finalize-appimage-artifact.mjs'++describe('finalizeAppImageArtifact', () => {+ it('embeds beta update information before rebuilding blockmap and zsync', async () => {+ const calls: string[] = []+ const event = makeEvent('2.0.0-beta.23', 1, 'x86_64', 12)+ const assertMetadata = vi.fn(+ (_inspection: unknown, options: { updateInformation: string }) => {+ calls.push(`metadata:${options.updateInformation || 'empty'}`)+ }+ )+ const writeUpdateInformation = vi.fn(+ async (_file: string, arch: string, update: string) => {+ calls.push(`write:${arch}:${update}`)+ }+ )+ const generateZsync = vi.fn(+ async (_appImagePath: string, zsyncPath: string) => {+ calls.push(`zsync:${path.basename(zsyncPath)}`)+ }+ )++ await finalizeAppImageArtifact(event, {+ getBuilderVersion: () => '26.15.7',+ inspectRuntime: async () => ({ runtime: Buffer.alloc(0) }),+ assertMetadata,+ stripBlockmap: async (_file: string, size: number) => {+ calls.push(`strip:${size}`)+ },+ writeUpdateInformation,+ appendBlockmap: async () => {+ calls.push('append')+ return { blockMapSize: 24, sha512: 'updated', size: 100 }+ },+ inspectBlockmap: async () => {+ calls.push('inspect-blockmap')+ return { blockMapSize: 24 }+ },+ generateZsync,+ verifyZsync: async () => {+ calls.push('verify-zsync')+ },+ })++ const update =+ 'gh-releases-zsync|agalwood|Motrix|latest-pre|Motrix-*-x86_64.AppImage.zsync'+ expect(calls).toEqual([+ 'metadata:empty',+ 'strip:12',+ `write:x64:${update}`,+ 'append',+ 'inspect-blockmap',+ `metadata:${update}`,+ 'zsync:Motrix-2.0.0-beta.23-x86_64.AppImage.zsync',+ 'verify-zsync',+ ])+ expect(event.updateInfo).toEqual({+ blockMapSize: 24,+ sha512: 'updated',+ size: 100,+ })+ })++ it('supports arm64 stable metadata', async () => {+ const event = makeEvent('2.0.0', 3, 'arm64', 12)+ const updates: string[] = []+ await finalizeAppImageArtifact(event, {+ getBuilderVersion: () => '26.15.7',+ inspectRuntime: async () => ({}),+ assertMetadata: () => {},+ stripBlockmap: async () => {},+ writeUpdateInformation: async (+ _file: string,+ arch: string,+ update: string+ ) => updates.push(`${arch}:${update}`),+ appendBlockmap: async () => ({ blockMapSize: 18 }),+ inspectBlockmap: async () => ({ blockMapSize: 18 }),+ generateZsync: async () => {},+ verifyZsync: async () => {},+ })++ expect(updates).toEqual([+ 'arm64:gh-releases-zsync|agalwood|Motrix|latest|Motrix-*-arm64.AppImage.zsync',+ ])+ })++ it('pins the supported toolset and electron-builder implementation', async () => {+ const event = makeEvent('2.0.0', 1, 'x86_64', 12)+ event.packager.config.toolsets.appimage = '0.0.0'+ await expect(+ finalizeAppImageArtifact(event, { getBuilderVersion: () => '26.15.7' })+ ).rejects.toThrow('AppImage toolset must be 1.0.3')++ event.packager.config.toolsets.appimage = '1.0.3'+ await expect(+ finalizeAppImageArtifact(event, { getBuilderVersion: () => '27.0.0' })+ ).rejects.toThrow('requires electron-builder 26.15.7')+ })++ it('ignores non-AppImage artifact events', async () => {+ await expect(+ finalizeAppImageArtifact({ target: { name: 'deb' } })+ ).resolves.toBeUndefined()+ })+})++function makeEvent(+ version: string,+ arch: number,+ artifactArch: string,+ blockMapSize: number+) {+ return {+ arch,+ file: `/tmp/Motrix-${version}-${artifactArch}.AppImage`,+ packager: {+ appInfo: { version },+ config: { toolsets: { appimage: '1.0.3' } },+ },+ target: { name: 'appImage' },+ updateInfo: { blockMapSize, sha512: 'initial', size: 80 },+ }+}diff --git a/tests/scripts/verify-appimage-artifact.test.ts b/tests/scripts/verify-appimage-artifact.test.tsindex a0e6dd08..a5ce3dac 100644--- a/tests/scripts/verify-appimage-artifact.test.ts+++ b/tests/scripts/verify-appimage-artifact.test.ts@@ -51,6 +51,10 @@ function ports(readArtifactHead: async () =>overrides.head ?? makeHead(overrides.arch ?? 'x64'),extractMimeType: async () => overrides.mime ?? FULL_MIME,+ inspectRuntime: async () => ({}),+ assertRuntimeMetadata: () => {},+ inspectBlockmap: async () => ({}),+ verifyZsync: async () => ({}),}}@@ -60,10 +64,15 @@ afterEach(async () => {)})-async function makeDir(files: string[]) {+async function makeDir(files: string[], addZsync = true) {const dir = await mkdtemp(path.join(os.tmpdir(), 'motrix-appimage-'))tempDirs.push(dir)for (const name of files) await writeFile(path.join(dir, name), name)+ if (addZsync && !files.some((name) => name.endsWith('.AppImage.zsync'))) {+ for (const name of files.filter((name) => name.endsWith('.AppImage'))) {+ await writeFile(path.join(dir, `${name}.zsync`), 'zsync')+ }+ }return dir}@@ -144,7 +153,22 @@ describe('verifyAppimageArtifact', () => {arch: 'x64',...ports(),})- ).resolves.toEqual({ appImage: 'Motrix-2.0.0-x86_64.AppImage' })+ ).resolves.toEqual({+ appImage: 'Motrix-2.0.0-x86_64.AppImage',+ zsync: 'Motrix-2.0.0-x86_64.AppImage.zsync',+ })+ })++ it('requires the architecture-specific zsync sidecar', async () => {+ const dir = await makeDir(['Motrix-2.0.0-x86_64.AppImage'], false)+ await expect(+ verifyAppimageArtifact({+ directory: dir,+ version: VERSION,+ arch: 'x64',+ ...ports(),+ })+ ).rejects.toThrow('Expected exactly one AppImage zsync')})it('rejects a missing AppImage', async () => {diff --git a/tests/scripts/verify-update-artifacts.test.ts b/tests/scripts/verify-update-artifacts.test.tsindex 6029df9e..7d075006 100644--- a/tests/scripts/verify-update-artifacts.test.ts+++ b/tests/scripts/verify-update-artifacts.test.ts@@ -37,6 +37,10 @@ describe('verifyUpdateArtifacts', () => {await writeFile(path.join(fixture, debName), deb)await writeFile(path.join(fixture, rpmName), rpm)await writeFile(path.join(fixture, appImageName), appImage)+ await writeFile(+ path.join(fixture, `${appImageName}.zsync`),+ zsync(appImageName, appImage)+ )await writeFile(path.join(fixture, 'latest-linux-arm64.yml'),manifest(@@ -53,7 +57,7 @@ describe('verifyUpdateArtifacts', () => {verifyUpdateArtifacts({ directory: fixture, version: '2.0.0' })).resolves.toEqual({manifests: ['latest-linux-arm64.yml'],- assets: [debName, rpmName, appImageName],+ assets: [debName, rpmName, appImageName, `${appImageName}.zsync`],})})@@ -285,6 +289,19 @@ function manifest()}+function zsync(name: string, content: Buffer) {+ return (+ 'zsync: 0.6.2\n' ++ `Filename: ${name}\n` ++ 'Blocksize: 2048\n' ++ `Length: ${content.length}\n` ++ 'Hash-Lengths: 1,2,4\n' ++ `URL: ${name}\n` ++ `SHA-1: ${createHash('sha1').update(content).digest('hex')}\n\n` ++ 'checksum-payload'+ )+}+function sha512(content: Buffer) {return createHash('sha512').update(content).digest('base64')}diff --git a/tests/scripts/workflow-release-matrix.test.ts b/tests/scripts/workflow-release-matrix.test.tsindex 7b70535c..ea04830c 100644--- a/tests/scripts/workflow-release-matrix.test.ts+++ b/tests/scripts/workflow-release-matrix.test.ts@@ -542,11 +542,14 @@ describe('general CI native-host split contract', () => {'tests/scripts/flatpak-native-host.test.ts')for (const test of [+ 'tests/scripts/appimage-artifact.test.ts','tests/scripts/electron-package-contract.test.ts',+ 'tests/scripts/finalize-appimage-artifact.test.ts','tests/scripts/native-binary-target.test.ts','tests/scripts/release-signing-input.test.ts','tests/scripts/stage-electron-app.test.ts','tests/scripts/verify-electron-package.test.ts',+ 'tests/scripts/verify-appimage-artifact.test.ts',]) {expect(contractCommand).toContain(test)}@@ -1297,6 +1300,20 @@ describe('release workflow publication contract', () => {expect(verificationCommand).toContain('sha256sum')expect(verificationCommand).toContain('beta) expected_count=4')expect(verificationCommand).toContain('stable) expected_count=8')++ const nativeMetadata = steps.find(+ (step) =>+ step.name === 'Verify native AppImage update metadata distribution'+ )+ const nativeMetadataCommand = stringField(+ nativeMetadata as LooseRecord,+ 'run'+ )+ expect(nativeMetadataCommand).toContain('release/*.AppImage.zsync')+ expect(nativeMetadataCommand).toContain('dl.motrix.app/releases/')+ expect(nativeMetadataCommand).toContain(+ 'github.com/agalwood/Motrix/releases/download/'+ )})it('uploads only stable and beta metadata from target builds', () => {@@ -1331,6 +1348,11 @@ describe('release workflow publication contract', () => {expect(releaseSource).toContain('release/*.AppImage')const buildJob = targetMatrix(releaseWorkflow).job+ const buildSteps = jobSteps(buildJob)+ const toolInstall = buildSteps.find(+ (step) => step.name === 'Install Linux packaging tools'+ )+ expect(stringField(toolInstall as LooseRecord, 'run')).toContain('zsync')const linuxVerification = jobSteps(buildJob).find((step) => step.name === 'Verify Linux package formats')@@ -1353,6 +1375,52 @@ describe('release workflow publication contract', () => {expect(stringField(appImageVerification as LooseRecord, 'run')).toContain('scripts/verify-appimage-artifact.mjs')++ const cleanSmoke = buildSteps.find(+ (step) => step.name === 'Smoke test AppImage without system FUSE2'+ )+ const cleanSmokeCommand = stringField(cleanSmoke as LooseRecord, 'run')+ expect(cleanSmokeCommand).toContain('docker run --rm --network none')+ expect(cleanSmokeCommand).toContain('[[ ! -e /dev/fuse ]]')+ expect(cleanSmokeCommand).toContain('libfuse.so.2')+ expect(cleanSmokeCommand).toContain('--appimage-updateinformation')+ expect(cleanSmokeCommand).toContain('--appimage-extract')++ const upload = buildSteps.find(+ (step) => step.name === 'Upload target release input'+ )+ const uploadPaths = stringField(+ asRecord(upload?.with, 'release upload'),+ 'path'+ )+ expect(uploadPaths).toContain('release/*.AppImage.zsync')+ })++ it('pins the modern AppImage toolset and finalization hook', () => {+ const builderConfig = asRecord(+ JSON.parse(+ readFileSync(path.join(ROOT, 'electron-builder.json'), 'utf8')+ ) as unknown,+ 'electron-builder config'+ )+ expect(+ stringField(asRecord(builderConfig.toolsets, 'toolsets'), 'appimage')+ ).toBe('1.0.3')+ expect(stringField(builderConfig, 'artifactBuildCompleted')).toBe(+ './scripts/finalize-appimage-artifact.mjs'+ )+ const packageJson = asRecord(+ JSON.parse(+ readFileSync(path.join(ROOT, 'package.json'), 'utf8')+ ) as unknown,+ 'package.json'+ )+ expect(+ stringField(+ asRecord(packageJson.devDependencies, 'dev dependencies'),+ 'electron-builder'+ )+ ).toBe('26.15.7')})it('publishes required Flatpak companions outside updater manifests', () => {