Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Faster Windows updates in mainland China: signed domestic mirror and source delta updates
Bowen Xue064153ff8500
diff --git a/MANIFEST.in b/MANIFEST.inindex 357098c..3b2bfbc 100644--- a/MANIFEST.in+++ b/MANIFEST.in@@ -27,3 +27,5 @@ prune benchmarksprune distributionprune .githubexclude AGENTS.md CHANGELOG.md++include freevideo_source_bootstrap.py freevideo_ed25519.py freevideo_update_keys.pydiff --git a/freevideo_ed25519.py b/freevideo_ed25519.pynew file mode 100644index 0000000..5aa0754--- /dev/null+++ b/freevideo_ed25519.py@@ -0,0 +1,95 @@+"""Dependency-free Ed25519 (RFC 8032), with strict encodings/subgroup checks.++Verification handles public inputs. Signing is an offline release utility, not+constant-time: keep signing seeds on a trusted release machine.+"""+import hashlib++P = 2**255 - 19+L = 2**252 + 27742317777372353535851937790883648493+D = -121665 * pow(121666, P-2, P) % P+I = pow(2, (P-1)//4, P)+IDENTITY = (0, 1, 1, 0)+++def _decode(data):+ if len(data) != 32:+ raise ValueError('Invalid point length')+ encoded = int.from_bytes(data, 'little')+ y, sign = encoded & (2**255-1), encoded >> 255+ if y >= P:+ raise ValueError('Noncanonical point')+ x2 = (y*y-1) * pow(D*y*y+1, P-2, P) % P+ x = pow(x2, (P+3)//8, P)+ if x*x % P != x2:+ x = x*I % P+ if x*x % P != x2 or (x == 0 and sign):+ raise ValueError('Invalid point')+ if x & 1 != sign:+ x = P-x+ return x, y, 1, x*y % P+++def _add(a, b):+ x, y, z, t = a+ u, v, w, s = b+ aa, bb = (y-x)*(v-u) % P, (y+x)*(v+u) % P+ cc, dd = 2*D*t*s % P, 2*z*w % P+ e, f, g, h = bb-aa, dd-cc, dd+cc, bb+aa+ return e*f % P, g*h % P, f*g % P, e*h % P+++def _mul(point, scalar):+ result = IDENTITY+ while scalar:+ if scalar & 1:+ result = _add(result, point)+ point = _add(point, point)+ scalar >>= 1+ return result+++def _encode(point):+ x, y, z, _ = point+ inverse = pow(z, P-2, P)+ return ((y*inverse % P) | ((x*inverse % P & 1) << 255)).to_bytes(32, 'little')+++B = _decode(bytes.fromhex('58' + '66'*31))+++def verify(public_key, message, signature):+ try:+ if len(public_key) != 32 or len(signature) != 64:+ return False+ a, r = _decode(public_key), _decode(signature[:32])+ scalar = int.from_bytes(signature[32:], 'little')+ neutral = _encode(IDENTITY)+ if scalar >= L or any(_encode(q) == neutral or _encode(_mul(q, L)) != neutral for q in (a, r)):+ return False+ challenge = int.from_bytes(hashlib.sha512(signature[:32]+public_key+message).digest(), 'little') % L+ return _encode(_mul(B, scalar)) == _encode(_add(r, _mul(a, challenge)))+ except (ValueError, TypeError, OverflowError):+ return False+++def _secret(seed):+ if len(seed) != 32:+ raise ValueError('Ed25519 seed must contain 32 bytes')+ hashed = hashlib.sha512(seed).digest()+ scalar = (int.from_bytes(hashed[:32], 'little') & (2**254-8)) | 2**254+ return scalar, hashed[32:]+++def public_key(seed):+ scalar, _ = _secret(seed)+ return _encode(_mul(B, scalar))+++def sign(seed, message):+ scalar, prefix = _secret(seed)+ public = _encode(_mul(B, scalar))+ nonce = int.from_bytes(hashlib.sha512(prefix+message).digest(), 'little') % L+ r = _encode(_mul(B, nonce))+ challenge = int.from_bytes(hashlib.sha512(r+public+message).digest(), 'little') % L+ return r + ((nonce+challenge*scalar) % L).to_bytes(32, 'little')diff --git a/freevideo_engine/comfy_launcher.py b/freevideo_engine/comfy_launcher.pyindex 6fb0265..d3111c3 100644--- a/freevideo_engine/comfy_launcher.py+++ b/freevideo_engine/comfy_launcher.py@@ -96,7 +96,7 @@ class Launcher:from .launcher_update import current_build, UpdateClientidentity = current_build()if identity:- update_client = UpdateClient(identity, launcher_root())+ update_client = UpdateClient(identity, launcher_root(), language='zh' if self.zh else 'en')if update_client is not None:from .launcher_update_ui import UpdateUIself.updates = UpdateUI(self, update_client, self.update_row)diff --git a/freevideo_engine/desktop_runtime.py b/freevideo_engine/desktop_runtime.pyindex aa62606..e307a11 100644--- a/freevideo_engine/desktop_runtime.py+++ b/freevideo_engine/desktop_runtime.py@@ -53,7 +53,10 @@ def source_files(root):'scripts/bootstrap_linux.sh', 'scripts/windows_app.py', 'scripts/build_windows.py','scripts/check_installation.py', 'scripts/build_launcher_notices.py']# Older deployed Windows payloads may predate the optional Mac entry points.- files_optional = ('scripts/build_macos.py', 'scripts/macos_app.py')+ files_optional = ('scripts/build_macos.py', 'scripts/macos_app.py',+ 'freevideo_source_bootstrap.py', 'freevideo_ed25519.py', 'freevideo_update_keys.py',+ 'scripts/source_build.py', 'scripts/build_source_delta.py', 'scripts/sign_update_manifest.py',+ 'scripts/prune_qt_bundle.py', 'scripts/deduplicate_bundle_data.py', 'scripts/pyi_rth_bundle_data.py')names += [name for name in files_optional if (root / name).is_file()]# Notice and licence files are carried when present; a launcher never fails to start without one.names += [name for name in NOTICE_FILES if (root / name).is_file()]@@ -62,7 +65,7 @@ def source_files(root):files += [p for folder in ('freevideo_engine', 'constraints', 'web', 'example_workflows')for p in (root / folder).rglob('*')if p.is_file() and (p.suffix in ('.py', '.json', '.txt', '.ps1', '.sh', '.js', '.css', '.svg', '.png', '.ico', '.qml',- '.woff2', '.webp')+ '.woff2', '.otf', '.webp')or folder == 'web' and p.parent.name == 'tutorial' and p.suffix == '.mp4')]return sorted(files)@@ -168,6 +171,10 @@ def check_launcher_payload(source, destination):def materialize_source(bundle=None, destination=None):"""A one-file executable's temporary extraction must never back an editable install."""+ if bundle is None:+ import freevideo_source_bootstrap+ if freevideo_source_bootstrap.ACTIVE:+ return Path(plain(freevideo_source_bootstrap.ACTIVE['source']))if bundle is None and not getattr(sys, 'frozen', False):return Path(plain(resolved(__file__).parents[1]))bundle = io_path(bundle or Path(sys._MEIPASS) / 'engine-source')diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.pyindex 15f2427..e16d0ee 100644--- a/freevideo_engine/launcher_session.py+++ b/freevideo_engine/launcher_session.py@@ -172,7 +172,7 @@ class Session:from .launcher_update import current_build, UpdateClientidentity = current_build()if identity:- self.updater = UpdateClient(identity, launcher_root())+ self.updater = UpdateClient(identity, launcher_root(), language=self.language)if self.updater and not self.updater.busy:self.updater.run('check')self.update_checked = time.monotonic()@@ -252,7 +252,10 @@ class Session:self.explain_busy()returnif key == 'language':- self.language = str(value); self.persist(); return+ self.language = str(value)+ if self.updater:+ self.updater.language = self.language+ self.persist(); returnif key == 'token':if self.controller.busy:raise ValueError(self.t('Pause installation before changing the token.', '请先暂停安装,再修改 Token。'))diff --git a/freevideo_engine/launcher_update.py b/freevideo_engine/launcher_update.pyindex 8598c7c..15d38ef 100644--- a/freevideo_engine/launcher_update.py+++ b/freevideo_engine/launcher_update.py@@ -5,6 +5,8 @@ forwards to a newer, explicitly approved download on subsequent starts."""import errnoimport hashlib+import logging+from concurrent.futures import ThreadPoolExecutor, as_completedfrom email.utils import parsedate_to_datetimeimport jsonimport os@@ -18,12 +20,35 @@ import urllib.errorimport urllib.parseimport urllib.request+import freevideo_ed25519 as ed25519+import freevideo_update_keys as keysfrom . import execution_pathsfrom .monitoring import savefrom .long_paths import io_path, resolved, plain, plain_errors-from . import disk_space+from . import disk_space, network+from .launcher_settings import default_language+from .system import windowsREPOSITORY = 'FlashML-org/FreeVideo'+# Mirror repository on the ModelScope domestic site; the release script uploads each release there.+MIRROR_BASE = 'https://modelscope.cn/models/BowenXue/FreeVideo-releases/resolve/master'+# ModelScope redirects large files to its regional CDN: cdn-lfs-cn-<n>.modelscope.cn.+MIRROR_CDN = re.compile(r'cdn-lfs-cn-[0-9]{1,2}\.modelscope\.cn')+UPDATE_STALL_SECONDS = 30+MANIFEST_CHECK_SECONDS = 20+_metadata_budget = threading.local()+log = logging.getLogger(__name__)+++def mirror_url(relative):+ return MIRROR_BASE + '/' + urllib.parse.quote(relative, safe='/')+++def source_order(language=None):+ language = default_language() if language is None else language+ return ('mirror', 'github') if language.lower().startswith('zh') else ('github', 'mirror')++# The channel names the platform; launchers from before combined releases read# these tags, which the release workflow keeps up to date for them.CHANNEL = 'windows-preview'@@ -42,6 +67,10 @@ RELEASE_ASSETS = {CHANNEL: ('FreeVideo.exe', 'update-windows.json'),MAC_CHANNEL: ('FreeVideo-Mac-arm64.dmg', 'update-macos.json'),LINUX_CHANNEL: ('FreeVideo-Linux-x86_64.AppImage', 'update-linux.json')}CHANNELS = tuple(RELEASE_ASSETS)+MANIFEST_DOMAIN = b'FreeVideo update manifest v1\x00'+# The mirror is only a source for packages whose own signature the launcher can+# check after download; DMG and AppImage have none, so they stay on GitHub.+MIRROR_CHANNELS = (CHANNEL,)RETRY_SECONDS = 60MAX_RETRY_SECONDS = 15 * 60MAX_DOWNLOAD_RETRIES = 3@@ -178,6 +207,9 @@ def current_build():if not getattr(sys, 'frozen', False):return Nonetry:+ import freevideo_source_bootstrap+ if freevideo_source_bootstrap.ACTIVE:+ return build_identity(freevideo_source_bootstrap.ACTIVE['manifest']['build'])return build_identity(json.loads((io_path(sys._MEIPASS) / 'launcher-build.json').read_text(encoding='utf-8')))except (OSError, ValueError, TypeError):return None@@ -222,40 +254,62 @@ def newer(candidate, current):def _trusted_url(url):+ if any(ord(character) <= 32 for character in url):+ raise ValueError('Invalid update URL')parsed = urllib.parse.urlsplit(url)- if (parsed.scheme != 'https' or parsed.username or parsed.password or parsed.port not in (None, 443)- or parsed.hostname not in ('api.github.com', 'github.com', 'release-assets.githubusercontent.com',- 'objects.githubusercontent.com', 'github-releases.githubusercontent.com')):- raise ValueError('Update redirect is not an approved HTTPS GitHub download')+ if (parsed.scheme != 'https' or parsed.username is not None or parsed.password is not None or parsed.port not in (None, 443)+ or not (parsed.hostname in ('api.github.com', 'github.com', 'release-assets.githubusercontent.com',+ 'objects.githubusercontent.com', 'github-releases.githubusercontent.com',+ 'modelscope.cn', 'www.modelscope.cn')+ or MIRROR_CDN.fullmatch(parsed.hostname or ''))):+ raise ValueError('Update redirect is not an approved HTTPS download')+++def _github_url(url):+ _trusted_url(url)+ if urllib.parse.urlsplit(url).hostname not in (+ 'api.github.com', 'github.com', 'release-assets.githubusercontent.com',+ 'objects.githubusercontent.com', 'github-releases.githubusercontent.com'):+ raise ValueError('Source trust requires GitHub HTTPS')class UpdateRedirect(urllib.request.HTTPRedirectHandler):+ def __init__(self, *, github_only=False):+ super().__init__()+ self.github_only = github_only+def redirect_request(self, request, fp, code, msg, headers, newurl):- _trusted_url(newurl)+ (_github_url if self.github_only else _trusted_url)(newurl)+ if time.monotonic() >= getattr(_metadata_budget, 'deadline', float('inf')):+ raise TimeoutError('Update metadata deadline exceeded')redirected = super().redirect_request(request, fp, code, msg, headers, newurl)if urllib.parse.urlsplit(newurl).hostname != 'api.github.com':redirected.remove_header('Authorization')return redirected-def open_download(url, token='', *, binary=False):+def open_download(url, token='', *, binary=False, github_only=False):# One inherited route, then one direct route. Do not mutate shell, Git or- # registry proxies. Never retry a slow-but-active binary on another source.+ # registry proxies. Package bodies use network.download instead.global _api_retry_atis_api = url.startswith(API + '/')if not is_api and not (url.startswith(WEB + '/releases/download/')- or url.startswith(RELEASE_PAGE + '/download/')):+ or url.startswith(RELEASE_PAGE + '/download/')+ or url.startswith(MIRROR_BASE + '/')):raise ValueError('Unexpected update download address')- _trusted_url(url)+ (_github_url if github_only else _trusted_url)(url)if is_api and time.time() < _api_retry_at:raise UpdateUnavailable('rate_limited', _api_retry_at - time.time())for direct in (False, True):- opener = urllib.request.build_opener(urllib.request.ProxyHandler({} if direct else None), UpdateRedirect())+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({} if direct else None), UpdateRedirect(github_only=github_only))headers = {'User-Agent': 'FreeVideo-launcher', 'Accept': 'application/octet-stream' if binary else 'application/vnd.github+json'}if token and is_api:headers['Authorization'] = 'Bearer ' + tokentry:- return opener.open(urllib.request.Request(url, headers=headers), timeout=5)+ remaining = getattr(_metadata_budget, 'deadline', time.monotonic()+5) - time.monotonic()+ if remaining <= 0:+ raise TimeoutError('Update metadata deadline exceeded')+ return opener.open(urllib.request.Request(url, headers=headers), timeout=min(5, remaining))except urllib.error.HTTPError as error:if failure_kind(error) == 'rate_limited':if is_api:@@ -269,7 +323,7 @@ def open_download(url, token='', *, binary=False):def _bytes(response, limit, cancel=None, seconds=15):- deadline = time.monotonic() + seconds+ deadline = min(time.monotonic() + seconds, getattr(_metadata_budget, 'deadline', float('inf')))done = 0read = getattr(response, 'read1', response.read)while True:@@ -350,7 +404,7 @@ def _selection(candidate, channel, track):raise ValueError('Update metadata belongs to a different release track')-def latest_release(token='', *, channel=CHANNEL, track='stable'):+def _github_release(token='', *, channel=CHANNEL, track='stable'):"""Read and validate the published build without downloading an executable."""if channel not in CHANNELS:raise ValueError('Unknown launcher update channel')@@ -378,9 +432,104 @@ def latest_release(token='', *, channel=CHANNEL, track='stable'):return candidate-def check(current, token=''):+def manifest_signature_ok(data, signature):+ """Whether `signature` (hex) is the release key's signature over the manifest bytes."""+ try:+ return (keys.ED25519_RELEASE_KEY_ENABLED and+ keys.ED25519_PUBLIC_KEY != keys.PLACEHOLDER_PUBLIC_KEY and+ ed25519.verify(keys.ED25519_PUBLIC_KEY, MANIFEST_DOMAIN + data,+ bytes.fromhex(signature.decode('ascii').strip())))+ except (TypeError, ValueError, UnicodeDecodeError):+ return False+++def _mirror_bytes(url, limit):+ with open_download(url, '', binary=True) as response:+ return b''.join(_bytes(response, limit))+++def _mirror_release(channel, track):+ if channel not in MIRROR_CHANNELS:+ raise ValueError('No mirror for this platform')+ name = RELEASE_ASSETS[channel][1]+ data = _mirror_bytes(mirror_url('channels/stable/' + name), MAX_MANIFEST_BYTES)+ # A mirror is not the publisher: its manifest counts only with the release+ # signature, otherwise this source is skipped and GitHub still decides.+ if not manifest_signature_ok(data, _mirror_bytes(mirror_url('channels/stable/' + name + '.sig'), 256)):+ raise ValueError('Mirror manifest signature is not valid')+ candidate = manifest(json.loads(data))+ _selection(candidate, channel, track)+ if not candidate.get('product_version'):+ raise ValueError('Mirror updates require a product version')+ return candidate+++def _choose_release(found, order):+ github, mirror = found.get('github'), found.get('mirror')+ conflict = (github is not None and mirror is not None+ and github.get('product_version') == mirror.get('product_version')+ and github['asset']['sha256'] != mirror['asset']['sha256'])+ if conflict:+ selected = github+ else:+ selected = next(found[name] for name in order if name in found)+ for candidate in found.values():+ if newer(candidate, selected):+ selected = candidate+ # Local provenance, never read from remote JSON. Persist it with the reminder+ # so a mirror-only check still requires the same verification after restart.+ result = dict(selected)+ if mirror is None:+ return result+ result['_update_sources'] = dict(github='github' in found, mirror='mirror' in found,+ mirror_allowed=not conflict)+ return result+++def latest_release(token='', *, channel=CHANNEL, track='stable', language=None, on_candidate=None):+ """Race bounded metadata requests; reconcile both before explicit download.++ A first valid result can immediately display a reminder. The background+ check settles the other small request before allowing activation/download,+ so neither a stale mirror nor a digest conflict can win on latency alone.+ """+ if channel not in CHANNELS or track not in TRACKS:+ raise ValueError('Unknown launcher update channel or track')+ if track != 'stable':+ return _github_release(token, channel=channel, track=track)+ order = [name for name in source_order(language) if name == 'github' or channel in MIRROR_CHANNELS]+ calls = dict(github=lambda: _github_release(token, channel=channel, track=track),+ mirror=lambda: _mirror_release(channel, track))+ def fetch(name):+ _metadata_budget.deadline = time.monotonic() + MANIFEST_CHECK_SECONDS+ try:+ return calls[name]()+ finally:+ del _metadata_budget.deadline+ found, failures = {}, {}+ with ThreadPoolExecutor(max_workers=2, thread_name_prefix='launcher-manifest') as pool:+ pending = {pool.submit(fetch, name): name for name in order}+ for future in as_completed(pending):+ name = pending[future]+ try:+ found[name] = future.result()+ except (OSError, ValueError, TypeError, AttributeError) as error:+ failures[name] = error+ if found and on_candidate:+ on_candidate(_choose_release(found, order))+ if not found:+ raise failures['github']+ return _choose_release(found, order)+++def check(current, token='', *, language=None, on_candidate=None):current = build_identity(current)- candidate = latest_release(token, channel=current['channel'], track=build_track(current))+ options = {}+ if language is not None:+ options['language'] = language+ if on_candidate is not None:+ options['on_candidate'] = on_candidate+ candidate = latest_release(token, channel=current['channel'], track=build_track(current), **options)return candidate if newer(candidate, current) else None@@ -408,52 +557,107 @@ def executable_path(root, candidate):return Path(plain(resolved(root))) / 'updates' / candidate['asset']['sha256'] / filename+def authenticode(path):+ """Use Windows PowerShell 5.1's WinTrust-backed check, with a literal path.++ Only an exit code leaves PowerShell; certificate/path/provider diagnostics+ and user data are never logged. The script contains no interpolated path.+ """+ from .windows_ux import external_python, hidden_console+ system = Path(os.environ.get('SystemRoot', r'C:\Windows'))+ executable = system / 'System32/WindowsPowerShell/v1.0/powershell.exe'+ script = ("$ErrorActionPreference='Stop'; try {"+ "$s=Get-AuthenticodeSignature -LiteralPath $env:FREEVIDEO_SIGNATURE_PATH;"+ "if ($s.Status -eq 'Valid' -and $s.SignerCertificate -and "+ "$s.SignerCertificate.Subject -cmatch '(^|,\\s*)CN=FlashML LLC(,|$)' -and "+ "$s.SignerCertificate.GetNameInfo([System.Security.Cryptography.X509Certificates.X509NameType]::SimpleName,$false) -ceq 'FlashML LLC') "+ "{exit 0}; exit 1} catch {exit 2}")+ env = dict(os.environ, FREEVIDEO_SIGNATURE_PATH=str(io_path(resolved(path))))+ try:+ with external_python():+ result = execution_paths.run([str(executable), '-NoLogo', '-NoProfile', '-NonInteractive',+ '-Command', script], env=env, stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20, **hidden_console())+ return {0: True, 1: False}.get(result.returncode) # None: the check itself could not be completed+ except (OSError, subprocess.SubprocessError):+ return None+++def _signature_verifier(candidate, provenance):+ if not windows() or build_target(candidate) != 'windows-x86_64' or provenance.get('github', True):+ return None+ current = authenticode(sys.executable)+ enforced = current is not False # A check that could not run is treated as signed: fail closed, switch source.+ def verify(path):+ valid = authenticode(path) is True+ (log.info if valid else log.warning)('Launcher Authenticode: current=%s enforced=%s valid=%s',+ current, enforced, valid)+ return valid or not enforced+ return verify+++def download_sources(candidate, language=None):+ sources = {'github': _asset_url(candidate)}+ provenance = candidate.get('_update_sources', {})+ if (build_track(candidate) == 'stable' and candidate.get('product_version')+ and candidate.get('channel') in MIRROR_CHANNELS and provenance.get('mirror_allowed', True)):+ sources['mirror'] = mirror_url('releases/v' + candidate['product_version'] + '/' ++ RELEASE_ASSETS[candidate['channel']][0])+ return [(name, sources[name]) for name in source_order(language) if name in sources]+++def download_fallbacks(candidate, token=''):+ if time.time() < _api_retry_at:+ return {}+ headers = ('Accept: application/octet-stream',)+ if token:+ headers += ('Authorization: Bearer ' + token,)+ return {'github': (API + '/releases/assets/' + str(candidate['asset']['id']), headers)}++@plain_errors-def download(candidate, root, token='', *, progress=None, cancel=None):- candidate = manifest(candidate)+def download(candidate, root, token='', *, progress=None, cancel=None, language=None):+ provenance = candidate.get('_update_sources', {})+ candidate = dict(manifest(candidate), _update_sources=provenance)+ from .source_update import try_download+ overlay = try_download(candidate, root, token, progress=progress, cancel=cancel, language=language)+ if overlay is not None:+ return overlayasset = candidate['asset']target = executable_path(root, candidate)- if verified(target, asset):+ def cancelled():+ if cancel is not None and cancel.is_set():+ raise InterruptedError('Update stopped before activation')+ cancelled()+ verify_signature = _signature_verifier(candidate, provenance)+ if verified(target, asset) and (verify_signature is None or verify_signature(target)):+ cancelled()return targetio_path(target.parent).mkdir(parents=True, exist_ok=True)- # Each attempt owns one stage. Failed stages cannot be resumed, so discard- # only ours; never touch another attempt, the original launcher or models.- import tempfile- if disk_space.free_bytes(target.parent) < asset['bytes'] + 16*2**20:+ # Only the selected cache artifact is ours. Other update versions/attempts+ # and the original launcher remain untouched.+ io_path(target).unlink(missing_ok=True)+ partial = io_path(str(target) + '.partial')+ retained = min(asset['bytes'], partial.stat().st_size) if partial.is_file() else 0+ if disk_space.free_bytes(target.parent) < asset['bytes'] - retained + 16*2**20:raise UpdateUnavailable('disk')- start, done = time.monotonic(), 0- stage = None+ def report(done, total, speed):+ cancelled()+ if progress:+ progress(dict(done=done, total=total, bytes_per_second=speed,+ remaining_seconds=(total-done)/speed if speed > 0 else 0))try:- try:- response = open_download(_asset_url(candidate), '', binary=True)- except OSError as error:- response = _fallback(error, lambda: open_download(API + '/releases/assets/' + str(asset['id']), token, binary=True))- with response:- with tempfile.NamedTemporaryFile(prefix='download-', suffix='.partial', dir=io_path(target.parent), delete=False) as stream:- stage = Path(plain(stream.name))- digest = hashlib.sha256()- for block in _bytes(response, asset['bytes'], cancel, seconds=1800):- stream.write(block); digest.update(block); done += len(block)- if progress:- elapsed = time.monotonic()-start- speed = done/max(.001, elapsed)- progress(dict(done=done, total=asset['bytes'], bytes_per_second=speed,- remaining_seconds=(asset['bytes']-done)/speed))- stream.flush(); os.fsync(stream.fileno())- if done != asset['bytes'] or digest.hexdigest() != asset['sha256']:- raise ValueError('Launcher update failed size/content verification; original EXE retained')- if cancel is not None and cancel.is_set():- raise InterruptedError('Update stopped before activation')- if build_target(candidate) == 'linux-x86_64':- io_path(stage).chmod(0o755) # An AppImage runs itself.- io_path(stage).replace(io_path(target))- return target- finally:- if stage is not None:- try:- io_path(stage).unlink(missing_ok=True)- except OSError:- pass # A cleanup failure must not mask the download error.+ network.download(download_sources(candidate, language), io_path(target), asset['sha256'], report,+ network=dict(quiet=True, resource_check=cancelled), size=asset['bytes'],+ stall_seconds=UPDATE_STALL_SECONDS, low_speed_limit=0, cycles=1,+ category='launcher-update', validate_url=_trusted_url, verify=verify_signature,+ fallbacks=download_fallbacks(candidate, token))+ except network.DownloadError as error:+ raise UpdateUnavailable('invalid' if getattr(error, 'integrity', False) else 'connection') from error+ cancelled()+ if build_target(candidate) == 'linux-x86_64':+ io_path(target).chmod(0o755)+ return targetclass DownloadedLauncherUnavailable(ValueError):@@ -463,6 +667,10 @@ class DownloadedLauncherUnavailable(ValueError):@plain_errorsdef launch_download(candidate, root, *, token='', popen=None):candidate = manifest(candidate)+ from . import source_update+ overlay = source_update.prepared(candidate, root)+ if overlay is not None:+ return source_update.launch(candidate, root, overlay, token=token, popen=popen)if build_target(candidate) == 'macos-arm64':raise ValueError('Mac update activation is not available in this development build')path = executable_path(root, candidate)@@ -545,18 +753,22 @@ def resumed_update(current, root, *, seconds=600):class UpdateClient:@plain_errors- def __init__(self, current, root, token=None):+ def __init__(self, current, root, token=None, *, language=None):# Python 3.9 on Windows can leave a nonexistent relative path relative# in resolve(). Updates must survive changing cwd to the EXE directory.self.current, self.root = build_identity(current), Path(plain(resolved(root)))self.token = token if token is not None else os.environ.get('GITHUB_TOKEN') or os.environ.get('GH_TOKEN', '')+ self.language = languageself.state = dict(status='idle')self.available = None# Older launchers saved this as a mandatory update. Read it only as a# cached reminder; a known newer version never prevents using this one.for name in ('available.json', 'required.json'):try:- candidate = manifest(json.loads((io_path(self.root) / 'updates' / name).read_text(encoding='utf-8')))+ cached = json.loads((io_path(self.root) / 'updates' / name).read_text(encoding='utf-8'))+ candidate = manifest(cached)+ if isinstance(cached.get('_update_sources'), dict):+ candidate['_update_sources'] = cached['_update_sources']if newer(candidate, self.current) and (self.available is None or newer(candidate, self.available)):self.available = candidateexcept (OSError, ValueError, TypeError):@@ -607,10 +819,20 @@ class UpdateClient:selected = candidatetry:if operation == 'check':- found = check(self.current, self.token)+ def noticed(value):+ if not self.cancelled.is_set() and newer(value, self.current):+ shown = self.available+ if shown is None or newer(value, shown):+ self.state = dict(status='available', candidate=value)+ found = check(self.current, self.token, language=self.language, on_candidate=noticed)if self.cancelled.is_set():raise InterruptedError('Update check cancelled')- if found and (self.available is None or newer(found, self.available)):+ if found and (self.available is None or newer(found, self.available)+ or (found['revision'] == self.available['revision']+ and found['built_at'] == self.available['built_at']+ and found.get('product_version') == self.available.get('product_version'))+ or (found.get('product_version') == self.available.get('product_version')+ and found.get('_update_sources', {}).get('mirror_allowed') is False)):self.available = foundsave(self.root / 'updates/available.json', found)self.state = dict(status='available' if self.available else 'current', candidate=self.available)@@ -618,12 +840,12 @@ class UpdateClient:if _retry and (not candidate['asset'].get('url') or build_track(candidate) == 'nightly'or candidate['asset']['url'] == asset_url(candidate['channel'], RELEASE_ASSETS[candidate['channel']][0])):# A rolling release or a legacy latest URL may have moved.- found = check(self.current, self.token)+ found = check(self.current, self.token, language=self.language)if found and newer(found, candidate):selected = founddef progress(value):self.state = dict(status='downloading', candidate=selected, progress=value)- download(selected, self.root, self.token, progress=progress, cancel=self.cancelled)+ download(selected, self.root, self.token, progress=progress, cancel=self.cancelled, language=self.language)self.state = dict(status='ready', candidate=selected)self.failures = 0except Exception as error:diff --git a/freevideo_engine/network.py b/freevideo_engine/network.pyindex d6e81fc..3fdd6a6 100644--- a/freevideo_engine/network.py+++ b/freevideo_engine/network.py@@ -826,12 +826,61 @@ def _faster_source(compare, now, started, offset, done, size, alternatives, timereturn None++def _redirect_fields(text):+ """curl's http_code and redirect_url output as (status, url); Windows curl ends its lines with CRLF."""+ status, _, destination = text.partition('\n')+ return status.strip(), destination.strip()++def download(candidates, path, expected, progress=None, *, network=None, env=None, size=None,algorithm='sha256', git_blob=False, headers_for=None, stall_seconds=None, category='download',- low_speed_limit=1024, max_seconds=None, cycles=2, slow_seconds=None, keep_partial=False):- """Resume across ranked sources; hash before accepting, retain rejected bytes."""+ low_speed_limit=1024, max_seconds=None, cycles=2, slow_seconds=None, keep_partial=False,+ validate_url=None, verify=None, fallbacks=None):+ """Resume ranked sources; defaults retain rejected bytes.++ validate_url checks each redirect before curl can follow it; verify runs+ after the digest and before publication. fallbacks maps a source name to+ an alternate (url, headers) within the same source/route retry round.+ """network = network or {}path = Path(path)+ updating = category == 'launcher-update'+ integrity_failed = False+ failed_sources = set()+ transferred, high_water, last_rate = 0, 0, 0.+ transfer_samples = deque([(time.monotonic(), 0)])++ def update_progress(done, added):+ nonlocal transferred, high_water, last_rate+ now = time.monotonic()+ transferred += added+ transfer_samples.append((now, transferred))+ while len(transfer_samples) > 2 and transfer_samples[1][0] < now - 5:+ transfer_samples.popleft()+ seconds = now - transfer_samples[0][0]+ last_rate = (transferred-transfer_samples[0][1]) / max(.001, seconds)+ # A clean retry keeps the visible bar. Completion is reported only+ # after the hash and optional caller verification have both succeeded.+ high_water = max(high_water, min(done, size-1) if size else done)+ if progress:+ progress(high_water, size or 0, last_rate)++ def reject(candidate, reason):+ if updating:+ candidate.unlink(missing_ok=True)+ else:+ retain_partial(candidate, reason)++ def publish(candidate):+ check = network.get('resource_check')+ if updating and check:+ check()+ from .file_ops import publish as move+ move(candidate, path)+ if updating and progress:+ progress(path.stat().st_size, size or 0, last_rate)+model = category in ('models', 'vdn-models', 'edge-models', 'image-models')stall_seconds = stall_seconds if stall_seconds is not None else 120 if model else 20@@ -839,7 +888,7 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonif size is not None and candidate.stat().st_size != size:return Falseevent(network, category=category, source=source, file=path.name, action='verifying', algorithm=algorithm)- check = network.get('resource_check') if keep_partial else None+ check = network.get('resource_check') if keep_partial or updating else Nonefrom .install_activity import byte_progressreport = byte_progress('verify_progress', path.name, report=lambda **row:event(network, category=category, source=source, action='verify-progress', **row))@@ -848,8 +897,11 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Noncheck()if model:report(done, total)- return hash_file(candidate, algorithm, git_blob, discard_cache=category in ('models', 'vdn-models', 'image-models'),- progress=verification if model or check else None) == expected+ matched = hash_file(candidate, algorithm, git_blob, discard_cache=category in ('models', 'vdn-models', 'image-models'),+ progress=verification if model or check else None) == expected+ if matched and verify is not None:+ matched = verify(candidate)+ return matchedif path.is_file():if matches(path):return@@ -858,15 +910,16 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonpartial = path.with_suffix(path.suffix + '.partial')if partial.is_file() and (size is None or partial.stat().st_size == size):if matches(partial):- from .file_ops import publish- publish(partial, path)+ publish(partial)returnif size is not None:# A complete-but-corrupt file is not a resumable prefix.- retain_partial(partial, 'hash-rejected')+ reject(partial, 'hash-rejected')timeout = network.get('timeout_seconds', 5)affinity = partial.with_name(partial.name + '.source.json')- candidates = [(name, url, route) for name, url in candidates+ candidates = [(name, address, route, headers) for name, url in candidates+ for address, headers in ([(url, ())] ++ ([(fallbacks[name][0], tuple(fallbacks[name][1]))] if fallbacks and name in fallbacks else []))for route in route_order(network, category, name, env)]if not candidates:raise RuntimeError('No download sources configured; existing files retained')@@ -885,18 +938,30 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Non# if the user's entire connection is slow. Do not oscillate forever.if cycle and measured_rates:candidates.sort(key=lambda row: -measured_rates.get((row[0], row[2]), 0))- for candidate_index, (name, url, route) in enumerate(candidates):- for restart in range(3 if model else 2):+ for candidate_index, (name, original_url, route, extra_headers) in enumerate(candidates):+ if name in failed_sources:+ continue+ url, redirects, restart = original_url, 0, 0+ # Redirects are individual curl requests when a caller supplies a+ # policy. Never let curl contact an unchecked redirect destination.+ for attempt in range(16 if validate_url else (3 if model else 2)):+ if updating and network.get('resource_check'):+ network['resource_check']()+ if validate_url:+ try:+ validate_url(url)+ except ValueError:+ failed_sources.add(name)+ breakoffset = partial.stat().st_size if partial.exists() else 0if keep_partial and size is not None and offset == size:if matches(partial, name):- from .file_ops import publish- publish(partial, path)+ publish(partial)return- retain_partial(partial, 'hash-rejected')+ reject(partial, 'hash-rejected')offset = 0if size and offset > size:- retain_partial(partial, 'oversized')+ reject(partial, 'oversized')offset = 0remembered = Falsedef remember_source():@@ -910,7 +975,11 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonevent(network, category=category, source=name, route=route, file=path.name, action='attempt', method='curl', cycle=cycle, resume_bytes=offset)attempt_env = route_environment(network, category, name, env, route)command = curl_command(timeout, attempt_env) + ['--output', str(partial), '--write-out', '%{http_code}']- if not model and slow_seconds is None:+ if validate_url:+ command += ['--disable', '--max-redirs', '0', '--write-out', '%{http_code}\n%{redirect_url}']+ # --disable must be the first option to suppress .curlrc.+ command.insert(1, command.pop(command.index('--disable')))+ if not model and slow_seconds is None and not updating:command += ['--speed-limit', str(low_speed_limit), '--speed-time', str(stall_seconds)]if max_seconds is not None:command += ['--max-time', str(max_seconds)]@@ -934,11 +1003,14 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonslow = Falsefaster = Nonecompare = dict(thread=None, rates={}, checks=0, at=started + SWITCH_AFTER_SECONDS, current=0.)- alternatives_ahead = [row for row in candidates[candidate_index+1:] if row[0] != name]+ alternatives_ahead = [row[:3] for row in candidates[candidate_index+1:] if row[0] != name]last_body, previous_done = started, offset+ reported_done = offsetrecent = deque([(started, offset)])try:- process.stdin.write(curl_config(url, headers_for(name) if headers_for else ()))+ process.stdin.write(curl_config(url,+ tuple(headers_for(name) if headers_for else ()) + extra_headers+ if urlsplit(url).netloc == urlsplit(original_url).netloc else ()))process.stdin.close()while process.poll() is None:if network.get('resource_check'):@@ -966,15 +1038,21 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonand (done - recent[0][1]) / (now - recent[0][0]) < low_speed_limit):slow = Truebreak- if (cycle == 0 and size and alternatives_ahead and compare['checks'] < SWITCH_MAX_CHECKS+ # Speed samples follow redirects themselves; guarded updates+ # must keep every request inside the caller's URL policy.+ if (not validate_url and cycle == 0 and size and alternatives_ahead and compare['checks'] < SWITCH_MAX_CHECKSand not network.get('manual_source_switch')):faster = _faster_source(compare, now, started, offset, done, size, alternatives_ahead,timeout, env, network, category, headers_for)if faster is not None:breakif progress:- sample = next((row for row in recent if row[0] >= now - 5), recent[0])- progress(done, size or 0, max(0, done - sample[1]) / max(.001, now - sample[0]))+ if updating:+ update_progress(done, max(0, done-reported_done))+ reported_done = done+ else:+ sample = next((row for row in recent if row[0] >= now - 5), recent[0])+ progress(done, size or 0, max(0, done - sample[1]) / max(.001, now - sample[0]))try:process.wait(timeout=.25)except subprocess.TimeoutExpired:@@ -990,11 +1068,22 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonexcept subprocess.TimeoutExpired:process.kill()process.wait()- status = process.stdout.read(16).decode(errors='replace')+ if not process.stdin.closed:+ process.stdin.close()+ status = process.stdout.read(65536 if validate_url else 16).decode(errors='replace')process.stdout.close()# --silent --show-error keeps this to a line or two.curl_message = _package_failure(SimpleNamespace(stderr=process.stderr.read(2048)))[1] if process.returncode else ''process.stderr.close()+ if validate_url:+ status, destination = _redirect_fields(status)+ if process.returncode == 47 and status in ('301', '302', '303', '307', '308'):+ redirects += 1+ if not destination or redirects > 5:+ failed_sources.add(name)+ break+ url = urljoin(url, destination)+ continuecurrent_size = partial.stat().st_size if partial.exists() else 0if slow_seconds is not None:measured_rates[name, route] = (max(0, current_size - offset) /@@ -1003,21 +1092,26 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonmeasured_rates[name, route] = compare['current']measured_rates.update(compare['rates'])# The faster source is tried next, with the retained prefix.- position = candidates.index(faster)+ position = next(i for i, row in enumerate(candidates) if row[:3] == faster)candidates.insert(candidate_index + 1, candidates.pop(position))if model and current_size > offset:remember_source()- if oversized is not None:- retain_partial(partial, 'oversized-response')+ if oversized is not None or (updating and process.returncode == 63):+ if partial.exists():+ reject(partial, 'oversized-response')+ if updating:+ integrity_failed = True+ failed_sources.add(name)source_health(network, category, name, False)event(network, category=category, source=name, file=path.name, action='fallback',method='curl', reason='response-size-exceeded', observed_bytes=oversized,expected_bytes=size, resume_bytes=offset)break+ if updating and (size is None or current_size <= size):+ update_progress(current_size, max(0, current_size-reported_done))if process.returncode == 0:if matches(partial, name):- from .file_ops import publish- publish(partial, path)+ publish(partial)if network.get('download_settings_path'):from .download_settings import record_speedrecord_speed(Path(network['download_settings_path']).parent,@@ -1026,7 +1120,15 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonroute_health(network, category, name, route)event(network, category=category, source=name, route=route, file=path.name, action='verified', method='curl', bytes=path.stat().st_size)return- retain_partial(partial, 'hash-rejected')+ reject(partial, 'hash-rejected')+ if updating:+ integrity_failed = True+ # A corrupt retained prefix must not poison the good+ # source. Give this source one clean fetch, then move on.+ if offset and restart == 0:+ restart += 1+ continue+ failed_sources.add(name)source_health(network, category, name, False)event(network, category=category, source=name, file=path.name, action='fallback', reason='integrity-mismatch')break@@ -1036,7 +1138,8 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonaction='resume-refused', resume_bytes=offset, reason='source-does-not-support-range')break# A mirror lacking Range must start over, with previous bytes kept.- retain_partial(partial, 'resume-unavailable')+ reject(partial, 'resume-unavailable')+ restart += 1continue# A connection that was moving bytes and then ended with an# unclassified exit is an interruption, not a refusal.@@ -1046,7 +1149,10 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonif model and transient and restart < 2 and candidate_index + 1 == len(candidates) and process.returncode not in (5, 7):retry_wait(network, restart, category=category, source=name, file=path.name,resume_bytes=current_size, reason='no-progress' if stalled else 'connection-interrupted')+ restart += 1continue+ if updating and stalled:+ failed_sources.add(name)reason = 'no-progress' if stalled else 'slow-transfer' if slow else 'faster-source' if faster else 'curl-' + str(process.returncode)alternatives = route_order(network, category, name, env)if alternatives.index(route) + 1 < len(alternatives):@@ -1063,7 +1169,9 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Nonevent(network, category=category, source=name, file=path.name, action='restart-approved',retained_bytes=partial.stat().st_size, reason='resume-unavailable')retain_partial(partial, 'restart-approved')- raise DownloadError('Every download source failed for %s. Check your network or choose another connection mode in Downloads. Partial files retained' % path.name)+ error = DownloadError('Every download source failed for %s. Check your network or choose another connection mode in Downloads. Partial files retained' % path.name)+ error.integrity = integrity_failed+ raise error# clone() passes the remote through GIT_CONFIG_PARAMETERS and writes the sparsediff --git a/freevideo_engine/source_update.py b/freevideo_engine/source_update.pynew file mode 100644index 0000000..7c53244--- /dev/null+++ b/freevideo_engine/source_update.py@@ -0,0 +1,239 @@+"""Explicit, authenticated small updates; unavailable deltas fall back to EXEs."""+import logging+import os+from pathlib import Path+import re+import shutil+import sys++import freevideo_ed25519 as ed25519+import freevideo_source_bootstrap as source+import freevideo_update_keys as keys+from . import disk_space, execution_paths, network+from . import launcher_update as update++log = logging.getLogger(__name__)+DOMAIN = b'FreeVideo source manifest v1\x00'+++def signed(value):+ try:+ signature = bytes.fromhex(value.get('signature', ''))+ payload = DOMAIN + source.canonical({k: v for k, v in value.items() if k != 'signature'})+ return (keys.ED25519_RELEASE_KEY_ENABLED and+ keys.ED25519_PUBLIC_KEY != keys.PLACEHOLDER_PUBLIC_KEY and+ ed25519.verify(keys.ED25519_PUBLIC_KEY, payload, signature))+ except (TypeError, ValueError):+ return False+++def metadata_name(candidate):+ version = candidate.get('product_version')+ if not source.VERSION.fullmatch(str(version)):+ raise ValueError('Source updates require a product version')+ return 'source-%s-%s.json' % (version, update.build_target(candidate))+++def read_metadata(url, token, *, github=False, limit=source.MAX_MANIFEST):+ with update.open_download(url, token, binary=True, github_only=github) as response:+ return b''.join(update._bytes(response, limit))+++def same_build(first, second):+ first, second = update.build_identity(first), update.build_identity(second)+ # publish_release may trim older notes to stay under the 64 KiB legacy cap.+ return all(first.get(key, default) == second.get(key, default) for key, default in (+ ('schema', None), ('repository', None), ('channel', None), ('target', 'windows-x86_64'),+ ('packaging', None), ('track', 'stable'), ('revision', None), ('built_at', None),+ ('version', None), ('product_version', None)))+++def fetch_manifest(candidate, token=''):+ """Never infer source trust from cached/remote _update_sources flags."""+ name = metadata_name(candidate)+ github = update.asset_url('v' + candidate['product_version'], name)+ try:+ digest = read_metadata(github + '.sha256', token, github=True, limit=65).decode('ascii').strip()+ if not source.HEX.fullmatch(digest):+ raise ValueError('Invalid GitHub source digest')+ data = read_metadata(github, token, github=True)+ if source.sha(data) != digest:+ raise ValueError('GitHub source digest mismatch')+ value = source.manifest(source.decode(data))+ except (OSError, ValueError, TypeError):+ # Mirrors may host a signed manifest, but a public RFC test key cannot+ # authorize anything. Fail quickly before fetching when still disabled.+ if not keys.ED25519_RELEASE_KEY_ENABLED or keys.ED25519_PUBLIC_KEY == keys.PLACEHOLDER_PUBLIC_KEY:+ raise ValueError('No authenticated source manifest') from None+ data = read_metadata(update.mirror_url('releases/v' + candidate['product_version'] + '/' + name), '')+ value = source.manifest(source.decode(data))+ if not signed(value):+ raise ValueError('Invalid source signature')+ if not same_build(value['build'], candidate):+ raise ValueError('Source manifest belongs to another release')+ return value+++def pending_path(home, candidate):+ return source.io_path(home) / 'updates' / ('source-' + candidate['revision'] + '.json')+++def try_download(candidate, home, token='', *, progress=None, cancel=None, language=None):+ context = source.bundle_context()+ if context is None or update.build_track(candidate) != 'stable':+ return None+ base, bundle = context+ active = source.ACTIVE+ previous = active['manifest'] if active else base+ current_source = active['source'] if active else bundle+ try:+ def cancelled():+ if cancel is not None and cancel.is_set():+ raise InterruptedError('Source update cancelled')+ cancelled()+ source.storage(source.io_path(home))+ value = fetch_manifest(candidate, token)+ delta = value.get('delta')+ if (not update.newer(value['build'], previous['build']) or not source.compatible(value, base) or+ not delta or delta['from'] != previous['identity'] or+ (not value['gui'] and value.get('launcher_files_changed', True))):+ return None+ target = source.io_path(home) / 'updates' / delta['sha256'] / delta['name']+ # Sparse overlay + complete composed tree + unzip buffer + download.+ needed = delta['bytes'] + 3*sum(row['bytes'] for row in value['files'].values()) + 16*2**20+ if disk_space.free_bytes(target.parent) < needed:+ raise update.UpdateUnavailable('disk')+ sources = {'github': update.asset_url('v' + candidate['product_version'], delta['name']),+ 'mirror': update.mirror_url('releases/v' + candidate['product_version'] + '/' + delta['name'])}+ candidates = [(name, sources[name]) for name in update.source_order(language)]+ def report(done, total, speed):+ cancelled()+ if progress:+ progress(dict(done=done, total=total, bytes_per_second=speed,+ remaining_seconds=(total-done)/speed if speed > 0 else 0))+ network.download(candidates, target, delta['sha256'], report,+ network=dict(quiet=True, resource_check=cancelled), size=delta['bytes'],+ category='launcher-update', cycles=1, stall_seconds=update.UPDATE_STALL_SECONDS,+ low_speed_limit=0, validate_url=update._trusted_url)+ cancelled()+ folder = source.prepare(value, previous, bundle, current_source, target, home, base)+ cancelled()+ source.atomic_json(pending_path(home, candidate), {'overlay': folder.name, 'identity': value['identity']})+ return folder+ except InterruptedError:+ raise+ except Exception as error:+ # No paths, metadata, response bodies or credentials enter diagnostics.+ log.info('Source update unavailable; using full package (%s)', type(error).__name__)+ try:+ pending_path(home, candidate).unlink(missing_ok=True)+ except OSError:+ pass+ return None+++def prepared(candidate, home):+ context = source.bundle_context()+ if context is None:+ return None+ base, bundle = context+ path = pending_path(home, candidate)+ if not path.exists():+ return None+ try:+ receipt = source.read_json(path)+ name = receipt['overlay']+ if not re.fullmatch(r'\d+\.\d+\.\d+-[0-9a-f]{16}', name):+ raise ValueError('Invalid overlay name')+ folder = source.io_path(home) / 'overlay' / name+ value = source.validate_overlay(folder, base)+ if (receipt['identity'] != value['identity'] or+ not same_build(value['build'], candidate)):+ raise ValueError('Prepared source identity changed')+ source.compose(bundle, folder, value, source.io_path(home) / 'source-overlay')+ return folder+ except (OSError, ValueError, KeyError, TypeError):+ path.unlink(missing_ok=True)+ raise update.DownloadedLauncherUnavailable('Prepared source changed; download again') from None+++def cleanup(home, keep):+ """Only remove validated, updater-owned obsolete directories; never user trees."""+ home = source.io_path(home)+ for folder in (home / 'overlay').iterdir():+ if folder.name in keep or not re.fullmatch(r'\d+\.\d+\.\d+-[0-9a-f]{16}', folder.name):+ continue+ # Another launcher may still be running from this version.+ if source.in_use(home, folder.name):+ continue+ try:+ if folder.is_symlink() or {p.name for p in folder.iterdir()} != {'receipt.json', 'files'}:+ continue+ receipt = source.read_json(folder / 'receipt.json')+ value = source.manifest(receipt['manifest'])+ if source.overlay_name(value) != folder.name or receipt['sha256'] != source.sha(source.canonical(value)):+ continue+ composed = home / 'source-overlay' / folder.name+ if composed.exists():+ source.verify_tree(composed, value['files'])+ shutil.rmtree(composed)+ # An edited overlay is retained for inspection, never executed.+ files = folder / 'files'+ for path in files.rglob('*'):+ if path.is_symlink():+ raise ValueError('Changed overlay')+ if path.is_file():+ name = path.relative_to(files).as_posix()+ source.verify_file(path, value['files'][name])+ shutil.rmtree(folder)+ except (OSError, ValueError, KeyError, TypeError):+ continue+++def launch(candidate, home, folder, *, token='', popen=None):+ home = source.io_path(home)+ active_path = home / 'overlay' / 'active.json'+ try:+ old = source.read_json(active_path)+ except (OSError, ValueError):+ old = {'entries': []}+ # Last actually running overlay is the rollback target, even after recovery.+ previous = source.ACTIVE['folder'].name if source.ACTIVE else None+ entries = [folder.name] + ([previous] if previous and previous != folder.name else [])+ from .linux_bundle import child_environment, appimage+ env = dict(child_environment(), FREEVIDEO_LAUNCHER_HOME=str(home), PYINSTALLER_RESET_ENVIRONMENT='1')+ if token:+ env['GITHUB_TOKEN'] = token+ executable = str(appimage() or sys.executable)+ kwargs = dict(cwd=Path(executable).parent, env=env, close_fds=True)+ if os.name == 'nt':+ kwargs['creationflags'] = subprocess_flags()+ else:+ kwargs['start_new_session'] = True+ executable_receipt = home / 'updates' / 'active.json'+ try:+ old_executable = source.read_json(executable_receipt)+ except (OSError, ValueError):+ old_executable = None+ source.atomic_json(active_path, {'entries': entries})+ try:+ # Let the established handoff/resume path finish installing the engine.+ update.save(home / 'updates' / 'active.json', dict(approved=True, candidate=update.manifest(candidate)))+ process = (popen or execution_paths.popen)([executable], **kwargs)+ except BaseException:+ source.atomic_json(active_path, old)+ if old_executable is None:+ executable_receipt.unlink(missing_ok=True)+ else:+ source.atomic_json(executable_receipt, old_executable)+ raise+ try:+ cleanup(home, set(entries))+ except OSError:+ pass+ return process+++def subprocess_flags():+ import subprocess+ return subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUPdiff --git a/freevideo_source_bootstrap.py b/freevideo_source_bootstrap.pynew file mode 100644index 0000000..a50c8c8--- /dev/null+++ b/freevideo_source_bootstrap.py@@ -0,0 +1,479 @@+"""Trusted source-overlay bootstrap; intentionally outside freevideo_engine.++Entry points call activate() BEFORE importing that package. This module and its+trust anchors remain frozen, and are part of the runtime compatibility key.+No network, widgets or third-party imports are needed to recover a broken update.+"""+import hashlib+import importlib.machinery+import json+import os+from pathlib import Path+import re+import shutil+import stat+import sys+import uuid+import zipfile++# Freeze the trust anchors before any source directory enters sys.path.+import freevideo_ed25519+import freevideo_update_keys++MAX_MANIFEST = 2 * 2**20+MAX_FILES = 4096+MAX_FILE = 32 * 2**20+MAX_SOURCE = 128 * 2**20+MAX_ZIP = 64 * 2**20+HEX = re.compile(r'[0-9a-f]{64}')+VERSION = re.compile(r'\d+\.\d+\.\d+')+TOP_FILES = {'pyproject.toml', 'README.md', 'LICENSE', 'NOTICE', 'THIRD_PARTY_NOTICES.md',+ 'MANIFEST.in', '__init__.py', 'freevideo_source_bootstrap.py', 'freevideo_ed25519.py',+ 'freevideo_update_keys.py', 'freevideo', 'freevideo.ps1', 'freevideo.cmd',+ 'setup.sh', 'setup.ps1', 'setup.cmd', 'test.sh', 'test.ps1', 'test.cmd'}+EXTENSIONS = {'.py', '.json', '.txt', '.ps1', '.sh', '.js', '.css', '.svg', '.png', '.ico',+ '.qml', '.woff2', '.otf', '.webp'}+ACTIVE = None+++def canonical(value):+ return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode('ascii')+++def sha(data):+ return hashlib.sha256(data).hexdigest()+++def digest(path):+ result = hashlib.sha256()+ with path.open('rb') as stream:+ for chunk in iter(lambda: stream.read(256*1024), b''):+ result.update(chunk)+ return result.hexdigest()+++def io_path(path):+ path = Path(os.path.abspath(path))+ if os.name == 'nt' and not str(path).startswith('\\\\?\\'):+ return Path('\\\\?\\UNC\\' + str(path)[2:] if str(path).startswith('\\\\') else '\\\\?\\' + str(path))+ return path+++def root():+ if os.environ.get('FREEVIDEO_LAUNCHER_HOME'):+ return io_path(os.environ['FREEVIDEO_LAUNCHER_HOME'])+ if sys.platform == 'darwin':+ return Path.home() / 'Library/Application Support/FreeVideo/launcher'+ return io_path(Path(os.environ.get('LOCALAPPDATA') or Path.home()) / 'FreeVideo-launcher')+++def safe_name(name):+ if not isinstance(name, str) or not 1 <= len(name) <= 240 or '\\' in name or ':' in name:+ raise ValueError('Invalid source path')+ parts = name.split('/')+ for part in parts:+ if (part in ('', '.', '..') or part.endswith((' ', '.')) or+ any(ord(c) < 32 or c in '<>"|?*' for c in part) or+ re.fullmatch(r'(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\..*)?', part, re.I)):+ raise ValueError('Invalid source path')+ if any(part == '__pycache__' for part in parts):+ raise ValueError('Bytecode caches are not source')+ if name not in TOP_FILES and name != 'web/vendor/three/LICENSE' and not (+ parts[0] == 'web' and len(parts) > 2 and parts[-2] == 'tutorial' and Path(name).suffix == '.mp4') and not (len(parts) > 1 and parts[0] in+ ('freevideo_engine', 'web', 'constraints', 'example_workflows', 'scripts') and+ Path(name).suffix in EXTENSIONS):+ raise ValueError('Source path is outside the payload')+ return name+++def _pairs(pairs):+ result = {}+ for key, value in pairs:+ if key in result:+ raise ValueError('Duplicate JSON key')+ result[key] = value+ return result+++def decode(data):+ if len(data) > MAX_MANIFEST:+ raise ValueError('Source manifest too large')+ return json.loads(data, object_pairs_hook=_pairs)+++def read_json(path):+ with path.open('rb') as stream:+ return decode(stream.read(MAX_MANIFEST+1))+++def atomic_json(path, value):+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_name('.' + path.name + '-' + uuid.uuid4().hex)+ try:+ with temporary.open('xb') as stream:+ stream.write(canonical(value))+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, path)+ finally:+ temporary.unlink(missing_ok=True)+++def source_identity(value):+ return sha(canonical({k: value[k] for k in ('base', 'build', 'files', 'gui')}))+++def manifest(value):+ if not isinstance(value, dict) or value.get('schema') != 1 or not HEX.fullmatch(str(value.get('base', ''))):+ raise ValueError('Invalid source manifest')+ build, files = value.get('build'), value.get('files')+ if (not isinstance(build, dict) or not VERSION.fullmatch(str(build.get('product_version', ''))) or+ not isinstance(build.get('version'), str) or not 1 <= len(build['version']) <= 64 or+ not re.fullmatch(r'[0-9a-f]{40,64}', str(build.get('revision', ''))) or+ type(build.get('built_at')) is not int or build['built_at'] <= 0 or+ build.get('repository') != 'FlashML-org/FreeVideo' or build.get('schema') != 1 or+ build.get('channel') not in ('windows-preview', 'macos-preview', 'linux-preview') or+ build.get('track', 'stable') != 'stable' or type(value.get('gui')) is not bool or+ not isinstance(files, dict) or not 1 <= len(files) <= MAX_FILES or+ # A source tree without its root package would let the older one load.+ 'freevideo_engine/__init__.py' not in files):+ raise ValueError('Invalid source build')+ total, seen = 0, set()+ for name, row in files.items():+ safe_name(name)+ if name.casefold() in seen or not isinstance(row, dict):+ raise ValueError('Duplicate source path')+ seen.add(name.casefold())+ if (type(row.get('bytes')) is not int or not 0 <= row['bytes'] <= MAX_FILE or+ not HEX.fullmatch(str(row.get('sha256', '')))):+ raise ValueError('Invalid source file')+ total += row['bytes']+ if total > MAX_SOURCE or value.get('identity') != source_identity(value):+ raise ValueError('Invalid source identity or size')+ # No file may be an ancestor of another, on case-insensitive systems either.+ if any('/'.join(name.casefold().split('/')[:i]) in seen+ for name in files for i in range(1, len(name.split('/')))):+ raise ValueError('Conflicting source paths')+ delta = value.get('delta')+ if delta is not None:+ if (not isinstance(delta, dict) or not HEX.fullmatch(str(delta.get('from', ''))) or+ not isinstance(delta.get('files'), list) or not isinstance(delta.get('deleted'), list) or+ len(delta['files']) + len(delta['deleted']) > 2*MAX_FILES or+ type(delta.get('bytes')) is not int or not 1 <= delta['bytes'] <= MAX_ZIP or+ not HEX.fullmatch(str(delta.get('sha256', ''))) or+ not re.fullmatch(r'delta-[0-9a-f]{16}-to-[0-9a-f]{16}\.zip', str(delta.get('name', '')))):+ raise ValueError('Invalid source delta')+ for field in ('files', 'deleted'):+ names = delta[field]+ if len(set(names)) != len(names):+ raise ValueError('Duplicate delta path')+ for name in names:+ safe_name(name)+ if (name in files) != (field == 'files'):+ raise ValueError('Inconsistent delta path')+ return value+++def read_manifest(path):+ return manifest(read_json(path))+++def regular(root_path, relative):+ current = root_path+ if current.is_symlink():+ raise ValueError('Symlink source directory')+ for part in relative.split('/'):+ current = current / part+ if current.is_symlink() or (hasattr(current, 'is_junction') and current.is_junction()):+ raise ValueError('Symlink source path')+ if not stat.S_ISREG(current.stat().st_mode):+ raise ValueError('Nonregular source file')+ return current+++def verify_file(path, row):+ if path.stat().st_size != row['bytes'] or digest(path) != row['sha256']:+ raise ValueError('Source file changed')+++def verify_tree(folder, files):+ for name, row in files.items():+ verify_file(regular(folder, name), row)+ found = set()+ for path in folder.rglob('*'):+ if path.is_symlink() or (hasattr(path, 'is_junction') and path.is_junction()):+ raise ValueError('Symlink in source tree')+ if path.is_file():+ found.add(path.relative_to(folder).as_posix())+ if found != set(files):+ raise ValueError('Unexpected source files')+++def compatible(value, base):+ a, b = value['build'], base['build']+ return (value['base'] == base['base'] and value['gui'] == base['gui'] and+ all(a.get(k, default) == b.get(k, default) for k, default in+ (('target', 'windows-x86_64'), ('channel', None), ('packaging', None), ('track', 'stable'))))+++def overlay_name(value):+ return value['build']['product_version'] + '-' + value['identity'][:16]+++def validate_overlay(folder, base):+ if {p.name for p in folder.iterdir()} != {'receipt.json', 'files'}:+ raise ValueError('Unexpected overlay files')+ receipt = read_json(regular(folder, 'receipt.json'))+ value = manifest(receipt['manifest'])+ if (receipt.get('sha256') != sha(canonical(value)) or not compatible(value, base) or+ folder.name != overlay_name(value)):+ raise ValueError('Overlay receipt changed')+ changed = {n: r for n, r in value['files'].items() if base['files'].get(n) != r}+ verify_tree(folder / 'files', changed)+ return value+++def compose(bundle, folder, value, destination):+ """Publish a complete verified source tree; sparse packages never enter sys.path."""+ target = destination / overlay_name(value)+ if target.exists():+ verify_tree(target, value['files'])+ return target+ stage = destination / ('.source-' + uuid.uuid4().hex)+ stage.mkdir(parents=True)+ try:+ for name, row in value['files'].items():+ origin = folder / 'files' / name+ origin = regular(folder / 'files', name) if origin.exists() else regular(bundle, name)+ verify_file(origin, row)+ output = stage / name+ output.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(origin, output)+ verify_tree(stage, value['files'])+ try:+ stage.rename(target)+ except OSError:+ # Another launcher published the same version first; it may already+ # be running from it, so verify and reuse it, never replace or delete.+ if not target.exists():+ raise+ verify_tree(target, value['files'])+ return target+ finally:+ shutil.rmtree(stage, ignore_errors=True)+++def storage(home):+ for name in ('overlay', 'source-overlay', 'updates'):+ path = home / name+ if path.is_symlink() or (hasattr(path, 'is_junction') and path.is_junction()):+ raise ValueError('Symlink update directory')+++def prepare(value, previous, bundle, current_source, archive, home, base):+ """Validate a single hop, then save independent cumulative sparse overlay."""+ value, previous = manifest(value), manifest(previous)+ delta = value.get('delta') or {}+ if (not compatible(value, base) or delta.get('from') != previous['identity'] or+ (not value['gui'] and value.get('launcher_files_changed', True))):+ raise ValueError('Incompatible source update')+ expected = {n for n, row in value['files'].items() if previous['files'].get(n) != row}+ deleted = set(previous['files']) - set(value['files'])+ if set(delta['files']) != expected or set(delta['deleted']) != deleted:+ raise ValueError('Delta inventory mismatch')+ verify_file(archive, delta)+ home = io_path(home)+ storage(home)+ parent = home / 'overlay'+ parent.mkdir(parents=True, exist_ok=True)+ target = parent / overlay_name(value)+ if target.exists():+ validate_overlay(target, base)+ compose(bundle, target, value, home / 'source-overlay')+ return target+ stage = parent / ('.stage-' + uuid.uuid4().hex)+ stage.mkdir()+ try:+ changed = {n: r for n, r in value['files'].items() if base['files'].get(n) != r}+ (stage / 'files').mkdir()+ with zipfile.ZipFile(archive) as zipped:+ rows = zipped.infolist()+ if len(rows) != len(expected) or len(rows) > MAX_FILES:+ raise ValueError('Invalid ZIP entry count')+ seen, expanded = set(), 0+ for item in rows:+ name = safe_name(item.filename)+ mode = item.external_attr >> 16+ if (name in seen or name not in expected or item.is_dir() or item.flag_bits & 1 or+ stat.S_IFMT(mode) not in (0, stat.S_IFREG) or item.file_size != value['files'][name]['bytes'] or+ item.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):+ raise ValueError('Invalid ZIP entry')+ seen.add(name)+ expanded += item.file_size+ if expanded > MAX_SOURCE or item.file_size > MAX_FILE:+ raise ValueError('ZIP expansion limit')+ # Read no more than the authenticated size, even with misleading headers.+ with zipped.open(item) as source:+ data = source.read(item.file_size+1)+ if len(data) != item.file_size or sha(data) != value['files'][name]['sha256']:+ raise ValueError('ZIP file checksum mismatch')+ if name.endswith('.py'):+ compile(data, name, 'exec')+ if name in changed:+ output = stage / 'files' / name+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_bytes(data)+ if seen != expected:+ raise ValueError('Missing ZIP files')+ for name, row in changed.items():+ if name not in expected:+ origin = regular(current_source, name)+ verify_file(origin, row)+ output = stage / 'files' / name+ output.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(origin, output)+ # Verify all reused base bytes as well; corrupt bases cannot be activated.+ for name, row in value['files'].items():+ if name not in changed:+ verify_file(regular(bundle, name), row)+ verify_tree(stage / 'files', changed)+ atomic_json(stage / 'receipt.json', {'manifest': value, 'sha256': sha(canonical(value))})+ try:+ stage.rename(target)+ except OSError:+ # A concurrent launcher published the same version; reuse its copy.+ if not target.exists():+ raise+ validate_overlay(target, base)+ compose(bundle, target, value, home / 'source-overlay')+ return target+ finally:+ # Only this attempt's stage is ours. A published (verified) overlay may+ # already be shared with another launcher, so it is never removed here.+ shutil.rmtree(stage, ignore_errors=True)+++LEASES = {}+++def _lock(handle):+ """Non-blocking exclusive lock; raises OSError while another process holds it."""+ if os.name == 'nt':+ import msvcrt+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)+ else:+ import fcntl+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)+++def lease(home, name):+ """Mark a source version as running for the life of this process."""+ key = (str(home), name)+ if key not in LEASES:+ folder = home / 'leases'+ folder.mkdir(parents=True, exist_ok=True)+ handle = open(folder / ('%s.%d.lock' % (name, os.getpid())), 'a+b')+ try:+ _lock(handle)+ except BaseException:+ handle.close()+ raise+ LEASES[key] = handle+ return LEASES[key]+++def release_leases():+ while LEASES:+ LEASES.popitem()[1].close()+++def in_use(home, name):+ """Whether any live launcher holds a lease on this source version."""+ for path in (home / 'leases').glob(name + '.*.lock'):+ try:+ handle = open(path, 'a+b')+ except OSError:+ return True+ try:+ _lock(handle)+ except OSError:+ handle.close()+ return True+ handle.close()+ try:+ path.unlink() # its owner has exited+ except OSError:+ pass+ return False+++def bundle_context():+ if not getattr(sys, 'frozen', False):+ return None+ bundle = io_path(sys._MEIPASS)+ try:+ base = read_manifest(bundle / 'source-base.json')+ return base, bundle / 'engine-source'+ except Exception:+ return None+++def activate(home=None, context=None):+ """Fail closed to the last good source or bundled GUI, before package import."""+ global ACTIVE+ ACTIVE = None+ context = context or bundle_context()+ if context is None:+ return None+ base, bundle = context+ home = io_path(home or root())+ try:+ storage(home)+ entries = read_json(home / 'overlay' / 'active.json')['entries']+ if not isinstance(entries, list) or len(entries) > 2:+ return None+ except Exception:+ return None+ for name in entries:+ try:+ if not isinstance(name, str) or not re.fullmatch(r'\d+\.\d+\.\d+-[0-9a-f]{16}', name):+ continue+ folder = home / 'overlay' / name+ value = validate_overlay(folder, base)+ if value['build']['built_at'] <= base['build']['built_at']:+ continue+ # Held before the tree is used so no cleanup can remove it from under us.+ lease(home, name)+ source = compose(bundle, folder, value, home / 'source-overlay')+ if value['gui']:+ if 'freevideo_engine' in sys.modules:+ return None # Never create a half-old, half-new GUI.+ # Only the regular source package is redirected; third-party+ # modules, stdlib and bootstrap remain in the frozen runtime.+ sys.meta_path.insert(0, SourceFinder(source))+ sys.path.insert(0, str(source))+ sys.dont_write_bytecode = True+ os.environ['PYTHONDONTWRITEBYTECODE'] = '1'+ ACTIVE = {'manifest': value, 'source': source, 'folder': folder}+ return ACTIVE+ except Exception:+ continue+ return None+++class SourceFinder:+ """Explicit package-only precedence also handles older meta-path freezers."""+ def __init__(self, source):+ self.source = source++ def find_spec(self, fullname, path=None, target=None):+ if fullname == 'freevideo_engine':+ return importlib.machinery.PathFinder.find_spec(fullname, [str(self.source)])+ if fullname.startswith('freevideo_engine.'):+ spec = importlib.machinery.PathFinder.find_spec(fullname, path)+ if spec is None:+ # Deleted modules must not resurrect from the older PYZ.+ raise ModuleNotFoundError(fullname)+ return spec+ return Nonediff --git a/freevideo_update_keys.py b/freevideo_update_keys.pynew file mode 100644index 0000000..70dfd7d--- /dev/null+++ b/freevideo_update_keys.py@@ -0,0 +1,7 @@+"""Release trust anchor: the public half of the update-signing key. Never ship a private key."""++# RFC 8032 test key; it never authorizes anything and only marks an unreplaced key.+PLACEHOLDER_PUBLIC_KEY = bytes.fromhex('d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a')+# Public key; SHA-256 7d3681f25aec9e54f249d0e877abdabb50de82af8ff0348d5c80fa124a748912.+ED25519_PUBLIC_KEY = bytes.fromhex('4db79633766fe1fbe01b53a0700021a001051466f03a4de86d2719dd7d44424c')+ED25519_RELEASE_KEY_ENABLED = Truediff --git a/pyproject.toml b/pyproject.tomlindex 530629b..2e898f6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -27,6 +27,9 @@ runtime = [[project.scripts]freevideo = "freevideo_engine.cli:main"+[tool.setuptools]+py-modules = ["freevideo_source_bootstrap", "freevideo_ed25519", "freevideo_update_keys"]+[tool.setuptools.packages.find]include = ["freevideo_engine*"]diff --git a/scripts/build_linux.py b/scripts/build_linux.pyindex 5d4e4ba..9712256 100644--- a/scripts/build_linux.py+++ b/scripts/build_linux.py@@ -224,7 +224,14 @@ def main():'--exclude-module', 'torch', '--exclude-module', 'triton', '--exclude-module', 'numpy','--exclude-module', 'transformers', '--exclude-module', 'tkinter',str(ROOT / 'scripts/linux_app.py')]- subprocess.run(command, cwd=ROOT, check=True)+ from scripts.source_build import run_pyinstaller+ # These files are added after PyInstaller; they belong to the same base key.+ extra_runtime = {'appimage-runtime': str(runtime), 'appimagetool': str(appimagetool)}+ for name in SYSTEM_LIBRARIES:+ path = system_library(name, args.libraries.resolve() if args.libraries else None)+ if path is not None:+ extra_runtime[name] = str(path.resolve())+ run_pyinstaller(command, ROOT, staged, build_file, extra_runtime)dist = out / 'dist' / 'FreeVideo'write_prune_report(out, prune_qt_bundle(dist))bundled = bundle_libraries(dist / '_internal', args.libraries.resolve() if args.libraries else None)diff --git a/scripts/build_macos.py b/scripts/build_macos.pyindex ab95e10..791c770 100644--- a/scripts/build_macos.py+++ b/scripts/build_macos.py@@ -18,6 +18,7 @@ sys.path.insert(0, str(ROOT))from freevideo_engine.desktop_runtime import check_launcher_dependencies, package_data_files, source_filesfrom freevideo_engine.launcher_update import MAC_CHANNEL, build_identityfrom scripts.build_windows import build_info, stamp_source+from scripts.source_build import spec_hookfrom freevideo_engine.release_notes import markdownfrom scripts.build_launcher_notices import collect as collect_notices@@ -162,6 +163,7 @@ a = Analysis([{str(ROOT / 'scripts/macos_app.py')!r}], pathex=[{str(ROOT)!r}],hiddenimports=['psutil', 'PySide6.QtQml', 'PySide6.QtQuick','PySide6.QtQuickControls2', 'PySide6.QtWidgets', 'freevideo_engine.managed'],excludes=['torch', 'triton', 'numpy', 'transformers', 'tkinter'])+{spec_hook(ROOT, staged, build_file)}pyz = PYZ(a.pure)exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='FreeVideo',debug=False, strip=False, upx=False, console=False, target_arch='arm64')diff --git a/scripts/build_source_delta.py b/scripts/build_source_delta.pynew file mode 100644index 0000000..0e8368e--- /dev/null+++ b/scripts/build_source_delta.py@@ -0,0 +1,79 @@+"""Generate a bounded, adjacent-release source delta from a staged source tree.++Use the source-base.json emitted by the SAME platform's PyInstaller build.+No signing seed is needed here; sign_update_manifest.py is a separate step.+"""+import argparse+import json+from pathlib import Path+import sys+import zipfile++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+import freevideo_source_bootstrap as source+++def inventory(tree):+ files = {}+ for path in sorted(tree.rglob('*')):+ if path.is_symlink():+ raise ValueError('Symlinks are not source files')+ if path.is_file():+ name = source.safe_name(path.relative_to(tree).as_posix())+ files[name] = {'bytes': path.stat().st_size, 'sha256': source.digest(path)}+ return files+++def manifest_name(value):+ return 'source-%s-%s.json' % (value['build']['product_version'],+ value['build'].get('target', 'windows-x86_64'))+++def generate(previous, tree, current, output):+ current = source.manifest(dict(current))+ if inventory(tree) != current['files']:+ raise ValueError('Current tree differs from its build inventory')+ output.mkdir(parents=True, exist_ok=True)+ value = {k: v for k, v in current.items() if k not in ('delta', 'signature')}+ if previous is not None:+ previous = source.manifest(previous)+ changed = sorted(n for n, row in value['files'].items() if previous['files'].get(n) != row)+ deleted = sorted(set(previous['files']) - set(value['files']))+ launcher_files = set(current.get('launcher_files', [])) | set(previous.get('launcher_files', []))+ value['launcher_files_changed'] = bool(launcher_files.intersection(changed + deleted))+ name = 'delta-%s-to-%s.zip' % (previous['identity'][:16], value['identity'][:16])+ archive = output / name+ with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zipped:+ for relative in changed:+ info = zipfile.ZipInfo(relative, date_time=(2020, 1, 1, 0, 0, 0))+ info.create_system = 3+ info.external_attr = 0o100644 << 16+ info.compress_type = zipfile.ZIP_DEFLATED+ zipped.writestr(info, (tree / relative).read_bytes())+ value['delta'] = {'from': previous['identity'], 'files': changed, 'deleted': deleted,+ 'name': name, 'bytes': archive.stat().st_size, 'sha256': source.digest(archive)}+ source.manifest(value)+ target = output / manifest_name(value)+ data = source.canonical(value)+ if len(data) > source.MAX_MANIFEST:+ raise ValueError('Source manifest is too large')+ target.write_bytes(data)+ target.with_suffix('.json.sha256').write_text(source.sha(data) + '\n', encoding='ascii')+ return target+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--previous', type=Path, help='Previous release source manifest; omit for initial baseline')+ parser.add_argument('--tree', type=Path, required=True, help='The build output engine-source directory')+ parser.add_argument('--current', type=Path, required=True, help='The build output source-base.json')+ parser.add_argument('--out', type=Path, required=True)+ args = parser.parse_args()+ target = generate(source.read_manifest(args.previous) if args.previous else None,+ args.tree, source.read_manifest(args.current), args.out)+ print(json.dumps({'manifest': str(target)}))+++if __name__ == '__main__':+ main()diff --git a/scripts/build_windows.py b/scripts/build_windows.pyindex bfb5d6f..27638d0 100644--- a/scripts/build_windows.py+++ b/scripts/build_windows.py@@ -116,8 +116,10 @@ def build_pyinstaller(command, out, *, onefolder):options += ['--runtime-hook', str(ROOT / 'scripts/pyi_rth_bundle_data.py')]subprocess.run([sys.executable, '-m', 'PyInstaller.utils.cliutils.makespec', *options], cwd=ROOT, check=True)spec = out / 'FreeVideo.spec'+ from scripts.source_build import spec_hook+ injection = spec_hook(ROOT, out / 'engine-source', out / 'launcher-build.json')if not onefolder:- injection = f'''+ pruning = f'''import syssys.path.insert(0, {str(ROOT)!r})from scripts.prune_qt_bundle import prune_qt_toc, write_prune_report@@ -126,13 +128,15 @@ a.binaries, removed_binaries = prune_qt_toc(a.binaries)a.datas, removed_data = prune_qt_toc(a.datas)write_prune_report({str(out)!r}, dict(files=removed_binaries['files'] + removed_data['files'],bytes=removed_binaries['bytes'] + removed_data['bytes']))+'''+ injection = pruning + injection + f'''a.datas, deduplicated = deduplicate_toc(a.datas, {str(out)!r})write_data_report({str(out)!r}, deduplicated)'''- text = spec.read_text(encoding='utf-8')- if text.count('pyz = PYZ(') != 1:- raise ValueError('Unexpected PyInstaller spec layout')- spec.write_text(text.replace('pyz = PYZ(', injection + '\npyz = PYZ('), encoding='utf-8')+ text = spec.read_text(encoding='utf-8')+ if text.count('pyz = PYZ(') != 1:+ raise ValueError('Unexpected PyInstaller spec layout')+ spec.write_text(text.replace('pyz = PYZ(', injection + '\npyz = PYZ('), encoding='utf-8')subprocess.run([sys.executable, '-m', 'PyInstaller', '--noconfirm','--distpath', str(out / 'dist'), '--workpath', str(out / 'build'), str(spec)],cwd=ROOT, check=True)diff --git a/scripts/linux_app.py b/scripts/linux_app.pyindex 5bb6997..158413b 100644--- a/scripts/linux_app.py+++ b/scripts/linux_app.py@@ -1,4 +1,7 @@"""PyInstaller entry point for the Linux AppImage; model modules stay out of the launcher."""+import freevideo_source_bootstrap+freevideo_source_bootstrap.activate()+from freevideo_engine.modern_launcher import mainif __name__ == '__main__':diff --git a/scripts/macos_app.py b/scripts/macos_app.pyindex 7fafd74..8d2ad33 100644--- a/scripts/macos_app.py+++ b/scripts/macos_app.py@@ -1,4 +1,7 @@"""Native Apple Silicon application; the interface is shared with Windows."""+import freevideo_source_bootstrap+freevideo_source_bootstrap.activate()+from freevideo_engine.modern_launcher import mainif __name__ == '__main__':diff --git a/scripts/sign_update_manifest.py b/scripts/sign_update_manifest.pynew file mode 100644index 0000000..bc2954f--- /dev/null+++ b/scripts/sign_update_manifest.py@@ -0,0 +1,58 @@+"""Sign a source manifest using a private 32-byte Ed25519 seed file (raw or hex).++The private file stays outside the repository. Output replaces only the public+manifest and its SHA-256 sidecar. No secret or private pathname is printed.+"""+import argparse+from pathlib import Path+import sys++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import freevideo_ed25519 as ed25519+import freevideo_source_bootstrap as source++DOMAIN = b'FreeVideo source manifest v1\x00'+++def signing_bytes(value):+ return DOMAIN + source.canonical({k: v for k, v in value.items() if k != 'signature'})+++def sign_manifest(path, private_key):+ value = source.read_manifest(path)+ raw = private_key.read_bytes()+ seed = raw if len(raw) == 32 else bytes.fromhex(raw.decode('ascii').strip())+ value['signature'] = ed25519.sign(seed, signing_bytes(value)).hex()+ data = source.canonical(value)+ path.write_bytes(data)+ path.with_suffix('.json.sha256').write_text(source.sha(data) + '\n', encoding='ascii')+++UPDATE_DOMAIN = b'FreeVideo update manifest v1\x00'+++def sign_update_manifest(path, private_key):+ """Write <name>.sig (hex) beside an update-*.json; the manifest stays byte-identical."""+ raw = private_key.read_bytes()+ seed = raw if len(raw) == 32 else bytes.fromhex(raw.decode('ascii').strip())+ signature = ed25519.sign(seed, UPDATE_DOMAIN + path.read_bytes()).hex()+ path.with_name(path.name + '.sig').write_text(signature + '\n', encoding='ascii')+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--manifest', type=Path, required=True)+ parser.add_argument('--private-key', type=Path, required=True)+ parser.add_argument('--update-manifest', action='store_true',+ help='the manifest is an update-<platform>.json: write a detached <name>.sig')+ args = parser.parse_args()+ if args.update_manifest:+ sign_update_manifest(args.manifest, args.private_key)+ print('Wrote the detached signature for the update manifest.')+ return+ sign_manifest(args.manifest, args.private_key)+ print('Signed source manifest and refreshed SHA-256 sidecar.')+++if __name__ == '__main__':+ main()diff --git a/scripts/source_build.py b/scripts/source_build.pynew file mode 100644index 0000000..de86093--- /dev/null+++ b/scripts/source_build.py@@ -0,0 +1,120 @@+"""Bind source deltas to the actual PyInstaller Analysis, before packaging."""+import importlib.metadata+import json+from pathlib import Path+import platform+import shutil+import subprocess+import sys+import zipfile++from scripts.build_source_delta import inventory+import freevideo_source_bootstrap as source+++def runtime_digest(path):+ if path.name != 'base_library.zip':+ return source.digest(path)+ # PyInstaller iterates a module set when writing this archive. Entry order+ # is not deterministic; every byte of every importable pyc still is hashed.+ with zipfile.ZipFile(path) as archive:+ names = archive.namelist()+ if len(names) != len(set(names)):+ raise ValueError('Duplicate standard-library ZIP entries')+ return source.sha(source.canonical({name: source.sha(archive.read(name)) for name in sorted(names)}))+++def finalize(analysis, root, staged, build_file, extra_runtime=None):+ root, staged, build_file = Path(root), Path(staged), Path(build_file)+ build = json.loads(build_file.read_text(encoding='utf-8'))+ # Nightly has mutable tags/identities and intentionally stays on full updates.+ if build.get('track', 'stable') != 'stable':+ return+ runtime, launcher_files = {}, set()+ # Source resources must follow __file__ when the package is loaded from disk.+ for name, filename, kind in list(analysis.datas):+ name = name.replace('\\', '/')+ if name.startswith('freevideo_engine/') and Path(name).suffix in source.EXTENSIONS:+ output = staged / name+ if not output.exists():+ output.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(filename, output)+ launcher_files.add(name)+ files = inventory(staged)+ for group in ('pure', 'binaries', 'datas', 'scripts'):+ for name, filename, kind in getattr(analysis, group):+ normalized = name.replace('\\', '/')+ if normalized.startswith('engine-source/') or normalized in ('launcher-build.json', 'source-base.json'):+ continue+ if group == 'pure' and Path(filename).is_relative_to(root):+ local = Path(filename).relative_to(root).as_posix()+ if local in files and source.digest(Path(filename)) != files[local]['sha256']:+ raise ValueError('Source changed during PyInstaller analysis; rebuild from a clean snapshot')+ if group == 'pure' and (name == 'freevideo_engine' or name.startswith('freevideo_engine.')):+ relative = Path(filename).relative_to(root).as_posix()+ if relative not in files:+ raise ValueError('Frozen application module missing from engine-source')+ launcher_files.add(relative)+ continue+ if group == 'datas' and normalized in files:+ continue+ path = Path(filename)+ if path.is_file():+ runtime[group + ':' + normalized] = runtime_digest(path)+ else:+ # Symlink TOCs contain their link target, not a source file.+ runtime[group + ':' + normalized] = str(filename)+ for name, filename in (extra_runtime or {}).items():+ runtime['packaging:' + name] = source.digest(Path(filename))+ # Include the PyInstaller bootloader and build policy, not just package versions.+ import PyInstaller+ for path in sorted((Path(PyInstaller.__file__).parent / 'bootloader').rglob('*')):+ if path.is_file():+ runtime['bootloader:' + path.relative_to(Path(PyInstaller.__file__).parent).as_posix()] = source.digest(path)+ for name in ('scripts/source_build.py', 'scripts/build_windows.py', 'scripts/build_macos.py', 'scripts/build_linux.py'):+ runtime[name] = source.digest(root / name)+ for name in ('scripts/prune_qt_bundle.py', 'scripts/deduplicate_bundle_data.py', 'scripts/pyi_rth_bundle_data.py'):+ if (root / name).is_file():+ runtime[name] = source.digest(root / name)+ descriptor = {'python': sys.version, 'platform': platform.system(), 'machine': platform.machine(),+ 'target': build.get('target', 'windows-x86_64'), 'packaging': build.get('packaging'),+ 'pyinstaller': importlib.metadata.version('pyinstaller'),+ 'optimization': getattr(analysis, 'optimize', 0), 'files': runtime}+ base = source.sha(source.canonical(descriptor))+ value = {'schema': 1, 'base': base, 'build': build, 'files': files, 'gui': True,+ 'launcher_files': sorted(launcher_files), 'launcher_files_changed': False}+ value['identity'] = source.source_identity(value)+ source.manifest(value)+ output = build_file.with_name('source-base.json')+ output.write_bytes(source.canonical(value))+ build_file.with_name('source-runtime.json').write_bytes(source.canonical(descriptor))+ analysis.datas.append(('source-base.json', str(output), 'DATA'))+ present = {name.replace('\\', '/') for name, _, _ in analysis.datas}+ for name in files:+ destination = 'engine-source/' + name+ if destination not in present:+ analysis.datas.append((destination, str(staged / name), 'DATA'))+++def spec_hook(root, staged, build_file, extra_runtime=None):+ return (f'\nimport sys\nsys.path.insert(0, {str(root)!r})\n'+ 'from scripts.source_build import finalize as finalize_source\n'+ f'finalize_source(a, {str(root)!r}, {str(staged)!r}, {str(build_file)!r}, {extra_runtime!r})\n')+++def run_pyinstaller(command, root, staged, build_file, extra_runtime=None):+ """Keep the established CLI options, inserting a hook after Analysis."""+ from PyInstaller.building.makespec import main as make_spec+ # Let PyInstaller's parser consume exactly the existing CLI arguments.+ from PyInstaller.__main__ import generate_parser+ parser = generate_parser()+ options = vars(parser.parse_args(command[3:]))+ filenames = options.pop('filenames')+ spec_path = Path(make_spec(filenames, **options))+ text = spec_path.read_text(encoding='utf-8')+ marker = '\npyz = PYZ('+ if marker not in text:+ raise ValueError('Unknown PyInstaller spec layout')+ spec_path.write_text(text.replace(marker, spec_hook(root, staged, build_file, extra_runtime) + marker, 1), encoding='utf-8')+ subprocess.run([*command[:3], '--noconfirm', '--distpath', options['distpath'],+ '--workpath', options['workpath'], str(spec_path)], cwd=root, check=True)diff --git a/scripts/windows_app.py b/scripts/windows_app.pyindex f86ea7c..5610bad 100644--- a/scripts/windows_app.py+++ b/scripts/windows_app.py@@ -1,4 +1,7 @@"""PyInstaller entry point; model modules stay out of the GUI executable."""+import freevideo_source_bootstrap+freevideo_source_bootstrap.activate()+from freevideo_engine.modern_launcher import mainif __name__ == '__main__':