feat: initial Cutdex application
Add the Flutter video editing application with project management, media import, timeline editing, preview, AI assistance, diagnostics and settings. Include shared UI and native host packages, platform runners, application tests and release tooling. Provide usage and contribution guides, the MIT license and third-party notices. Exclude local credentials, build outputs and validation data.
This commit is contained in:
commit
27e77fff39
718 files changed
+183958
No files matched your search
@@ -0,0 +1,91 @@
|
||||
"""Audit Windows x64 PE imports without trusting the build host's System32.
|
||||
|
||||
Build-host dependency: pefile==2024.8.26. The target computer needs no Python.
|
||||
This is a static dependency gate, not a substitute for a clean Windows VM run.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
# Inbox components on supported, fully updated Windows 10/11 (non-N editions).
|
||||
# Never infer this list from files installed on the developer's machine.
|
||||
SYSTEM_DLLS = set('''
|
||||
advapi32 avicap32 avrt bcrypt bcryptprimitives cfgmgr32 combase comctl32 comdlg32
|
||||
crypt32 d2d1 d3d11 d3d12 d3d9 d3dcompiler_47 dbghelp dnsapi dwmapi dwrite dxgi
|
||||
gdi32 imagehlp imm32 iphlpapi kernel32 mf mfplat mfplay mfreadwrite msimg32
|
||||
ncrypt ntdll ole32 oleacc oleaut32 opengl32 propsys psapi rpcrt4 secur32
|
||||
setupapi shell32 shlwapi uiautomationcore user32 userenv usp10 winmm wintrust
|
||||
ws2_32 ucrtbase version
|
||||
'''.split())
|
||||
SYSTEM_DLLS = {name + '.dll' for name in SYSTEM_DLLS}
|
||||
REQUIRED = (
|
||||
'cutdex.exe', 'flutter_windows.dll', 'cutdex_runtime_plugin.dll',
|
||||
'deskup_plugin.dll', 'velopack_libc.dll',
|
||||
'cutdex_windows_ffi.dll', 'sqlite3.dll', 'data/app.so', 'data/icudtl.dat',
|
||||
'processing/bin/cutdex-processing-worker.exe',
|
||||
'processing/bin/cutdex_processing_ffi.dll', 'processing/bin/ffmpeg.exe',
|
||||
'processing/bin/ffprobe.exe', 'processing/bin/onnxruntime.dll',
|
||||
'processing/bin/DirectML.dll',
|
||||
'processing/workers/asr/cutdex-asr-worker.exe',
|
||||
'processing/workers/audio/cutdex-audio-worker.exe',
|
||||
'processing/workers/translation/cutdex-m2m100-worker.exe',
|
||||
)
|
||||
|
||||
|
||||
def system_dependency(name):
|
||||
name = name.lower()
|
||||
return name in SYSTEM_DLLS or name.startswith(('api-ms-win-', 'ext-ms-win-'))
|
||||
|
||||
|
||||
def pe_imports(path):
|
||||
import pefile
|
||||
with pefile.PE(str(path), fast_load=True) as pe:
|
||||
if pe.FILE_HEADER.Machine != 0x8664:
|
||||
raise ValueError(f'Not an x64 PE: {path}')
|
||||
pe.parse_data_directories(directories=[1, 13])
|
||||
return sorted({item.dll.decode('ascii').lower() for attribute in
|
||||
('DIRECTORY_ENTRY_IMPORT', 'DIRECTORY_ENTRY_DELAY_IMPORT')
|
||||
for item in getattr(pe, attribute, [])})
|
||||
|
||||
|
||||
def audit(root, read_imports=pe_imports):
|
||||
root = Path(root).resolve()
|
||||
missing = [name for name in REQUIRED if not (root / name).is_file()]
|
||||
if missing:
|
||||
raise ValueError(f'Missing release files: {missing}')
|
||||
if not (root / 'data/flutter_assets').is_dir():
|
||||
raise ValueError('Missing Flutter assets')
|
||||
report = {}
|
||||
unresolved = []
|
||||
for binary in sorted(root.rglob('*')):
|
||||
if binary.suffix.lower() not in ('.dll', '.exe'):
|
||||
continue
|
||||
if binary.is_symlink():
|
||||
raise ValueError(f'External/symlink binary: {binary}')
|
||||
# Each worker is a separate process. A DLL in another worker directory
|
||||
# (or only in the main app directory) does not satisfy its dependency.
|
||||
local = {p.name.lower() for p in binary.parent.iterdir() if p.is_file()}
|
||||
names = read_imports(binary)
|
||||
report[binary.relative_to(root).as_posix()] = names
|
||||
for name in names:
|
||||
if name.lower() not in local and not system_dependency(name):
|
||||
unresolved.append(f'{binary.relative_to(root)} -> {name}')
|
||||
if unresolved:
|
||||
raise ValueError('Unbundled dependencies: ' + '; '.join(unresolved))
|
||||
return {'architecture': 'x64', 'imports': report, 'unresolved': [],
|
||||
'cleanSystemValidated': False}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--app', type=Path, required=True)
|
||||
parser.add_argument('--report', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
result = audit(args.app)
|
||||
args.report.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.report.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
|
||||
print(f'Windows dependency gate passed: {len(result["imports"])} PE files')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Stage an audited portable Windows x64 app from a normal Flutter Release build.
|
||||
|
||||
Requires pefile on the build host. Models remain separate from the application.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
from check_windows_release import audit
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--app', type=Path, required=True)
|
||||
parser.add_argument('--processing', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
source, runtime, output = [p.resolve() for p in (args.app, args.processing, args.output)]
|
||||
if output.exists() or output.is_relative_to(source) or output.is_relative_to(runtime):
|
||||
raise ValueError('Output must be a new directory outside the source packages')
|
||||
if not (source / 'cutdex.exe').is_file() or not (runtime / 'checksums.json').is_file():
|
||||
raise ValueError('Provide a complete Release directory and processing package')
|
||||
checksums = json.loads((runtime / 'checksums.json').read_text(encoding='utf-8-sig'))
|
||||
for name, expected in checksums.items():
|
||||
path = (runtime / name).resolve()
|
||||
if not path.is_relative_to(runtime):
|
||||
raise ValueError(f'Invalid processing manifest path: {name}')
|
||||
with path.open('rb') as stream:
|
||||
actual = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
if actual.lower() != expected.lower():
|
||||
raise ValueError(f'Processing checksum mismatch: {name}')
|
||||
# Older Flutter builds can retain the unused JNI plugin from Android's
|
||||
# path_provider dependency. Windows has its own provider and needs no JVM.
|
||||
shutil.copytree(source, output, ignore=shutil.ignore_patterns('processing', '*.pdb', '*.lib', '*.exp', 'dartjni.dll'))
|
||||
shutil.copytree(runtime, output / 'processing')
|
||||
result = audit(output)
|
||||
(output / 'dependency-audit.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
|
||||
manifest = {}
|
||||
for path in sorted(output.rglob('*')):
|
||||
if path.is_file():
|
||||
with path.open('rb') as stream:
|
||||
manifest[path.relative_to(output).as_posix()] = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
(output / 'checksums.json').write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
|
||||
print(f'Portable package staged: {output} ({len(manifest)} files)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Create a Windows Sandbox launch file; no developer tools are mapped into it.
|
||||
|
||||
Inputs must contain fixture.mp4 (short SDR H.264 + AAC). Model folders are mapped
|
||||
read-only; the vocals folder must contain melband.pt. Only results are writable.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ('app', 'smoke', 'inputs', 'whisper', 'translation', 'vocals', 'results', 'output'):
|
||||
parser.add_argument('--' + name, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
paths = {name: getattr(args, name).resolve() for name in
|
||||
('app', 'smoke', 'inputs', 'whisper', 'translation', 'vocals', 'results')}
|
||||
for name in ('app', 'smoke'):
|
||||
if not (paths[name] / 'checksums.json').is_file():
|
||||
raise ValueError(f'Not an audited package: {paths[name]}')
|
||||
for name in ('inputs', 'whisper', 'translation', 'vocals'):
|
||||
if not paths[name].is_dir():
|
||||
raise ValueError(f'Missing directory: {paths[name]}')
|
||||
if not (paths['inputs'] / 'fixture.mp4').is_file() or not (paths['vocals'] / 'melband.pt').is_file():
|
||||
raise ValueError('Missing fixture.mp4 or vocals/melband.pt')
|
||||
paths['results'].mkdir(parents=True, exist_ok=True)
|
||||
config = ET.Element('Configuration')
|
||||
ET.SubElement(config, 'VGpu').text = 'Enable'
|
||||
ET.SubElement(config, 'MemoryInMB').text = '8192'
|
||||
ET.SubElement(config, 'Networking').text = 'Disable'
|
||||
folders = ET.SubElement(config, 'MappedFolders')
|
||||
# Copy just the standalone guest script; never map the source/build tool tree.
|
||||
script = Path(__file__).with_name('test_windows_release.ps1')
|
||||
(paths['inputs'] / script.name).write_bytes(script.read_bytes())
|
||||
mapping = {'app': r'C:\Cutdex', 'smoke': r'C:\Smoke', 'inputs': r'C:\Inputs',
|
||||
'whisper': r'C:\Models\whisper', 'translation': r'C:\Models\translation',
|
||||
'vocals': r'C:\Models\vocals', 'results': r'C:\Results'}
|
||||
for name, guest in mapping.items():
|
||||
folder = ET.SubElement(folders, 'MappedFolder')
|
||||
ET.SubElement(folder, 'HostFolder').text = str(paths[name])
|
||||
ET.SubElement(folder, 'SandboxFolder').text = guest
|
||||
ET.SubElement(folder, 'ReadOnly').text = 'false' if name == 'results' else 'true'
|
||||
(paths['inputs'] / 'models.json').write_text(json.dumps({
|
||||
'whisper': mapping['whisper'],
|
||||
'translation': mapping['translation'],
|
||||
'vocals': mapping['vocals'] + r'\melband.pt',
|
||||
}, indent=2), encoding='utf-8')
|
||||
command = ET.SubElement(config, 'LogonCommand')
|
||||
ET.SubElement(command, 'Command').text = (
|
||||
'powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\\Inputs\\test_windows_release.ps1 '
|
||||
'-App C:\\Cutdex -SmokeApp C:\\Smoke -Inputs C:\\Inputs -Results C:\\Results')
|
||||
ET.indent(config)
|
||||
args.output.write_text(ET.tostring(config, encoding='unicode') + '\n', encoding='utf-8')
|
||||
print(f'Log into Windows, then open {args.output}. Results: {paths["results"]}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,46 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from check_windows_release import REQUIRED, audit
|
||||
|
||||
|
||||
class DependencyGateTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
for name in REQUIRED:
|
||||
path = self.root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.touch()
|
||||
(self.root / 'data/flutter_assets').mkdir()
|
||||
|
||||
def test_vc_runtime_in_another_worker_does_not_satisfy_app(self):
|
||||
(self.root / 'processing/workers/asr/vcruntime140.dll').touch()
|
||||
with self.assertRaisesRegex(ValueError, 'cutdex.exe -> vcruntime140.dll'):
|
||||
audit(self.root, lambda p: ['vcruntime140.dll'] if p.name == 'cutdex.exe' else [])
|
||||
|
||||
def test_unknown_dependency_is_not_assumed_to_be_a_system_dll(self):
|
||||
with self.assertRaisesRegex(ValueError, 'vendor.dll'):
|
||||
audit(self.root, lambda p: ['vendor.dll'])
|
||||
|
||||
def test_local_runtime_and_inbox_api_sets_pass(self):
|
||||
(self.root / 'VCRUNTIME140.dll').touch()
|
||||
result = audit(self.root, lambda p: ['vcruntime140.dll', 'KERNEL32.dll',
|
||||
'VERSION.dll', 'COMCTL32.dll', 'api-ms-win-crt-runtime-l1-1-0.dll'] if p.name == 'cutdex.exe' else [])
|
||||
self.assertEqual(result['unresolved'], [])
|
||||
self.assertFalse(result['cleanSystemValidated'])
|
||||
|
||||
def test_missing_flutter_aot_is_rejected(self):
|
||||
(self.root / 'data/app.so').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'data/app.so'):
|
||||
audit(self.root, lambda p: [])
|
||||
|
||||
def test_jvm_is_not_assumed_to_be_a_system_dependency(self):
|
||||
with self.assertRaisesRegex(ValueError, 'jvm.dll'):
|
||||
audit(self.root, lambda p: ['jvm.dll'] if p.name == 'cutdex.exe' else [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,100 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Validates a normal and smoke release package on an interactive Windows desktop.
|
||||
.DESCRIPTION
|
||||
Requires App, SmokeApp, Inputs and Results paths. Writes result.json and process
|
||||
logs to Results. Returns a nonzero status on failure; does not publish packages.
|
||||
.EXAMPLE
|
||||
Get-Help ./tool/windows/test_windows_release.ps1 -Full
|
||||
.EXAMPLE
|
||||
./tool/windows/test_windows_release.ps1 -App C:\Cutdex -SmokeApp C:\Smoke -Inputs C:\Inputs -Results C:\Results
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$App,
|
||||
[Parameter(Mandatory=$true)][string]$SmokeApp,
|
||||
[Parameter(Mandatory=$true)][string]$Inputs,
|
||||
[Parameter(Mandatory=$true)][string]$Results
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
New-Item -ItemType Directory -Force $Results | Out-Null
|
||||
$report = @{ passed = $false; sandbox = ($env:USERNAME -eq 'WDAGUtilityAccount'); sessionId = (Get-Process -Id $PID).SessionId }
|
||||
$normal = $null
|
||||
try {
|
||||
if ($report.sessionId -eq 0) { throw 'Interactive Windows desktop required; SSH Session 0 is not a display test.' }
|
||||
foreach ($folder in @($App, $SmokeApp)) {
|
||||
$manifest = Get-Content (Join-Path $folder 'checksums.json') -Raw | ConvertFrom-Json
|
||||
foreach ($entry in $manifest.PSObject.Properties) {
|
||||
if ((Get-FileHash -LiteralPath (Join-Path $folder $entry.Name) -Algorithm SHA256).Hash -ne $entry.Value) {
|
||||
throw "Package checksum mismatch: $($entry.Name)"
|
||||
}
|
||||
}
|
||||
}
|
||||
Get-ChildItem Env:CUTDEX_* | Remove-Item
|
||||
$env:PATH = "$env:SystemRoot\System32;$env:SystemRoot"
|
||||
$env:PATHEXT = '.COM;.EXE;.BAT;.CMD'
|
||||
$normal = Start-Process (Join-Path $App 'cutdex.exe') -WorkingDirectory $App -PassThru -RedirectStandardOutput (Join-Path $Results 'app.stdout.log') -RedirectStandardError (Join-Path $Results 'app.stderr.log')
|
||||
Start-Sleep -Seconds 5
|
||||
$normal.Refresh()
|
||||
if ($normal.HasExited -or $normal.MainWindowHandle -eq 0) { throw 'Normal app did not create a window.' }
|
||||
$loaded = @{}
|
||||
foreach ($module in $normal.Modules) {
|
||||
if ($module.ModuleName -match '^(msvcp140|vcruntime140(_1)?)\.dll$') {
|
||||
$loaded[$module.ModuleName] = $module.FileName
|
||||
if ([IO.Path]::GetFullPath([IO.Path]::GetDirectoryName($module.FileName)) -ne [IO.Path]::GetFullPath($App)) {
|
||||
throw "VC runtime loaded outside app: $($module.FileName)"
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($name in @('msvcp140.dll','vcruntime140.dll','vcruntime140_1.dll')) {
|
||||
if (!$loaded.ContainsKey($name)) { throw "VC runtime module missing: $name" }
|
||||
}
|
||||
$report.loadedVcRuntime = $loaded
|
||||
Stop-Process -Id $normal.Id
|
||||
$normal = $null
|
||||
& "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File (Join-Path $App 'processing\verify.ps1') -Report (Join-Path $Results 'processing.json')
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Processing package verification failed.' }
|
||||
$config = Get-Content (Join-Path $Inputs 'models.json') -Raw | ConvertFrom-Json
|
||||
foreach ($configured in @($false, $true)) {
|
||||
Get-ChildItem Env:CUTDEX_* | Remove-Item
|
||||
$name = if ($configured) { 'with-models' } else { 'without-models' }
|
||||
$caseDirectory = Join-Path $Results $name
|
||||
New-Item -ItemType Directory -Force $caseDirectory | Out-Null
|
||||
$env:LOCALAPPDATA = $caseDirectory
|
||||
$env:APPDATA = $caseDirectory
|
||||
$env:USERPROFILE = $caseDirectory
|
||||
$env:CUTDEX_SMOKE_REPORT = Join-Path $caseDirectory 'result.json'
|
||||
$env:CUTDEX_SMOKE_MODELS = [int]$configured
|
||||
$env:CUTDEX_SMOKE_VIDEO = '1'
|
||||
$env:CUTDEX_SMOKE_MEDIA = Join-Path $Inputs 'fixture.mp4'
|
||||
if ($configured) {
|
||||
$processing = Join-Path $caseDirectory 'Documents\Cutdex\Resources\Processing'
|
||||
$whisperTarget = Join-Path $processing 'Transcription\whisper-turbo\1'
|
||||
$translationTarget = Join-Path $processing 'Translation\m2m100-418m\1'
|
||||
New-Item -ItemType Directory -Force $whisperTarget, $translationTarget | Out-Null
|
||||
Copy-Item -Recurse -Force (Join-Path $config.whisper '*') $whisperTarget
|
||||
Copy-Item -Recurse -Force (Join-Path $config.translation '*') $translationTarget
|
||||
New-Item -ItemType Directory -Force (Join-Path $processing 'VocalSeparation\melband\1') | Out-Null
|
||||
Copy-Item -Force $config.vocals (Join-Path $processing 'VocalSeparation\melband\1\melband.pt')
|
||||
}
|
||||
$process = Start-Process (Join-Path $SmokeApp 'cutdex.exe') -WorkingDirectory $SmokeApp -PassThru -RedirectStandardOutput (Join-Path $caseDirectory 'stdout.log') -RedirectStandardError (Join-Path $caseDirectory 'stderr.log')
|
||||
# Retain the process handle before it exits so PowerShell 5.1 can read
|
||||
# ExitCode after WaitForExit instead of returning null.
|
||||
$null = $process.Handle
|
||||
try {
|
||||
if (!$process.WaitForExit(600000)) { throw "Smoke timed out: $name" }
|
||||
if ($process.ExitCode -ne 0) { throw "Smoke failed: $name ($($process.ExitCode))" }
|
||||
$result = Get-Content $env:CUTDEX_SMOKE_REPORT -Raw | ConvertFrom-Json
|
||||
if (!$result.passed -or !$result.videoPreviewAndExport) { throw "Incomplete smoke: $name" }
|
||||
$report[$name] = $result
|
||||
} finally {
|
||||
if (!$process.HasExited) { Stop-Process -Id $process.Id }
|
||||
}
|
||||
}
|
||||
$report.passed = $true
|
||||
} catch {
|
||||
$report.error = $_.ToString()
|
||||
throw
|
||||
} finally {
|
||||
if ($normal -and !$normal.HasExited) { Stop-Process -Id $normal.Id }
|
||||
$report | ConvertTo-Json -Depth 12 | Set-Content -Encoding UTF8 (Join-Path $Results 'result.json')
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Build two disposable Flutter apps and verify updates through a Python HTTP server.
|
||||
|
||||
Uses Cutdex.Dev only. Tests checksum rejection, retry, install, relaunch and no-op
|
||||
checks. Requires Flutter, the pinned vpk tool and Windows. Never uploads releases.
|
||||
"""
|
||||
import argparse
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from windows_updates import DESKUP_VERSION, ROOT, check_tool, pack_release, update_version, vpk_command
|
||||
|
||||
|
||||
class TestHandler(SimpleHTTPRequestHandler):
|
||||
corrupt = True
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.endswith('.nupkg') and type(self).corrupt:
|
||||
type(self).corrupt = False
|
||||
file = Path(self.directory) / self.path.lstrip('/')
|
||||
payload = bytearray(file.read_bytes())
|
||||
payload[len(payload) // 2] ^= 1
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Length', str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
else:
|
||||
super().do_GET()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--vpk', type=Path, required=True)
|
||||
parser.add_argument('--flutter', default=shutil.which('flutter'))
|
||||
parser.add_argument('--work', type=Path, default=ROOT / '.local/windows-update-test')
|
||||
parser.add_argument('--port', type=int, default=8765)
|
||||
parser.add_argument('--offline', action='store_true', help='Use already cached Flutter packages')
|
||||
args = parser.parse_args()
|
||||
if sys.platform != 'win32':
|
||||
parser.error('This test requires Windows')
|
||||
work = args.work.resolve()
|
||||
if work.exists():
|
||||
parser.error('Use a new work directory so previous reports cannot pass this test')
|
||||
work.mkdir(parents=True)
|
||||
command = vpk_command(args.vpk)
|
||||
check_tool(command)
|
||||
definitions = work / 'defines.json'
|
||||
definitions.write_text(json.dumps({'CUTDEX_UPDATE_SMOKE_ROOT': work.as_posix()}), encoding='utf-8')
|
||||
environment = dict(os.environ, CUTDEX_WINDOWS_UPDATE_URL=f'http://127.0.0.1:{args.port}',
|
||||
CUTDEX_UPDATE_TEST_HTTP='1')
|
||||
# Isolate Flutter caches, generated runner files and output from live builds.
|
||||
source = work / 'source'
|
||||
source.mkdir()
|
||||
for name in ['windows']:
|
||||
shutil.copytree(ROOT / name, source / name,
|
||||
ignore=shutil.ignore_patterns('ephemeral', 'build', '__pycache__'))
|
||||
# Exercise the real Runner/update bridge with a small Flutter test entry.
|
||||
# Media processing is covered separately and need not be rebuilt here.
|
||||
(source / 'pubspec.yaml').write_text(
|
||||
'name: cutdex_update_smoke\nversion: 1.0.0+1\n'
|
||||
'environment:\n sdk: ^3.13.2\n'
|
||||
'dependencies:\n flutter:\n sdk: flutter\n'
|
||||
f' deskup: {DESKUP_VERSION}\n'
|
||||
'flutter:\n uses-material-design: true\n', encoding='utf-8')
|
||||
entry = source / 'tool/testing/windows_update_smoke.dart'
|
||||
entry.parent.mkdir(parents=True)
|
||||
shutil.copyfile(ROOT / 'tool/testing/windows_update_smoke.dart', entry)
|
||||
subprocess.run([args.flutter, 'pub', 'get'] + (['--offline'] if args.offline else []),
|
||||
cwd=source, env=environment, check=True)
|
||||
# Keep test packages separate from the app's normal release output.
|
||||
for build in [900001, 900002]:
|
||||
subprocess.run([args.flutter, 'build', 'windows', '--no-pub', '--release', '--flavor', 'development',
|
||||
'--target', 'tool/testing/windows_update_smoke.dart', '--build-name', '1.0.0',
|
||||
'--build-number', str(build), '--dart-define-from-file', str(definitions)],
|
||||
cwd=source, env=environment, check=True)
|
||||
app = source / 'build/windows/x64/development/runner/Release'
|
||||
release = work / ('baseline' if build == 900001 else 'public')
|
||||
pack_release(command, app=app, output=release, package_id='Cutdex.Dev',
|
||||
version=update_version('1.0.0', build), title='Cutdex update test')
|
||||
verify_update(work, args.port)
|
||||
|
||||
|
||||
def verify_update(work, port):
|
||||
reports = ['corrupt-rejected', 'before', 'after', 'failure']
|
||||
if any((work / f'{name}.json').exists() for name in reports):
|
||||
raise ValueError('Previous reports must not pass this test; use a fresh work directory')
|
||||
portable = next((work / 'baseline').glob('*Portable.zip'))
|
||||
if not (work / 'installed').exists():
|
||||
shutil.unpack_archive(portable, work / 'installed')
|
||||
TestHandler.corrupt = True
|
||||
server = ThreadingHTTPServer(('127.0.0.1', port),
|
||||
partial(TestHandler, directory=str(work / 'public')))
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
# Hide the helper process console; the test app itself shows its test window.
|
||||
app = work / 'installed/Cutdex update test.exe'
|
||||
process = None
|
||||
try:
|
||||
process = subprocess.Popen([str(app)], cwd=app.parent, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
deadline = time.monotonic() + 240
|
||||
while time.monotonic() < deadline:
|
||||
if (work / 'failure.json').exists():
|
||||
raise RuntimeError((work / 'failure.json').read_text())
|
||||
if (work / 'after.json').exists():
|
||||
break
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise TimeoutError('Update did not relaunch within 240 seconds')
|
||||
for report in ['corrupt-rejected', 'before', 'after']:
|
||||
print(report + ': ' + (work / f'{report}.json').read_text())
|
||||
process.wait(timeout=20)
|
||||
print(f'Velopack end-to-end update passed: {work}')
|
||||
finally:
|
||||
if process is not None and process.poll() is None:
|
||||
process.terminate()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,121 @@
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from windows_updates import resolved_deskup, numeric_version, pack_release, update_version, validate_previous, verify_manifest
|
||||
|
||||
|
||||
class UpdatePublicationTests(unittest.TestCase):
|
||||
def test_deskup_is_located_from_resolved_package_config(self):
|
||||
with tempfile.TemporaryDirectory(prefix='deskup package ') as directory:
|
||||
root = Path(directory)
|
||||
config = root / '.dart_tool/package_config.json'
|
||||
config.parent.mkdir()
|
||||
package = root / 'cache/deskup-0.1.0'
|
||||
for uri in ['../cache/deskup-0.1.0/', package.as_uri() + '/']:
|
||||
config.write_text(json.dumps({'packages': [
|
||||
{'name': 'deskup', 'rootUri': uri},
|
||||
]}), encoding='utf-8')
|
||||
with patch('windows_updates.ROOT', root):
|
||||
self.assertEqual(resolved_deskup().resolve(), package.resolve())
|
||||
|
||||
def test_missing_package_config_requests_pub_get(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
with patch('windows_updates.ROOT', Path(directory)):
|
||||
with self.assertRaisesRegex(ValueError, 'flutter pub get'):
|
||||
resolved_deskup()
|
||||
|
||||
def test_display_version_conversion_is_shared_and_ordered(self):
|
||||
self.assertEqual(update_version('1.2.3', '42'), '1.2.3-build.42')
|
||||
self.assertEqual(update_version('1.2.3', '0042'), '1.2.3-build.42')
|
||||
for version, build in [('1.2', 1), ('1.2.3', -1), ('1.2.3', 'beta')]:
|
||||
with self.assertRaises(ValueError):
|
||||
update_version(version, build)
|
||||
|
||||
def test_invalid_pack_version_never_starts_vpk(self):
|
||||
with patch('windows_updates.subprocess.run') as run:
|
||||
with self.assertRaises(ValueError):
|
||||
pack_release(['vpk'], app=Path('app'), output=Path('release'),
|
||||
package_id='Cutdex', version='1.0.0.42', title='Cutdex')
|
||||
run.assert_not_called()
|
||||
|
||||
def test_build_number_participates_in_version_order(self):
|
||||
self.assertLess(numeric_version('1.0.0-build.1'), numeric_version('1.0.0-build.2'))
|
||||
self.assertLess(numeric_version('1.0.0-build.9'), numeric_version('1.0.0-build.10'))
|
||||
self.assertLess(numeric_version('1.0.0-build.999'), numeric_version('1.0.1-build.1'))
|
||||
self.assertLess(numeric_version('1.0.0-build.999'), numeric_version('1.0.0'))
|
||||
for version in ['1.0', '1.0.0+2', '1.0.0.2', '1.0.0-build.02', '1.0.0-beta', '../1.0.0']:
|
||||
with self.assertRaises(ValueError):
|
||||
numeric_version(version)
|
||||
|
||||
def test_reused_build_and_mixed_identity_are_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / 'releases.win-x64.json').write_text(json.dumps({
|
||||
'Assets': [{'PackageId': 'Cutdex', 'Version': '1.0.0-build.2'}]}))
|
||||
for candidate in ['1.0.0-build.1', '1.0.0-build.2']:
|
||||
with self.assertRaises(ValueError):
|
||||
validate_previous(root, 'Cutdex', candidate)
|
||||
with self.assertRaises(ValueError):
|
||||
validate_previous(root, 'Cutdex.Dev', '1.0.0-build.3')
|
||||
validate_previous(root, 'Cutdex', '1.0.0-build.3')
|
||||
|
||||
def test_post_audit_tampering_and_added_files_are_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / 'cutdex.exe').write_bytes(b'app')
|
||||
(root / 'processing').mkdir()
|
||||
(root / 'processing/checksums.json').write_text('{}')
|
||||
manifest = {name: hashlib.sha256((root / name).read_bytes()).hexdigest()
|
||||
for name in ['cutdex.exe', 'processing/checksums.json']}
|
||||
(root / 'checksums.json').write_text(json.dumps(manifest))
|
||||
verify_manifest(root)
|
||||
(root / 'cutdex.exe').write_bytes(b'changed')
|
||||
with self.assertRaises(ValueError):
|
||||
verify_manifest(root)
|
||||
(root / 'cutdex.exe').write_bytes(b'app')
|
||||
(root / 'injected.dll').write_bytes(b'new')
|
||||
with self.assertRaises(ValueError):
|
||||
verify_manifest(root)
|
||||
|
||||
def test_escaping_manifest_path_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / 'checksums.json').write_text(json.dumps({'../outside.exe': '0' * 64}))
|
||||
with self.assertRaises(ValueError):
|
||||
verify_manifest(root)
|
||||
|
||||
def test_relative_staging_directory_is_normalized(self):
|
||||
with tempfile.TemporaryDirectory(dir=Path.cwd()) as directory:
|
||||
root = Path(directory).relative_to(Path.cwd())
|
||||
(root / 'cutdex.exe').write_bytes(b'app')
|
||||
(root / 'checksums.json').write_text(json.dumps({
|
||||
'cutdex.exe': hashlib.sha256(b'app').hexdigest(),
|
||||
}))
|
||||
verify_manifest(root)
|
||||
|
||||
def test_symlink_inside_staging_directory_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
original = root / 'cutdex.exe'
|
||||
original.write_bytes(b'app')
|
||||
try:
|
||||
(root / 'linked.exe').symlink_to(original)
|
||||
except OSError as error:
|
||||
if getattr(error, 'winerror', None) != 1314:
|
||||
raise
|
||||
self.skipTest(f'Symlinks unavailable: {error}')
|
||||
digest = hashlib.sha256(b'app').hexdigest()
|
||||
(root / 'checksums.json').write_text(json.dumps({
|
||||
'cutdex.exe': digest,
|
||||
'linked.exe': digest,
|
||||
}))
|
||||
with self.assertRaisesRegex(ValueError, 'Invalid manifest path'):
|
||||
verify_manifest(root)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Package audited Windows releases with Velopack, or serve a loopback test feed."""
|
||||
import argparse
|
||||
from functools import partial
|
||||
import hashlib
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.parse import urljoin, urlparse
|
||||
from urllib.request import url2pathname
|
||||
|
||||
from check_windows_release import audit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
def resolved_deskup():
|
||||
config = ROOT / '.dart_tool/package_config.json'
|
||||
if not config.is_file():
|
||||
raise ValueError('Run flutter pub get before using Windows update tools')
|
||||
packages = json.loads(config.read_text(encoding='utf-8'))['packages']
|
||||
package = next(item for item in packages if item['name'] == 'deskup')
|
||||
uri = urlparse(urljoin(config.as_uri(), package['rootUri']))
|
||||
if uri.scheme != 'file' or uri.netloc:
|
||||
raise ValueError('Expected a local resolved deskup package')
|
||||
return Path(url2pathname(uri.path))
|
||||
|
||||
|
||||
DESKUP_ROOT = resolved_deskup()
|
||||
DESKUP_VERSION = re.search(r'^version: ([^\s]+)',
|
||||
(DESKUP_ROOT / 'pubspec.yaml').read_text(encoding='utf-8'),
|
||||
re.MULTILINE).group(1)
|
||||
SDK_VERSION = re.search(r'set\(DESKUP_VELOPACK_VERSION "([^"]+)"\)',
|
||||
(DESKUP_ROOT / 'windows/velopack.cmake').read_text(encoding='utf-8')).group(1)
|
||||
|
||||
|
||||
def vpk_command(path):
|
||||
path = Path(path).resolve()
|
||||
if path.suffix.lower() == '.dll':
|
||||
# Useful with a locally extracted official vpk tool package.
|
||||
return ['dotnet', str(path), '--legacyConsole', '--skip-updates']
|
||||
return [str(path), '--legacyConsole', '--skip-updates']
|
||||
|
||||
|
||||
def check_tool(command):
|
||||
result = subprocess.run(command + ['--help'], capture_output=True, text=True,
|
||||
encoding='utf-8', errors='replace', check=True, timeout=30)
|
||||
if not re.search(rf'(?<![\d.]){re.escape(SDK_VERSION)}(?![\d.])', result.stdout + result.stderr):
|
||||
raise ValueError(f'Use vpk {SDK_VERSION} to match the native SDK')
|
||||
|
||||
|
||||
def pack_release(command, *, app, output, package_id, version, title):
|
||||
numeric_version(version)
|
||||
subprocess.run(command + ['pack', '--packId', package_id, '--packVersion', version,
|
||||
'--packDir', str(app), '--mainExe', 'cutdex.exe',
|
||||
'--packTitle', title, '--runtime', 'win-x64',
|
||||
'--channel', 'win-x64', '--outputDir', str(output),
|
||||
'--delta', 'none'], check=True)
|
||||
|
||||
|
||||
def update_version(display_version, build):
|
||||
version = display_version + '-build.' + str(int(build))
|
||||
numeric_version(version)
|
||||
return version
|
||||
|
||||
|
||||
def file_version(app):
|
||||
import pefile
|
||||
with pefile.PE(str(app / 'cutdex.exe')) as pe:
|
||||
for group in pe.FileInfo:
|
||||
for block in group:
|
||||
if block.Key == b'StringFileInfo':
|
||||
for table in block.StringTable:
|
||||
value = table.entries.get(b'ProductVersion', b'').decode('utf-8')
|
||||
match = re.fullmatch(r'(\d+\.\d+\.\d+)\+(\d+)', value)
|
||||
if match:
|
||||
return update_version(match[1], match[2])
|
||||
raise ValueError('Missing Flutter display version and build number in PE resources')
|
||||
|
||||
|
||||
def numeric_version(version):
|
||||
number = r'(0|[1-9]\d*)'
|
||||
match = re.fullmatch(rf'{number}\.{number}\.{number}(?:-build\.{number})?', version)
|
||||
if not match:
|
||||
raise ValueError('Windows update versions must use major.minor.patch-build.number')
|
||||
major, minor, patch, build = match.groups()
|
||||
# SemVer build metadata (+number) does not participate in precedence.
|
||||
# A numeric prerelease component does, and stable versions rank above it.
|
||||
return (int(major), int(minor), int(patch), int(build is None), int(build or 0))
|
||||
|
||||
|
||||
def validate_previous(output, package_id, version):
|
||||
candidate = numeric_version(version)
|
||||
for feed in output.glob('releases.*.json'):
|
||||
for asset in json.loads(feed.read_text(encoding='utf-8-sig')).get('Assets', []):
|
||||
if asset.get('PackageId') != package_id:
|
||||
raise ValueError('Do not mix production and development packages in one release directory')
|
||||
if numeric_version(asset['Version']) >= candidate:
|
||||
raise ValueError('Update version must be greater than every previously published version')
|
||||
|
||||
|
||||
def verify_manifest(app):
|
||||
app = app.resolve()
|
||||
manifest = json.loads((app / 'checksums.json').read_text(encoding='utf-8-sig'))
|
||||
actual_files = {file.relative_to(app).as_posix() for file in app.rglob('*')
|
||||
if file.is_file() and file.name != 'checksums.json'}
|
||||
# The processing subtree has its own checksum manifest, which is included
|
||||
# as a file in the outer app manifest.
|
||||
actual_files.update(file.relative_to(app).as_posix() for file in app.rglob('checksums.json')
|
||||
if file != app / 'checksums.json')
|
||||
if set(manifest) != actual_files:
|
||||
raise ValueError('Release files differ from the audited staging manifest')
|
||||
for name, expected in manifest.items():
|
||||
candidate = app / name
|
||||
file = candidate.resolve()
|
||||
if not file.is_relative_to(app) or candidate.is_symlink():
|
||||
raise ValueError(f'Invalid manifest path: {name}')
|
||||
with file.open('rb') as stream:
|
||||
if hashlib.file_digest(stream, 'sha256').hexdigest().lower() != expected.lower():
|
||||
raise ValueError(f'Release checksum mismatch: {name}')
|
||||
|
||||
|
||||
def package(args):
|
||||
app, output = args.app.resolve(), args.output.resolve()
|
||||
if output == app or output.is_relative_to(app) or app.is_relative_to(output):
|
||||
raise ValueError('Release output must be outside the staged app')
|
||||
audit(app)
|
||||
verify_manifest(app)
|
||||
sdk_dll = app / 'velopack_libc.dll'
|
||||
if not sdk_dll.is_file():
|
||||
raise ValueError('Rebuild the app with the Velopack integration before packaging')
|
||||
command = vpk_command(args.vpk)
|
||||
check_tool(command)
|
||||
version = file_version(app)
|
||||
package_id = 'Cutdex.Dev' if args.development else 'Cutdex'
|
||||
# The expected identity is compiled into the runner and must match the package.
|
||||
identity = package_id.encode('ascii') + b'\0'
|
||||
if identity not in (app / 'cutdex.exe').read_bytes():
|
||||
raise ValueError('Package identity does not match the Flutter build flavor')
|
||||
validate_previous(output, package_id, version)
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
pack_release(command, app=app, output=output, package_id=package_id, version=version,
|
||||
title='Cutdex Dev' if args.development else 'Cutdex')
|
||||
print(json.dumps({'version': version, 'packageId': package_id, 'output': str(output)}))
|
||||
|
||||
|
||||
def serve(directory, port):
|
||||
directory = directory.resolve()
|
||||
if not directory.is_dir():
|
||||
raise ValueError('Provide an existing Velopack release directory')
|
||||
with ThreadingHTTPServer(('127.0.0.1', port),
|
||||
partial(SimpleHTTPRequestHandler, directory=str(directory))) as server:
|
||||
print(f'Test update source: http://127.0.0.1:{server.server_port}', flush=True)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
pack = commands.add_parser('pack', help='Package a complete audited release; never uploads')
|
||||
pack.add_argument('--app', type=Path, required=True)
|
||||
pack.add_argument('--output', type=Path, required=True)
|
||||
pack.add_argument('--vpk', type=Path, required=True)
|
||||
pack.add_argument('--development', action='store_true')
|
||||
server = commands.add_parser('serve', help='Serve a test feed on 127.0.0.1 only')
|
||||
server.add_argument('--directory', type=Path, required=True)
|
||||
server.add_argument('--port', type=int, default=8765)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.command == 'pack':
|
||||
package(args)
|
||||
else:
|
||||
serve(args.directory, args.port)
|
||||
except KeyboardInterrupt:
|
||||
return
|
||||
except (ValueError, OSError) as error:
|
||||
print(str(error), file=sys.stderr)
|
||||
raise SystemExit(1) from error
|
||||
except subprocess.CalledProcessError as error:
|
||||
raise SystemExit(error.returncode) from error
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user