A full-featured download manager.
ci(fnos): publish verified native packages for stable releases (#2507)
Dr_rOota45a729e9854
diff --git a/.github/workflows/fnos-publish.yml b/.github/workflows/fnos-publish.ymlnew file mode 100644index 00000000..b1528b53--- /dev/null+++ b/.github/workflows/fnos-publish.yml@@ -0,0 +1,139 @@+name: Publish fnOS FPK++on:+ workflow_run:+ workflows: ['Build/Release']+ types: [completed]+ workflow_dispatch:+ inputs:+ release_tag:+ description: Existing stable release tag whose exact source will be packaged+ required: true+ type: string++permissions:+ contents: read+ actions: read++concurrency:+ group: fnos-publication+ cancel-in-progress: false++jobs:+ preflight:+ if: >-+ github.event_name == 'workflow_dispatch' ||+ (github.event.workflow_run.conclusion == 'success' &&+ github.event.workflow_run.event == 'push')+ name: Verify stable release provenance+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ outputs:+ publish: ${{ steps.source.outputs.publish }}+ tag: ${{ steps.source.outputs.tag }}+ version: ${{ steps.source.outputs.version }}+ source_sha: ${{ steps.source.outputs.source_sha }}+ release_run_id: ${{ steps.source.outputs.release_run_id }}+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ fetch-depth: 0+ - name: Verify exact tag, ancestry and completed formal release+ id: source+ env:+ GH_TOKEN: ${{ github.token }}+ run: python3 scripts/fnos_publication.py preflight++ build:+ name: Build verified FPK / ${{ matrix.arch }}+ needs: preflight+ if: needs.preflight.outputs.publish == 'true'+ runs-on: ${{ matrix.os }}+ timeout-minutes: 45+ strategy:+ fail-fast: false+ matrix:+ include:+ - arch: x64+ os: ubuntu-24.04+ rust_target: x86_64-unknown-linux-musl+ - arch: arm64+ os: ubuntu-24.04-arm+ rust_target: aarch64-unknown-linux-musl+ steps:+ - name: Checkout the immutable released application+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ needs.preflight.outputs.source_sha }}+ persist-credentials: false+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ with:+ version: 12.16.1+ run_install: false+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0+ with:+ node-version: 24.18.0+ cache: pnpm+ - uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable+ with:+ toolchain: 1.94.1+ targets: ${{ matrix.rust_target }}+ - name: Install locked dependencies+ run: pnpm install --frozen-lockfile+ env:+ MOTRIX_SKIP_ELECTRON_REBUILD: '1'+ MOTRIX_SKIP_ENGINE_FETCH: '1'+ - name: Build and verify native package and lifecycle+ env:+ MOTRIX_FNOS_BUILD: '1'+ run: |+ pnpm run fetch:engine -- --platform linux --arch '${{ matrix.arch }}'+ pnpm run build:server+ pnpm run check:third-party-notices+ pnpm run stage:server -- --platform linux --arch '${{ matrix.arch }}' --libc gnu --strict+ pnpm run build:fnos -- --arch '${{ matrix.arch }}'+ - name: Upload only verified release files+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: fnos-release-${{ matrix.arch }}+ path: |+ release/fnos/Motrix-${{ needs.preflight.outputs.version }}-fnos-${{ matrix.arch }}.fpk+ release/fnos/Motrix-${{ needs.preflight.outputs.version }}-fnos-${{ matrix.arch }}.fpk.sha256+ if-no-files-found: error+ retention-days: 14+ overwrite: true++ publish:+ name: Publish complete verified FPK set+ needs: [preflight, build]+ if: needs.preflight.outputs.publish == 'true'+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ environment: github-release+ permissions:+ contents: write+ actions: read+ steps:+ - name: Checkout trusted publication tools+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ fetch-depth: 0+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ with:+ name: fnos-release-x64+ path: release/fnos-publish+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ with:+ name: fnos-release-arm64+ path: release/fnos-publish+ - name: Revalidate provenance and publish without overwriting assets+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_TAG: ${{ needs.preflight.outputs.tag }}+ SOURCE_SHA: ${{ needs.preflight.outputs.source_sha }}+ RELEASE_RUN_ID: ${{ needs.preflight.outputs.release_run_id }}+ run: >-+ python3 scripts/fnos_publication.py publish+ release/fnos-publish "$RELEASE_TAG" "$SOURCE_SHA" "$RELEASE_RUN_ID"diff --git a/.github/workflows/fnos.yml b/.github/workflows/fnos.ymlindex 383ec9eb..d11d67cb 100644--- a/.github/workflows/fnos.yml+++ b/.github/workflows/fnos.yml@@ -12,6 +12,8 @@ on:- 'src/server/http/fnos-auth*'- 'src/renderer/platform/fnos*'- '.github/workflows/fnos.yml'+ - '.github/workflows/fnos-publish.yml'+ - 'scripts/fnos_publication.py'permissions:contents: readdiff --git a/README.md b/README.mdindex f8f2fe49..c913cde2 100644--- a/README.md+++ b/README.md@@ -24,7 +24,7 @@ The same core powers two ways to run Motrix:Motrix 2.3.0 refreshes the application artwork, restores cloud-drive directorydownloads with aria2 1.37.0-motrix.23, and improves Server media tools, settingsand update checks. It also introduces native fnOS integration; FPK packages-remain separate test artifacts, not official Release downloads.+follow a separate verified publication workflow.Download [v2.3.0 from GitHub Releases](https://github.com/agalwood/Motrix/releases/tag/v2.3.0)and read the [full release notes](./docs/release-notes/2.3.0.md).diff --git a/README.zh-CN.md b/README.zh-CN.mdindex c7e532c8..89c3fcf5 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -23,7 +23,7 @@ Motrix 是一款界面简洁、功能丰富的桌面下载管理器,可处理Motrix 2.3.0 更新应用图标,随 aria2 1.37.0-motrix.23 恢复网盘目录下载,并完善 Server 媒体工具、设置和更新检查。同时引入飞牛 fnOS 原生集成;-FPK 仍为单独的测试构建产物,尚不属于正式 Release 下载。+FPK 通过单独的验证与发布流程提供。从 GitHub Releases 下载 [v2.3.0](https://github.com/agalwood/Motrix/releases/tag/v2.3.0),并阅读[完整发布说明](./docs/release-notes/2.3.0.zh-CN.md)。diff --git a/docs/release-notes/2.3.0.md b/docs/release-notes/2.3.0.mdindex b790f222..782a1e85 100644--- a/docs/release-notes/2.3.0.md+++ b/docs/release-notes/2.3.0.md@@ -1,10 +1,10 @@# Motrix 2.3.0-English | [简体中文](https://github.com/agalwood/Motrix/blob/v2.3.0/docs/release-notes/2.3.0.zh-CN.md)+English | [简体中文](https://github.com/agalwood/Motrix/blob/main/docs/release-notes/2.3.0.zh-CN.md)Motrix 2.3.0 refreshes the application artwork, restores cloud-drive directorydownloads, and improves media tools and settings in Motrix Server. It also adds-native fnOS integration, currently distributed through separate test builds.+native fnOS integration, with a separate verified package publication workflow.## Changes since 2.2.1@@ -27,11 +27,16 @@ native fnOS integration, currently distributed through separate test builds.tasks and settings, and ordinary users are denied access. It does not provideper-user task isolation.-Electron remains **45.2.1**. Native fnOS FPKs are **test artifacts** from the-[fnOS workflow](https://github.com/agalwood/Motrix/actions/workflows/fnos.yml),-not assets of this GitHub Release or a verified app-store publication. Real-device-compatibility and installation validation remain necessary; see the-[fnOS package guide](https://github.com/agalwood/Motrix/blob/v2.3.0/packaging/fnos/README.md).+Electron remains **45.2.1**. Native fnOS packages are published separately by the+[protected fnOS publication workflow](https://github.com/agalwood/Motrix/actions/workflows/fnos-publish.yml)+after the formal release succeeds and both native architecture builds pass+package and lifecycle checks. The Release attachments use+`Motrix-2.3.0-fnos-x64.fpk` and `Motrix-2.3.0-fnos-arm64.fpk`, each with a+`.sha256` checksum file. Download the package matching your NAS architecture.+This is direct package distribution, not an app-store submission. Automated+lifecycle checks use a simulated fnOS file API; real-device compatibility still+requires installation testing. See the+[fnOS package guide](https://github.com/agalwood/Motrix/blob/main/packaging/fnos/README.md).## Upgrade compatibilitydiff --git a/docs/release-notes/2.3.0.zh-CN.md b/docs/release-notes/2.3.0.zh-CN.mdindex 39f297ea..778abbc5 100644--- a/docs/release-notes/2.3.0.zh-CN.md+++ b/docs/release-notes/2.3.0.zh-CN.md@@ -1,9 +1,9 @@# Motrix 2.3.0-[English](https://github.com/agalwood/Motrix/blob/v2.3.0/docs/release-notes/2.3.0.md) | 简体中文+[English](https://github.com/agalwood/Motrix/blob/main/docs/release-notes/2.3.0.md) | 简体中文Motrix 2.3.0 更新应用图标,恢复网盘目录下载,并完善 Motrix Server 的媒体工具和设置。-本版还引入飞牛 fnOS 原生集成,目前通过单独的测试构建提供。+本版还引入飞牛 fnOS 原生集成,并通过独立流程验证和发布安装包。## 相比 2.2.1 的变化@@ -21,11 +21,14 @@ Motrix 2.3.0 更新应用图标,恢复网盘目录下载,并完善 Motrix Se系统目录授权及服务生命周期检查。首版采用管理员共享实例:管理员共享任务和设置,普通用户无法访问;不提供按用户隔离任务的能力。-Electron 保持为 **45.2.1**。原生 fnOS FPK 是-[fnOS 工作流](https://github.com/agalwood/Motrix/actions/workflows/fnos.yml)生成的-**测试构建产物**,不是本次 GitHub Release 的附件,也不代表已经验证的应用商店上架。-仍需在真实设备上验证兼容性和安装行为,详见-[fnOS 打包指南](https://github.com/agalwood/Motrix/blob/v2.3.0/packaging/fnos/README.md)。+Electron 保持为 **45.2.1**。原生 fnOS 安装包由+[受保护的 fnOS 发布流程](https://github.com/agalwood/Motrix/actions/workflows/fnos-publish.yml)+单独发布,前提是正式发布成功,且两种架构均通过原生打包和生命周期检查。+Release 附件名为 `Motrix-2.3.0-fnos-x64.fpk` 和+`Motrix-2.3.0-fnos-arm64.fpk`,各附带一个 `.sha256` 校验文件。+请下载与 NAS 架构匹配的安装包。这是直接分发安装包,不代表应用商店上架。+自动化生命周期检查使用模拟的 fnOS 文件 API,真实设备兼容性仍需安装验证。+详见 [fnOS 打包指南](https://github.com/agalwood/Motrix/blob/main/packaging/fnos/README.md)。## 升级兼容性diff --git a/packaging/fnos/README.md b/packaging/fnos/README.mdindex 7c2e869e..01e677ac 100644--- a/packaging/fnos/README.md+++ b/packaging/fnos/README.md@@ -54,8 +54,24 @@ build; preparation never silently removes an existing output directory.`prepare:fnos` and `verify:fnos` can inspect cross-architecture payloads withoutexecuting them. They are not substitutes for the native build's smoke checks.-The `fnOS native FPK` workflow builds both architectures and uploads test-artifacts. It does not publish releases or submit packages to the app store.+The `fnOS native FPK` workflow builds both architectures for pull-request+validation and uploads test artifacts. Stable packages are distributed separately+by `Publish fnOS FPK` after a successful protected-tag `Build/Release` run.+The publication workflow builds the exact released commit on matching Linux+hardware, verifies both packages and their SHA-256 files, and adds the complete+set to the existing GitHub Release. It never overwrites a different existing+asset. This distribution does not submit packages to the fnOS app store.++For direct installation, download `Motrix-<version>-fnos-x64.fpk` for an x86 NAS+or `Motrix-<version>-fnos-arm64.fpk` for an ARM64 NAS, together with its `.sha256`+file, from the matching stable GitHub Release. Check the file before installing:++```sh+sha256sum -c Motrix-<version>-fnos-x64.fpk.sha256+```++The first native 2.3.0 packages are supplemented from the original `v2.3.0`+commit; the application tag and the other release assets remain unchanged.The locks use official Node SHASUMS256 and observed fnpack binary hashes. Atimplementation time the official fnpack page linked 1.2.3 binaries returningdiff --git a/scripts/fnos_publication.py b/scripts/fnos_publication.pynew file mode 100644index 00000000..7f724460--- /dev/null+++ b/scripts/fnos_publication.py@@ -0,0 +1,196 @@+#!/usr/bin/env python3+"""Verify stable fnOS publication provenance and immutable release assets."""+import hashlib+import io+import json+import os+from pathlib import Path+import re+import subprocess+import sys+import tarfile++REPOSITORY = 'agalwood/Motrix'+VERSION = re.compile(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\Z')+SHA = re.compile(r'[a-f0-9]{40}\Z')+++def run(*args):+ return subprocess.check_output(args, text=True).strip()+++def api(endpoint):+ return json.loads(run('gh', 'api', f'repos/{REPOSITORY}/{endpoint}'))+++def stable_version(tag):+ if not isinstance(tag, str) or not tag.startswith('v') or not VERSION.fullmatch(tag[1:]):+ raise ValueError('fnOS publication requires a strict stable v<major.minor.patch> tag')+ return tag[1:]+++def validate_run(value, tag, sha, workflow_id):+ if not (value.get('event') == 'push'+ and value.get('status') == 'completed'+ and value.get('conclusion') == 'success'+ and value.get('head_branch') == tag+ and value.get('head_sha') == sha+ and value.get('workflow_id') == workflow_id+ and value.get('path') == '.github/workflows/release.yml'+ and value.get('head_repository', {}).get('full_name') == REPOSITORY):+ raise ValueError('Missing successful protected-tag Build/Release provenance')+++def validate_release(value, tag):+ if value.get('tag_name') != tag or value.get('draft') is not False or value.get('prerelease') is not False:+ raise ValueError('Target must be an existing public stable GitHub Release')+++def source(tag, source_run_id=None):+ version = stable_version(tag)+ subprocess.run(['git', 'fetch', '--no-tags', 'origin',+ 'refs/heads/main:refs/remotes/origin/main'], check=True)+ subprocess.run(['git', 'fetch', '--no-tags', 'origin',+ f'refs/tags/{tag}:refs/remotes/origin/fnos-source-tag'], check=True)+ sha = run('git', 'rev-parse', 'refs/remotes/origin/fnos-source-tag^{commit}')+ if not SHA.fullmatch(sha):+ raise ValueError('Invalid source commit')+ subprocess.run(['git', 'merge-base', '--is-ancestor', sha, 'origin/main'], check=True)+ manifest = json.loads(run('git', 'show', f'{sha}:package.json'))+ if manifest.get('version') != version:+ raise ValueError('Tag and package version differ')+ workflow = api('actions/workflows/release.yml')+ if source_run_id:+ if not str(source_run_id).isdigit():+ raise ValueError('Invalid release workflow run ID')+ release_run = api(f'actions/runs/{source_run_id}')+ validate_run(release_run, tag, sha, workflow['id'])+ else:+ runs = api(f'actions/workflows/release.yml/runs?branch={tag}&event=push&status=success&per_page=100')['workflow_runs']+ release_run = None+ for candidate in runs:+ try:+ validate_run(candidate, tag, sha, workflow['id'])+ release_run = candidate+ break+ except ValueError:+ continue+ if release_run is None:+ raise ValueError('No successful formal release workflow for this exact tag and commit')+ validate_release(api(f'releases/tags/{tag}'), tag)+ return {'tag': tag, 'version': version, 'source_sha': sha,+ 'release_run_id': str(release_run['id'])}+++def preflight():+ if os.environ.get('GITHUB_REPOSITORY') != REPOSITORY:+ raise ValueError('Publication is restricted to the official repository')+ if os.environ.get('GITHUB_REF') != 'refs/heads/main' or os.environ.get('GITHUB_REF_PROTECTED') != 'true':+ raise ValueError('Publication tooling must run from protected main')+ event = json.loads(Path(os.environ['GITHUB_EVENT_PATH']).read_text())+ event_name = os.environ.get('GITHUB_EVENT_NAME')+ if event_name == 'workflow_run':+ triggering_run = event['workflow_run']+ tag = triggering_run.get('head_branch', '')+ # Beta releases have no native fnOS package version.+ if re.fullmatch(r'v(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)-beta\.(?:0|[1-9][0-9]*)', tag):+ return {'publish': 'false'}+ result = source(tag, triggering_run['id'])+ elif event_name == 'workflow_dispatch':+ result = source(event.get('inputs', {}).get('release_tag', ''))+ else:+ raise ValueError('Unsupported publication trigger')+ return {'publish': 'true', **result}+++def archive_file(archive, name, limit):+ matches = [m for m in archive.getmembers() if m.name.removeprefix('./') == name]+ if len(matches) != 1 or not matches[0].isfile() or not 0 < matches[0].size <= limit:+ raise ValueError(f'Invalid archive member: {name}')+ return archive.extractfile(matches[0]).read()+++def verify_bundle(directory, version):+ stable_version('v' + version)+ root = Path(directory)+ expected = {f'Motrix-{version}-fnos-{arch}.fpk{suffix}'+ for arch in ['x64', 'arm64'] for suffix in ['', '.sha256']}+ if {p.name for p in root.iterdir()} != expected:+ raise ValueError('Both exact architecture packages and checksums are required')+ results = []+ for arch, platform in [('x64', 'x86'), ('arm64', 'arm')]:+ name = f'Motrix-{version}-fnos-{arch}.fpk'+ package = root / name+ checksum = root / (name + '.sha256')+ if any(p.is_symlink() or not p.is_file() for p in [package, checksum]):+ raise ValueError('Release assets must be regular files')+ digest = hashlib.file_digest(package.open('rb'), 'sha256').hexdigest()+ if checksum.read_text() != f'{digest} {name}\n':+ raise ValueError('FPK checksum mismatch')+ # Read only bounded regular members; never extract archive paths to disk.+ with tarfile.open(package) as archive:+ manifest = dict(tuple(part.strip() for part in line.split('=', 1)) for line in archive_file(archive, 'manifest', 65536).decode().splitlines() if '=' in line)+ if manifest.get('appname') != 'motrix' or manifest.get('version') != version or manifest.get('platform') != platform:+ raise ValueError('FPK manifest version or architecture mismatch')+ payload = archive_file(archive, 'app.tgz', 1024 ** 3)+ with tarfile.open(fileobj=io.BytesIO(payload), mode='r:gz') as archive:+ receipt = json.loads(archive_file(archive, 'fnos-build.json', 65536))+ server = json.loads(archive_file(archive, 'server/package.json', 65536))+ if not (receipt.get('schemaVersion') == 2 and receipt.get('version') == version+ and receipt.get('packageVersion') == version and receipt.get('revision') == 0+ and receipt.get('arch') == arch and server.get('version') == version):+ raise ValueError('FPK build receipt differs from the approved version')+ results.append({'file': name, 'sha256': digest, 'arch': arch})+ return results+++def publish(directory, tag, sha, release_run_id):+ current = source(tag, release_run_id)+ if current['source_sha'] != sha:+ raise ValueError('Release tag changed since build preflight')+ records = verify_bundle(directory, current['version'])+ release = api(f'releases/tags/{tag}')+ files = sorted(Path(directory).iterdir())+ # Preflight every collision before uploading anything. Never replace assets.+ missing = []+ for file in files:+ matches = [a for a in release['assets'] if a['name'] == file.name]+ if len(matches) > 1:+ raise ValueError('Duplicate existing release asset')+ if not matches:+ missing.append(file)+ continue+ asset = matches[0]+ digest = 'sha256:' + hashlib.file_digest(file.open('rb'), 'sha256').hexdigest()+ if asset.get('size') != file.stat().st_size or asset.get('digest') != digest:+ raise ValueError(f'Existing immutable release asset differs: {file.name}')+ if missing:+ subprocess.run(['gh', 'release', 'upload', tag, '--repo', REPOSITORY,+ *map(str, missing)], check=True)+ published = api(f'releases/tags/{tag}')+ for file in files:+ asset = next(a for a in published['assets'] if a['name'] == file.name)+ digest = 'sha256:' + hashlib.file_digest(file.open('rb'), 'sha256').hexdigest()+ if asset.get('digest') != digest or asset['size'] != file.stat().st_size:+ raise ValueError('Published fnOS asset digest or size mismatch')+ print(json.dumps({'source': current, 'packages': records}, indent=2))+++def main():+ command = sys.argv[1]+ if command == 'preflight':+ outputs = preflight()+ with open(os.environ['GITHUB_OUTPUT'], 'a') as output:+ for key, value in outputs.items():+ output.write(f'{key}={value}\n')+ print(json.dumps(outputs))+ elif command == 'verify':+ print(json.dumps(verify_bundle(sys.argv[2], sys.argv[3])))+ elif command == 'publish':+ publish(*sys.argv[2:])+ else:+ raise ValueError('Unsupported command')+++if __name__ == '__main__':+ main()diff --git a/tests/scripts/fnos-publication.test.ts b/tests/scripts/fnos-publication.test.tsnew file mode 100644index 00000000..b5d74fe8--- /dev/null+++ b/tests/scripts/fnos-publication.test.ts@@ -0,0 +1,56 @@+import { spawnSync } from 'node:child_process'+import { readFileSync } from 'node:fs'+import { load } from 'js-yaml'+import { expect, it } from 'vitest'++it.skipIf(process.platform === 'win32')(+ 'publishes only complete, verified fnOS packages from an exact stable release',+ () => {+ const result = spawnSync(+ 'python3',+ ['tests/scripts/test_fnos_publication.py'],+ {+ encoding: 'utf8',+ env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1' },+ }+ )+ expect(result.status, result.stdout + result.stderr).toBe(0)+ }+)++it('isolates fnOS build credentials from protected publication', () => {+ const workflow = load(+ readFileSync('.github/workflows/fnos-publish.yml', 'utf8')+ ) as {+ permissions: Record<string, string>+ jobs: Record<+ string,+ {+ needs?: string[] | string+ permissions?: Record<string, string>+ environment?: string+ steps: {+ name?: string+ uses?: string+ with?: Record<string, unknown>+ }[]+ }+ >+ }+ expect(workflow.permissions.contents).toBe('read')+ expect(workflow.jobs.build.permissions).toBeUndefined()+ expect(workflow.jobs.publish.permissions?.contents).toBe('write')+ expect(workflow.jobs.publish.environment).toBe('github-release')+ expect(workflow.jobs.publish.needs).toEqual(['preflight', 'build'])+ const checkout = workflow.jobs.build.steps[0]+ // biome-ignore lint/suspicious/noTemplateCurlyInString: GitHub Actions expression, not JavaScript interpolation.+ expect(checkout.with?.ref).toBe('${{ needs.preflight.outputs.source_sha }}')+ expect(checkout.with?.['persist-credentials']).toBe(false)+ const artifacts = workflow.jobs.publish.steps.filter((step) =>+ step.uses?.startsWith('actions/download-artifact@')+ )+ expect(artifacts.map((step) => step.with?.name)).toEqual([+ 'fnos-release-x64',+ 'fnos-release-arm64',+ ])+})diff --git a/tests/scripts/test_fnos_publication.py b/tests/scripts/test_fnos_publication.pynew file mode 100644index 00000000..b4fbd023--- /dev/null+++ b/tests/scripts/test_fnos_publication.py@@ -0,0 +1,159 @@+import copy+import hashlib+import importlib.util+import io+import json+from pathlib import Path+import tarfile+import tempfile+import unittest+from unittest.mock import patch++spec = importlib.util.spec_from_file_location('fnos_publication', Path(__file__).resolve().parents[2] / 'scripts/fnos_publication.py')+pub = importlib.util.module_from_spec(spec)+spec.loader.exec_module(pub)+VERSION = '2.3.0'+TAG = 'v' + VERSION+SHA = 'a' * 40+RUN = {'id': 123, 'event': 'push', 'status': 'completed', 'conclusion': 'success',+ 'head_branch': TAG, 'head_sha': SHA, 'workflow_id': 456,+ 'path': '.github/workflows/release.yml', 'head_repository': {'full_name': pub.REPOSITORY}}+SOURCE = {'tag': TAG, 'version': VERSION, 'source_sha': SHA, 'release_run_id': '123'}+++def tar_bytes(files, mode='w'):+ out = io.BytesIO()+ with tarfile.open(fileobj=out, mode=mode) as archive:+ for name, value in files:+ data = value.encode() if isinstance(value, str) else value+ member = tarfile.TarInfo(name)+ member.size = len(data)+ archive.addfile(member, io.BytesIO(data))+ return out.getvalue()+++def fixture(root, arch, *, manifest_version=VERSION, receipt_arch=None, duplicate=False):+ name = f'Motrix-{VERSION}-fnos-{arch}.fpk'+ receipt = {'schemaVersion': 2, 'version': VERSION, 'packageVersion': VERSION,+ 'revision': 0, 'arch': receipt_arch or arch}+ app = tar_bytes([('./fnos-build.json', json.dumps(receipt)),+ ('./server/package.json', json.dumps({'version': VERSION}))], 'w:gz')+ files = [('manifest', f'appname = motrix\nversion = {manifest_version}\nplatform = {"x86" if arch == "x64" else "arm"}\n'), ('app.tgz', app)]+ if duplicate:+ files.append(files[0])+ data = tar_bytes(files)+ (root / name).write_bytes(data)+ (root / (name + '.sha256')).write_text(f'{hashlib.sha256(data).hexdigest()} {name}\n')+++def assets(root):+ return [{'name': p.name, 'size': p.stat().st_size,+ 'digest': 'sha256:' + hashlib.sha256(p.read_bytes()).hexdigest()} for p in root.iterdir()]+++class PublicationTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ for arch in ['x64', 'arm64']:+ fixture(self.root, arch)++ def test_strict_stable_only(self):+ self.assertEqual(pub.stable_version(TAG), VERSION)+ for tag in ['2.3.0', 'v02.3.0', 'v2.3.0-beta.1', 'v2.3.0+build', 'v2.3.0\n', 'v2.3.0;echo hi']:+ with self.subTest(tag=tag), self.assertRaises(ValueError):+ pub.stable_version(tag)++ def test_exact_successful_formal_run(self):+ pub.validate_run(RUN, TAG, SHA, 456)+ for field, value in [('event', 'workflow_dispatch'), ('status', 'in_progress'),+ ('conclusion', 'failure'), ('head_branch', 'v2.2.1'),+ ('head_sha', 'b' * 40), ('workflow_id', 999),+ ('path', '.github/workflows/fnos.yml'),+ ('head_repository', {'full_name': 'fork/Motrix'})]:+ with self.subTest(field=field), self.assertRaises(ValueError):+ pub.validate_run({**RUN, field: value}, TAG, SHA, 456)++ def test_public_stable_release_required(self):+ value = {'tag_name': TAG, 'draft': False, 'prerelease': False}+ pub.validate_release(value, TAG)+ for field, val in [('tag_name', 'v2.2.1'), ('draft', True), ('prerelease', True)]:+ with self.subTest(field=field), self.assertRaises(ValueError):+ pub.validate_release({**value, field: val}, TAG)++ def test_exact_dual_architecture_bundle(self):+ self.assertEqual([v['arch'] for v in pub.verify_bundle(self.root, VERSION)], ['x64', 'arm64'])++ def test_partial_bundle_rejected(self):+ (self.root / 'Motrix-2.3.0-fnos-arm64.fpk').unlink()+ with self.assertRaisesRegex(ValueError, 'Both exact'):+ pub.verify_bundle(self.root, VERSION)++ def test_extra_asset_rejected(self):+ (self.root / 'unverified.fpk').write_bytes(b'bad')+ with self.assertRaisesRegex(ValueError, 'Both exact'):+ pub.verify_bundle(self.root, VERSION)++ def test_checksum_tampering_rejected(self):+ (self.root / 'Motrix-2.3.0-fnos-x64.fpk').write_bytes(b'changed')+ with self.assertRaisesRegex(ValueError, 'checksum'):+ pub.verify_bundle(self.root, VERSION)++ def test_wrong_manifest_version_rejected_even_with_valid_checksum(self):+ fixture(self.root, 'arm64', manifest_version='2.2.1')+ with self.assertRaisesRegex(ValueError, 'manifest'):+ pub.verify_bundle(self.root, VERSION)++ def test_wrong_embedded_architecture_rejected(self):+ fixture(self.root, 'arm64', receipt_arch='x64')+ with self.assertRaisesRegex(ValueError, 'receipt'):+ pub.verify_bundle(self.root, VERSION)++ def test_duplicate_manifest_rejected(self):+ fixture(self.root, 'x64', duplicate=True)+ with self.assertRaisesRegex(ValueError, 'archive member'):+ pub.verify_bundle(self.root, VERSION)++ def test_symlink_rejected(self):+ p = self.root / 'Motrix-2.3.0-fnos-arm64.fpk'+ data = p.read_bytes()+ p.unlink()+ target = self.root.parent / (self.root.name + '-target')+ target.write_bytes(data)+ self.addCleanup(target.unlink)+ p.symlink_to(target)+ with self.assertRaisesRegex(ValueError, 'regular files'):+ pub.verify_bundle(self.root, VERSION)++ def test_moved_tag_aborts_before_any_upload(self):+ with patch.object(pub, 'source', return_value={**SOURCE, 'source_sha': 'b' * 40}), patch.object(pub.subprocess, 'run') as mutation:+ with self.assertRaisesRegex(ValueError, 'tag changed'):+ pub.publish(self.root, TAG, SHA, '123')+ mutation.assert_not_called()++ def test_existing_different_asset_never_overwritten(self):+ existing = assets(self.root)+ existing[0]['digest'] = 'sha256:' + '0' * 64+ with patch.object(pub, 'source', return_value=SOURCE), patch.object(pub, 'api', return_value={'assets': existing}), patch.object(pub.subprocess, 'run') as mutation:+ with self.assertRaisesRegex(ValueError, 'immutable'):+ pub.publish(self.root, TAG, SHA, '123')+ mutation.assert_not_called()++ def test_retry_reuses_identical_assets(self):+ with patch.object(pub, 'source', return_value=SOURCE), patch.object(pub, 'api', return_value={'assets': assets(self.root)}), patch.object(pub.subprocess, 'run') as mutation:+ pub.publish(self.root, TAG, SHA, '123')+ mutation.assert_not_called()++ def test_publish_adds_only_missing_verified_assets(self):+ existing = assets(self.root)+ with patch.object(pub, 'source', return_value=SOURCE), patch.object(pub, 'api', side_effect=[{'assets': existing[:1]}, {'assets': existing}]), patch.object(pub.subprocess, 'run') as mutation:+ pub.publish(self.root, TAG, SHA, '123')+ command = mutation.call_args.args[0]+ self.assertNotIn('--clobber', command)+ self.assertEqual(len(command[6:]), 3)+ self.assertNotIn(str(self.root / existing[0]['name']), command)+++if __name__ == '__main__':+ unittest.main()