Skip to content

A full-featured download manager.

feat(ffmpeg): add verified one-click installation (#2299)

Dr_rOot4e7fc18f2c4a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ff52ce9f..6f0b4d18 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -221,6 +221,17 @@ jobs:
- name: Type-check (root)
run: pnpm exec tsc --noEmit
+ - name: Verified FFmpeg installation contracts
+ run: >-
+ pnpm exec vitest run
+ src/core/ffmpeg/verified-install.test.ts
+ src/core/plugin/capabilities/ffmpeg.test.ts
+ src/main/plugin/ffmpeg-fetch-electron.test.ts
+ src/main/plugin/ffmpeg-macos-trust.test.ts
+ src/main/plugin/ffmpeg-probe-managed.test.ts
+ src/main/plugin/ffmpeg-probe-electron.test.ts
+ src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx
+
- name: Tests (root)
# Temporarily non-blocking. Known pre-existing failures (unrelated to
# Plan G — all confirmed on main):
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 042e5726..c3eb5762 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -898,7 +898,7 @@ jobs:
EXPECTED_COMMIT: ${{ github.sha }}
EXPECTED_PLATFORM: ${{ matrix.platform }}
# Updated only after reviewing the verifier source itself.
- VERIFIER_SHA256: efafa6f55cb39d854bdde01a031862dd6ae14ff890ef17175680508317a8e730
+ VERIFIER_SHA256: 4d85e46f0a1e5c1df740dcf0aa8509151ba4c7e673a904398e7f538734e552fe
run: |
const crypto = require('node:crypto')
const fs = require('node:fs')
diff --git a/e2e/media-settings.spec.ts b/e2e/media-settings.spec.ts
index 56d803fd..bf8a82f8 100644
--- a/e2e/media-settings.spec.ts
+++ b/e2e/media-settings.spec.ts
@@ -1,6 +1,71 @@
+import { readFile } from 'node:fs/promises'
+import path from 'node:path'
import { expect, test } from './fixtures/electron-app'
test.describe('media settings', () => {
+ test('downloads, verifies and installs the public FFmpeg release through the desktop UI', async ({
+ mainWindow,
+ userDataDir,
+ }, testInfo) => {
+ test.skip(
+ process.env.MOTRIX_FFMPEG_PUBLIC_RELEASE_TEST !== '1' ||
+ process.platform !== 'darwin',
+ 'Explicit macOS-only public Release acceptance'
+ )
+ test.setTimeout(600_000)
+ await mainWindow
+ .getByRole('link', { name: 'Settings', exact: true })
+ .click()
+ await mainWindow.getByText('Integration', { exact: true }).first().click()
+ const card = mainWindow.getByTestId('media-detection-card')
+ await card.scrollIntoViewIfNeeded()
+ await card.getByRole('button', { name: 'Download FFmpeg' }).click()
+ await expect(
+ card.getByText(/Apple’s online notarization ticket/)
+ ).toBeVisible()
+ await card.getByRole('button', { name: 'Download and verify' }).click()
+ await expect(
+ card.getByRole('button', { name: 'Verifying…' })
+ ).toBeDisabled()
+ const terminalStatus = card.getByRole('status').filter({
+ hasText: /Verified and installed\.|Download or verification failed/,
+ })
+ await expect(terminalStatus).toBeVisible({ timeout: 580_000 })
+ if (
+ !(await terminalStatus.textContent())?.includes('Verified and installed.')
+ ) {
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('ffmpeg-failed.png'),
+ })
+ }
+ expect(await terminalStatus.textContent()).toContain(
+ 'Verified and installed.'
+ )
+ await expect(
+ card.getByText(
+ 'Restart Motrix for active plugins to detect the installation.'
+ )
+ ).toBeVisible()
+ const receipt = JSON.parse(
+ await readFile(
+ path.join(userDataDir, 'ffmpeg-verified', 'current.json'),
+ 'utf8'
+ )
+ )
+ await expect(
+ card.getByText(`FFmpeg ${receipt.releaseVersion.split('-motrix.')[0]}`, {
+ exact: true,
+ })
+ ).toBeVisible({ timeout: 120_000 })
+ await expect(
+ card.getByText(
+ new RegExp(`${receipt.manifestHash}-darwin-${process.arch}`)
+ )
+ ).toBeVisible()
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('verified-ffmpeg-install.png'),
+ })
+ })
test('shows detection status and saves a manual path', async ({
mainWindow,
}) => {
diff --git a/scripts/electron-package-size-budgets.json b/scripts/electron-package-size-budgets.json
index 929855f4..d4380708 100644
--- a/scripts/electron-package-size-budgets.json
+++ b/scripts/electron-package-size-budgets.json
@@ -1,6 +1,6 @@
{
"schemaVersion": 1,
- "payloadBytes": 26279936,
+ "payloadBytes": 26476544,
"betterSqlite3Bytes": 4194304,
"unexpectedPackageNames": 0,
"foreignBetterSqlite3Prebuilds": 0,
diff --git a/scripts/release-signing-input.mjs b/scripts/release-signing-input.mjs
index 8ba7e0a7..8e65b32f 100644
--- a/scripts/release-signing-input.mjs
+++ b/scripts/release-signing-input.mjs
@@ -67,7 +67,7 @@ const TRUSTED_INPUT_SHA256 = Object.freeze({
'signing-tool/package-lock.json':
'8fa0825cd7a7605cab5cfc4d77357b3f29452b12abe64e51851796d04406b1e6',
'scripts/electron-package-size-budgets.json':
- '64e4646581c981632858d8b7fa4c0dbd248e9f3d9e6c3d929aadf682a07a6be7',
+ '7c75adea3a6abf8958160534229cf3e46e9d32208312a20f707fa989bf422ec6',
'scripts/electron-package-utils.mjs':
'9d408f9edc91182be5d5aed39f2c5a5d20f5523e08d9c08e630c23c66302daa8',
'scripts/before-build-use-staged-dependencies.mjs':
diff --git a/src/core/ffmpeg/verified-install.test.ts b/src/core/ffmpeg/verified-install.test.ts
new file mode 100644
index 00000000..c337e39d
--- /dev/null
+++ b/src/core/ffmpeg/verified-install.test.ts
@@ -0,0 +1,870 @@
+// @vitest-environment node
+import { sign } from 'node:crypto'
+import {
+ link,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { gzipSync } from 'node:zlib'
+import certificate from '@shared/config/ffmpeg-macos-certificate.json'
+import {
+ FFMPEG_SIGNATURE_DOMAIN,
+ FFMPEG_WINDOWS_LICENSE,
+ type FfmpegPlatform,
+} from '@shared/schemas/ffmpeg-release'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ assertManagedFfmpegTrusted,
+ extractVerifiedFfmpeg,
+ getFfmpegInstallStatus,
+ installVerifiedFfmpeg,
+ resolveManagedFfmpegCandidate,
+} from './verified-install'
+import {
+ compareFfmpegReleases,
+ sha256,
+ verifyFfmpegRelease,
+} from './verified-release'
+
+// A distinct, ephemeral test root. Production private keys never enter fixtures.
+const testKeys = await vi.hoisted(async () => {
+ const crypto = await import('node:crypto')
+ const pair = crypto.generateKeyPairSync('ed25519')
+ const der = pair.publicKey.export({ type: 'spki', format: 'der' })
+ return {
+ privateKey: pair.privateKey,
+ publicKey: pair.publicKey
+ .export({ type: 'spki', format: 'pem' })
+ .toString(),
+ keyId: `sha256:${crypto.createHash('sha256').update(der).digest('hex')}`,
+ }
+})
+vi.mock('@shared/config/ffmpeg-release-key.json', () => ({ default: testKeys }))
+
+function crc32(data: Buffer) {
+ let crc = 0xffffffff
+ for (const byte of data) {
+ crc ^= byte
+ for (let bit = 0; bit < 8; bit += 1)
+ crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0)
+ }
+ return (crc ^ 0xffffffff) >>> 0
+}
+function zip(
+ entries: Array<{
+ name: string
+ data: Buffer
+ mode?: number
+ declaredSize?: number
+ }>
+) {
+ const local: Buffer[] = []
+ const central: Buffer[] = []
+ let offset = 0
+ for (const entry of entries) {
+ const name = Buffer.from(entry.name)
+ const header = Buffer.alloc(30)
+ header.writeUInt32LE(0x04034b50)
+ header.writeUInt16LE(20, 4)
+ header.writeUInt32LE(crc32(entry.data), 14)
+ header.writeUInt32LE(entry.data.length, 18)
+ header.writeUInt32LE(entry.declaredSize ?? entry.data.length, 22)
+ header.writeUInt16LE(name.length, 26)
+ const record = Buffer.alloc(46)
+ record.writeUInt32LE(0x02014b50)
+ record.writeUInt16LE(0x0314, 4)
+ record.writeUInt16LE(20, 6)
+ record.writeUInt32LE(crc32(entry.data), 16)
+ record.writeUInt32LE(entry.data.length, 20)
+ record.writeUInt32LE(entry.declaredSize ?? entry.data.length, 24)
+ record.writeUInt16LE(name.length, 28)
+ record.writeUInt32LE(((entry.mode ?? 0x81a4) * 65536) >>> 0, 38)
+ record.writeUInt32LE(offset, 42)
+ local.push(header, name, entry.data)
+ central.push(record, name)
+ offset += header.length + name.length + entry.data.length
+ }
+ const end = Buffer.alloc(22)
+ end.writeUInt32LE(0x06054b50)
+ end.writeUInt16LE(entries.length, 8)
+ end.writeUInt16LE(entries.length, 10)
+ end.writeUInt32LE(Buffer.concat(central).length, 12)
+ end.writeUInt32LE(offset, 16)
+ return Buffer.concat([...local, ...central, end])
+}
+function pe(arch: 'x64' | 'arm64') {
+ const bytes = Buffer.alloc(512)
+ bytes.write('MZ')
+ bytes.writeUInt32LE(64, 60)
+ bytes.writeUInt32LE(0x00004550, 64)
+ bytes.writeUInt16LE(arch === 'x64' ? 0x8664 : 0xaa64, 68)
+ bytes.writeUInt16LE(240, 84)
+ bytes.writeUInt16LE(0x20b, 88)
+ return bytes
+}
+function nativeBinary(platform: FfmpegPlatform, arch: 'x64' | 'arm64') {
+ if (platform === 'win32') return pe(arch)
+ const bytes = Buffer.alloc(512)
+ if (platform === 'darwin') {
+ bytes.writeUInt32LE(0xfeedfacf, 0)
+ bytes.writeUInt32LE(arch === 'arm64' ? 0x0100000c : 0x01000007, 4)
+ bytes.writeUInt32LE(2, 12)
+ } else {
+ Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1]).copy(bytes)
+ bytes.writeUInt16LE(2, 16)
+ bytes.writeUInt16LE(arch === 'arm64' ? 183 : 62, 18)
+ }
+ return bytes
+}
+function tar(
+ entries: Array<{ name: string; data: Buffer; type?: string; mode?: number }>
+) {
+ const records: Buffer[] = []
+ for (const entry of entries) {
+ const header = Buffer.alloc(512)
+ header.write(entry.name, 0, 100)
+ const number = (value: number, offset: number, size: number) =>
+ header.write(value.toString(8).padStart(size - 1, '0'), offset, size - 1)
+ number(
+ entry.mode ??
+ (entry.name === 'ffmpeg' || entry.name === 'ffprobe' ? 0o755 : 0o644),
+ 100,
+ 8
+ )
+ number(0, 108, 8)
+ number(0, 116, 8)
+ number(entry.data.length, 124, 12)
+ number(0, 136, 12)
+ header.fill(32, 148, 156)
+ header.write(entry.type ?? '0', 156)
+ header.write('ustar\0', 257)
+ header.write('00', 263)
+ number(
+ header.reduce((sum, byte) => sum + byte, 0),
+ 148,
+ 7
+ )
+ header[155] = 32
+ records.push(
+ header,
+ entry.data,
+ Buffer.alloc((512 - (entry.data.length % 512)) % 512)
+ )
+ }
+ return gzipSync(Buffer.concat([...records, Buffer.alloc(1024)]))
+}
+function fixture(
+ version = '9.0.2-motrix.8',
+ arch: 'x64' | 'arm64' = 'x64',
+ platform: FfmpegPlatform = 'win32',
+ additionalManifest: Record<string, unknown> = {}
+) {
+ const licenseFiles = [
+ { path: 'LICENSES/GPL.txt', sha256: sha256(Buffer.from('license')) },
+ ]
+ const inventory = Buffer.from(
+ JSON.stringify({
+ schemaVersion: 2,
+ target: `${platform}-${arch}`,
+ files: licenseFiles,
+ })
+ )
+ const files = new Map([
+ [
+ platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg',
+ nativeBinary(platform, arch),
+ ],
+ [
+ platform === 'win32' ? 'ffprobe.exe' : 'ffprobe',
+ nativeBinary(platform, arch),
+ ],
+ ['BUILD-INFO.json', Buffer.from('{}')],
+ ['LICENSES.json', inventory],
+ ['configure.txt', Buffer.from('--enable-gpl')],
+ ['README.txt', Buffer.from('readme')],
+ ['LICENSES/GPL.txt', Buffer.from('license')],
+ ])
+ const entries = [...files].map(([name, data]) => ({ name, data }))
+ const archive = platform === 'linux' ? tar(entries) : zip(entries)
+ const target = {
+ schemaVersion: 2 as const,
+ releaseVersion: version,
+ target: `${platform}-${arch}`,
+ platform,
+ arch,
+ minimumOs: {
+ name: { darwin: 'macos', win32: 'windows', linux: 'linux' }[platform],
+ version:
+ platform === 'darwin' ? '12.0' : platform === 'win32' ? '10.0' : '4.18',
+ },
+ license:
+ platform === 'win32'
+ ? FFMPEG_WINDOWS_LICENSE
+ : FFMPEG_WINDOWS_LICENSE.split(' AND (Apache-2.0')[0] +
+ (platform === 'linux'
+ ? ' AND 0BSD AND SunPro AND (GPL-3.0-or-later WITH GCC-exception-3.1)'
+ : ''),
+ archive: `ffmpeg-${version}-${platform}-${arch}.${platform === 'linux' ? 'tar.gz' : 'zip'}`,
+ archiveSha256: sha256(archive),
+ archiveSize: archive.length,
+ binaryPath:
+ platform === 'win32' ? ('ffmpeg.exe' as const) : ('ffmpeg' as const),
+ binarySha256: sha256(nativeBinary(platform, arch)),
+ ffprobePath:
+ platform === 'win32' ? ('ffprobe.exe' as const) : ('ffprobe' as const),
+ ffprobeSha256: sha256(nativeBinary(platform, arch)),
+ buildInfoSha256: sha256(Buffer.from('{}')),
+ configureSha256: sha256(Buffer.from('--enable-gpl')),
+ licensesSha256: sha256(inventory),
+ signing: null,
+ signingEvidenceSha256: null,
+ licenseFiles,
+ }
+ const metadataFor = (name: string) => {
+ if (name === target.target) return target
+ const [otherPlatform, otherArch] = name.split('-') as [
+ FfmpegPlatform,
+ 'x64' | 'arm64',
+ ]
+ return {
+ ...target,
+ target: name,
+ platform: otherPlatform,
+ arch: otherArch,
+ archive: `ffmpeg-${version}-${name}.${otherPlatform === 'linux' ? 'tar.gz' : 'zip'}`,
+ binaryPath: otherPlatform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg',
+ ffprobePath: otherPlatform === 'win32' ? 'ffprobe.exe' : 'ffprobe',
+ binarySha256: sha256(nativeBinary(otherPlatform, otherArch)),
+ ffprobeSha256: sha256(nativeBinary(otherPlatform, otherArch)),
+ minimumOs: {
+ name: { darwin: 'macos', win32: 'windows', linux: 'linux' }[
+ otherPlatform
+ ],
+ version:
+ otherPlatform === 'darwin'
+ ? '12.0'
+ : otherPlatform === 'win32'
+ ? '10.0'
+ : '4.18',
+ },
+ license:
+ otherPlatform === 'win32'
+ ? FFMPEG_WINDOWS_LICENSE
+ : FFMPEG_WINDOWS_LICENSE.split(' AND (Apache-2.0')[0] +
+ (otherPlatform === 'linux'
+ ? ' AND 0BSD AND SunPro AND (GPL-3.0-or-later WITH GCC-exception-3.1)'
+ : ''),
+ }
+ }
+ const allTargets = [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64',
+ 'linux-x64',
+ 'win32-arm64',
+ 'win32-x64',
+ ]
+ .map(metadataFor)
+ .map((item) => {
+ if (item.platform !== 'darwin') return item
+ return {
+ ...item,
+ signingEvidenceSha256: 'a'.repeat(64),
+ signing: {
+ schemaVersion: 3,
+ target: item.target,
+ platform: 'darwin',
+ kind: 'apple-developer-id',
+ identity: {
+ teamId: 'TESTTEAM01',
+ subject: 'Developer ID Application: Test (TESTTEAM01)',
+ certificateSha256: certificate.certificateSha256,
+ },
+ binaries: Object.fromEntries(
+ ['ffmpeg', 'ffprobe'].map((name) => [
+ name,
+ {
+ sha256: item.binarySha256,
+ cdHash: 'a'.repeat(40),
+ timestamp: '2026-09-30T12:00:00Z',
+ hardenedRuntime: true,
+ },
+ ])
+ ),
+ notarization: {
+ submissionId: '00000000-0000-4000-8000-000000000000',
+ status: 'Accepted',
+ submissionResultSha256: 'a'.repeat(64),
+ developerLog: {
+ name: `ffmpeg-${version}-${item.target}.notarization-log.json`,
+ sha256: 'a'.repeat(64),
+ size: 10,
+ },
+ },
+ },
+ }
+ })
+ const selected = allTargets.find((item) => item.target === target.target)!
+ const manifest = {
+ schemaVersion: 3,
+ repository: 'motrixapp/ffmpeg-static',
+ windowsTrust: 'motrix-ed25519',
+ formalRelease: true,
+ releaseVersion: version,
+ releaseTag: `v${version}`,
+ releaseCommit: 'a'.repeat(40),
+ controlCommit: 'a'.repeat(40),
+ profile: 'motrix-full-gpl',
+ targets: allTargets,
+ ...additionalManifest,
+ }
+ const raw = Buffer.from(JSON.stringify(manifest))
+ const signature = sign(
+ null,
+ Buffer.concat([Buffer.from(FFMPEG_SIGNATURE_DOMAIN), raw]),
+ testKeys.privateKey
+ )
+ const envelope = Buffer.from(
+ JSON.stringify({
+ schemaVersion: 1,
+ algorithm: 'Ed25519',
+ keyId: testKeys.keyId,
+ signature: signature.toString('base64'),
+ })
+ )
+ const fetcher = vi.fn<typeof fetch>(async (input) => {
+ const url = String(input)
+ if (url.endsWith('/latest'))
+ return new Response(
+ JSON.stringify({
+ tag_name: `v${version}`,
+ draft: false,
+ prerelease: false,
+ immutable: true,
+ published_at: '2026-10-01T01:00:00Z',
+ html_url: `https://github.com/motrixapp/ffmpeg-static/releases/tag/v${version}`,
+ assets: [
+ { name: 'ffmpeg-manifest.json', size: raw.length },
+ { name: 'ffmpeg-manifest.json.sig', size: envelope.length },
+ ...allTargets.map((item) => ({
+ name: item.archive,
+ size: item.archiveSize,
+ })),
+ ].map((item, index) => ({
+ ...item,
+ id: index + 1,
+ state: 'uploaded',
+ browser_download_url: `https://github.com/motrixapp/ffmpeg-static/releases/download/v${version}/${item.name}`,
+ })),
+ })
+ )
+ if (url.endsWith('.json.sig')) return new Response(envelope)
+ if (url.endsWith('ffmpeg-manifest.json')) return new Response(raw)
+ if (url.endsWith(target.archive)) return new Response(archive)
+ throw new Error('Unexpected URL')
+ })
+ return {
+ raw,
+ envelope,
+ archive,
+ target: selected as import('@shared/schemas/ffmpeg-release').FfmpegTarget,
+ entries,
+ fetcher,
+ }
+}
+const directories: string[] = []
+async function temp() {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'motrix-ffmpeg-test-'))
+ directories.push(dir)
+ return dir
+}
+afterEach(async () => {
+ await Promise.all(
+ directories
+ .splice(0)
+ .map((dir) => rm(dir, { recursive: true, force: true }))
+ )
+})
+
+describe('verified FFmpeg releases', () => {
+ it.each(['root', 'releases', 'version'])(
+ 'rejects a managed %s directory symlink before creating or writing its target',
+ async (component) => {
+ const userDataDir = await temp()
+ const outside = await temp()
+ const release = fixture()
+ const root = path.join(userDataDir, 'ffmpeg-verified')
+ let linkPath = root
+ if (component !== 'root') {
+ await mkdir(root, { mode: 0o700 })
+ linkPath = path.join(root, 'releases')
+ }
+ if (component === 'version') {
+ await mkdir(linkPath, { mode: 0o700 })
+ linkPath = path.join(linkPath, `${sha256(release.raw)}-win32-x64`)
+ }
+ await symlink(
+ outside,
+ linkPath,
+ process.platform === 'win32' ? 'junction' : 'dir'
+ )
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: release.fetcher,
+ })
+ ).rejects.toThrow()
+ expect(await readdir(outside)).toEqual([])
+ expect(getFfmpegInstallStatus(userDataDir).error).toBe('install')
+ if (component !== 'version')
+ expect(release.fetcher).not.toHaveBeenCalled()
+ else
+ expect(
+ release.fetcher.mock.calls.some(([url]) =>
+ String(url).endsWith(release.target.archive)
+ )
+ ).toBe(false)
+ }
+ )
+ it('reports an invalid installation root as an install error, not a download failure', async () => {
+ const userDataDir = await temp()
+ await writeFile(
+ path.join(userDataDir, 'ffmpeg-verified'),
+ 'not a directory'
+ )
+ const fetcher = fixture().fetcher
+ await expect(
+ installVerifiedFfmpeg({ userDataDir, arch: 'x64', fetcher })
+ ).rejects.toThrow()
+ expect(getFfmpegInstallStatus(userDataDir).error).toBe('install')
+ expect(fetcher).not.toHaveBeenCalled()
+ })
+ it('rejects a signed same-version replacement and tampered reused files without changing the pointer', async () => {
+ const userDataDir = await temp()
+ const release = fixture()
+ await installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: release.fetcher,
+ })
+ const pointer = path.join(userDataDir, 'ffmpeg-verified', 'current.json')
+ const before = await readFile(pointer)
+ const replacement = fixture(undefined, 'x64', 'win32', {
+ extra: 'same version substitution',
+ })
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: replacement.fetcher,
+ })
+ ).rejects.toThrow()
+ expect(await readFile(pointer)).toEqual(before)
+ const directory =
+ getFfmpegInstallStatus(userDataDir).directory ??
+ path.join(
+ userDataDir,
+ 'ffmpeg-verified',
+ 'releases',
+ `${sha256(release.raw)}-win32-x64`
+ )
+ await writeFile(path.join(directory, 'ffprobe.exe'), 'tampered')
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: release.fetcher,
+ })
+ ).rejects.toThrow()
+ expect(await readFile(pointer)).toEqual(before)
+ })
+ it.each([
+ ['darwin', 'x64'],
+ ['darwin', 'arm64'],
+ ['linux', 'x64'],
+ ['linux', 'arm64'],
+ ] as const)(
+ 'installs %s-%s without executing payloads and emits bounded phase progress',
+ async (platform, arch) => {
+ const userDataDir = await temp()
+ const release = fixture(undefined, arch, platform)
+ const systemTrust = vi.fn(async () => {})
+ const onStatus = vi.fn()
+ await installVerifiedFfmpeg({
+ userDataDir,
+ platform,
+ arch,
+ fetcher: release.fetcher,
+ systemTrust,
+ onStatus,
+ })
+ const binary = resolveManagedFfmpegCandidate(
+ userDataDir,
+ path.join(userDataDir, 'binaries', 'ffmpeg'),
+ platform
+ )
+ assertManagedFfmpegTrusted(userDataDir, binary)
+ expect(getFfmpegInstallStatus(userDataDir)).toMatchObject({
+ phase: 'installed',
+ directory: path.dirname(binary),
+ })
+ const phases = onStatus.mock.calls.map(([status]) => status.phase)
+ expect(phases).toContain('downloading')
+ expect(phases).toContain('extracting')
+ expect(phases.at(-1)).toBe('installed')
+ expect(systemTrust).toHaveBeenCalledTimes(platform === 'darwin' ? 1 : 0)
+ }
+ )
+ it('requires macOS system trust and preserves the old version on rejection', async () => {
+ const userDataDir = await temp()
+ const original = fixture(undefined, 'arm64', 'darwin')
+ await installVerifiedFfmpeg({
+ userDataDir,
+ platform: 'darwin',
+ arch: 'arm64',
+ fetcher: original.fetcher,
+ systemTrust: async () => {},
+ })
+ const pointer = path.join(userDataDir, 'ffmpeg-verified', 'current.json')
+ const before = await readFile(pointer)
+ const next = fixture('9.0.2-motrix.9', 'arm64', 'darwin')
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ platform: 'darwin',
+ arch: 'arm64',
+ fetcher: next.fetcher,
+ })
+ ).rejects.toThrow()
+ expect(getFfmpegInstallStatus(userDataDir).error).toBe('systemTrust')
+ expect(await readFile(pointer)).toEqual(before)
+ })
+ it('rechecks the actual reused macOS directory and keeps its pointer on trust rejection', async () => {
+ const userDataDir = await temp()
+ const release = fixture(undefined, 'arm64', 'darwin')
+ const firstTrust = vi.fn(async () => {})
+ await installVerifiedFfmpeg({
+ userDataDir,
+ platform: 'darwin',
+ arch: 'arm64',
+ fetcher: release.fetcher,
+ systemTrust: firstTrust,
+ })
+ const installedDirectory = getFfmpegInstallStatus(userDataDir).directory
+ const pointer = path.join(userDataDir, 'ffmpeg-verified', 'current.json')
+ const before = await readFile(pointer)
+ const reusedTrust = vi.fn(async (directory: string) => {
+ if (directory === installedDirectory)
+ throw new Error('reused directory no longer passes Gatekeeper')
+ })
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ platform: 'darwin',
+ arch: 'arm64',
+ fetcher: release.fetcher,
+ systemTrust: reusedTrust,
+ })
+ ).rejects.toThrow()
+ expect(reusedTrust).toHaveBeenCalledTimes(2)
+ expect(reusedTrust.mock.calls[0][0]).not.toBe(installedDirectory)
+ expect(reusedTrust.mock.calls[1][0]).toBe(installedDirectory)
+ expect(getFfmpegInstallStatus(userDataDir).error).toBe('systemTrust')
+ expect(await readFile(pointer)).toEqual(before)
+ })
+ it('does not let a failing progress observer change the atomic installation outcome', async () => {
+ const userDataDir = await temp()
+ const release = fixture()
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: release.fetcher,
+ onStatus: () => {
+ throw new Error('observer failed')
+ },
+ })
+ ).resolves.toMatchObject({ ok: true })
+ expect(getFfmpegInstallStatus(userDataDir).phase).toBe('installed')
+ })
+ it.each([
+ 'draft',
+ 'prerelease',
+ 'mutable',
+ 'wrong-repo',
+ 'missing-asset',
+ 'wrong-size',
+ 'wrong-url',
+ 'duplicate-asset',
+ ])('rejects %s Release metadata before installing', async (kind) => {
+ const userDataDir = await temp()
+ const release = fixture()
+ const fetcher = release.fetcher.getMockImplementation()!
+ release.fetcher.mockImplementation(async (...args) => {
+ const response = await fetcher(...args)
+ if (!String(args[0]).endsWith('/latest')) return response
+ const meta = await response.json()
+ if (kind === 'draft') meta.draft = true
+ if (kind === 'prerelease') meta.prerelease = true
+ if (kind === 'mutable') meta.immutable = false
+ if (kind === 'wrong-repo')
+ meta.html_url = meta.html_url.replace('motrixapp/', 'evil/')
+ if (kind === 'missing-asset') meta.assets.pop()
+ if (kind === 'wrong-size') meta.assets[0].size++
+ if (kind === 'wrong-url')
+ meta.assets[0].browser_download_url = 'https://evil.test/manifest'
+ if (kind === 'duplicate-asset') meta.assets.push(meta.assets[0])
+ return new Response(JSON.stringify(meta))
+ })
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: release.fetcher,
+ })
+ ).rejects.toThrow()
+ expect(getFfmpegInstallStatus(userDataDir).phase).toBe('failed')
+ })
+ it('rejects missing formal Releases, concurrent installs, and oversized streaming responses', async () => {
+ const userDataDir = await temp()
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: vi.fn(async () => new Response(null, { status: 404 })),
+ })
+ ).rejects.toThrow()
+ expect(getFfmpegInstallStatus(userDataDir).error).toBe('unavailable')
+ let releaseResponse!: (value: Response) => void
+ const waiting = installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: vi.fn(
+ () =>
+ new Promise<Response>((resolve) => {
+ releaseResponse = resolve
+ })
+ ),
+ })
+ await expect(
+ installVerifiedFfmpeg({ userDataDir, arch: 'x64' })
+ ).rejects.toThrow('already in progress')
+ releaseResponse(new Response('x'.repeat(1024 * 1024 + 1)))
+ await expect(waiting).rejects.toThrow()
+ })
+ it.each(['symlink', 'hardlink'])(
+ 'rejects installed binary %s substitution before execution',
+ async (kind) => {
+ const userDataDir = await temp()
+ const release = fixture()
+ await installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: release.fetcher,
+ })
+ const binary = resolveManagedFfmpegCandidate(
+ userDataDir,
+ path.join(userDataDir, 'binaries', 'ffmpeg.exe'),
+ 'win32'
+ )
+ const elsewhere = path.join(userDataDir, 'elsewhere')
+ await writeFile(elsewhere, pe('x64'))
+ await rm(binary)
+ if (kind === 'symlink') await symlink(elsewhere, binary)
+ else await link(elsewhere, binary)
+ expect(() => assertManagedFfmpegTrusted(userDataDir, binary)).toThrow()
+ }
+ )
+ it.each([
+ 'traversal',
+ 'symlink',
+ 'hardlink',
+ 'device',
+ 'pax',
+ 'duplicate',
+ 'case',
+ 'wrong-arch',
+ 'trailer',
+ ])('rejects authenticated TAR %s violations', async (kind) => {
+ const release = fixture(undefined, 'x64', 'linux')
+ const entries: Array<{ name: string; data: Buffer; type?: string }> = [
+ ...release.entries,
+ ]
+ if (kind === 'traversal') entries[0] = { ...entries[0], name: '../ffmpeg' }
+ if (kind === 'symlink') entries[0] = { ...entries[0], type: '2' }
+ if (kind === 'hardlink') entries[0] = { ...entries[0], type: '1' }
+ if (kind === 'device') entries[0] = { ...entries[0], type: '3' }
+ if (kind === 'pax') entries[0] = { ...entries[0], type: 'x' }
+ if (kind === 'duplicate') entries.push(entries[0])
+ if (kind === 'case') entries[0] = { ...entries[0], name: 'FFMPEG' }
+ if (kind === 'wrong-arch')
+ entries[0] = { ...entries[0], data: nativeBinary('linux', 'arm64') }
+ let archive = tar(entries)
+ if (kind === 'trailer')
+ archive = Buffer.concat([archive, gzipSync(Buffer.from('evil'))])
+ const target = {
+ ...release.target,
+ archiveSize: archive.length,
+ archiveSha256: sha256(archive),
+ }
+ await expect(
+ extractVerifiedFfmpeg(archive, await temp(), target)
+ ).rejects.toThrow()
+ })
+ it.each(['x64', 'arm64'] as const)(
+ 'installs and verifies %s without executing payloads',
+ async (arch) => {
+ const userDataDir = await temp()
+ const release = fixture(undefined, arch)
+ await expect(
+ installVerifiedFfmpeg({ userDataDir, arch, fetcher: release.fetcher })
+ ).resolves.toEqual({ ok: true, releaseVersion: '9.0.2-motrix.8' })
+ const binary = resolveManagedFfmpegCandidate(
+ userDataDir,
+ path.join(userDataDir, 'binaries', 'ffmpeg.exe'),
+ 'win32'
+ )
+ expect(binary).toContain(sha256(release.raw))
+ assertManagedFfmpegTrusted(userDataDir, binary)
+ await writeFile(binary, Buffer.from('tampered'))
+ expect(() => assertManagedFfmpegTrusted(userDataDir, binary)).toThrow()
+ }
+ )
+ it('rejects altered raw bytes, missing signatures, unknown keys and replayed tag identities', () => {
+ const release = fixture()
+ expect(() =>
+ verifyFfmpegRelease(
+ Buffer.concat([release.raw, Buffer.from(' ')]),
+ release.envelope,
+ 'x64'
+ )
+ ).toThrow()
+ expect(() =>
+ verifyFfmpegRelease(release.raw, Buffer.from('{}'), 'x64')
+ ).toThrow()
+ expect(() =>
+ verifyFfmpegRelease(release.raw, release.envelope.subarray(0, -1), 'x64')
+ ).toThrow()
+ expect(() =>
+ verifyFfmpegRelease(release.raw.subarray(0, -1), release.envelope, 'x64')
+ ).toThrow('signature')
+ const wrongKey = Buffer.from(
+ release.envelope
+ .toString()
+ .replace(testKeys.keyId, `sha256:${'0'.repeat(64)}`)
+ )
+ expect(() => verifyFfmpegRelease(release.raw, wrongKey, 'x64')).toThrow()
+ expect(() =>
+ verifyFfmpegRelease(
+ release.raw,
+ release.envelope,
+ 'x64',
+ 'v9.0.3-motrix.2'
+ )
+ ).toThrow()
+ })
+ it('compares revision numerically and rejects below-floor releases', () => {
+ expect(compareFfmpegReleases('9.0.1-motrix.10', '9.0.1-motrix.2')).toBe(1)
+ const old = fixture('9.0.1-motrix.1')
+ expect(() => verifyFfmpegRelease(old.raw, old.envelope, 'x64')).toThrow()
+ })
+ it('retains last-good pointer after a failed download and prevents signed rollback', async () => {
+ const userDataDir = await temp()
+ const newer = fixture('9.0.3-motrix.2')
+ await installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: newer.fetcher,
+ })
+ const pointer = path.join(userDataDir, 'ffmpeg-verified', 'current.json')
+ const before = await readFile(pointer)
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: fixture().fetcher,
+ })
+ ).rejects.toThrow('installation failed')
+ expect((await readFile(pointer)).equals(before)).toBe(true)
+ const broken = fixture('9.0.4-motrix.2')
+ broken.fetcher.mockImplementation(
+ async () => new Response('oops', { status: 503 })
+ )
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ arch: 'x64',
+ fetcher: broken.fetcher,
+ })
+ ).rejects.toThrow()
+ expect((await readFile(pointer)).equals(before)).toBe(true)
+ })
+ it('rejects untrusted redirects without following them', async () => {
+ const fetcher = vi.fn<typeof fetch>(
+ async () =>
+ new Response(null, {
+ status: 302,
+ headers: { location: 'http://localhost/private' },
+ })
+ )
+ await expect(
+ installVerifiedFfmpeg({ userDataDir: await temp(), arch: 'x64', fetcher })
+ ).rejects.toThrow('installation failed')
+ expect(fetcher).toHaveBeenCalledTimes(1)
+ })
+ it.each([
+ 'traversal',
+ 'duplicate',
+ 'case',
+ 'symlink',
+ 'wrong-arch',
+ 'extra',
+ 'missing',
+ 'size',
+ 'expansion',
+ ])('rejects a signed ZIP with %s violation', async (kind) => {
+ const release = fixture()
+ const entries = [...release.entries]
+ if (kind === 'traversal')
+ entries.push({ name: '../escape.exe', data: pe('x64') })
+ if (kind === 'duplicate') entries.push(entries[0])
+ if (kind === 'case') entries.push({ name: 'FFMPEG.EXE', data: pe('x64') })
+ if (kind === 'symlink')
+ entries[0] = { ...entries[0], mode: 0xa1ff } as (typeof entries)[0]
+ if (kind === 'extra') entries.push({ name: 'evil.dll', data: pe('x64') })
+ if (kind === 'missing') entries.pop()
+ if (kind === 'size')
+ entries[0] = {
+ ...entries[0],
+ declaredSize: 257 * 1024 * 1024,
+ } as (typeof entries)[0]
+ if (kind === 'expansion')
+ entries[0] = { ...entries[0], declaredSize: 8 } as (typeof entries)[0]
+ if (kind === 'wrong-arch') {
+ entries[0] = { ...entries[0], data: pe('arm64') }
+ release.target.binarySha256 = sha256(entries[0].data)
+ }
+ const archive = zip(entries)
+ const target = {
+ ...release.target,
+ archiveSize: archive.length,
+ archiveSha256: sha256(archive),
+ }
+ await expect(
+ extractVerifiedFfmpeg(archive, await temp(), target)
+ ).rejects.toThrow()
+ })
+ it('leaves explicitly user-managed installations outside project trust policy', async () => {
+ const userDataDir = await temp()
+ const external = path.join(userDataDir, 'external', 'ffmpeg.exe')
+ expect(resolveManagedFfmpegCandidate(userDataDir, external)).toBe(external)
+ })
+})
diff --git a/src/core/ffmpeg/verified-install.ts b/src/core/ffmpeg/verified-install.ts
new file mode 100644
index 00000000..f3e2574d
--- /dev/null
+++ b/src/core/ffmpeg/verified-install.ts
@@ -0,0 +1,1014 @@
+import { createHash, randomUUID } from 'node:crypto'
+import {
+ closeSync,
+ constants,
+ existsSync,
+ fstatSync,
+ lstatSync,
+ openSync,
+ readSync,
+} from 'node:fs'
+import {
+ chmod,
+ mkdir,
+ mkdtemp,
+ open,
+ readFile,
+ rename,
+ rm,
+ writeFile,
+} from 'node:fs/promises'
+import path from 'node:path'
+import { Readable } from 'node:stream'
+import { createGunzip } from 'node:zlib'
+import { AppError, ErrorCode } from '@shared/errors'
+import type {
+ FfmpegInstallStatus,
+ FfmpegPlatform,
+ FfmpegTarget,
+} from '@shared/schemas/ffmpeg-release'
+import {
+ FFMPEG_REPOSITORY,
+ ffmpegLicenseInventorySchema,
+ ffmpegReleaseVersionSchema,
+} from '@shared/schemas/ffmpeg-release'
+import * as yauzl from 'yauzl'
+import { z } from 'zod'
+import {
+ compareFfmpegReleases,
+ sha256,
+ verifyFfmpegBinary,
+ verifyFfmpegRelease,
+} from './verified-release'
+
+const MAX_BINARY = 256 * 1024 * 1024
+const MAX_EXTRACTED = 600 * 1024 * 1024
+const fileSystemErrorCodes = new Set([
+ 'EACCES',
+ 'EPERM',
+ 'ENOSPC',
+ 'EROFS',
+ 'EMFILE',
+ 'ENFILE',
+ 'EDQUOT',
+ 'EIO',
+ 'EISDIR',
+ 'ENOTDIR',
+ 'EEXIST',
+])
+const receiptSchema = z
+ .object({
+ manifestHash: z.string().regex(/^[0-9a-f]{64}$/),
+ releaseVersion: ffmpegReleaseVersionSchema,
+ arch: z.enum(['x64', 'arm64']),
+ platform: z.enum(['darwin', 'linux', 'win32']).default('win32'),
+ layoutVersion: z.union([z.literal(1), z.literal(2)]).default(1),
+ })
+ .strict()
+const activeInstalls = new Set<string>()
+const statuses = new Map<string, FfmpegInstallStatus>()
+export function getFfmpegInstallStatus(
+ userDataDir: string
+): FfmpegInstallStatus {
+ const current = statuses.get(rootFor(userDataDir))
+ if (current) return { ...current }
+ try {
+ const installed = readInstalled(userDataDir)
+ return {
+ phase: 'installed',
+ bytesReceived: 0,
+ bytesTotal: 0,
+ percent: null,
+ releaseVersion: installed.receipt.releaseVersion,
+ directory: installed.directory,
+ error: null,
+ }
+ } catch {
+ return {
+ phase: 'idle',
+ bytesReceived: 0,
+ bytesTotal: 0,
+ percent: null,
+ releaseVersion: null,
+ directory: null,
+ error: null,
+ }
+ }
+}
+const downloadHosts = new Set([
+ 'api.github.com',
+ 'github.com',
+ 'release-assets.githubusercontent.com',
+ 'objects.githubusercontent.com',
+])
+const releaseApiSchema = z
+ .object({
+ tag_name: z.string().max(80),
+ draft: z.literal(false),
+ prerelease: z.literal(false),
+ immutable: z.literal(true),
+ published_at: z.iso.datetime(),
+ html_url: z.string().max(256),
+ assets: z
+ .array(
+ z
+ .object({
+ id: z.number().int().positive(),
+ name: z.string().max(200),
+ state: z.literal('uploaded'),
+ size: z.number().int().positive(),
+ browser_download_url: z.string().max(512),
+ })
+ .passthrough()
+ )
+ .max(128),
+ })
+ .passthrough()
+
+function rootFor(userDataDir: string) {
+ return path.resolve(userDataDir, 'ffmpeg-verified')
+}
+
+function assertManagedDirectory(directory: string, allowMissing = false) {
+ let info: ReturnType<typeof lstatSync>
+ try {
+ info = lstatSync(directory)
+ } catch (error) {
+ if (allowMissing && (error as NodeJS.ErrnoException).code === 'ENOENT')
+ return
+ throw error
+ }
+ if (
+ !info.isDirectory() ||
+ (process.platform !== 'win32' &&
+ ((typeof process.getuid === 'function' &&
+ info.uid !== process.getuid()) ||
+ (info.mode & 0o022) !== 0))
+ )
+ throw new AppError(
+ ErrorCode.FfmpegInstallFailed,
+ 'Invalid managed FFmpeg directory'
+ )
+}
+
+async function ensureManagedDirectory(directory: string) {
+ // Reject existing links before mkdir can follow them into an external tree.
+ assertManagedDirectory(directory, true)
+ try {
+ await mkdir(directory, { mode: 0o700 })
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
+ }
+ assertManagedDirectory(directory)
+}
+
+function regularBytes(file: string, limit: number): Buffer {
+ const info = lstatSync(file)
+ if (!info.isFile() || info.size > limit)
+ throw new Error('Invalid FFmpeg receipt file')
+ const fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
+ try {
+ const opened = fstatSync(fd)
+ if (
+ !opened.isFile() ||
+ opened.nlink !== 1 ||
+ opened.size > limit ||
+ opened.ino !== info.ino ||
+ opened.dev !== info.dev
+ )
+ throw new Error('Invalid FFmpeg receipt file')
+ const bytes = Buffer.alloc(opened.size)
+ let offset = 0
+ while (offset < bytes.length) {
+ const count = readSync(fd, bytes, offset, bytes.length - offset, offset)
+ if (count === 0) throw new Error('FFmpeg receipt changed')
+ offset += count
+ }
+ if (
+ readSync(fd, Buffer.alloc(1), 0, 1, offset) !== 0 ||
+ fstatSync(fd).size !== opened.size
+ )
+ throw new Error('FFmpeg receipt changed')
+ return bytes
+ } finally {
+ closeSync(fd)
+ }
+}
+
+function hashBinary(
+ file: string,
+ expected: string,
+ arch: 'x64' | 'arm64',
+ platform: FfmpegPlatform
+) {
+ const info = lstatSync(file)
+ if (!info.isFile() || info.size <= 0 || info.size > MAX_BINARY) {
+ throw new Error('Invalid managed FFmpeg binary')
+ }
+ const fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
+ try {
+ const opened = fstatSync(fd)
+ if (
+ !opened.isFile() ||
+ opened.nlink !== 1 ||
+ opened.ino !== info.ino ||
+ opened.dev !== info.dev ||
+ opened.size !== info.size
+ )
+ throw new Error('FFmpeg binary changed')
+ const header = Buffer.alloc(Math.min(info.size, 64 * 1024 + 512))
+ const size = readSync(fd, header, 0, header.length, 0)
+ verifyFfmpegBinary(header.subarray(0, size), platform, arch)
+ const digest = createHash('sha256')
+ const chunk = Buffer.alloc(1024 * 1024)
+ let offset = 0
+ for (;;) {
+ const count = readSync(fd, chunk, 0, chunk.length, offset)
+ if (count === 0) break
+ offset += count
+ if (offset > MAX_BINARY) throw new Error('FFmpeg binary exceeds limits')
+ digest.update(chunk.subarray(0, count))
+ }
+ if (offset !== info.size || digest.digest('hex') !== expected) {
+ throw new Error('Managed FFmpeg binary digest mismatch')
+ }
+ } finally {
+ closeSync(fd)
+ }
+}
+
+function readInstalled(userDataDir: string) {
+ const root = rootFor(userDataDir)
+ assertManagedDirectory(root)
+ const receipt = receiptSchema.parse(
+ JSON.parse(
+ regularBytes(path.join(root, 'current.json'), 4096).toString('utf8')
+ )
+ )
+ const directory = path.join(
+ root,
+ 'releases',
+ receipt.layoutVersion === 2
+ ? `${receipt.manifestHash}-${receipt.platform}-${receipt.arch}`
+ : receipt.manifestHash
+ )
+ for (const component of [path.join(root, 'releases'), directory]) {
+ assertManagedDirectory(component)
+ }
+ const raw = regularBytes(
+ path.join(directory, 'ffmpeg-manifest.json'),
+ 1024 * 1024
+ )
+ const sig = regularBytes(
+ path.join(directory, 'ffmpeg-manifest.json.sig'),
+ 4096
+ )
+ const verified = verifyFfmpegRelease(
+ raw,
+ sig,
+ receipt.arch,
+ undefined,
+ receipt.platform
+ )
+ if (
+ verified.manifestHash !== receipt.manifestHash ||
+ verified.manifest.releaseVersion !== receipt.releaseVersion
+ ) {
+ throw new Error('FFmpeg receipt does not match signed manifest')
+ }
+ return { ...verified, directory, receipt }
+}
+
+/** Synchronous pre-spawn guard for cached plugin paths. External installations remain user-managed. */
+export function assertManagedFfmpegTrusted(
+ userDataDir: string,
+ binaryPath: string
+) {
+ const relative = path.relative(rootFor(userDataDir), path.resolve(binaryPath))
+ if (
+ relative.startsWith(`..${path.sep}`) ||
+ relative === '..' ||
+ path.isAbsolute(relative)
+ )
+ return
+ const installed = readInstalled(userDataDir)
+ const expectedPath = path.join(
+ installed.directory,
+ installed.target.binaryPath
+ )
+ if (path.resolve(binaryPath) !== expectedPath)
+ throw new Error('Inactive managed FFmpeg version')
+ hashBinary(
+ expectedPath,
+ installed.target.binarySha256,
+ installed.target.arch,
+ installed.target.platform
+ )
+ hashBinary(
+ path.join(installed.directory, installed.target.ffprobePath),
+ installed.target.ffprobeSha256,
+ installed.target.arch,
+ installed.target.platform
+ )
+ if (installed.target.platform === 'win32' && process.platform === 'win32') {
+ for (const name of [
+ installed.target.binaryPath,
+ installed.target.ffprobePath,
+ ]) {
+ const marker = regularBytes(
+ path.join(installed.directory, `${name}:Zone.Identifier`),
+ 4096
+ ).toString('utf8')
+ if (!/(?:^|\r?\n)ZoneId=3(?:\r?\n|$)/.test(marker))
+ throw new Error('Managed FFmpeg Internet origin marker is missing')
+ }
+ }
+ return installed.target
+}
+
+/** Project signature verification does not remove Internet-zone treatment or SmartScreen warnings. */
+async function markWindowsInternetOrigin(
+ directory: string,
+ target: FfmpegTarget,
+ sourceUrl: string
+) {
+ if (target.platform !== 'win32' || process.platform !== 'win32') return
+ for (const name of [target.binaryPath, target.ffprobePath]) {
+ await writeFile(
+ path.join(directory, `${name}:Zone.Identifier`),
+ `[ZoneTransfer]\r\nZoneId=3\r\nHostUrl=${sourceUrl}\r\n`,
+ { mode: 0o600 }
+ )
+ }
+}
+
+/** Substitute only the conventional userData candidate; do not hijack manual/PATH installs. */
+export function resolveManagedFfmpegCandidate(
+ userDataDir: string,
+ candidate: string,
+ platform: FfmpegPlatform = process.platform as FfmpegPlatform
+): string {
+ if (
+ path.resolve(candidate) ===
+ path.resolve(
+ userDataDir,
+ 'binaries',
+ platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
+ ) &&
+ existsSync(path.join(rootFor(userDataDir), 'current.json'))
+ ) {
+ const installed = readInstalled(userDataDir)
+ if (installed.target.platform !== platform)
+ throw new Error('Managed FFmpeg platform mismatch')
+ candidate = path.join(installed.directory, installed.target.binaryPath)
+ }
+ assertManagedFfmpegTrusted(userDataDir, candidate)
+ return candidate
+}
+
+async function download(
+ url: string,
+ limit: number,
+ fetcher: typeof fetch,
+ signal: AbortSignal,
+ onProgress?: (received: number, total: number) => void
+) {
+ for (let redirects = 0; redirects <= 5; redirects += 1) {
+ const location = new URL(url)
+ if (
+ location.protocol !== 'https:' ||
+ location.port ||
+ location.username ||
+ location.password ||
+ !downloadHosts.has(location.hostname)
+ ) {
+ throw new Error('Untrusted FFmpeg download location')
+ }
+ const response = await fetcher(url, {
+ signal,
+ redirect: 'manual',
+ credentials: 'omit',
+ })
+ if (
+ response.status === 404 &&
+ location.hostname === 'api.github.com' &&
+ location.pathname === `/repos/${FFMPEG_REPOSITORY}/releases/latest`
+ ) {
+ await response.body?.cancel()
+ throw new AppError(
+ ErrorCode.FfmpegReleaseUnavailable,
+ 'No formal FFmpeg release'
+ )
+ }
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
+ const next = response.headers.get('location')
+ await response.body?.cancel()
+ if (!next) throw new Error('Missing download redirect')
+ url = new URL(next, url).href
+ continue
+ }
+ if (
+ !response.ok ||
+ !response.body ||
+ Number(response.headers.get('content-length')) > limit
+ ) {
+ await response.body?.cancel()
+ throw new Error('FFmpeg download failed or exceeds limits')
+ }
+ const chunks: Uint8Array[] = []
+ let size = 0
+ let lastEmit = 0
+ const header = response.headers.get('content-length')
+ const total = header && /^\d+$/.test(header) ? Number(header) : 0
+ const reader = response.body.getReader()
+ try {
+ for (;;) {
+ const { value, done } = await reader.read()
+ if (done) break
+ size += value.length
+ if (size > limit) throw new Error('FFmpeg download exceeds limits')
+ chunks.push(value)
+ if (Date.now() - lastEmit >= 250) {
+ lastEmit = Date.now()
+ onProgress?.(size, total)
+ }
+ }
+ } finally {
+ try {
+ await reader.cancel()
+ } catch {
+ /* Preserve the primary failure. */
+ }
+ }
+ onProgress?.(size, total || size)
+ return Buffer.concat(chunks, size)
+ }
+ throw new Error('Too many FFmpeg redirects')
+}
+
+/** Authenticated archives still get an exact, bounded, regular-file-only extraction policy. */
+export function extractVerifiedFfmpeg(
+ archive: Buffer,
+ destination: string,
+ target: FfmpegTarget
+) {
+ if (
+ archive.length !== target.archiveSize ||
+ sha256(archive) !== target.archiveSha256
+ ) {
+ return Promise.reject(new Error('FFmpeg archive digest mismatch'))
+ }
+ const expected = new Map<string, string | null>([
+ [target.binaryPath, target.binarySha256],
+ [target.ffprobePath, target.ffprobeSha256],
+ ['BUILD-INFO.json', target.buildInfoSha256],
+ ['configure.txt', target.configureSha256],
+ ['LICENSES.json', target.licensesSha256],
+ ['README.txt', null],
+ ...target.licenseFiles.map((item): [string, string] => [
+ item.path,
+ item.sha256,
+ ]),
+ ])
+ if (target.platform === 'linux')
+ return extractVerifiedTar(archive, destination, target, expected)
+ return new Promise<void>((resolve, reject) => {
+ yauzl.fromBuffer(
+ archive,
+ { lazyEntries: true, strictFileNames: true, validateEntrySizes: true },
+ (error, zip) => {
+ if (error || !zip) {
+ reject(error ?? new Error('Invalid FFmpeg ZIP'))
+ return
+ }
+ const seen = new Set<string>()
+ let total = 0
+ let failed = false
+ const fail = (reason: unknown) => {
+ failed = true
+ zip.close()
+ reject(reason)
+ }
+ zip.on('error', fail)
+ zip.on('end', () => {
+ if (failed) return
+ if (seen.size !== expected.size) {
+ fail(new Error('Incomplete FFmpeg ZIP'))
+ return
+ }
+ void readFile(path.join(destination, 'LICENSES.json'))
+ .then((bytes) => {
+ const inventory = ffmpegLicenseInventorySchema.parse(
+ JSON.parse(bytes.toString('utf8'))
+ )
+ if (
+ inventory.target !== target.target ||
+ inventory.files.length !== target.licenseFiles.length ||
+ inventory.files.some(
+ (file) =>
+ !target.licenseFiles.some(
+ (expectedFile) =>
+ expectedFile.path === file.path &&
+ expectedFile.sha256 === file.sha256
+ )
+ ) ||
+ new Set(inventory.files.map((file) => file.path)).size !==
+ inventory.files.length
+ ) {
+ throw new Error('FFmpeg license inventory mismatch')
+ }
+ resolve()
+ })
+ .catch(fail)
+ })
+ zip.on('entry', (entry: yauzl.Entry) => {
+ const name = entry.fileName
+ const mode = (entry.externalFileAttributes >>> 16) & 0xf000
+ if (
+ !expected.has(name) ||
+ seen.has(name) ||
+ (mode !== 0 && mode !== 0x8000) ||
+ (entry.externalFileAttributes & 0x10) !== 0 ||
+ (entry.externalFileAttributes & 0x400) !== 0 ||
+ (entry.generalPurposeBitFlag & 1) !== 0 ||
+ entry.uncompressedSize > MAX_BINARY ||
+ (name !== target.binaryPath &&
+ name !== target.ffprobePath &&
+ entry.uncompressedSize > 16 * 1024 * 1024) ||
+ seen.size >= expected.size
+ ) {
+ fail(new Error('Unsafe or unexpected FFmpeg ZIP member'))
+ return
+ }
+ seen.add(name)
+ zip.openReadStream(entry, (streamError, stream) => {
+ if (streamError || !stream) {
+ fail(streamError ?? new Error('Invalid ZIP stream'))
+ return
+ }
+ void (async () => {
+ const output = path.join(destination, name)
+ await mkdir(path.dirname(output), {
+ recursive: true,
+ mode: 0o700,
+ })
+ const file = await open(output, 'wx', 0o600)
+ const digest = createHash('sha256')
+ let size = 0
+ try {
+ for await (const chunk of stream) {
+ size += chunk.length
+ total += chunk.length
+ if (size > entry.uncompressedSize || total > MAX_EXTRACTED)
+ throw new Error('ZIP expansion exceeds limits')
+ digest.update(chunk)
+ await file.writeFile(chunk)
+ }
+ const expectedHash = expected.get(name)
+ if (
+ size !== entry.uncompressedSize ||
+ (expectedHash !== null &&
+ digest.digest('hex') !== expectedHash)
+ ) {
+ throw new Error('FFmpeg ZIP member digest mismatch')
+ }
+ if (name === target.binaryPath || name === target.ffprobePath) {
+ const bytes = await readFile(output)
+ verifyFfmpegBinary(bytes, target.platform, target.arch)
+ }
+ } finally {
+ await file.close()
+ }
+ if (!failed) zip.readEntry()
+ })().catch(fail)
+ })
+ })
+ zip.readEntry()
+ }
+ )
+ })
+}
+
+/** The producer emits regular USTAR-compatible records only; reject extension records and links. */
+async function extractVerifiedTar(
+ archive: Buffer,
+ destination: string,
+ target: FfmpegTarget,
+ expected: Map<string, string | null>
+) {
+ const stream = Readable.from([archive]).pipe(createGunzip())
+ const iterator = stream[Symbol.asyncIterator]()
+ let pending = Buffer.alloc(0)
+ let expanded = 0
+ const take = async (length: number) => {
+ const chunks: Buffer[] = []
+ let count = 0
+ while (count < length) {
+ if (pending.length === 0) {
+ const next = await iterator.next()
+ if (next.done) throw new Error('Truncated FFmpeg TAR')
+ pending = Buffer.from(next.value)
+ expanded += pending.length
+ if (expanded > MAX_EXTRACTED + 1024 * 1024)
+ throw new Error('TAR expansion exceeds limits')
+ }
+ const size = Math.min(length - count, pending.length)
+ chunks.push(pending.subarray(0, size))
+ pending = pending.subarray(size)
+ count += size
+ }
+ return Buffer.concat(chunks, length)
+ }
+ const octal = (field: Buffer) => {
+ const text = field.toString('ascii').replace(/\0.*$/, '').trim()
+ if (!/^[0-7]{1,12}$/.test(text)) throw new Error('Invalid TAR number')
+ const value = Number.parseInt(text, 8)
+ if (!Number.isSafeInteger(value)) throw new Error('Invalid TAR size')
+ return value
+ }
+ const seen = new Set<string>()
+ try {
+ for (;;) {
+ const header = await take(512)
+ if (header.every((byte) => byte === 0)) {
+ if (
+ !(await take(512)).every((byte) => byte === 0) ||
+ seen.size !== expected.size
+ )
+ throw new Error('Incomplete FFmpeg TAR')
+ // Only zero record padding may follow the end marker; no concatenated archives.
+ if (!pending.every((byte) => byte === 0))
+ throw new Error('Unexpected TAR trailer')
+ for (;;) {
+ const next = await iterator.next()
+ if (next.done) break
+ expanded += next.value.length
+ if (
+ expanded > MAX_EXTRACTED + 1024 * 1024 ||
+ !Buffer.from(next.value).every((byte) => byte === 0)
+ )
+ throw new Error('Unexpected TAR trailer')
+ }
+ break
+ }
+ const storedChecksum = octal(header.subarray(148, 156))
+ let checksum = 0
+ for (let index = 0; index < 512; index++)
+ checksum += index >= 148 && index < 156 ? 32 : header[index]
+ const name = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '')
+ const size = octal(header.subarray(124, 136))
+ const binary = name === target.binaryPath || name === target.ffprobePath
+ if (
+ checksum !== storedChecksum ||
+ !expected.has(name) ||
+ seen.has(name) ||
+ ![0, 48].includes(header[156]) ||
+ !header.subarray(157, 257).every((byte) => byte === 0) ||
+ header.subarray(257, 263).toString('ascii') !== 'ustar\0' ||
+ !header.subarray(345, 500).every((byte) => byte === 0) ||
+ octal(header.subarray(100, 108)) !== (binary ? 0o755 : 0o644) ||
+ size <= 0 ||
+ size > (binary ? MAX_BINARY : 16 * 1024 * 1024)
+ )
+ throw new Error('Unsafe or unexpected FFmpeg TAR member')
+ seen.add(name)
+ const bytes = await take(size)
+ const digest = expected.get(name)
+ if (digest !== null && sha256(bytes) !== digest)
+ throw new Error('FFmpeg TAR member digest mismatch')
+ if (binary) verifyFfmpegBinary(bytes, target.platform, target.arch)
+ const padding = await take((512 - (size % 512)) % 512)
+ if (!padding.every((byte) => byte === 0))
+ throw new Error('Invalid TAR padding')
+ const output = path.join(destination, name)
+ await mkdir(path.dirname(output), { recursive: true, mode: 0o700 })
+ await writeFile(output, bytes, { flag: 'wx', mode: 0o600 })
+ }
+ const inventory = ffmpegLicenseInventorySchema.parse(
+ JSON.parse(
+ (await readFile(path.join(destination, 'LICENSES.json'))).toString(
+ 'utf8'
+ )
+ )
+ )
+ if (
+ inventory.target !== target.target ||
+ inventory.files.length !== target.licenseFiles.length ||
+ new Set(inventory.files.map((file) => file.path)).size !==
+ inventory.files.length ||
+ inventory.files.some(
+ (file) =>
+ !target.licenseFiles.some(
+ (item) => item.path === file.path && item.sha256 === file.sha256
+ )
+ )
+ )
+ throw new Error('FFmpeg license inventory mismatch')
+ } finally {
+ stream.destroy()
+ }
+}
+
+export async function installVerifiedFfmpeg(options: {
+ userDataDir: string
+ arch: 'x64' | 'arm64'
+ fetcher?: typeof fetch
+ platform?: FfmpegPlatform
+ onStatus?: (status: FfmpegInstallStatus) => void
+ systemTrust?: (
+ directory: string,
+ target: FfmpegTarget,
+ sourceUrl: string
+ ) => Promise<void>
+}) {
+ const { userDataDir, arch } = options
+ const platform = options.platform ?? 'win32'
+ const root = rootFor(userDataDir)
+ if (activeInstalls.has(root))
+ throw new AppError(
+ ErrorCode.FfmpegInstallBusy,
+ 'FFmpeg installation already in progress'
+ )
+ activeInstalls.add(root)
+ let status: FfmpegInstallStatus = {
+ phase: 'metadata',
+ bytesReceived: 0,
+ bytesTotal: 0,
+ percent: null,
+ releaseVersion: null,
+ directory: null,
+ error: null,
+ }
+ const publish = (patch: Partial<FfmpegInstallStatus>) => {
+ status = { ...status, ...patch }
+ statuses.set(root, status)
+ try {
+ options.onStatus?.({ ...status })
+ } catch {
+ /* Observers cannot alter installation state. */
+ }
+ }
+ publish({})
+ const signal = AbortSignal.timeout(10 * 60 * 1000)
+ const fetcher = options.fetcher ?? fetch
+ let staging: string | undefined
+ let pointer: string | undefined
+ try {
+ assertManagedDirectory(root, true)
+ assertManagedDirectory(path.join(root, 'releases'), true)
+ const latestRaw = JSON.parse(
+ (
+ await download(
+ `https://api.github.com/repos/${FFMPEG_REPOSITORY}/releases/latest`,
+ 1024 * 1024,
+ fetcher,
+ signal
+ )
+ ).toString('utf8')
+ )
+ const parsed = releaseApiSchema.safeParse(latestRaw)
+ if (
+ !parsed.success ||
+ latestRaw.html_url !==
+ `https://github.com/${FFMPEG_REPOSITORY}/releases/tag/${latestRaw.tag_name}`
+ ) {
+ throw new AppError(
+ ErrorCode.FfmpegReleaseUnavailable,
+ 'No immutable formal FFmpeg release'
+ )
+ }
+ const latest = parsed.data
+ const version = ffmpegReleaseVersionSchema.parse(
+ String(latest.tag_name).replace(/^v/, '')
+ )
+ const tag = `v${version}`
+ const base = `https://github.com/${FFMPEG_REPOSITORY}/releases/download/${tag}/`
+ const raw = await download(
+ `${base}ffmpeg-manifest.json`,
+ 1024 * 1024,
+ fetcher,
+ signal
+ )
+ const sig = await download(
+ `${base}ffmpeg-manifest.json.sig`,
+ 4096,
+ fetcher,
+ signal
+ )
+ publish({ phase: 'verifying', releaseVersion: version })
+ const verified = verifyFfmpegRelease(raw, sig, arch, tag, platform)
+ const assetNames = new Set(latest.assets.map((asset) => asset.name))
+ if (
+ assetNames.size !== latest.assets.length ||
+ new Set(latest.assets.map((asset) => asset.id)).size !==
+ latest.assets.length
+ )
+ throw new Error('Duplicate FFmpeg release assets')
+ const requiredAssets = [
+ { name: 'ffmpeg-manifest.json', size: raw.length },
+ { name: 'ffmpeg-manifest.json.sig', size: sig.length },
+ ...verified.allTargets.map((item) => ({
+ name: item.archive,
+ size: item.archiveSize,
+ })),
+ ]
+ for (const required of requiredAssets) {
+ const asset = latest.assets.find((item) => item.name === required.name)
+ if (
+ !asset ||
+ asset.size !== required.size ||
+ asset.browser_download_url !== `${base}${required.name}`
+ )
+ throw new Error('Formal FFmpeg release asset identity mismatch')
+ }
+ if (existsSync(path.join(root, 'current.json'))) {
+ const current = readInstalled(userDataDir)
+ const comparison = compareFfmpegReleases(
+ version,
+ current.manifest.releaseVersion
+ )
+ if (
+ comparison < 0 ||
+ (comparison === 0 && verified.manifestHash !== current.manifestHash)
+ ) {
+ throw new Error('FFmpeg release rollback or same-version substitution')
+ }
+ }
+ assertManagedDirectory(
+ path.join(
+ root,
+ 'releases',
+ `${verified.manifestHash}-${platform}-${arch}`
+ ),
+ true
+ )
+ await ensureManagedDirectory(root)
+ await ensureManagedDirectory(path.join(root, 'releases'))
+ publish({
+ phase: 'downloading',
+ bytesTotal: verified.target.archiveSize,
+ percent: 0,
+ })
+ const archive = await download(
+ `${base}${verified.target.archive}`,
+ verified.target.archiveSize,
+ fetcher,
+ signal,
+ (received) =>
+ publish({
+ bytesReceived: received,
+ bytesTotal: verified.target.archiveSize,
+ percent: Math.min(1, received / verified.target.archiveSize),
+ })
+ )
+ staging = await mkdtemp(path.join(root, '.install-'))
+ publish({ phase: 'extracting', percent: null })
+ await extractVerifiedFfmpeg(archive, staging, verified.target)
+ await markWindowsInternetOrigin(
+ staging,
+ verified.target,
+ `${base}${verified.target.archive}`
+ )
+ if (platform !== 'win32') {
+ for (const name of [
+ verified.target.binaryPath,
+ verified.target.ffprobePath,
+ ])
+ await chmod(path.join(staging, name), 0o700)
+ }
+ if (platform === 'darwin') {
+ publish({ phase: 'systemTrust' })
+ if (!options.systemTrust)
+ throw new Error('macOS system trust verifier is required')
+ await options.systemTrust(
+ staging,
+ verified.target,
+ `${base}${verified.target.archive}`
+ )
+ }
+ hashBinary(
+ path.join(staging, verified.target.binaryPath),
+ verified.target.binarySha256,
+ arch,
+ platform
+ )
+ hashBinary(
+ path.join(staging, verified.target.ffprobePath),
+ verified.target.ffprobeSha256,
+ arch,
+ platform
+ )
+ await writeFile(path.join(staging, 'ffmpeg-manifest.json'), raw, {
+ flag: 'wx',
+ mode: 0o600,
+ })
+ await writeFile(path.join(staging, 'ffmpeg-manifest.json.sig'), sig, {
+ flag: 'wx',
+ mode: 0o600,
+ })
+ const directory = path.join(
+ root,
+ 'releases',
+ `${verified.manifestHash}-${platform}-${arch}`
+ )
+ publish({ phase: 'installing' })
+ if (existsSync(directory)) {
+ assertManagedDirectory(directory)
+ if (
+ !regularBytes(
+ path.join(directory, 'ffmpeg-manifest.json'),
+ 1024 * 1024
+ ).equals(raw) ||
+ !regularBytes(
+ path.join(directory, 'ffmpeg-manifest.json.sig'),
+ 4096
+ ).equals(sig)
+ ) {
+ throw new Error('Existing FFmpeg version directory conflicts')
+ }
+ hashBinary(
+ path.join(directory, verified.target.binaryPath),
+ verified.target.binarySha256,
+ arch,
+ platform
+ )
+ hashBinary(
+ path.join(directory, verified.target.ffprobePath),
+ verified.target.ffprobeSha256,
+ arch,
+ platform
+ )
+ // Reusing an identical version never drops the Internet-origin treatment.
+ await markWindowsInternetOrigin(
+ directory,
+ verified.target,
+ `${base}${verified.target.archive}`
+ )
+ if (platform === 'darwin') {
+ publish({ phase: 'systemTrust' })
+ if (!options.systemTrust)
+ throw new Error('macOS system trust verifier is required')
+ await options.systemTrust(
+ directory,
+ verified.target,
+ `${base}${verified.target.archive}`
+ )
+ publish({ phase: 'installing' })
+ }
+ } else {
+ await rename(staging, directory)
+ staging = undefined
+ }
+ pointer = path.join(root, `.current-${randomUUID()}.json`)
+ signal.throwIfAborted()
+ const pointerFile = await open(pointer, 'wx', 0o600)
+ try {
+ await pointerFile.writeFile(
+ JSON.stringify({
+ manifestHash: verified.manifestHash,
+ releaseVersion: version,
+ arch,
+ platform,
+ layoutVersion: 2,
+ })
+ )
+ await pointerFile.sync()
+ } finally {
+ await pointerFile.close()
+ }
+ await rename(pointer, path.join(root, 'current.json'))
+ pointer = undefined
+ publish({ phase: 'installed', directory, percent: 1 })
+ return { ok: true as const, releaseVersion: version }
+ } catch (error) {
+ const code =
+ error instanceof AppError &&
+ error.code === ErrorCode.FfmpegReleaseUnavailable
+ ? 'unavailable'
+ : (error instanceof AppError &&
+ error.code === ErrorCode.FfmpegInstallFailed) ||
+ (error instanceof Error &&
+ fileSystemErrorCodes.has(
+ (error as NodeJS.ErrnoException).code ?? ''
+ ))
+ ? 'install'
+ : status.phase === 'metadata' || status.phase === 'downloading'
+ ? 'download'
+ : status.phase === 'systemTrust'
+ ? 'systemTrust'
+ : status.phase === 'installing'
+ ? 'install'
+ : 'verification'
+ publish({ phase: 'failed', error: code, percent: null })
+ throw new AppError(
+ ErrorCode.FfmpegInstallFailed,
+ 'FFmpeg installation failed',
+ error
+ )
+ } finally {
+ if (staging)
+ await rm(staging, { recursive: true, force: true }).catch(() => {})
+ if (pointer) await rm(pointer, { force: true }).catch(() => {})
+ activeInstalls.delete(root)
+ }
+}
diff --git a/src/core/ffmpeg/verified-release.ts b/src/core/ffmpeg/verified-release.ts
new file mode 100644
index 00000000..a1a14cb5
--- /dev/null
+++ b/src/core/ffmpeg/verified-release.ts
@@ -0,0 +1,140 @@
+import { createHash, createPublicKey, verify } from 'node:crypto'
+import macosCertificate from '@shared/config/ffmpeg-macos-certificate.json'
+import releaseKey from '@shared/config/ffmpeg-release-key.json'
+import {
+ FFMPEG_MINIMUM_RELEASE,
+ FFMPEG_SIGNATURE_DOMAIN,
+ type FfmpegPlatform,
+ ffmpegManifestSchema,
+ ffmpegReleaseVersionSchema,
+ ffmpegSignatureSchema,
+ ffmpegTargetSchema,
+} from '@shared/schemas/ffmpeg-release'
+
+export function sha256(bytes: Uint8Array): string {
+ return createHash('sha256').update(bytes).digest('hex')
+}
+
+export function compareFfmpegReleases(left: string, right: string): number {
+ const parts = (value: string) =>
+ ffmpegReleaseVersionSchema
+ .parse(value)
+ .split(/\.|-motrix\./)
+ .map(Number)
+ const a = parts(left)
+ const b = parts(right)
+ for (let i = 0; i < a.length; i += 1) {
+ if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
+ }
+ return 0
+}
+
+/** Verify exact bytes BEFORE parsing the manifest; download never supplies a key. */
+export function verifyFfmpegRelease(
+ raw: Buffer,
+ envelope: Buffer,
+ arch: 'x64' | 'arm64',
+ expectedTag?: string,
+ platform: FfmpegPlatform = 'win32'
+) {
+ if (raw.length === 0 || raw.length > 1024 * 1024 || envelope.length > 4096) {
+ throw new Error('FFmpeg manifest exceeds limits')
+ }
+ const signature = ffmpegSignatureSchema.parse(
+ JSON.parse(envelope.toString('utf8'))
+ )
+ const key = createPublicKey(releaseKey.publicKey)
+ const derivedId = `sha256:${sha256(key.export({ format: 'der', type: 'spki' }))}`
+ const decoded = Buffer.from(signature.signature, 'base64')
+ if (
+ key.asymmetricKeyType !== 'ed25519' ||
+ derivedId !== releaseKey.keyId ||
+ signature.keyId !== releaseKey.keyId ||
+ decoded.length !== 64 ||
+ decoded.toString('base64') !== signature.signature ||
+ !verify(
+ null,
+ Buffer.concat([Buffer.from(FFMPEG_SIGNATURE_DOMAIN), raw]),
+ key,
+ decoded
+ )
+ ) {
+ throw new Error('Untrusted FFmpeg release signature')
+ }
+ const manifest = ffmpegManifestSchema.parse(JSON.parse(raw.toString('utf8')))
+ const allTargets = manifest.targets.map((item) =>
+ ffmpegTargetSchema.parse(item)
+ )
+ if (
+ (expectedTag !== undefined && manifest.releaseTag !== expectedTag) ||
+ compareFfmpegReleases(manifest.releaseVersion, FFMPEG_MINIMUM_RELEASE) < 0
+ ) {
+ throw new Error('FFmpeg release identity or minimum version mismatch')
+ }
+ const target = ffmpegTargetSchema.parse(
+ allTargets.find((item) => item.target === `${platform}-${arch}`)
+ )
+ if (target.releaseVersion !== manifest.releaseVersion) {
+ throw new Error('FFmpeg target version mismatch')
+ }
+ if (
+ target.platform === 'darwin' &&
+ target.signing?.identity.certificateSha256 !==
+ macosCertificate.certificateSha256
+ ) {
+ throw new Error('FFmpeg Developer ID certificate identity mismatch')
+ }
+ if (
+ allTargets.some((item) => item.releaseVersion !== manifest.releaseVersion)
+ )
+ throw new Error('FFmpeg platform set version mismatch')
+ return { manifest, target, allTargets, manifestHash: sha256(raw) }
+}
+
+/** Inspect architecture without executing the downloaded payload. */
+export function verifyFfmpegBinary(
+ bytes: Buffer,
+ platform: FfmpegPlatform,
+ arch: 'x64' | 'arm64'
+) {
+ if (platform === 'win32') return verifyWindowsPe(bytes, arch)
+ if (platform === 'darwin') {
+ if (
+ bytes.length < 32 ||
+ bytes.readUInt32LE(0) !== 0xfeedfacf ||
+ bytes.readUInt32LE(4) !== (arch === 'arm64' ? 0x0100000c : 0x01000007) ||
+ bytes.readUInt32LE(12) !== 2
+ )
+ throw new Error('Invalid FFmpeg Mach-O architecture')
+ return
+ }
+ if (
+ bytes.length < 64 ||
+ !bytes.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) ||
+ bytes[4] !== 2 ||
+ bytes[5] !== 1 ||
+ bytes[6] !== 1 ||
+ ![2, 3].includes(bytes.readUInt16LE(16)) ||
+ bytes.readUInt16LE(18) !== (arch === 'arm64' ? 183 : 62)
+ )
+ throw new Error('Invalid FFmpeg ELF architecture')
+}
+
+export function verifyWindowsPe(bytes: Buffer, arch: 'x64' | 'arm64') {
+ if (bytes.length < 256 || bytes.toString('ascii', 0, 2) !== 'MZ') {
+ throw new Error('Invalid Windows FFmpeg executable')
+ }
+ const offset = bytes.readUInt32LE(60)
+ if (
+ offset > 64 * 1024 ||
+ offset + 176 > bytes.length ||
+ bytes.readUInt32LE(offset) !== 0x00004550 ||
+ bytes.readUInt16LE(offset + 4) !== (arch === 'arm64' ? 0xaa64 : 0x8664) ||
+ bytes.readUInt16LE(offset + 24) !== 0x20b ||
+ bytes.readUInt16LE(offset + 20) < 152 ||
+ bytes.readUInt32LE(offset + 24 + 112 + 4 * 8) !== 0 ||
+ bytes.readUInt32LE(offset + 24 + 112 + 4 * 8 + 4) !== 0
+ ) {
+ throw new Error('Windows FFmpeg architecture or unsigned policy mismatch')
+ }
+}
diff --git a/src/core/plugin/capabilities/ffmpeg.test.ts b/src/core/plugin/capabilities/ffmpeg.test.ts
index d322921d..18731261 100644
--- a/src/core/plugin/capabilities/ffmpeg.test.ts
+++ b/src/core/plugin/capabilities/ffmpeg.test.ts
@@ -77,6 +77,28 @@ const UNAVAILABLE_DETECT: FfmpegDetection = {
available: false,
}
+describe('FFmpeg managed pre-spawn trust guard', () => {
+ it('does not spawn run or probe when a cached managed binary fails revalidation', async () => {
+ const spawnFn = vi.fn()
+ const validateBinaryPath = vi.fn(() => {
+ throw new Error('digest mismatch')
+ })
+ const host = new FfmpegCapabilityHost({
+ detect: AVAILABLE_DETECT,
+ spawnFn,
+ validateBinaryPath,
+ })
+ await expect(
+ host.run({ argv: [], outputPath: '/output' }).result
+ ).rejects.toThrow()
+ await expect(host.probe({ path: '/input' })).rejects.toThrow(
+ 'integrity check'
+ )
+ expect(validateBinaryPath).toHaveBeenCalledTimes(2)
+ expect(spawnFn).not.toHaveBeenCalled()
+ })
+})
+
// A valid ffmpeg progress stderr line.
const PROGRESS_LINE =
'frame= 42 fps=30.0 q=-0.0 size=N/A time=00:00:05.000 bitrate=N/A speed=1.50x'
diff --git a/src/core/plugin/capabilities/ffmpeg.ts b/src/core/plugin/capabilities/ffmpeg.ts
index f4018164..1bcea357 100644
--- a/src/core/plugin/capabilities/ffmpeg.ts
+++ b/src/core/plugin/capabilities/ffmpeg.ts
@@ -87,6 +87,8 @@ export interface MediaInfo {
export interface FfmpegCapabilityHostOptions {
detect: FfmpegDetection
+ /** Revalidate managed binaries immediately before every spawn, including cached paths. */
+ validateBinaryPath?: (binaryPath: string) => void
/**
* Optional staging redirect. Primary callers (CapabilityBridge.gateFfmpegOutput)
* pre-redirect the output before invoking run/transcode/etc., so this hook is
@@ -230,11 +232,15 @@ export class FfmpegCapabilityHost {
private readonly detect: FfmpegDetection
private readonly stagingPathFor: ((p: string) => string) | undefined
private readonly spawnFn: typeof spawn
+ private readonly validateBinaryPath:
+ | ((binaryPath: string) => void)
+ | undefined
constructor(opts: FfmpegCapabilityHostOptions) {
this.detect = opts.detect
this.stagingPathFor = opts.stagingPathFor
this.spawnFn = opts.spawnFn ?? spawn
+ this.validateBinaryPath = opts.validateBinaryPath
}
get available(): boolean {
@@ -253,6 +259,11 @@ export class FfmpegCapabilityHost {
if (!this.detect.available || !this.detect.binaryPath) {
return unavailableHandle(randomUUID())
}
+ try {
+ this.validateBinaryPath?.(this.detect.binaryPath)
+ } catch {
+ return unavailableHandle(randomUUID())
+ }
const id = randomUUID()
const clampedTimeoutMs = Math.min(
@@ -420,6 +431,17 @@ export class FfmpegCapabilityHost {
const binaryPath = this.detect.binaryPath!
return new Promise<MediaInfo>((resolve, reject) => {
+ try {
+ this.validateBinaryPath?.(binaryPath)
+ } catch {
+ reject(
+ new FfmpegError(
+ 'plugin.ffmpeg.untrusted',
+ 'FFmpeg integrity check failed'
+ )
+ )
+ return
+ }
// `ffmpeg -i <input>` prints the container/stream metadata to stderr
// during input analysis, then exits non-zero ("output file must be
// specified") — we ignore the exit code. We deliberately do NOT append
diff --git a/src/main/index.ts b/src/main/index.ts
index 4c283f2b..0bd7e50c 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -154,7 +154,6 @@ import { BridgeManager } from './bridge/bridge-manager'
import { isPackagedLinuxFlatpak } from './bridge/flatpak-environment'
import { resolvePackagedLinuxSnapEnvironment } from './bridge/snap-environment'
import { CliToolService } from './cli/cli-tool-service'
-import { resolveExecutable } from './cli/shell-environment'
import { CommandRegistry } from './commands/command-registry'
import { ContextStore } from './commands/context-store'
import { registerAllCommands } from './commands/definitions'
@@ -208,6 +207,7 @@ import {
} from './plugin/ffmpeg-detect-electron'
import { resolvePluginHostLanguage } from './plugin/host-language'
import { resolvePluginsDir } from './plugin/plugins-dir'
+import { resolveVerifiedFfmpeg } from './plugin/verified-ffmpeg-electron'
import { createMainProxyApplier } from './proxy/wiring'
import { QuitController } from './quit/quit-controller'
import {
@@ -2507,7 +2507,7 @@ async function initializeMainProcess(): Promise<void> {
platform: process.platform,
envPath: resolveElectronFfmpegEnvPath(),
},
- (candidate) => resolveExecutable(candidate, process.env)
+ (candidate) => resolveVerifiedFfmpeg(platform.userDataDir, candidate)
)
const segmentAria2Client = new Aria2SegmentClient(rpcClient, adapter)
segmentClient = segmentAria2Client
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index b30d6a0e..e1d28971 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -28,6 +28,13 @@ import { WINDOWS_DEFAULT_APPS_SETTINGS_URL } from '../platform/windows-default-a
import type { CommandContext } from './commands'
import { buildCommandHandlers, registerCommandHandlers } from './commands'
+const installManagedFfmpegMock = vi.hoisted(() =>
+ vi.fn(async () => ({ ok: true, releaseVersion: '9.0.2-motrix.2' }))
+)
+vi.mock('../plugin/verified-ffmpeg-electron', () => ({
+ installManagedFfmpeg: installManagedFfmpegMock,
+}))
+
const { resolveWindowsDefaultAppsSettingsUrlMock } = vi.hoisted(() => ({
resolveWindowsDefaultAppsSettingsUrlMock: vi.fn(
async () => 'ms-settings:defaultapps'
@@ -291,6 +298,26 @@ function fakeCtx() {
}
describe('buildCommandHandlers', () => {
+ it('installs FFmpeg only from the fixed service with no renderer-supplied URLs or keys', async () => {
+ const ctx = fakeCtx()
+ const handlers = buildCommandHandlers(ctx as unknown as CommandContext)
+ await expect(
+ handlers[Commands.InstallFfmpeg]?.({
+ url: 'https://evil.test',
+ publicKey: 'forged',
+ })
+ ).rejects.toThrow()
+ const before = installManagedFfmpegMock.mock.calls.length
+ await expect(handlers[Commands.InstallFfmpeg]?.()).resolves.toEqual({
+ ok: true,
+ releaseVersion: '9.0.2-motrix.2',
+ })
+ expect(installManagedFfmpegMock.mock.calls.length).toBe(before + 1)
+ expect(installManagedFfmpegMock).toHaveBeenLastCalledWith(
+ ctx.userDataDir,
+ expect.any(Function)
+ )
+ })
it('delegates CLI installation to the shared singleton service', async () => {
const ctx = fakeCtx()
const status = { phase: 'installed', version: '0.4.0' }
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 67cc490a..58f51b3e 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -153,6 +153,7 @@ import { syncAutoLaunch } from '../platform/auto-launch'
import { setLinuxDefaultTorrentHandler } from '../platform/linux-default-apps'
import type { createProtocolManager } from '../platform/protocol-manager'
import { resolveWindowsDefaultAppsSettingsUrl } from '../platform/windows-default-apps'
+import { installManagedFfmpeg } from '../plugin/verified-ffmpeg-electron'
import type { createMainProxyApplier } from '../proxy/wiring'
import type { WindowManager } from '../window/window-manager'
import { createOpenTaskFileHandler } from './commands/open-task-file'
@@ -657,6 +658,15 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
cliInstallRequestSchema.parse(payload) as CliInstallRequest
),
+ [Commands.InstallFfmpeg]: async (payload: unknown) => {
+ z.undefined().parse(payload)
+ const operation = () =>
+ installManagedFfmpeg(userDataDir, (status) =>
+ ctx.eventBus.emit(Events.FfmpegInstallStatusChanged, status)
+ )
+ return ctx.trackAsyncWork ? ctx.trackAsyncWork(operation) : operation()
+ },
+
[Commands.ParseTorrent]: async ({ base64 }: { base64: string }) => {
return torrentParser.parse(base64)
},
diff --git a/src/main/ipc/queries.test.ts b/src/main/ipc/queries.test.ts
index 64b88cc3..9e15d1f0 100644
--- a/src/main/ipc/queries.test.ts
+++ b/src/main/ipc/queries.test.ts
@@ -146,6 +146,17 @@ function serializeCommandGraphRecords(): string {
}
describe('buildQueryHandlers', () => {
+ it('returns FFmpeg installation state without accepting renderer paths', async () => {
+ const handlers = buildQueryHandlers({
+ userDataDir: '/fixture',
+ } as QueryContext)
+ await expect(
+ handlers[Queries.GetFfmpegInstallStatus]?.()
+ ).resolves.toMatchObject({ phase: 'idle' })
+ await expect(
+ handlers[Queries.GetFfmpegInstallStatus]?.({ userDataDir: '/other' })
+ ).rejects.toThrow()
+ })
it('returns one General draft snapshot and validates before reading it', async () => {
const snapshot = generalSettingsSnapshot({
favorites: ['/saved'],
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index 1c0b7eef..7d3b59b5 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -3,6 +3,7 @@ import type { TaskActivityService } from '@core/activity'
import type { EngineAdapter } from '@core/engine/engine-adapter'
import type { EngineSupervisor } from '@core/engine/engine-supervisor'
import { getTuningRecommendation } from '@core/engine/get-tuning-recommendation'
+import { getFfmpegInstallStatus } from '@core/ffmpeg/verified-install'
import type { GeoIPManager } from '@core/geoip/geo-ip-manager'
import { createGetGeoIPStatusHandler } from '@core/geoip/get-geo-ip-status'
import type { CapabilityHost } from '@core/plugin/capabilities/interface'
@@ -273,6 +274,11 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
}),
[Queries.GetGeoIPStatus]: createGetGeoIPStatusHandler({ geoipManager }),
+ [Queries.GetFfmpegInstallStatus]: async (payload: unknown) => {
+ if (payload !== undefined)
+ throw new Error('Unexpected FFmpeg status payload')
+ return getFfmpegInstallStatus(userDataDir)
+ },
[Queries.GetFfmpegDetection]: async () => detectFfmpeg(),
diff --git a/src/main/plugin/capability-host.ts b/src/main/plugin/capability-host.ts
index c782b18f..da904776 100644
--- a/src/main/plugin/capability-host.ts
+++ b/src/main/plugin/capability-host.ts
@@ -1,5 +1,6 @@
import path from 'node:path'
import { locateFfmpeg } from '@core/ffmpeg/ffmpeg-locator'
+import { assertManagedFfmpegTrusted } from '@core/ffmpeg/verified-install'
import { AppCapabilityHost } from '@core/plugin/capabilities/app'
import { CommandsCapabilityHost } from '@core/plugin/capabilities/commands'
import { ConfigCapabilityHost } from '@core/plugin/capabilities/config'
@@ -28,9 +29,9 @@ import { LibsodiumSecretStore } from '@core/plugin/secret-store-libsodium'
import type { SettingsManager } from '@core/settings/settings-manager'
import type { SupportedLocale } from '@shared/constants/locales'
import type Database from 'better-sqlite3'
-import { resolveExecutable } from '../cli/shell-environment'
import { resolveElectronFfmpegEnvPath } from './ffmpeg-detect-electron'
import { ElectronNotifyHost } from './notify-electron'
+import { resolveVerifiedFfmpeg } from './verified-ffmpeg-electron'
export interface ElectronCapabilityHostOptions {
appVersion: string
@@ -115,9 +116,12 @@ export async function createElectronCapabilityHost(
platform: process.platform,
envPath: resolveElectronFfmpegEnvPath(),
},
- (candidate) => resolveExecutable(candidate, process.env)
+ (candidate) => resolveVerifiedFfmpeg(opts.userDataDir, candidate)
)
const ffmpeg = new FfmpegCapabilityHost({
+ validateBinaryPath: (binaryPath) => {
+ assertManagedFfmpegTrusted(opts.userDataDir, binaryPath)
+ },
detect: ffmpegLocation.binaryPath
? { available: true, binaryPath: ffmpegLocation.binaryPath }
: { available: false },
diff --git a/src/main/plugin/ffmpeg-detect-electron.ts b/src/main/plugin/ffmpeg-detect-electron.ts
index 48b65fe8..8c80fc06 100644
--- a/src/main/plugin/ffmpeg-detect-electron.ts
+++ b/src/main/plugin/ffmpeg-detect-electron.ts
@@ -37,7 +37,7 @@ export function makeElectronFfmpegDetect(
opts: ElectronFfmpegDetectOptions
): () => Promise<FfmpegDetectionResult> {
const userDataBinariesDir = path.join(opts.userDataDir, 'binaries')
- const probe = makeElectronFfmpegProbe()
+ const probe = makeElectronFfmpegProbe({ userDataDir: opts.userDataDir })
return async () =>
detectInOrder(
{
diff --git a/src/main/plugin/ffmpeg-fetch-electron.test.ts b/src/main/plugin/ffmpeg-fetch-electron.test.ts
new file mode 100644
index 00000000..f6942e8b
--- /dev/null
+++ b/src/main/plugin/ffmpeg-fetch-electron.test.ts
@@ -0,0 +1,189 @@
+// @vitest-environment node
+import { EventEmitter } from 'node:events'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { fetchFfmpegAsset } from './ffmpeg-fetch-electron'
+
+const electron = vi.hoisted(() => ({ request: vi.fn() }))
+vi.mock('electron', () => ({ net: electron }))
+
+class Request extends EventEmitter {
+ abort = vi.fn(() => {
+ this.emit('abort')
+ this.emit('close')
+ })
+ end = vi.fn()
+ followRedirect = vi.fn()
+}
+class Incoming extends EventEmitter {
+ statusCode = 200
+ headers: Record<string, string | string[]> = {
+ 'content-length': '3',
+ 'content-type': 'application/octet-stream',
+ }
+}
+let request: Request
+const url =
+ 'https://github.com/motrixapp/ffmpeg-static/releases/download/v9.0.2-motrix.8/ffmpeg-manifest.json'
+function fetchAsset(signal?: AbortSignal) {
+ return fetchFfmpegAsset(url, {
+ redirect: 'manual',
+ credentials: 'omit',
+ signal,
+ })
+}
+beforeEach(() => {
+ vi.clearAllMocks()
+ request = new Request()
+ electron.request.mockReturnValue(request)
+})
+
+describe('Electron FFmpeg manual-redirect transport', () => {
+ it('exposes one redirect without following or sending cookies/authentication', async () => {
+ const pending = fetchAsset()
+ const destination =
+ 'https://release-assets.githubusercontent.com/asset?temporary=public'
+ request.emit('redirect', 302, 'GET', destination, {})
+ const response = await pending
+ expect(response.status).toBe(302)
+ expect(response.headers.get('location')).toBe(destination)
+ expect(response.body).toBeNull()
+ expect(request.followRedirect).not.toHaveBeenCalled()
+ expect(request.abort).toHaveBeenCalledOnce()
+ expect(electron.request).toHaveBeenCalledWith({
+ url,
+ method: 'GET',
+ redirect: 'manual',
+ credentials: 'omit',
+ useSessionCookies: false,
+ bypassCustomProtocolHandlers: true,
+ cache: 'no-store',
+ })
+ // Chromium emits cancellation after a manual redirect; it must not become unhandled.
+ request.emit('error', new Error('Redirect cancelled'))
+ })
+ it('leaves an untrusted redirect visible to the core rather than requesting it', async () => {
+ const pending = fetchAsset()
+ request.emit('redirect', 302, 'GET', 'http://untrusted.invalid/payload', {})
+ expect((await pending).headers.get('location')).toBe(
+ 'http://untrusted.invalid/payload'
+ )
+ expect(electron.request).toHaveBeenCalledOnce()
+ expect(request.followRedirect).not.toHaveBeenCalled()
+ })
+ it('streams bytes and preserves content-length for the core size limit', async () => {
+ const pending = fetchAsset()
+ // Real Electron emits writable close before the valid response arrives.
+ request.emit('close')
+ const incoming = new Incoming()
+ request.emit('response', incoming)
+ const response = await pending
+ const bytes = response.arrayBuffer()
+ request.emit('close')
+ incoming.emit('data', Buffer.from('abc'))
+ incoming.emit('end')
+ incoming.emit('close')
+ request.emit('close')
+ expect(Buffer.from(await bytes).toString()).toBe('abc')
+ expect(response.headers.get('content-length')).toBe('3')
+ expect(request.abort).not.toHaveBeenCalled()
+ })
+ it('cleans up when ending the native request throws', async () => {
+ request.end.mockImplementation(() => {
+ throw new Error('Native failure')
+ })
+ await expect(fetchAsset()).rejects.toThrow('FFmpeg network request failed')
+ expect(request.abort).toHaveBeenCalledOnce()
+ request.emit('error', new Error('Late error'))
+ })
+ it('does not create a request for an already aborted signal', async () => {
+ const abort = new AbortController()
+ abort.abort()
+ await expect(fetchAsset(abort.signal)).rejects.toThrow()
+ expect(electron.request).not.toHaveBeenCalled()
+ })
+ it('aborts during the body and rejects the pending reader without exposing remote errors', async () => {
+ const abort = new AbortController()
+ const remove = vi.spyOn(abort.signal, 'removeEventListener')
+ const pending = fetchAsset(abort.signal)
+ const incoming = new Incoming()
+ request.emit('response', incoming)
+ const reader = (await pending).body!.getReader()
+ const reading = reader.read()
+ abort.abort()
+ await expect(reading).rejects.toThrow('FFmpeg network request failed')
+ expect(request.abort).toHaveBeenCalledOnce()
+ expect(remove).toHaveBeenCalledWith('abort', expect.any(Function))
+ expect(incoming.listenerCount('data')).toBe(0)
+ expect(incoming.listenerCount('end')).toBe(0)
+ expect(request.listenerCount('redirect')).toBe(0)
+ incoming.emit('data', Buffer.from('late'))
+ incoming.emit('error', new Error('Private remote diagnostic'))
+ })
+ it('cancels the request when the core cancels an oversize response', async () => {
+ const pending = fetchAsset()
+ const incoming = new Incoming()
+ incoming.headers['content-length'] = String(256 * 1024 * 1024)
+ request.emit('response', incoming)
+ const response = await pending
+ expect(response.headers.get('content-length')).toBe(
+ String(256 * 1024 * 1024)
+ )
+ await response.body!.cancel()
+ expect(request.abort).toHaveBeenCalledOnce()
+ expect(incoming.listenerCount('data')).toBe(0)
+ })
+ it('rejects abort before response headers and removes the signal listener', async () => {
+ const abort = new AbortController()
+ const remove = vi.spyOn(abort.signal, 'removeEventListener')
+ const pending = fetchAsset(abort.signal)
+ abort.abort()
+ await expect(pending).rejects.toThrow('FFmpeg network request failed')
+ expect(request.abort).toHaveBeenCalledOnce()
+ expect(remove).toHaveBeenCalledWith('abort', expect.any(Function))
+ request.emit('error', new Error('Late error'))
+ })
+ it.each(['request', 'response', 'aborted', 'close'])(
+ 'rejects a pending reader after a late %s failure',
+ async (source) => {
+ const pending = fetchAsset()
+ const incoming = new Incoming()
+ request.emit('response', incoming)
+ const reading = (await pending).body!.getReader().read()
+ if (source === 'request') request.emit('error', new Error('Remote text'))
+ else if (source === 'response')
+ incoming.emit('error', new Error('Remote text'))
+ else if (source === 'aborted') incoming.emit('aborted')
+ else incoming.emit('close')
+ await expect(reading).rejects.toThrow('FFmpeg network request failed')
+ expect(request.abort).toHaveBeenCalledOnce()
+ }
+ )
+ it('bounds queued bytes when the consumer is not reading', async () => {
+ const pending = fetchAsset()
+ const incoming = new Incoming()
+ request.emit('response', incoming)
+ const response = await pending
+ incoming.emit('data', Buffer.alloc(8 * 1024 * 1024))
+ incoming.emit('data', Buffer.from('over limit'))
+ await expect(response.arrayBuffer()).rejects.toThrow(
+ 'FFmpeg network request failed'
+ )
+ expect(request.abort).toHaveBeenCalledOnce()
+ })
+ it.each([
+ { method: 'POST' },
+ { credentials: 'include' },
+ { redirect: 'follow' },
+ { body: 'payload' },
+ { headers: { authorization: 'not-allowed' } },
+ ])('rejects unsupported request options', async (extra) => {
+ await expect(
+ fetchFfmpegAsset(url, {
+ redirect: 'manual',
+ credentials: 'omit',
+ ...extra,
+ } as RequestInit)
+ ).rejects.toThrow('Unsupported FFmpeg download request')
+ expect(electron.request).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/plugin/ffmpeg-fetch-electron.ts b/src/main/plugin/ffmpeg-fetch-electron.ts
new file mode 100644
index 00000000..87a9e6ba
--- /dev/null
+++ b/src/main/plugin/ffmpeg-fetch-electron.ts
@@ -0,0 +1,158 @@
+import type { EventEmitter } from 'node:events'
+import { net } from 'electron'
+
+const MAX_QUEUED_BYTES = 8 * 1024 * 1024
+
+/**
+ * Electron fetch rejects manual redirects instead of exposing their Location.
+ * Return each redirect without following it so the core can validate every hop.
+ */
+export const fetchFfmpegAsset: typeof fetch = async (input, init) => {
+ if (
+ !(typeof input === 'string' || input instanceof URL) ||
+ init?.redirect !== 'manual' ||
+ init.credentials !== 'omit' ||
+ (init.method !== undefined && init.method !== 'GET') ||
+ init.body !== undefined ||
+ init.headers !== undefined
+ )
+ throw new Error('Unsupported FFmpeg download request')
+ const signal = init.signal
+ signal?.throwIfAborted()
+ return new Promise<Response>((resolve, reject) => {
+ const request = net.request({
+ url: String(input),
+ method: 'GET',
+ redirect: 'manual',
+ credentials: 'omit',
+ useSessionCookies: false,
+ bypassCustomProtocolHandlers: true,
+ cache: 'no-store',
+ })
+ let settled = false
+ let finished = false
+ let controller: ReadableStreamDefaultController<Uint8Array> | undefined
+ const cleanups: (() => void)[] = []
+ const finish = () => {
+ finished = true
+ signal?.removeEventListener('abort', abort)
+ for (const cleanup of cleanups) cleanup()
+ }
+ const fail = () => {
+ if (finished) return
+ finish()
+ const error = new Error('FFmpeg network request failed')
+ if (controller) controller.error(error)
+ if (!settled) {
+ settled = true
+ reject(error)
+ }
+ request.abort()
+ }
+ const abort = () => fail()
+ signal?.addEventListener('abort', abort, { once: true })
+ request.on('error', fail)
+ request.on('abort', fail)
+ cleanups.push(() => {
+ request.off('abort', fail)
+ })
+ // ClientRequest is an auto-destroyed Writable, not the response stream.
+ // Its early close is normal; response close before end is truncation.
+ const redirected = (
+ status: number,
+ _method: string,
+ redirectUrl: string
+ ) => {
+ if (finished || settled) return
+ try {
+ const response = new Response(null, {
+ status,
+ headers: { location: redirectUrl },
+ })
+ settled = true
+ finish()
+ resolve(response)
+ // Never call followRedirect: the next URL has not passed core policy yet.
+ request.abort()
+ } catch {
+ fail()
+ }
+ }
+ request.on('redirect', redirected)
+ cleanups.push(() => request.off('redirect', redirected))
+ const received = (response: Electron.IncomingMessage) => {
+ if (finished || settled) return
+ try {
+ // Installed typings omit close, but the actual IncomingMessage extends Readable.
+ const responseEvents = response as Electron.IncomingMessage &
+ Pick<EventEmitter, 'on' | 'off'>
+ const headers = new Headers()
+ for (const name of ['content-length', 'content-type', 'location']) {
+ const value = response.headers[name]
+ if (value !== undefined)
+ headers.set(name, Array.isArray(value) ? value.join(', ') : value)
+ }
+ const body = new ReadableStream<Uint8Array>(
+ {
+ start(streamController) {
+ controller = streamController
+ // Electron requires end to be registered before data.
+ const ended = () => {
+ if (finished) return
+ finish()
+ streamController.close()
+ }
+ response.on('end', ended)
+ response.on('error', fail)
+ response.on('aborted', fail)
+ responseEvents.on('close', fail)
+ const data = (chunk: Buffer) => {
+ if (finished) return
+ if (
+ chunk.length > MAX_QUEUED_BYTES ||
+ (streamController.desiredSize ?? 0) - chunk.length < 0
+ ) {
+ fail()
+ return
+ }
+ streamController.enqueue(new Uint8Array(chunk))
+ }
+ response.on('data', data)
+ // Keep only the harmless error sink for late Chromium errors.
+ cleanups.push(() => {
+ response.off('end', ended)
+ response.off('aborted', fail)
+ responseEvents.off('close', fail)
+ response.off('data', data)
+ })
+ },
+ cancel() {
+ finish()
+ request.abort()
+ },
+ },
+ new ByteLengthQueuingStrategy({ highWaterMark: MAX_QUEUED_BYTES })
+ )
+ const result = new Response(body, {
+ status: response.statusCode,
+ headers,
+ })
+ settled = true
+ resolve(result)
+ } catch {
+ fail()
+ }
+ }
+ request.on('response', received)
+ cleanups.push(() => request.off('response', received))
+ // An abort can race between the initial check and listener registration.
+ if (signal?.aborted) abort()
+ else {
+ try {
+ request.end()
+ } catch {
+ fail()
+ }
+ }
+ })
+}
diff --git a/src/main/plugin/ffmpeg-macos-trust.test.ts b/src/main/plugin/ffmpeg-macos-trust.test.ts
new file mode 100644
index 00000000..19150de7
--- /dev/null
+++ b/src/main/plugin/ffmpeg-macos-trust.test.ts
@@ -0,0 +1,153 @@
+// @vitest-environment node
+import { createHash } from 'node:crypto'
+import { writeFile } from 'node:fs/promises'
+import type { FfmpegTarget } from '@shared/schemas/ffmpeg-release'
+import { describe, expect, it, vi } from 'vitest'
+import type { RunCommand } from '../cli/command-runner'
+import { verifyMacFfmpegTrust } from './ffmpeg-macos-trust'
+
+const identity = vi.hoisted(() => {
+ const bytes = Buffer.from('ephemeral certificate fixture')
+ return { bytes }
+})
+vi.mock('@shared/config/ffmpeg-macos-certificate.json', () => ({
+ default: {
+ certificateSha256: createHash('sha256')
+ .update(identity.bytes)
+ .digest('hex'),
+ },
+}))
+function target(): FfmpegTarget {
+ return {
+ platform: 'darwin',
+ signing: {
+ identity: {
+ teamId: 'TESTTEAM01',
+ subject: 'Developer ID Application: Test (TESTTEAM01)',
+ certificateSha256: createHash('sha256')
+ .update(identity.bytes)
+ .digest('hex'),
+ },
+ binaries: {
+ ffmpeg: { cdHash: 'a'.repeat(40), timestamp: '2026-09-30T12:00:00Z' },
+ ffprobe: { cdHash: 'a'.repeat(40), timestamp: '2026-09-30T12:00:00Z' },
+ },
+ },
+ } as FfmpegTarget
+}
+function runner(violation?: string) {
+ return vi.fn<RunCommand>(async (command, args) => {
+ if (violation === 'os-failed')
+ return { code: 1, stdout: '', stderr: 'rejected' }
+ if (violation === 'truncated')
+ return { code: 0, stdout: '', stderr: '', truncated: true }
+ if (
+ args.includes('--verify') &&
+ ['notary', 'expired', 'apple-unavailable'].includes(violation ?? '')
+ )
+ return {
+ code: 1,
+ stdout: '',
+ stderr: 'explicit trust requirement failed',
+ }
+ if (violation === 'timeout')
+ return { code: null, stdout: '', stderr: '', timedOut: true }
+ if (args.some((arg) => arg.startsWith('--extract-certificates='))) {
+ const prefix = args
+ .find((arg) => arg.startsWith('--extract-certificates='))!
+ .split('=')[1]
+ await writeFile(
+ `${prefix}0`,
+ violation === 'certificate' ? Buffer.from('wrong cert') : identity.bytes
+ )
+ }
+ if (args.includes('--verbose=4') && command.endsWith('codesign')) {
+ const name = args.at(-1)!.endsWith('ffprobe') ? 'ffprobe' : 'ffmpeg'
+ let stderr = `Identifier=net.agalwood.motrix.${name}\nTeamIdentifier=TESTTEAM01\nCDHash=${'a'.repeat(40)}\nTimestamp=Sep 30, 2026 at 12:00:00 PM\nAuthority=Developer ID Application: Test (TESTTEAM01)\nCodeDirectory v=20500 size=42 flags=0x10000(runtime)\n`
+ if (violation === 'team')
+ stderr = stderr.replace(
+ 'TeamIdentifier=TESTTEAM01',
+ 'TeamIdentifier=WRONGTEAM1'
+ )
+ if (violation === 'cdhash')
+ stderr = stderr.replace('CDHash=aa', 'CDHash=bb')
+ if (violation === 'timestamp')
+ stderr = stderr.replace(
+ 'Timestamp=Sep 30, 2026 at 12:00:00 PM',
+ 'Timestamp=none'
+ )
+ if (violation === 'nbsp') stderr = stderr.replace('00 PM', '00\u00a0PM')
+ if (violation === 'narrow-nbsp')
+ stderr = stderr.replace('00 PM', '00\u202fPM')
+ if (violation === 'hardened')
+ stderr = stderr.replace('flags=0x10000(runtime)', 'flags=0x0(none)')
+ if (violation === 'ambiguous') stderr += 'TeamIdentifier=TESTTEAM01\n'
+ return { code: 0, stdout: '', stderr }
+ }
+ return { code: 0, stdout: '', stderr: '' }
+ })
+}
+const url =
+ 'https://github.com/motrixapp/ffmpeg-static/releases/download/v9.0.2-motrix.8/ffmpeg-9.0.2-motrix.8-darwin-arm64.zip'
+describe('managed macOS FFmpeg system trust', () => {
+ it('checks both CLI binaries with Apple anchoring, online notarization, a pinned leaf certificate and secure UTC timestamps', async () => {
+ const run = runner()
+ await verifyMacFfmpegTrust('/fixture', target(), url, run)
+ const calls = run.mock.calls
+ expect(calls.filter(([command]) => command.endsWith('spctl'))).toHaveLength(
+ 0
+ )
+ expect(calls.filter(([command]) => command.endsWith('xattr'))).toHaveLength(
+ 2
+ )
+ expect(calls.filter(([, args]) => args.includes('--verify'))).toHaveLength(
+ 2
+ )
+ for (const [, args] of calls.filter(([, args]) =>
+ args.includes('--verify')
+ )) {
+ expect(args[args.indexOf('-R') + 1]).toBe(
+ '=anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and notarized'
+ )
+ expect(args).toContain('--check-notarization')
+ }
+ expect(calls.every(([, , options]) => options?.env?.TZ === 'UTC')).toBe(
+ true
+ )
+ expect(
+ calls.some(([, args]) => args.includes('-d') || args.includes('-c'))
+ ).toBe(false)
+ })
+ it.each(['nbsp', 'narrow-nbsp'])(
+ 'accepts the macOS %s AM/PM separator without relaxing timestamp evidence',
+ async (separator) => {
+ await expect(
+ verifyMacFfmpegTrust('/fixture', target(), url, runner(separator))
+ ).resolves.toBeUndefined()
+ }
+ )
+ it.each([
+ 'certificate',
+ 'team',
+ 'cdhash',
+ 'timestamp',
+ 'hardened',
+ 'ambiguous',
+ 'notary',
+ 'expired',
+ 'apple-unavailable',
+ 'timeout',
+ 'os-failed',
+ 'truncated',
+ ])('fails closed on %s without executing the payload', async (violation) => {
+ const run = runner(violation)
+ await expect(
+ verifyMacFfmpegTrust('/fixture', target(), url, run)
+ ).rejects.toThrow()
+ expect(
+ run.mock.calls.every(([command]) =>
+ ['/usr/bin/xattr', '/usr/bin/codesign'].includes(command)
+ )
+ ).toBe(true)
+ })
+})
diff --git a/src/main/plugin/ffmpeg-macos-trust.ts b/src/main/plugin/ffmpeg-macos-trust.ts
new file mode 100644
index 00000000..683cae85
--- /dev/null
+++ b/src/main/plugin/ffmpeg-macos-trust.ts
@@ -0,0 +1,147 @@
+import { randomUUID } from 'node:crypto'
+import { mkdtemp, readFile, rm } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { sha256 } from '@core/ffmpeg/verified-release'
+import certificate from '@shared/config/ffmpeg-macos-certificate.json'
+import type { FfmpegTarget } from '@shared/schemas/ffmpeg-release'
+import { type RunCommand, runCommand } from '../cli/command-runner'
+
+/** Static OS checks only. Never execute an unverified payload or remove quarantine. */
+export async function verifyMacFfmpegTrust(
+ directory: string,
+ target: FfmpegTarget,
+ sourceUrl: string,
+ run: RunCommand = runCommand
+): Promise<void> {
+ const signing = target.signing
+ if (
+ target.platform !== 'darwin' ||
+ !signing ||
+ signing.identity.certificateSha256 !== certificate.certificateSha256
+ )
+ throw new Error('Unexpected Developer ID identity')
+ const temporary = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-ffmpeg-certificate-')
+ )
+ const checked = async (command: string, args: string[]) => {
+ const result = await run(command, args, {
+ env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
+ timeoutMs: 30_000,
+ maxBuffer: 64_000,
+ })
+ if (
+ result.code !== 0 ||
+ result.spawnError ||
+ result.timedOut ||
+ result.truncated
+ )
+ throw new Error('FFmpeg system trust check failed')
+ return result
+ }
+ try {
+ for (const name of ['ffmpeg', 'ffprobe'] as const) {
+ const binary = path.join(directory, name)
+ // Chromium networking does not propagate Finder quarantine; mark this Internet download explicitly.
+ await checked('/usr/bin/xattr', [
+ '-w',
+ 'com.apple.quarantine',
+ `0081;${Math.floor(Date.now() / 1000).toString(16)};Motrix;${randomUUID()}`,
+ binary,
+ ])
+ // The source URL is bounded by the authenticated target and fixed repository.
+ if (
+ !sourceUrl.startsWith(
+ 'https://github.com/motrixapp/ffmpeg-static/releases/download/'
+ )
+ )
+ throw new Error('Unexpected FFmpeg source')
+ await checked('/usr/bin/codesign', [
+ '--verify',
+ '--strict',
+ '--check-notarization',
+ '--verbose=2',
+ '-R',
+ '=anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and notarized',
+ binary,
+ ])
+ const display = await checked('/usr/bin/codesign', [
+ '--display',
+ '--verbose=4',
+ binary,
+ ])
+ const text = `${display.stdout}\n${display.stderr}`
+ const field = (label: string) => {
+ const values = text
+ .split(/\r?\n/)
+ .filter((line) => line.startsWith(`${label}=`))
+ .map((line) => line.slice(label.length + 1))
+ if (values.length !== 1)
+ throw new Error('Ambiguous FFmpeg signing identity')
+ return values[0]
+ }
+ const record = signing.binaries[name]
+ // macOS locales can retain a nonbreaking AM/PM separator even with LC_ALL=C.
+ // Normalize horizontal whitespace only; line breaks must never be accepted here.
+ const rawTimestamp = field('Timestamp').replace(
+ /[ \t\u00a0\u202f]+/g,
+ ' '
+ )
+ const timestamp =
+ /^([A-Z][a-z]{2}) (\d{1,2}), (\d{4}) at (\d{1,2}):(\d{2}):(\d{2})(?: (AM|PM))?$/.exec(
+ rawTimestamp
+ )
+ if (!timestamp) throw new Error('Missing secure FFmpeg timestamp')
+ const month = [
+ 'Jan',
+ 'Feb',
+ 'Mar',
+ 'Apr',
+ 'May',
+ 'Jun',
+ 'Jul',
+ 'Aug',
+ 'Sep',
+ 'Oct',
+ 'Nov',
+ 'Dec',
+ ].indexOf(timestamp[1])
+ let hour = Number(timestamp[4])
+ if (timestamp[7]) {
+ if (hour < 1 || hour > 12)
+ throw new Error('Invalid secure FFmpeg timestamp')
+ hour = (hour % 12) + (timestamp[7] === 'PM' ? 12 : 0)
+ }
+ const canonicalTimestamp = `${timestamp[3]}-${String(month + 1).padStart(2, '0')}-${timestamp[2].padStart(2, '0')}T${String(hour).padStart(2, '0')}:${timestamp[5]}:${timestamp[6]}Z`
+ const flags = /flags=0x([0-9a-f]+)\(/i.exec(text)
+ // The Team ID is authenticated by the pinned manifest and compared only in memory.
+ if (
+ field('TeamIdentifier') !== signing.identity.teamId ||
+ field('CDHash') !== record.cdHash ||
+ month < 0 ||
+ canonicalTimestamp !== record.timestamp ||
+ field('Identifier') !== `net.agalwood.motrix.${name}` ||
+ !text
+ .split(/\r?\n/)
+ .includes(`Authority=${signing.identity.subject}`) ||
+ !flags ||
+ (Number.parseInt(flags[1], 16) & 0x10000) === 0
+ )
+ throw new Error('FFmpeg signature evidence mismatch')
+ const prefix = path.join(temporary, name)
+ await checked('/usr/bin/codesign', [
+ '--display',
+ `--extract-certificates=${prefix}`,
+ binary,
+ ])
+ if (
+ sha256(await readFile(`${prefix}0`)) !== certificate.certificateSha256
+ )
+ throw new Error('FFmpeg leaf certificate mismatch')
+ // Apple prescribes the notarized requirement for standalone CLI tools;
+ // spctl's application assessment rejects valid non-app executables.
+ }
+ } finally {
+ await rm(temporary, { recursive: true, force: true })
+ }
+}
diff --git a/src/main/plugin/ffmpeg-probe-electron.ts b/src/main/plugin/ffmpeg-probe-electron.ts
index 936c7dfb..34643fa3 100644
--- a/src/main/plugin/ffmpeg-probe-electron.ts
+++ b/src/main/plugin/ffmpeg-probe-electron.ts
@@ -1,17 +1,25 @@
-// Electron-host FFmpeg probe with a non-executing macOS trust preflight.
-//
-// Candidate paths are resolved to an existing executable before any probe is
-// attempted. On macOS, quarantined binaries are assessed by Gatekeeper first,
-// so a rejected binary is never spawned merely to discover its version.
+// Resolve candidates and check trust before executing any version probe.
+// Managed macOS CLI tools require authenticated metadata, hashes and Apple's
+// online notarized code requirement. External quarantined paths keep their
+// existing Gatekeeper application assessment, without any fallback on denial.
import path from 'node:path'
+import {
+ assertManagedFfmpegTrusted,
+ resolveManagedFfmpegCandidate,
+} from '@core/ffmpeg/verified-install'
import {
type FfmpegDetection,
type FfmpegDetectionFailureReason,
probeBinary,
} from '@core/plugin/capabilities/ffmpeg-detect'
+import {
+ FFMPEG_REPOSITORY,
+ type FfmpegTarget,
+} from '@shared/schemas/ffmpeg-release'
import { type RunCommand, runCommand } from '../cli/command-runner'
import { resolveExecutable } from '../cli/shell-environment'
+import { verifyMacFfmpegTrust } from './ffmpeg-macos-trust'
const XATTR_BIN = '/usr/bin/xattr'
const SPCTL_BIN = '/usr/sbin/spctl'
@@ -35,6 +43,7 @@ type ProbeFfmpegBinary = (
) => Promise<ElectronFfmpegProbeResult>
export interface ElectronFfmpegProbeOptions {
+ userDataDir?: string
platform?: NodeJS.Platform
env?: NodeJS.ProcessEnv
run?: RunCommand
@@ -67,10 +76,27 @@ export function makeElectronFfmpegProbe(
return async (candidate) => {
let resolved: string | null
+ let managedTarget: FfmpegTarget | undefined
try {
+ if (
+ options.userDataDir &&
+ ['darwin', 'linux', 'win32'].includes(platform)
+ ) {
+ candidate = resolveManagedFfmpegCandidate(
+ options.userDataDir,
+ candidate,
+ platform as 'darwin' | 'linux' | 'win32'
+ )
+ }
resolved = await resolve(candidate, env, { platform })
+ if (options.userDataDir && resolved) {
+ managedTarget = assertManagedFfmpegTrusted(
+ options.userDataDir,
+ resolved
+ )
+ }
} catch {
- return unavailable('missing')
+ return unavailable(options.userDataDir ? 'untrusted' : 'missing')
}
if (!resolved || !pathApi.isAbsolute(resolved)) {
@@ -79,6 +105,20 @@ export function makeElectronFfmpegProbe(
if (platform !== 'darwin') return probe(resolved)
+ if (managedTarget) {
+ try {
+ await verifyMacFfmpegTrust(
+ path.dirname(resolved),
+ managedTarget,
+ `https://github.com/${FFMPEG_REPOSITORY}/releases/download/v${managedTarget.releaseVersion}/${managedTarget.archive}`,
+ run
+ )
+ } catch {
+ return unavailable('untrusted', resolved)
+ }
+ return probe(resolved)
+ }
+
let quarantineResult: Awaited<ReturnType<RunCommand>>
try {
quarantineResult = await run(XATTR_BIN, [resolved], {
diff --git a/src/main/plugin/ffmpeg-probe-managed.test.ts b/src/main/plugin/ffmpeg-probe-managed.test.ts
new file mode 100644
index 00000000..79bc8bbf
--- /dev/null
+++ b/src/main/plugin/ffmpeg-probe-managed.test.ts
@@ -0,0 +1,102 @@
+// @vitest-environment node
+import type { FfmpegTarget } from '@shared/schemas/ffmpeg-release'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { makeElectronFfmpegProbe } from './ffmpeg-probe-electron'
+
+const guards = vi.hoisted(() => ({
+ authenticated: vi.fn(),
+ candidate: vi.fn(),
+ systemTrust: vi.fn(),
+}))
+vi.mock('@core/ffmpeg/verified-install', () => ({
+ assertManagedFfmpegTrusted: guards.authenticated,
+ resolveManagedFfmpegCandidate: guards.candidate,
+}))
+vi.mock('./ffmpeg-macos-trust', () => ({
+ verifyMacFfmpegTrust: guards.systemTrust,
+}))
+
+const userDataDir = '/fixture/user-data'
+const managedBinary =
+ '/fixture/user-data/ffmpeg-verified/releases/verified-darwin-arm64/ffmpeg'
+const target = {
+ platform: 'darwin',
+ arch: 'arm64',
+ releaseVersion: '9.0.2-motrix.8',
+ archive: 'ffmpeg-9.0.2-motrix.8-darwin-arm64.zip',
+} as FfmpegTarget
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ guards.candidate.mockReturnValue(managedBinary)
+ guards.authenticated.mockReturnValue(target)
+ guards.systemTrust.mockResolvedValue(undefined)
+})
+describe('authenticated managed macOS FFmpeg probing', () => {
+ it('requires the authenticated target and full CLI notarization before executing the version probe', async () => {
+ const probe = vi.fn(async () => ({
+ available: true,
+ binaryPath: managedBinary,
+ version: '9.0.2',
+ }))
+ const run = vi.fn()
+ await expect(
+ makeElectronFfmpegProbe({
+ userDataDir,
+ platform: 'darwin',
+ resolve: async () => managedBinary,
+ run,
+ probe,
+ })('/fixture/user-data/binaries/ffmpeg')
+ ).resolves.toMatchObject({ available: true })
+ expect(guards.authenticated).toHaveBeenCalledWith(
+ userDataDir,
+ managedBinary
+ )
+ expect(guards.systemTrust).toHaveBeenCalledWith(
+ '/fixture/user-data/ffmpeg-verified/releases/verified-darwin-arm64',
+ target,
+ 'https://github.com/motrixapp/ffmpeg-static/releases/download/v9.0.2-motrix.8/ffmpeg-9.0.2-motrix.8-darwin-arm64.zip',
+ run
+ )
+ expect(guards.systemTrust.mock.invocationCallOrder[0]).toBeLessThan(
+ probe.mock.invocationCallOrder[0]
+ )
+ expect(run).not.toHaveBeenCalled()
+ })
+ it.each(['invalid receipt', 'missing signature', 'modified binary'])(
+ 'does not execute code when the managed guard rejects %s',
+ async (reason) => {
+ guards.authenticated.mockImplementation(() => {
+ throw new Error(reason)
+ })
+ const probe = vi.fn()
+ await expect(
+ makeElectronFfmpegProbe({
+ userDataDir,
+ platform: 'darwin',
+ resolve: async () => managedBinary,
+ probe,
+ })('/fixture/user-data/binaries/ffmpeg')
+ ).resolves.toMatchObject({ available: false, failureReason: 'untrusted' })
+ expect(guards.systemTrust).not.toHaveBeenCalled()
+ expect(probe).not.toHaveBeenCalled()
+ }
+ )
+ it.each(['not notarized', 'incorrect identity', 'Apple service unavailable'])(
+ 'does not execute code when the real CLI checker rejects %s',
+ async (reason) => {
+ guards.systemTrust.mockRejectedValue(new Error(reason))
+ const probe = vi.fn()
+ await expect(
+ makeElectronFfmpegProbe({
+ userDataDir,
+ platform: 'darwin',
+ resolve: async () => managedBinary,
+ probe,
+ })('/fixture/user-data/binaries/ffmpeg')
+ ).resolves.toMatchObject({ available: false, failureReason: 'untrusted' })
+ expect(probe).not.toHaveBeenCalled()
+ }
+ )
+})
diff --git a/src/main/plugin/verified-ffmpeg-electron.ts b/src/main/plugin/verified-ffmpeg-electron.ts
new file mode 100644
index 00000000..32f3eb1c
--- /dev/null
+++ b/src/main/plugin/verified-ffmpeg-electron.ts
@@ -0,0 +1,58 @@
+import {
+ assertManagedFfmpegTrusted,
+ getFfmpegInstallStatus,
+ installVerifiedFfmpeg,
+ resolveManagedFfmpegCandidate,
+} from '@core/ffmpeg/verified-install'
+import { AppError, ErrorCode } from '@shared/errors'
+import type {
+ FfmpegInstallStatus,
+ FfmpegPlatform,
+} from '@shared/schemas/ffmpeg-release'
+import { resolveExecutable } from '../cli/shell-environment'
+import { fetchFfmpegAsset } from './ffmpeg-fetch-electron'
+import { verifyMacFfmpegTrust } from './ffmpeg-macos-trust'
+
+export async function resolveVerifiedFfmpeg(
+ userDataDir: string,
+ candidate: string
+) {
+ try {
+ const mapped = resolveManagedFfmpegCandidate(userDataDir, candidate)
+ const resolved = await resolveExecutable(mapped, process.env)
+ if (resolved) assertManagedFfmpegTrusted(userDataDir, resolved)
+ return resolved
+ } catch {
+ return null
+ }
+}
+
+export async function installManagedFfmpeg(
+ userDataDir: string,
+ onStatus?: (status: FfmpegInstallStatus) => void
+) {
+ if (
+ !['darwin', 'linux', 'win32'].includes(process.platform) ||
+ !['x64', 'arm64'].includes(process.arch)
+ )
+ return { ok: false as const, error: 'unsupported' as const }
+ try {
+ return await installVerifiedFfmpeg({
+ userDataDir,
+ arch: process.arch as 'x64' | 'arm64',
+ platform: process.platform as FfmpegPlatform,
+ onStatus,
+ systemTrust: verifyMacFfmpegTrust,
+ fetcher: fetchFfmpegAsset,
+ })
+ } catch (error) {
+ // No remote error text crosses IPC. Failed installs retain the last verified version.
+ return {
+ ok: false as const,
+ error:
+ error instanceof AppError && error.code === ErrorCode.FfmpegInstallBusy
+ ? ('busy' as const)
+ : (getFfmpegInstallStatus(userDataDir).error ?? ('install' as const)),
+ }
+ }
+}
diff --git a/src/renderer/hooks/use-ffmpeg-install.ts b/src/renderer/hooks/use-ffmpeg-install.ts
new file mode 100644
index 00000000..c3972997
--- /dev/null
+++ b/src/renderer/hooks/use-ffmpeg-install.ts
@@ -0,0 +1,57 @@
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import {
+ type FfmpegInstallStatus,
+ ffmpegInstallResultSchema,
+ ffmpegInstallStatusSchema,
+} from '@shared/schemas/ffmpeg-release'
+import { useRef, useState } from 'react'
+import { useTransportMirror } from './use-transport-mirror'
+
+const busyPhases = new Set([
+ 'metadata',
+ 'downloading',
+ 'verifying',
+ 'extracting',
+ 'systemTrust',
+ 'installing',
+])
+
+export function useFfmpegInstall() {
+ const [status, setStatus] = useState<FfmpegInstallStatus | null>(null)
+ const [submitting, setSubmitting] = useState(false)
+ const pending = useRef(false)
+ const { refresh } = useTransportMirror({
+ events: [Events.FfmpegInstallStatusChanged],
+ refreshOnSettingsSave: false,
+ load: async (stale) => {
+ if (transport.platform === 'web') return
+ const next = ffmpegInstallStatusSchema.parse(
+ await transport.invoke(Queries.GetFfmpegInstallStatus)
+ )
+ if (!stale()) setStatus(next)
+ },
+ })
+ const install = async () => {
+ if (pending.current || (status && busyPhases.has(status.phase))) return null
+ pending.current = true
+ setSubmitting(true)
+ try {
+ const result = ffmpegInstallResultSchema.parse(
+ await transport.invoke(Commands.InstallFfmpeg)
+ )
+ await refresh()
+ return result
+ } finally {
+ pending.current = false
+ setSubmitting(false)
+ }
+ }
+ return {
+ status,
+ installing: submitting || Boolean(status && busyPhases.has(status.phase)),
+ install,
+ }
+}
diff --git a/src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx b/src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx
index ed390973..48361dff 100644
--- a/src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx
+++ b/src/renderer/routes/settings/cards/integration/media-tools-section.test.tsx
@@ -6,6 +6,9 @@ import {
} from '@renderer/components/settings-kit/use-settings-form'
import { transport } from '@renderer/lib/transport'
import { EXTERNAL_URLS } from '@shared/external-urls'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
import { DEFAULT_MEDIA_SETTINGS } from '@shared/schemas'
import {
fireEvent,
@@ -23,6 +26,8 @@ import { MediaToolsSection } from './media-tools-section'
vi.mock('@renderer/lib/transport', () => ({
transport: {
invoke: vi.fn(),
+ on: vi.fn(),
+ off: vi.fn(),
},
}))
@@ -50,14 +55,215 @@ function TestForm({
}
describe('MediaToolsSection', () => {
+ it.each(['darwin', 'linux'])(
+ 'offers verified one-click install on %s only after consent',
+ async (platform) => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: platform,
+ })
+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>
+ channel === Commands.InstallFfmpeg
+ ? { ok: true, releaseVersion: '9.0.2-motrix.2' }
+ : channel === Queries.GetFfmpegInstallStatus
+ ? {
+ phase: 'idle',
+ bytesReceived: 0,
+ bytesTotal: 0,
+ percent: null,
+ directory: null,
+ releaseVersion: null,
+ error: null,
+ }
+ : { active: null, candidates: [] }
+ )
+ render(<TestForm />)
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Download FFmpeg' })
+ )
+ expect(transport.invoke).not.toHaveBeenCalledWith(Commands.InstallFfmpeg)
+ expect(
+ screen.getByText(/GPL-licensed; included licenses/)
+ ).toBeInTheDocument()
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Download and verify' })
+ )
+ await waitFor(() =>
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Verified and installed.'
+ )
+ )
+ }
+ )
+ it('mirrors an in-flight download after reopening, shows byte progress, and prevents duplicate operations', async () => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'linux',
+ })
+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>
+ channel === Queries.GetFfmpegInstallStatus
+ ? {
+ phase: 'downloading',
+ bytesReceived: 50,
+ bytesTotal: 100,
+ percent: 0.5,
+ directory: null,
+ releaseVersion: '9.0.2-motrix.2',
+ error: null,
+ }
+ : { active: null, candidates: [] }
+ )
+ render(<TestForm />)
+ expect(
+ await screen.findByRole('progressbar', {
+ name: 'FFmpeg download progress',
+ })
+ ).toHaveAttribute('aria-valuenow', '50')
+ expect(screen.getByText('50 / 100 bytes')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Verifying…' })).toBeDisabled()
+ fireEvent.click(screen.getByRole('button', { name: 'Verifying…' }))
+ expect(transport.invoke).not.toHaveBeenCalledWith(Commands.InstallFfmpeg)
+ expect(transport.on).toHaveBeenCalledWith(
+ Events.FfmpegInstallStatusChanged,
+ expect.any(Function)
+ )
+ })
beforeEach(() => {
vi.clearAllMocks()
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: undefined,
+ })
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText: vi.fn().mockResolvedValue(undefined) },
})
})
+ it('requires an explicit Windows install action and reports failed verification', async () => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'win32',
+ })
+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>
+ channel === Commands.InstallFfmpeg
+ ? { ok: false, error: 'verification' }
+ : channel === Queries.GetFfmpegInstallStatus
+ ? {
+ phase: 'idle',
+ bytesReceived: 0,
+ bytesTotal: 0,
+ percent: null,
+ directory: null,
+ releaseVersion: null,
+ error: null,
+ }
+ : { active: null, candidates: [] }
+ )
+ render(<TestForm />)
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Download FFmpeg' })
+ )
+ expect(transport.invoke).not.toHaveBeenCalledWith(Commands.InstallFfmpeg)
+ expect(
+ screen.getByText(/no public Authenticode signature/)
+ ).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Download and verify' }))
+ await waitFor(() =>
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Download or verification failed'
+ )
+ )
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.InstallFfmpeg)
+ expect(
+ screen.queryByText('Verified and installed.')
+ ).not.toBeInTheDocument()
+ })
+
+ it('refreshes detection only after successful verified Windows installation', async () => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'win32',
+ })
+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>
+ channel === Commands.InstallFfmpeg
+ ? { ok: true, releaseVersion: '9.0.2-motrix.2' }
+ : channel === Queries.GetFfmpegInstallStatus
+ ? {
+ phase: 'idle',
+ bytesReceived: 0,
+ bytesTotal: 0,
+ percent: null,
+ directory: null,
+ releaseVersion: null,
+ error: null,
+ }
+ : { active: null, candidates: [] }
+ )
+ render(<TestForm />)
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Download FFmpeg' })
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Download and verify' }))
+ await waitFor(() =>
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Verified and installed.'
+ )
+ )
+ expect(
+ vi
+ .mocked(transport.invoke)
+ .mock.calls.filter(
+ ([channel]) => channel === Queries.GetFfmpegDetection
+ )
+ ).toHaveLength(2)
+ })
+ it('keeps a successful install result when the separate detection refresh fails', async () => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'darwin',
+ })
+ let detections = 0
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === Commands.InstallFfmpeg)
+ return { ok: true, releaseVersion: '9.0.2-motrix.8' }
+ if (channel === Queries.GetFfmpegInstallStatus)
+ return {
+ phase: 'idle',
+ bytesReceived: 0,
+ bytesTotal: 0,
+ percent: null,
+ directory: null,
+ releaseVersion: null,
+ error: null,
+ }
+ if (channel === Queries.GetFfmpegDetection && ++detections > 1)
+ throw new Error('detection refresh unavailable')
+ return { active: null, candidates: [] }
+ })
+ render(<TestForm />)
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Download FFmpeg' })
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Download and verify' }))
+ await waitFor(() =>
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Verified and installed.'
+ )
+ )
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'Couldn’t refresh FFmpeg detection'
+ )
+ expect(
+ screen.getByText(
+ 'Restart Motrix for active plugins to detect the installation.'
+ )
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByText(/Download or verification failed/)
+ ).not.toBeInTheDocument()
+ })
+
it('places the FFmpeg download action before refresh without a separate card', async () => {
vi.mocked(transport.invoke).mockResolvedValue({
active: null,
diff --git a/src/renderer/routes/settings/cards/integration/media-tools-section.tsx b/src/renderer/routes/settings/cards/integration/media-tools-section.tsx
index 03928120..b2b4d228 100644
--- a/src/renderer/routes/settings/cards/integration/media-tools-section.tsx
+++ b/src/renderer/routes/settings/cards/integration/media-tools-section.tsx
@@ -25,6 +25,8 @@ import {
FormMessage,
} from '@renderer/components/ui/form'
import { Input } from '@renderer/components/ui/input'
+import { Progress } from '@renderer/components/ui/progress'
+import { useFfmpegInstall } from '@renderer/hooks/use-ffmpeg-install'
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
import { EXTERNAL_URLS } from '@shared/external-urls'
@@ -74,6 +76,21 @@ export function MediaToolsSection() {
)
const [detailsOpen, setDetailsOpen] = useState(false)
const [customPathEditing, setCustomPathEditing] = useState(false)
+ const [installPrompt, setInstallPrompt] = useState(false)
+ const {
+ status: installStatus,
+ installing,
+ install: installFfmpeg,
+ } = useFfmpegInstall()
+ const [installResult, setInstallResult] = useState<
+ 'installed' | 'failed' | null
+ >(null)
+ const [installError, setInstallError] = useState<string | null>(null)
+ const [detectionRefreshFailed, setDetectionRefreshFailed] = useState(false)
+ const canInstall = ['darwin', 'linux', 'win32'].includes(transport.platform)
+ const visibleResult =
+ installResult ?? (installStatus?.phase === 'failed' ? 'failed' : null)
+ const visibleError = installError ?? installStatus?.error
const pathError = form.formState.errors.media?.ffmpegBinaryPath
const editingPath = customPathEditing || Boolean(pathError)
@@ -92,10 +109,31 @@ export function MediaToolsSection() {
}, [])
const refresh = async () => {
- const r = (await transport.invoke(
- Queries.GetFfmpegDetection
- )) as FfmpegDetectionResultUI
- setDetection(r)
+ try {
+ const r = (await transport.invoke(
+ Queries.GetFfmpegDetection
+ )) as FfmpegDetectionResultUI
+ setDetection(r)
+ setDetectionRefreshFailed(false)
+ } catch {
+ // Detection is independent of the already committed installation result.
+ setDetectionRefreshFailed(true)
+ }
+ }
+
+ const install = async () => {
+ setInstallResult(null)
+ setInstallError(null)
+ try {
+ const result = await installFfmpeg()
+ if (!result) return
+ setInstallResult(result.ok ? 'installed' : 'failed')
+ if (!result.ok) setInstallError(result.error)
+ if (result.ok) await refresh()
+ } catch {
+ setInstallResult('failed')
+ setInstallError('download')
+ }
}
const activeCandidate = detection?.candidates.find(
@@ -112,14 +150,22 @@ export function MediaToolsSection() {
version: detection.active.version,
})
: hasUntrustedCandidate
- ? t('settings.integration.media.detection.untrustedTitle')
+ ? t(
+ transport.platform === 'win32'
+ ? 'settings.integration.media.download.failed'
+ : 'settings.integration.media.detection.untrustedTitle'
+ )
: t('settings.integration.media.detection.unavailableTitle')
const activeDescription = detection?.active
? t('settings.integration.media.detection.usingSource', {
source: activeSource,
})
: hasUntrustedCandidate
- ? t('settings.integration.media.detection.untrustedDesc')
+ ? t(
+ transport.platform === 'win32'
+ ? 'settings.integration.media.download.disclosure'
+ : 'settings.integration.media.detection.untrustedDesc'
+ )
: t('settings.integration.media.detection.unavailableDesc')
const candidates = detection?.candidates ?? []
const editableCandidates: FfmpegDetectionResultUI['candidates'] =
@@ -148,27 +194,43 @@ export function MediaToolsSection() {
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
- <Button
- render={
- <a
- href={EXTERNAL_URLS.github.ffmpegStaticReleases}
- target="_blank"
- rel="noopener noreferrer"
- aria-label={t('settings.integration.media.download.action')}
- title={t('settings.integration.media.download.action')}
- // biome-ignore lint/a11y/noRedundantRoles: Base UI Button applies button semantics unless this rendered anchor explicitly overrides them.
- role="link"
+ {canInstall ? (
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ disabled={installing}
+ aria-label={t('settings.integration.media.download.action')}
+ onClick={() => setInstallPrompt(true)}
+ >
+ <InstallIcon
+ className="size-4 text-muted-foreground"
+ aria-hidden
/>
- }
- nativeButton={false}
- size="icon-sm"
- variant="ghost"
- >
- <InstallIcon
- className="size-4 text-muted-foreground"
- aria-hidden
- />
- </Button>
+ </Button>
+ ) : (
+ <Button
+ render={
+ <a
+ href={EXTERNAL_URLS.github.ffmpegStaticReleases}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={t('settings.integration.media.download.action')}
+ title={t('settings.integration.media.download.action')}
+ // biome-ignore lint/a11y/noRedundantRoles: Base UI Button applies button semantics unless this rendered anchor explicitly overrides them.
+ role="link"
+ />
+ }
+ nativeButton={false}
+ size="icon-sm"
+ variant="ghost"
+ >
+ <InstallIcon
+ className="size-4 text-muted-foreground"
+ aria-hidden
+ />
+ </Button>
+ )}
<Button
type="button"
size="icon-sm"
@@ -181,6 +243,85 @@ export function MediaToolsSection() {
</div>
</div>
+ {(installPrompt || installing || visibleResult) && canInstall && (
+ <div className="space-y-2 text-xs text-muted-foreground">
+ <p>{t('settings.integration.media.download.projectDisclosure')}</p>
+ {transport.platform === 'win32' && (
+ <p>{t('settings.integration.media.download.disclosure')}</p>
+ )}
+ {transport.platform === 'darwin' && (
+ <p>{t('settings.integration.media.download.macDisclosure')}</p>
+ )}
+ <Button
+ type="button"
+ size="sm"
+ disabled={installing}
+ onClick={install}
+ >
+ {t(
+ `settings.integration.media.download.${installing ? 'installing' : 'verifyInstall'}`
+ )}
+ </Button>
+ {installing && installStatus && (
+ <div className="space-y-1" role="status" aria-live="polite">
+ <p>
+ {t(
+ `settings.integration.media.download.phases.${installStatus.phase}`
+ )}
+ </p>
+ {installStatus.percent !== null && (
+ <Progress
+ value={installStatus.percent * 100}
+ aria-label={t(
+ 'settings.integration.media.download.progress'
+ )}
+ />
+ )}
+ {installStatus.phase === 'downloading' && (
+ <p>
+ {t('settings.integration.media.download.bytes', {
+ received: installStatus.bytesReceived.toLocaleString(),
+ total: installStatus.bytesTotal.toLocaleString(),
+ })}
+ </p>
+ )}
+ </div>
+ )}
+ {visibleResult && (
+ <p role="status">
+ {t(`settings.integration.media.download.${visibleResult}`)}
+ {visibleError && (
+ <span>
+ {' '}
+ {t(
+ `settings.integration.media.download.errors.${visibleError}`
+ )}
+ </span>
+ )}
+ </p>
+ )}
+ {visibleResult === 'installed' && (
+ <p>
+ {t('settings.integration.media.download.restartPluginHint')}
+ </p>
+ )}
+ {installStatus?.directory && (
+ <p className="break-all">
+ {t('settings.integration.media.download.directory', {
+ path: installStatus.directory,
+ })}
+ </p>
+ )}
+ {detectionRefreshFailed && (
+ <p role="alert">
+ {t(
+ 'settings.integration.media.download.detectionRefreshFailed'
+ )}
+ </p>
+ )}
+ </div>
+ )}
+
{transport.platform !== 'web' && (
<p className="text-xs text-muted-foreground">
{t('settings.integration.media.applyHint')}
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index 855fcd73..1fa0e0ca 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -201,6 +201,21 @@ function makeFakeCtx() {
}
}
+describe('desktop-only FFmpeg installation boundary', () => {
+ it('does not install server executables through web commands', async () => {
+ const handlers = buildServerCommandHandlers(
+ makeFakeCtx() as ServerCommandContext
+ )
+ await expect(handlers[Commands.InstallFfmpeg]?.()).resolves.toEqual({
+ ok: false,
+ error: 'unsupported',
+ })
+ await expect(
+ handlers[Commands.InstallFfmpeg]?.({ url: 'https://evil.test' })
+ ).rejects.toThrow()
+ })
+})
+
function makeSettings(
proxy: typeof PROXY_OFF,
tracker: {
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index c6fa6655..5fee6807 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -397,6 +397,10 @@ export function buildServerCommandHandlers(
})
return {
+ [Commands.InstallFfmpeg]: async (payload: unknown) => {
+ z.undefined().parse(payload)
+ return { ok: false, error: 'unsupported' }
+ },
[Commands.CreateServerDirectory]: async (request: unknown) =>
ctx.serverDirectoryService.create(request),
[Commands.SetDisclaimerLanguage]: async (payload: unknown) => {
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index db077b07..56a69078 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -172,6 +172,15 @@ export function buildServerQueryHandlers(
})
return {
+ [Queries.GetFfmpegInstallStatus]: async () => ({
+ phase: 'idle',
+ bytesReceived: 0,
+ bytesTotal: 0,
+ percent: null,
+ releaseVersion: null,
+ directory: null,
+ error: 'unsupported',
+ }),
[Queries.ListServerDirectoryLocations]: async (request: unknown) => {
if (
!ListServerDirectoryLocationsRequestSchema.safeParse(request).success
diff --git a/src/shared/config/ffmpeg-macos-certificate.json b/src/shared/config/ffmpeg-macos-certificate.json
new file mode 100644
index 00000000..f23ee354
--- /dev/null
+++ b/src/shared/config/ffmpeg-macos-certificate.json
@@ -0,0 +1,3 @@
+{
+ "certificateSha256": "2407e0fae276c94bfff07ca60d4e43dd5265004aba41cd48efdc59207c2e8be9"
+}
diff --git a/src/shared/config/ffmpeg-release-key.json b/src/shared/config/ffmpeg-release-key.json
new file mode 100644
index 00000000..7ad786d2
--- /dev/null
+++ b/src/shared/config/ffmpeg-release-key.json
@@ -0,0 +1,4 @@
+{
+ "keyId": "sha256:2b5d2575808c8c0ef2a9d616e994ccc96c4af3c93e66fcf853f67dfb33866044",
+ "publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEASmn08KLiL7ElA9KURvsKBRAxEX9tgY7Ow4hWi/kmeL8=\n-----END PUBLIC KEY-----\n"
+}
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
index 242089b3..9175913d 100644
--- a/src/shared/errors.ts
+++ b/src/shared/errors.ts
@@ -76,6 +76,9 @@ export enum ErrorCode {
GeoIPDownloadFailed = 'GEOIP_DOWNLOAD_FAILED',
GeoIPSourceUnsupported = 'GEOIP_SOURCE_UNSUPPORTED',
GeoIPDatabaseInvalid = 'GEOIP_DATABASE_INVALID',
+ FfmpegInstallBusy = 'FFMPEG_INSTALL_BUSY',
+ FfmpegInstallFailed = 'FFMPEG_INSTALL_FAILED',
+ FfmpegReleaseUnavailable = 'FFMPEG_RELEASE_UNAVAILABLE',
}
export enum DownloadErrorCode {
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index 410aaeca..a192eebc 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -2468,7 +2468,39 @@
"usingSource": "يُستخدم {{source}}"
},
"download": {
- "action": "تنزيل FFmpeg"
+ "action": "تنزيل FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "يتطلب هذا التنزيل FFmpeg. اضبطه في الإعدادات ← التكامل ← أدوات الوسائط، واحفظ، ثم حاول مجددًا.",
"notDetected": "لم يُكتشف FFmpeg",
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index 789976ac..a18760bc 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -2388,7 +2388,39 @@
"usingSource": "Използва се {{source}}"
},
"download": {
- "action": "Изтегляне на FFmpeg"
+ "action": "Изтегляне на FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "Това изтегляне изисква FFmpeg. Настройте го в Настройки → Интеграция → Мултимедийни инструменти, запазете и опитайте отново.",
"notDetected": "FFmpeg не е открит",
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index 78902493..3e583567 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -2408,7 +2408,39 @@
"usingSource": "S'utilitza {{source}}"
},
"download": {
- "action": "Baixar l'FFmpeg"
+ "action": "Baixar l'FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "Aquesta baixada necessita l'FFmpeg. Configureu-lo a Configuració → Integració → Eines multimèdia, deseu i torneu-ho a provar.",
"notDetected": "No s'ha detectat l'FFmpeg",
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index b388efa2..b1e2774b 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -1971,7 +1971,39 @@
"binaryPath": "Benutzerdefinierter FFmpeg-Pfad",
"browse": "Durchsuchen…",
"download": {
- "action": "FFmpeg herunterladen"
+ "action": "FFmpeg herunterladen",
+ "verifyInstall": "Herunterladen und prüfen",
+ "installing": "Wird geprüft…",
+ "installed": "Geprüft und installiert.",
+ "failed": "Download oder Prüfung fehlgeschlagen. Die bisherige Installation bleibt erhalten.",
+ "disclosure": "Motrix prüft die Projektsignatur. Diese Windows-Dateien haben keine öffentliche Authenticode-Signatur; Warnungen können weiterhin erscheinen. FFmpeg wird unter der GPL mit Lizenztexten verteilt.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index 0f9e2a10..caf3e678 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -2388,7 +2388,39 @@
"usingSource": "Χρησιμοποιείται: {{source}}"
},
"download": {
- "action": "Λήψη FFmpeg"
+ "action": "Λήψη FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "Αυτή η λήψη απαιτεί FFmpeg. Ρυθμίστε το στην ενότητα Ρυθμίσεις → Ενσωμάτωση → Εργαλεία πολυμέσων, αποθηκεύστε και δοκιμάστε ξανά.",
"notDetected": "Δεν εντοπίστηκε το FFmpeg",
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index a620caba..da22dee9 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1971,7 +1971,39 @@
"binaryPath": "Custom FFmpeg path",
"browse": "Browse…",
"download": {
- "action": "Download FFmpeg"
+ "action": "Download FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 2dac9148..a0878478 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -1985,7 +1985,39 @@
"binaryPath": "Ruta personalizada de FFmpeg",
"browse": "Examinar…",
"download": {
- "action": "Descargar FFmpeg"
+ "action": "Descargar FFmpeg",
+ "verifyInstall": "Descargar y verificar",
+ "installing": "Verificando…",
+ "installed": "Verificado e instalado.",
+ "failed": "La descarga o verificación falló. Se conserva la instalación anterior.",
+ "disclosure": "Motrix verifica la firma del proyecto. Estos binarios de Windows no tienen firma Authenticode pública; pueden aparecer advertencias. FFmpeg se distribuye bajo la GPL con los textos de licencia.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index dde346fa..ee669f68 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -2388,7 +2388,39 @@
"usingSource": "در حال استفاده از {{source}}"
},
"download": {
- "action": "دانلود FFmpeg"
+ "action": "دانلود FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "این دانلود به FFmpeg نیاز دارد. آن را در تنظیمات ← یکپارچگی ← ابزارهای رسانه تنظیم و ذخیره کنید، سپس دوباره تلاش کنید.",
"notDetected": "FFmpeg شناسایی نشد",
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index ac0b37b9..30f68d9c 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -2408,7 +2408,39 @@
"usingSource": "Source utilisée : {{source}}"
},
"download": {
- "action": "Télécharger FFmpeg"
+ "action": "Télécharger FFmpeg",
+ "verifyInstall": "Télécharger et vérifier",
+ "installing": "Vérification…",
+ "installed": "Vérifié et installé.",
+ "failed": "Le téléchargement ou la vérification a échoué. L’installation précédente est conservée.",
+ "disclosure": "Motrix vérifie la signature du projet. Ces binaires Windows n’ont pas de signature Authenticode publique ; des avertissements peuvent subsister. FFmpeg est distribué sous GPL avec les licences.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "Ce téléchargement nécessite FFmpeg. Configurez-le dans Paramètres → Intégration → Outils multimédias, enregistrez, puis réessayez.",
"notDetected": "FFmpeg non détecté",
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 307f61a7..a23a8763 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -1971,7 +1971,39 @@
"binaryPath": "Az FFmpeg egyéni elérési útja",
"browse": "Tallózás…",
"download": {
- "action": "FFmpeg letöltése"
+ "action": "FFmpeg letöltése",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index 206b2d5e..d31071ec 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -1957,7 +1957,39 @@
"binaryPath": "Jalur FFmpeg khusus",
"browse": "Telusuri…",
"download": {
- "action": "Unduh FFmpeg"
+ "action": "Unduh FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index cdf3f762..3410252b 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -1985,7 +1985,39 @@
"binaryPath": "Percorso personalizzato di FFmpeg",
"browse": "Sfoglia…",
"download": {
- "action": "Scarica FFmpeg"
+ "action": "Scarica FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index 16a4880f..8c3bdaed 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -1957,7 +1957,39 @@
"binaryPath": "FFmpeg のカスタムパス",
"browse": "参照…",
"download": {
- "action": "FFmpeg をダウンロード"
+ "action": "FFmpeg をダウンロード",
+ "verifyInstall": "ダウンロードして検証",
+ "installing": "検証中…",
+ "installed": "検証してインストールしました。",
+ "failed": "ダウンロードまたは検証に失敗しました。既存のインストールは保持されます。",
+ "disclosure": "Motrix はプロジェクトの署名を検証します。Windows バイナリに公開 Authenticode 署名はなく、警告が表示される場合があります。FFmpeg は GPL で配布され、ライセンス文書が同梱されます。",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index 1c3ab687..8548ed61 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -1957,7 +1957,39 @@
"binaryPath": "사용자 지정 FFmpeg 경로",
"browse": "찾아보기…",
"download": {
- "action": "FFmpeg 다운로드"
+ "action": "FFmpeg 다운로드",
+ "verifyInstall": "다운로드 및 검증",
+ "installing": "검증 중…",
+ "installed": "검증 후 설치되었습니다.",
+ "failed": "다운로드 또는 검증에 실패했습니다. 기존 설치는 유지됩니다.",
+ "disclosure": "Motrix가 프로젝트 서명을 검증합니다. Windows 바이너리에 공인 Authenticode 서명이 없어 시스템 경고가 표시될 수 있습니다. FFmpeg는 GPL로 배포되며 라이선스 문서가 포함됩니다.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 524744dc..d27a8685 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -2388,7 +2388,39 @@
"usingSource": "Bruker {{source}}"
},
"download": {
- "action": "Last ned FFmpeg"
+ "action": "Last ned FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "Denne nedlastingen krever FFmpeg. Konfigurer det under Innstillinger → Integrasjon → Medieverktøy, lagre og prøv igjen.",
"notDetected": "FFmpeg ble ikke funnet",
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index 709c7cde..761751e8 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -2388,7 +2388,39 @@
"usingSource": "{{source}} wordt gebruikt"
},
"download": {
- "action": "FFmpeg downloaden"
+ "action": "FFmpeg downloaden",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "Deze download vereist FFmpeg. Configureer het via Instellingen → Integratie → Mediahulpmiddelen, sla op en probeer het opnieuw.",
"notDetected": "FFmpeg niet gedetecteerd",
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index 30f11a29..d28eee5d 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -1999,7 +1999,39 @@
"binaryPath": "Własna ścieżka do FFmpeg",
"browse": "Przeglądaj…",
"download": {
- "action": "Pobierz FFmpeg"
+ "action": "Pobierz FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 1ce2ad6d..eaeac6a3 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -1985,7 +1985,39 @@
"binaryPath": "Caminho personalizado do FFmpeg",
"browse": "Procurar…",
"download": {
- "action": "Baixar FFmpeg"
+ "action": "Baixar FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index fa7023aa..5598dece 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -2408,7 +2408,39 @@
"usingSource": "Se folosește {{source}}"
},
"download": {
- "action": "Descarcă FFmpeg"
+ "action": "Descarcă FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "Această descărcare necesită FFmpeg. Configurează-l în Setări → Integrare → Instrumente media, salvează, apoi încearcă din nou.",
"notDetected": "FFmpeg nu a fost detectat",
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index beea47e4..20d4c7ab 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -1999,7 +1999,39 @@
"binaryPath": "Свой путь к FFmpeg",
"browse": "Обзор…",
"download": {
- "action": "Скачать FFmpeg"
+ "action": "Скачать FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index eb2c2bb2..52537048 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -2368,7 +2368,39 @@
"usingSource": "กำลังใช้ {{source}}"
},
"download": {
- "action": "ดาวน์โหลด FFmpeg"
+ "action": "ดาวน์โหลด FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "การดาวน์โหลดนี้ต้องใช้ FFmpeg ตั้งค่าใน การตั้งค่า → การผสานการทำงาน → เครื่องมือสื่อ บันทึก แล้วลองอีกครั้ง",
"notDetected": "ตรวจไม่พบ FFmpeg",
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index ebed6001..1521cafd 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -1971,7 +1971,39 @@
"binaryPath": "Özel FFmpeg yolu",
"browse": "Göz at…",
"download": {
- "action": "FFmpeg’i indir"
+ "action": "FFmpeg’i indir",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index b1737ff9..ae16ffe4 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -2428,7 +2428,39 @@
"usingSource": "Використовується {{source}}"
},
"download": {
- "action": "Завантажити FFmpeg"
+ "action": "Завантажити FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"ffmpegRequired": "Для цього завантаження потрібен FFmpeg. Налаштуйте його в розділі «Налаштування → Інтеграція → Медіаінструменти», збережіть і спробуйте ще раз.",
"notDetected": "FFmpeg не виявлено",
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index 3e7ee7da..9a49c491 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -1957,7 +1957,39 @@
"binaryPath": "Đường dẫn FFmpeg tùy chỉnh",
"browse": "Duyệt…",
"download": {
- "action": "Tải FFmpeg"
+ "action": "Tải FFmpeg",
+ "verifyInstall": "Download and verify",
+ "installing": "Verifying…",
+ "installed": "Verified and installed.",
+ "failed": "Download or verification failed. The previous installation was kept.",
+ "disclosure": "Motrix verifies its project signature. These Windows binaries have no public Authenticode signature; Windows warnings may remain. FFmpeg is GPL-licensed; license texts are included.",
+ "projectDisclosure": "Download the official Motrix FFmpeg build separately, verify its signature, and install it in Motrix’s data directory. FFmpeg is GPL-licensed; included licenses and corresponding sources apply.",
+ "macDisclosure": "macOS verifies the pinned Developer ID certificate and Apple’s online notarization ticket. Internet quarantine remains enabled; system protections aren’t bypassed.",
+ "progress": "FFmpeg download progress",
+ "bytes": "{{received}} / {{total}} bytes",
+ "directory": "Installed directory: {{path}}",
+ "detectionRefreshFailed": "Couldn’t refresh FFmpeg detection. Try Refresh again.",
+ "restartPluginHint": "Restart Motrix for active plugins to detect the installation.",
+ "phases": {
+ "idle": "Ready to download",
+ "metadata": "Checking the formal release…",
+ "downloading": "Downloading FFmpeg…",
+ "verifying": "Verifying the release signature…",
+ "extracting": "Verifying and extracting files…",
+ "systemTrust": "Checking macOS signing and notarization…",
+ "installing": "Installing FFmpeg…",
+ "installed": "Verified and installed.",
+ "failed": "Installation failed."
+ },
+ "errors": {
+ "unavailable": "No complete, immutable formal release is available yet.",
+ "unsupported": "One-click installation isn’t supported on this platform.",
+ "busy": "Another FFmpeg installation is already running.",
+ "download": "The download failed or timed out. Check the network and try again.",
+ "verification": "The signature, package layout, or file integrity check failed.",
+ "install": "Files couldn’t be installed. Check the data directory’s permissions and free space.",
+ "systemTrust": "macOS rejected the signing identity or notarization. System security checks weren’t bypassed."
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index ba872c75..8d1b7145 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1957,7 +1957,39 @@
"binaryPath": "自定义 FFmpeg 路径",
"browse": "浏览…",
"download": {
- "action": "下载 FFmpeg"
+ "action": "下载 FFmpeg",
+ "verifyInstall": "下载并验证",
+ "installing": "正在验证…",
+ "installed": "已验证并安装。",
+ "failed": "下载或验证失败,已保留原有安装。",
+ "disclosure": "Motrix 会校验项目签名。这些 Windows 二进制没有公共 Authenticode 签名,系统警告可能仍会出现。FFmpeg 按 GPL 分发,附带许可证文本。",
+ "projectDisclosure": "单独下载 Motrix 官方构建的 FFmpeg,验证签名后安装到 Motrix 数据目录。FFmpeg 按 GPL 分发,请遵循随附许可证和对应源码的使用条款。",
+ "macDisclosure": "macOS 会验证固定的 Developer ID 证书及 Apple 在线公证凭据。互联网隔离属性保持启用,不绕过系统保护。",
+ "progress": "FFmpeg 下载进度",
+ "bytes": "{{received}} / {{total}} 字节",
+ "directory": "安装目录:{{path}}",
+ "detectionRefreshFailed": "FFmpeg 检测状态刷新失败,请再次点击“刷新”。",
+ "restartPluginHint": "已启用的插件需要重启 Motrix 才能检测到此次安装。",
+ "phases": {
+ "idle": "准备下载",
+ "metadata": "正在检查正式发布…",
+ "downloading": "正在下载 FFmpeg…",
+ "verifying": "正在校验发布签名…",
+ "extracting": "正在校验并解压文件…",
+ "systemTrust": "正在检查 macOS 签名与公证…",
+ "installing": "正在安装 FFmpeg…",
+ "installed": "已验证并安装。",
+ "failed": "安装失败。"
+ },
+ "errors": {
+ "unavailable": "暂时没有完整且不可变的正式发布。",
+ "unsupported": "当前平台不支持一键安装。",
+ "busy": "另一项 FFmpeg 安装正在进行。",
+ "download": "下载失败或超时,请检查网络后重试。",
+ "verification": "签名、压缩包结构或文件完整性校验失败。",
+ "install": "无法安装文件,请检查数据目录的权限及剩余空间。",
+ "systemTrust": "macOS 拒绝了签名身份或公证状态,未绕过系统安全检查。"
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 181bb938..a683eec7 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1957,7 +1957,39 @@
"binaryPath": "自訂 FFmpeg 路徑",
"browse": "瀏覽…",
"download": {
- "action": "下載 FFmpeg"
+ "action": "下載 FFmpeg",
+ "verifyInstall": "下載並驗證",
+ "installing": "正在驗證…",
+ "installed": "已驗證並安裝。",
+ "failed": "下載或驗證失敗,已保留原有安裝。",
+ "disclosure": "Motrix 會驗證專案簽章。這些 Windows 執行檔沒有公共 Authenticode 簽章,系統警告可能仍會出現。FFmpeg 依 GPL 分發,附帶授權條款。",
+ "projectDisclosure": "單獨下載 Motrix 官方建置的 FFmpeg,驗證簽章後安裝到 Motrix 資料目錄。FFmpeg 按 GPL 散布,請遵循隨附授權條款和對應原始碼的使用條款。",
+ "macDisclosure": "macOS 會驗證固定的 Developer ID 憑證及 Apple 線上公證憑據。網際網路隔離屬性維持啟用,不略過系統保護。",
+ "progress": "FFmpeg 下載進度",
+ "bytes": "{{received}} / {{total}} 位元組",
+ "directory": "安裝目錄:{{path}}",
+ "detectionRefreshFailed": "FFmpeg 偵測狀態更新失敗,請再次點擊「重新整理」。",
+ "restartPluginHint": "已啟用的外掛程式需要重新啟動 Motrix 才能偵測到此次安裝。",
+ "phases": {
+ "idle": "準備下載",
+ "metadata": "正在檢查正式發布…",
+ "downloading": "正在下載 FFmpeg…",
+ "verifying": "正在驗證發布簽章…",
+ "extracting": "正在驗證並解壓縮檔案…",
+ "systemTrust": "正在檢查 macOS 簽章與公證…",
+ "installing": "正在安裝 FFmpeg…",
+ "installed": "已驗證並安裝。",
+ "failed": "安裝失敗。"
+ },
+ "errors": {
+ "unavailable": "暫時沒有完整且不可變的正式發布。",
+ "unsupported": "目前平台不支援一鍵安裝。",
+ "busy": "另一項 FFmpeg 安裝正在進行。",
+ "download": "下載失敗或逾時,請檢查網路後重試。",
+ "verification": "簽章、壓縮檔結構或檔案完整性檢查失敗。",
+ "install": "無法安裝檔案,請檢查資料目錄的權限及剩餘空間。",
+ "systemTrust": "macOS 拒絕了簽章身分或公證狀態,未略過系統安全檢查。"
+ }
},
"detection": {
"readyTitle": "FFmpeg {{version}}",
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index f93b21e3..dce0c820 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -115,6 +115,7 @@ export const Commands = {
DeleteNotification: 'command:deleteNotification',
ClearNotifications: 'command:clearNotifications',
InstallCliTool: 'command:installCliTool',
+ InstallFfmpeg: 'command:installFfmpeg',
} as const
export type CommandChannel = (typeof Commands)[keyof typeof Commands]
diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.ts
index a60e2dab..ecd8ce96 100644
--- a/src/shared/protocol/events.ts
+++ b/src/shared/protocol/events.ts
@@ -85,6 +85,7 @@ export const Events = {
// GeoIP database lifecycle
GeoIPUpdateProgress: 'event:geoipUpdateProgress',
GeoIPStatusChanged: 'event:geoipStatusChanged',
+ FfmpegInstallStatusChanged: 'event:ffmpegInstallStatusChanged',
// Plugin config
PluginConfigChanged: 'event:pluginConfigChanged',
// Spec §I30 — optional-permission grants mutated; payload is `{pluginId}`.
diff --git a/src/shared/protocol/forwardable-events.test.ts b/src/shared/protocol/forwardable-events.test.ts
index 33b0bb46..aa047e5f 100644
--- a/src/shared/protocol/forwardable-events.test.ts
+++ b/src/shared/protocol/forwardable-events.test.ts
@@ -27,7 +27,7 @@ describe('ForwardableEvents', () => {
})
it('has the expected number of forwardable events', () => {
- expect(ForwardableEvents).toHaveLength(58)
+ expect(ForwardableEvents).toHaveLength(59)
})
it('includes the bridge approval events (web-shell pairing)', () => {
diff --git a/src/shared/protocol/forwardable-events.ts b/src/shared/protocol/forwardable-events.ts
index dc1c6494..8e4c8270 100644
--- a/src/shared/protocol/forwardable-events.ts
+++ b/src/shared/protocol/forwardable-events.ts
@@ -40,6 +40,7 @@ export const ForwardableEvents = [
Events.UpdateError,
Events.GeoIPUpdateProgress,
Events.GeoIPStatusChanged,
+ Events.FfmpegInstallStatusChanged,
Events.LocaleChanged,
Events.ReducedMotionChanged,
Events.LiquidGlassChanged,
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index 7ef5fce6..702a92c3 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -70,6 +70,7 @@ export const Queries = {
// Media settings: enriched ffmpeg detection (per-candidate state).
// Consumed by the Media settings card to render the 4-row status table.
GetFfmpegDetection: 'query:getFfmpegDetection',
+ GetFfmpegInstallStatus: 'query:getFfmpegInstallStatus',
// Dashboard
GetSpeedHistory: 'query:getSpeedHistory',
GetTransferStats: 'query:getTransferStats',
diff --git a/src/shared/schemas/ffmpeg-release.ts b/src/shared/schemas/ffmpeg-release.ts
new file mode 100644
index 00000000..ea605bfe
--- /dev/null
+++ b/src/shared/schemas/ffmpeg-release.ts
@@ -0,0 +1,261 @@
+import { z } from 'zod'
+
+export const FFMPEG_REPOSITORY = 'motrixapp/ffmpeg-static'
+export const FFMPEG_SIGNATURE_DOMAIN = 'Motrix FFmpeg release manifest v1\n'
+export const FFMPEG_MINIMUM_RELEASE = '9.0.2-motrix.8'
+export const FFMPEG_WINDOWS_LICENSE =
+ 'GPL-2.0-or-later AND LGPL-2.1-or-later AND IJG AND ISC AND MIT AND BSD-1-Clause AND BSD-2-Clause AND BSD-3-Clause AND Zlib AND BSL-1.0 AND (Apache-2.0 WITH LLVM-exception) AND LicenseRef-MinGW-w64-runtime'
+export const ffmpegReleaseVersionSchema = z
+ .string()
+ .max(64)
+ .regex(/^\d{1,6}\.\d{1,6}\.\d{1,6}-motrix\.\d{1,6}$/)
+const hash = z.string().regex(/^[0-9a-f]{64}$/)
+const targets = [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64',
+ 'linux-x64',
+ 'win32-arm64',
+ 'win32-x64',
+] as const
+export const ffmpegPlatformSchema = z.enum(['darwin', 'linux', 'win32'])
+export const ffmpegArchSchema = z.enum(['x64', 'arm64'])
+const baseLicense = FFMPEG_WINDOWS_LICENSE.split(' AND (Apache-2.0')[0]
+const licenses = {
+ darwin: baseLicense,
+ linux: `${baseLicense} AND 0BSD AND SunPro AND (GPL-3.0-or-later WITH GCC-exception-3.1)`,
+ win32: FFMPEG_WINDOWS_LICENSE,
+}
+export const ffmpegMacSigningSchema = z
+ .object({
+ schemaVersion: z.literal(3),
+ target: z.enum(['darwin-x64', 'darwin-arm64']),
+ platform: z.literal('darwin'),
+ kind: z.literal('apple-developer-id'),
+ identity: z
+ .object({
+ teamId: z.string().regex(/^[A-Z0-9]{10}$/),
+ subject: z.string().max(256).startsWith('Developer ID Application:'),
+ certificateSha256: hash,
+ })
+ .strict(),
+ binaries: z.record(
+ z.enum(['ffmpeg', 'ffprobe']),
+ z
+ .object({
+ sha256: hash,
+ cdHash: z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),
+ timestamp: z.iso.datetime(),
+ hardenedRuntime: z.literal(true),
+ })
+ .strict()
+ ),
+ notarization: z
+ .object({
+ submissionId: z.uuid(),
+ status: z.literal('Accepted'),
+ submissionResultSha256: hash,
+ developerLog: z
+ .object({
+ name: z.string().max(160),
+ sha256: hash,
+ size: z
+ .number()
+ .int()
+ .positive()
+ .max(8 * 1024 * 1024),
+ })
+ .strict(),
+ })
+ .strict(),
+ })
+ .strict()
+
+export const ffmpegSignatureSchema = z
+ .object({
+ schemaVersion: z.literal(1),
+ algorithm: z.literal('Ed25519'),
+ keyId: z.string().regex(/^sha256:[0-9a-f]{64}$/),
+ signature: z.string().length(88),
+ })
+ .strict()
+
+export const ffmpegManifestSchema = z
+ .object({
+ schemaVersion: z.literal(3),
+ repository: z.literal(FFMPEG_REPOSITORY),
+ windowsTrust: z.literal('motrix-ed25519'),
+ formalRelease: z.literal(true),
+ releaseVersion: ffmpegReleaseVersionSchema,
+ releaseTag: z.string().max(80),
+ releaseCommit: z.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/),
+ controlCommit: z.string(),
+ profile: z.literal('motrix-full-gpl'),
+ targets: z
+ .array(z.object({ target: z.enum(targets) }).passthrough())
+ .length(6),
+ })
+ .passthrough()
+ .superRefine((value, ctx) => {
+ if (
+ value.releaseTag !== `v${value.releaseVersion}` ||
+ value.releaseCommit !== value.controlCommit ||
+ new Set(value.targets.map((item) => item.target)).size !== 6
+ ) {
+ ctx.addIssue({ code: 'custom', message: 'Invalid release identity' })
+ }
+ })
+
+export const ffmpegTargetSchema = z
+ .object({
+ schemaVersion: z.literal(2),
+ releaseVersion: ffmpegReleaseVersionSchema,
+ target: z.enum(targets),
+ platform: ffmpegPlatformSchema,
+ arch: ffmpegArchSchema,
+ minimumOs: z
+ .object({
+ name: z.enum(['macos', 'linux', 'windows']),
+ version: z.string().regex(/^\d+\.\d+(?:\.\d+)?$/),
+ })
+ .strict(),
+ license: z.string().max(512),
+ archive: z.string().max(120),
+ archiveSha256: hash,
+ archiveSize: z
+ .number()
+ .int()
+ .positive()
+ .max(256 * 1024 * 1024),
+ binaryPath: z.enum(['ffmpeg', 'ffmpeg.exe']),
+ binarySha256: hash,
+ ffprobePath: z.enum(['ffprobe', 'ffprobe.exe']),
+ ffprobeSha256: hash,
+ buildInfoSha256: hash,
+ configureSha256: hash,
+ licensesSha256: hash,
+ signing: ffmpegMacSigningSchema.nullable(),
+ signingEvidenceSha256: hash.nullable(),
+ licenseFiles: z
+ .array(
+ z
+ .object({
+ path: z
+ .string()
+ .regex(/^LICENSES\/[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/),
+ sha256: hash,
+ })
+ .passthrough()
+ )
+ .min(1)
+ .max(64),
+ })
+ .passthrough()
+ .superRefine((value, ctx) => {
+ if (
+ value.target !== `${value.platform}-${value.arch}` ||
+ value.archive !==
+ `ffmpeg-${value.releaseVersion}-${value.target}.${value.platform === 'linux' ? 'tar.gz' : 'zip'}` ||
+ value.binaryPath !==
+ (value.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg') ||
+ value.ffprobePath !==
+ (value.platform === 'win32' ? 'ffprobe.exe' : 'ffprobe') ||
+ value.license !== licenses[value.platform] ||
+ value.minimumOs.name !==
+ { darwin: 'macos', linux: 'linux', win32: 'windows' }[value.platform] ||
+ (value.platform === 'win32' && value.minimumOs.version !== '10.0') ||
+ (value.platform !== 'darwin' &&
+ (value.signing !== null || value.signingEvidenceSha256 !== null)) ||
+ (value.platform === 'darwin' &&
+ (!value.signing ||
+ !value.signingEvidenceSha256 ||
+ value.signing.target !== value.target ||
+ value.signing.binaries.ffmpeg.sha256 !== value.binarySha256 ||
+ value.signing.binaries.ffprobe.sha256 !== value.ffprobeSha256 ||
+ !value.signing.identity.subject.includes(
+ `(${value.signing.identity.teamId})`
+ ) ||
+ value.signing.notarization.developerLog.name !==
+ `ffmpeg-${value.releaseVersion}-${value.target}.notarization-log.json`)) ||
+ new Set(value.licenseFiles.map((item) => item.path.toLowerCase()))
+ .size !== value.licenseFiles.length ||
+ value.licenseFiles.some(
+ (item) =>
+ item.path.endsWith('.') ||
+ /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(
+ item.path.slice('LICENSES/'.length)
+ )
+ )
+ ) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Invalid FFmpeg artifact identity',
+ })
+ }
+ })
+
+export const ffmpegInstallResultSchema = z.discriminatedUnion('ok', [
+ z
+ .object({ ok: z.literal(true), releaseVersion: ffmpegReleaseVersionSchema })
+ .strict(),
+ z
+ .object({
+ ok: z.literal(false),
+ error: z.enum([
+ 'unavailable',
+ 'unsupported',
+ 'busy',
+ 'download',
+ 'verification',
+ 'install',
+ 'systemTrust',
+ ]),
+ })
+ .strict(),
+])
+export type FfmpegTarget = z.infer<typeof ffmpegTargetSchema>
+export type FfmpegPlatform = z.infer<typeof ffmpegPlatformSchema>
+export type FfmpegArch = z.infer<typeof ffmpegArchSchema>
+export const ffmpegInstallStatusSchema = z
+ .object({
+ phase: z.enum([
+ 'idle',
+ 'metadata',
+ 'downloading',
+ 'verifying',
+ 'extracting',
+ 'systemTrust',
+ 'installing',
+ 'installed',
+ 'failed',
+ ]),
+ bytesReceived: z.number().int().nonnegative(),
+ bytesTotal: z.number().int().nonnegative(),
+ percent: z.number().min(0).max(1).nullable(),
+ releaseVersion: ffmpegReleaseVersionSchema.nullable(),
+ directory: z.string().max(4096).nullable(),
+ error: z
+ .enum([
+ 'unavailable',
+ 'unsupported',
+ 'busy',
+ 'download',
+ 'verification',
+ 'install',
+ 'systemTrust',
+ ])
+ .nullable(),
+ })
+ .strict()
+export type FfmpegInstallStatus = z.infer<typeof ffmpegInstallStatusSchema>
+
+export const ffmpegLicenseInventorySchema = z
+ .object({
+ schemaVersion: z.literal(2),
+ target: z.enum(targets),
+ files: z
+ .array(z.object({ path: z.string(), sha256: hash }).passthrough())
+ .min(1)
+ .max(64),
+ })
+ .strict()
diff --git a/tests/ffmpeg-public-release.test.ts b/tests/ffmpeg-public-release.test.ts
new file mode 100644
index 00000000..7885108a
--- /dev/null
+++ b/tests/ffmpeg-public-release.test.ts
@@ -0,0 +1,263 @@
+// @vitest-environment node
+import { mkdtemp, readFile, rm } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import {
+ assertManagedFfmpegTrusted,
+ getFfmpegInstallStatus,
+ installVerifiedFfmpeg,
+ resolveManagedFfmpegCandidate,
+} from '@core/ffmpeg/verified-install'
+import {
+ compareFfmpegReleases,
+ verifyFfmpegRelease,
+} from '@core/ffmpeg/verified-release'
+import { ErrorCode } from '@shared/errors'
+import {
+ FFMPEG_MINIMUM_RELEASE,
+ type FfmpegInstallStatus,
+ type FfmpegPlatform,
+} from '@shared/schemas/ffmpeg-release'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { runCommand } from '../src/main/cli/command-runner'
+import { verifyMacFfmpegTrust } from '../src/main/plugin/ffmpeg-macos-trust'
+import { makeElectronFfmpegProbe } from '../src/main/plugin/ffmpeg-probe-electron'
+
+// macOS-only explicit opt-in: checks actual Apple trust for both Darwin archives.
+// Uses only the latest public immutable GitHub Release, never CI artifacts.
+// Run: MOTRIX_FFMPEG_PUBLIC_RELEASE_TEST=1 pnpm exec vitest run tests/ffmpeg-public-release.test.ts
+const enabled = process.env.MOTRIX_FFMPEG_PUBLIC_RELEASE_TEST === '1'
+const directories: string[] = []
+async function isolatedData() {
+ const directory = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-ffmpeg-public-')
+ )
+ directories.push(directory)
+ return directory
+}
+afterEach(async () => {
+ await Promise.all(
+ directories
+ .splice(0)
+ .map((directory) => rm(directory, { recursive: true, force: true }))
+ )
+})
+
+async function checkedInstallation(
+ userDataDir: string,
+ platform: FfmpegPlatform,
+ arch: 'x64' | 'arm64'
+) {
+ const status = getFfmpegInstallStatus(userDataDir)
+ expect(status.phase).toBe('installed')
+ const directory = status.directory!
+ const verified = verifyFfmpegRelease(
+ await readFile(path.join(directory, 'ffmpeg-manifest.json')),
+ await readFile(path.join(directory, 'ffmpeg-manifest.json.sig')),
+ arch,
+ `v${status.releaseVersion}`,
+ platform
+ )
+ expect(
+ compareFfmpegReleases(
+ verified.manifest.releaseVersion,
+ FFMPEG_MINIMUM_RELEASE
+ )
+ ).toBeGreaterThanOrEqual(0)
+ expect(directory).toBe(
+ path.join(
+ userDataDir,
+ 'ffmpeg-verified',
+ 'releases',
+ `${verified.manifestHash}-${platform}-${arch}`
+ )
+ )
+ const candidate = resolveManagedFfmpegCandidate(
+ userDataDir,
+ path.join(
+ userDataDir,
+ 'binaries',
+ platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
+ ),
+ platform
+ )
+ assertManagedFfmpegTrusted(userDataDir, candidate)
+ if (platform === 'darwin') {
+ for (const name of [
+ verified.target.binaryPath,
+ verified.target.ffprobePath,
+ ]) {
+ const marker = await runCommand(
+ '/usr/bin/xattr',
+ ['-p', 'com.apple.quarantine', path.join(directory, name)],
+ { timeoutMs: 30_000, maxBuffer: 4096 }
+ )
+ expect(marker.code).toBe(0)
+ expect(marker.stdout).toMatch(/^0081;[0-9a-f]+;Motrix;/)
+ }
+ }
+ return { candidate, verified, directory }
+}
+
+describe.skipIf(!enabled || process.platform !== 'darwin')(
+ 'public FFmpeg release download and installation',
+ () => {
+ it.each([
+ ['darwin', 'arm64'],
+ ['darwin', 'x64'],
+ ['linux', 'arm64'],
+ ['linux', 'x64'],
+ ['win32', 'arm64'],
+ ['win32', 'x64'],
+ ] as const)(
+ 'verifies the actual %s-%s archive without executing foreign payloads',
+ async (platform, arch) => {
+ const userDataDir = await isolatedData()
+ const progress: FfmpegInstallStatus[] = []
+ const result = await installVerifiedFfmpeg({
+ userDataDir,
+ platform,
+ arch,
+ onStatus: (status) => progress.push(status),
+ systemTrust: platform === 'darwin' ? verifyMacFfmpegTrust : undefined,
+ })
+ expect(result.ok).toBe(true)
+ const { verified } = await checkedInstallation(
+ userDataDir,
+ platform,
+ arch
+ )
+ expect(result.releaseVersion).toBe(verified.manifest.releaseVersion)
+ expect(progress.map((status) => status.phase)).toEqual(
+ expect.arrayContaining([
+ 'metadata',
+ 'verifying',
+ 'downloading',
+ 'extracting',
+ 'installing',
+ 'installed',
+ ])
+ )
+ const downloads = progress.filter(
+ (status) => status.phase === 'downloading'
+ )
+ expect(downloads.at(-1)?.bytesReceived).toBe(
+ verified.target.archiveSize
+ )
+ expect(
+ downloads.every(
+ (status) =>
+ status.bytesReceived <= status.bytesTotal &&
+ status.bytesTotal === verified.target.archiveSize
+ )
+ ).toBe(true)
+ if (platform === 'darwin')
+ expect(
+ progress.some((status) => status.phase === 'systemTrust')
+ ).toBe(true)
+ },
+ 600_000
+ )
+
+ it.skipIf(
+ process.platform !== 'darwin' || !['x64', 'arm64'].includes(process.arch)
+ )(
+ 'probes only trusted native macOS code, rejects concurrent operations, rechecks reused files, and retains the old version on network failure',
+ async () => {
+ const userDataDir = await isolatedData()
+ const arch = process.arch as 'x64' | 'arm64'
+ let entered!: () => void
+ let resume!: () => void
+ const started = new Promise<void>((resolve) => {
+ entered = resolve
+ })
+ const released = new Promise<void>((resolve) => {
+ resume = resolve
+ })
+ const fetcher = vi.fn<typeof fetch>(async (input, init) => {
+ entered()
+ await released
+ return fetch(input, init)
+ })
+ const trustDirectories: string[] = []
+ const systemTrust: typeof verifyMacFfmpegTrust = async (
+ directory,
+ target,
+ source
+ ) => {
+ trustDirectories.push(directory)
+ await verifyMacFfmpegTrust(directory, target, source)
+ }
+ const first = installVerifiedFfmpeg({
+ userDataDir,
+ platform: 'darwin',
+ arch,
+ fetcher,
+ systemTrust,
+ })
+ await started
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ platform: 'darwin',
+ arch,
+ fetcher,
+ systemTrust,
+ })
+ ).rejects.toMatchObject({ code: ErrorCode.FfmpegInstallBusy })
+ expect(fetcher).toHaveBeenCalledTimes(1)
+ resume()
+ await first
+ const installed = await checkedInstallation(userDataDir, 'darwin', arch)
+ const probe = makeElectronFfmpegProbe({ userDataDir })
+ await expect(
+ probe(path.join(userDataDir, 'binaries', 'ffmpeg'))
+ ).resolves.toMatchObject({
+ available: true,
+ binaryPath: installed.candidate,
+ version:
+ installed.verified.manifest.releaseVersion.split('-motrix.')[0],
+ })
+ // The production probe above has checked both native binaries' Apple
+ // identities and online tickets. Recheck both hashes before this smoke.
+ assertManagedFfmpegTrusted(userDataDir, installed.candidate)
+ const ffprobe = await runCommand(
+ path.join(installed.directory, installed.verified.target.ffprobePath),
+ ['-version'],
+ { timeoutMs: 5000, maxBuffer: 64_000 }
+ )
+ expect(ffprobe.code).toBe(0)
+ expect(ffprobe.stdout.split(/\r?\n/)[0]).toContain(
+ `ffprobe version ${installed.verified.manifest.releaseVersion.split('-motrix.')[0]}`
+ )
+ const pointer = path.join(
+ userDataDir,
+ 'ffmpeg-verified',
+ 'current.json'
+ )
+ const before = await readFile(pointer)
+ await installVerifiedFfmpeg({
+ userDataDir,
+ platform: 'darwin',
+ arch,
+ systemTrust,
+ })
+ expect(trustDirectories.at(-1)).toBe(installed.directory)
+ expect(trustDirectories).toHaveLength(3)
+ expect(await readFile(pointer)).toEqual(before)
+ await expect(
+ installVerifiedFfmpeg({
+ userDataDir,
+ platform: 'darwin',
+ arch,
+ systemTrust,
+ fetcher: async () => new Response('offline', { status: 503 }),
+ })
+ ).rejects.toThrow()
+ expect(await readFile(pointer)).toEqual(before)
+ assertManagedFfmpegTrusted(userDataDir, installed.candidate)
+ },
+ 600_000
+ )
+ }
+)
diff --git a/tests/scripts/electron-package-contract.test.ts b/tests/scripts/electron-package-contract.test.ts
index 24816eb4..8ba0c8fd 100644
--- a/tests/scripts/electron-package-contract.test.ts
+++ b/tests/scripts/electron-package-contract.test.ts
@@ -289,7 +289,7 @@ describe('Electron package contracts', () => {
expect(contract).toEqual({
schemaVersion: 1,
- payloadBytes: 25 * 1024 * 1024 + 64 * 1024,
+ payloadBytes: 25 * 1024 * 1024 + 256 * 1024,
betterSqlite3Bytes: 4 * 1024 * 1024,
unexpectedPackageNames: 0,
foreignBetterSqlite3Prebuilds: 0,