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.
ci: sign the Windows launcher and its scripts with Azure Artifact Signing (#34)
Xiaoze Fan02d2c91b5300
diff --git a/.github/workflows/install.yml b/.github/workflows/install.ymlindex c620f93..b09ea3e 100644--- a/.github/workflows/install.yml+++ b/.github/workflows/install.yml@@ -52,6 +52,9 @@ jobs:timeout-minutes: 60permissions:contents: write+ id-token: write+ # Pull requests and forks build unsigned. Every other run uses the release environment, whose deployment rules and reviewers decide who can mint the OIDC token Azure trusts for signing.+ environment: ${{ github.event_name != 'pull_request' && github.repository == 'FlashML-org/FreeVideo' && 'release' || '' }}concurrency:group: windows-launcher-release-${{ github.ref }}cancel-in-progress: false@@ -82,24 +85,64 @@ jobs:# The old package is evidence, not the replacement candidate. The# new final bytes must pass the mandatory protection gate below.exit 0+ - name: Azure login (OIDC)+ if: github.event_name != 'pull_request' && github.repository == 'FlashML-org/FreeVideo'+ uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0+ with:+ client-id: ${{ vars.AZURE_CLIENT_ID }}+ tenant-id: ${{ vars.AZURE_TENANT_ID }}+ subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}+ # The GitHub OIDC assertion behind the login expires after 5 minutes (azure-cli#29063). A signing token fetched now is cached by az for the whole job.+ - name: Fetch the signing token+ if: github.event_name != 'pull_request' && github.repository == 'FlashML-org/FreeVideo'+ run: |+ az account get-access-token --scope https://codesigning.azure.net/.default --output none+ if ($LASTEXITCODE -ne 0) { throw 'Could not get a codesigning.azure.net token' }+ # The launcher runs these scripts from its unpacked tree, where the executable's signature does not cover them. Sign the checkout's copies before the build bundles them.+ - name: Sign bundled PowerShell scripts+ if: github.event_name != 'pull_request' && github.repository == 'FlashML-org/FreeVideo'+ uses: azure/trusted-signing-action@c7ab2a863ab5f9a846ddb8265964877ef296ee82 # v2.0.0+ with:+ endpoint: https://eus.codesigning.azure.net/+ signing-account-name: flashmlsigning+ certificate-profile-name: freetoken-public+ files: |+ ${{ github.workspace }}/freevideo.ps1+ ${{ github.workspace }}/setup.ps1+ ${{ github.workspace }}/test.ps1+ ${{ github.workspace }}/freevideo_engine/windows_bootstrap.ps1+ file-digest: SHA256+ timestamp-rfc3161: http://timestamp.acs.microsoft.com+ timestamp-digest: SHA256- name: Build Windows launcherrun: |python scripts/build_windows.py --onefolder --out build/windows-folderif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }python scripts/build_windows.py --out build/windows-exeif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }- Copy-Item build/windows-folder/dist/FreeVideo-Windows-folder.zip build/windows-exe/dist/- - name: Sign Windows launchers when a certificate is configured+ - name: Sign Windows launchers+ if: github.event_name != 'pull_request' && github.repository == 'FlashML-org/FreeVideo'+ uses: azure/trusted-signing-action@c7ab2a863ab5f9a846ddb8265964877ef296ee82 # v2.0.0+ with:+ endpoint: https://eus.codesigning.azure.net/+ signing-account-name: flashmlsigning+ certificate-profile-name: freetoken-public+ files: |+ ${{ github.workspace }}/build/windows-exe/dist/FreeVideo.exe+ ${{ github.workspace }}/build/windows-folder/dist/FreeVideo/FreeVideo.exe+ file-digest: SHA256+ timestamp-rfc3161: http://timestamp.acs.microsoft.com+ timestamp-digest: SHA256+ # Check the copies that ship: the folder layout exposes every bundled script on disk, and the one-file launcher is built from the same inputs.+ - name: Verify signatures and rebuild the folder ZIP around the signed launcher+ if: github.event_name != 'pull_request' && github.repository == 'FlashML-org/FreeVideo'shell: pwsh- env:- WINDOWS_CODESIGN_PFX_B64: ${{ secrets.WINDOWS_CODESIGN_PFX_B64 }}- WINDOWS_CODESIGN_PFX_PASSWORD: ${{ secrets.WINDOWS_CODESIGN_PFX_PASSWORD }}- WINDOWS_CODESIGN_TIMESTAMP_URL: ${{ secrets.WINDOWS_CODESIGN_TIMESTAMP_URL }}run: |- ./scripts/sign_windows_release.ps1 `- -OneFile build/windows-exe/dist/FreeVideo.exe `- -FolderZip build/windows-exe/dist/FreeVideo-Windows-folder.zip `- -FolderExecutable build/windows-folder/dist/FreeVideo/FreeVideo.exe+ $scripts = @(Get-ChildItem build/windows-folder/dist -Recurse -Filter *.ps1 | ForEach-Object FullName)+ "bundled scripts: $($scripts.Count)"+ ./scripts/verify_windows_release.ps1 -FolderDist build/windows-folder/dist -Signed ($scripts + 'build/windows-exe/dist/FreeVideo.exe' + 'build/windows-folder/dist/FreeVideo/FreeVideo.exe')+ - name: Collect the folder launcher+ run: Copy-Item build/windows-folder/dist/FreeVideo-Windows-folder.zip build/windows-exe/dist/- name: Hash final Windows launchersshell: pwshrun: |@@ -110,7 +153,8 @@ jobs:timeout-minutes: 20shell: pwshrun: |- python scripts/scan_windows_release.py --file build/windows-exe/dist/FreeVideo.exe --file build/windows-folder/dist/FreeVideo/FreeVideo.exe --file build/windows-exe/dist/FreeVideo-Windows-folder.zip --verify-launches build/windows-exe/dist/FreeVideo.exe build/windows-exe/dist/FreeVideo-Windows-folder.zip --report antivirus/report.json+ $scripts = @(Get-ChildItem build/windows-folder/dist -Recurse -Filter *.ps1 | ForEach-Object { '--script', $_.FullName })+ python scripts/scan_windows_release.py --file build/windows-exe/dist/FreeVideo.exe --file build/windows-folder/dist/FreeVideo/FreeVideo.exe --file build/windows-exe/dist/FreeVideo-Windows-folder.zip @scripts --verify-launches build/windows-exe/dist/FreeVideo.exe build/windows-exe/dist/FreeVideo-Windows-folder.zip --report antivirus/report.json$scanExit = $LASTEXITCODEif (Test-Path antivirus/report.json) { Get-Content antivirus/report.json -Raw }exit $scanExitdiff --git a/scripts/scan_windows_release.py b/scripts/scan_windows_release.pyindex e9815d9..b8007ba 100644--- a/scripts/scan_windows_release.py+++ b/scripts/scan_windows_release.py@@ -5,6 +5,7 @@ archives, and retain detected files for investigation. A missing scanner, failedupdate, timeout or changed artifact is an error, never a clean scan.Explicit launch verification also enables real-time/cloud protection on thedisposable runner and checks Internet-zone downloads with Attachment Services.+Scripts get the AMSI verdict PowerShell would receive before running them."""import argparseimport hashlib@@ -129,6 +130,41 @@ ConvertTo-Json -InputObject $rows -Depth 4 -Compress""")+AMSI_BLOCKED = 16384 # AMSI_RESULT_BLOCKED_BY_ADMIN_START; detections are 32768 and above+++def amsi_verdicts(paths):+ """Scan each script's text the way PowerShell does before running it; returns {path: AMSI_RESULT}."""+ for path in paths:+ if "'" in str(path):+ raise ValueError('Script path must not contain a quote: ' + str(path))+ listing = ', '.join("'%s'" % Path(path).resolve() for path in paths)+ return powershell("""+$ErrorActionPreference = 'Stop'+[Console]::OutputEncoding = [Text.UTF8Encoding]::new()+Add-Type -TypeDefinition @'+using System;+using System.Runtime.InteropServices;+public static class Amsi {+ [DllImport("amsi.dll", CharSet = CharSet.Unicode)] public static extern int AmsiInitialize(string appName, out IntPtr context);+ [DllImport("amsi.dll", CharSet = CharSet.Unicode)] public static extern int AmsiScanString(IntPtr context, string content, string name, IntPtr session, out int result);+ [DllImport("amsi.dll")] public static extern void AmsiUninitialize(IntPtr context);+}+'@+[IntPtr]$context = 0+if ([Amsi]::AmsiInitialize('FreeVideo release validation', [ref]$context) -ne 0) { throw 'AmsiInitialize failed' }+$rows = [ordered]@{}+foreach ($path in @(%s)) {+ $verdict = 0+ $status = [Amsi]::AmsiScanString($context, [IO.File]::ReadAllText($path), $path, [IntPtr]::Zero, [ref]$verdict)+ if ($status -ne 0) { throw "AmsiScanString failed for $path (HRESULT 0x$($status.ToString('x8')))" }+ $rows[$path] = $verdict+}+[Amsi]::AmsiUninitialize($context)+ConvertTo-Json -InputObject $rows -Compress+""" % listing)++def mark_download(path):# Preserve the Internet-zone evidence a browser supplies. Never unblock it.url = 'https://github.com/FlashML-org/FreeVideo/releases/download/windows-preview/'@@ -251,10 +287,10 @@ def verify_launches(onefile, folder_zip, program, report, logs, *, blocked_layourequire_realtime(report['defender_after_launch'])-def scan(files, report_path, *, launches=None):+def scan(files, report_path, *, launches=None, scripts=()):report_path = Path(report_path)report_path.parent.mkdir(parents=True, exist_ok=True)- report = dict(schema=1, status='error', started_at=time.time(), files=[],+ report = dict(schema=1, status='error', started_at=time.time(), files=[], scripts=[],scope='Microsoft Defender custom file/archive scan; not a SmartScreen or malware-free certification')try:if platform.system() != 'Windows':@@ -285,8 +321,10 @@ def scan(files, report_path, *, launches=None):if (not info.get('signatures') or type(info.get('signature_age_days')) is not intor not 0 <= info['signature_age_days'] <= 2 or not info.get('service_enabled')):raise RuntimeError('Defender service or current signatures are unavailable; scan inconclusive')- if launches:+ if launches or scripts:+ # Defender answers AMSI from its real-time engine; with protection off every script reads as clean.require_realtime(info)+ if launches:report['maps_exit_code'] = command([program, '-ValidateMapsConnection'], report_path.parent/'defender-maps.log')if report['maps_exit_code'] != 0:raise RuntimeError('Defender cloud connection unavailable; release validation is inconclusive')@@ -297,10 +335,14 @@ def scan(files, report_path, *, launches=None):row['exit_code'] = command([program, '-Scan', '-ScanType', '3', '-File', path, '-DisableRemediation'], log)unchanged = path.is_file() and path.stat().st_size == row['bytes'] and digest(path) == row['sha256']row['status'] = 'clean' if row['exit_code'] == 0 and unchanged else 'blocked'- blocked = [row for row in report['files'] if row['status'] != 'clean']+ if scripts:+ for path, verdict in amsi_verdicts(scripts).items():+ report['scripts'].append(dict(path=path, amsi_result=verdict,+ status='clean' if verdict < AMSI_BLOCKED else 'blocked'))+ blocked = [row for row in report['files'] + report['scripts'] if row['status'] != 'clean']if launches:blocked_layouts = {'onefile' if Path(row['path']) == Path(launches[0]).resolve() else 'folder'- for row in blocked}+ for row in report['files'] if row['status'] != 'clean'}verify_launches(*map(Path, launches), program, report, report_path.parent, blocked_layouts=blocked_layouts)report['detections'] = threat_history()previous = {row['id'] for row in report['detections_before']}@@ -339,11 +381,14 @@ def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--file', type=Path, action='append', required=True)parser.add_argument('--report', type=Path, required=True)+ parser.add_argument('--script', type=Path, action='append', default=[],+ help='PowerShell script to check with AMSI; may be repeated')parser.add_argument('--verify-launches', nargs=2, type=Path, metavar=('EXE', 'FOLDER_ZIP'),help='Enable real-time/cloud Defender on this test machine and open Internet-zone copies')args = parser.parse_args()- result = scan(args.file, args.report, launches=args.verify_launches)- print('Defender scan completed for %d release files. Report: %s' % (len(result['files']), args.report))+ result = scan(args.file, args.report, launches=args.verify_launches, scripts=args.script)+ print('Defender scan completed for %d release files and %d scripts. Report: %s'+ % (len(result['files']), len(result['scripts']), args.report))if __name__ == '__main__':diff --git a/scripts/sign_windows_release.ps1 b/scripts/sign_windows_release.ps1deleted file mode 100644index c402b01..0000000--- a/scripts/sign_windows_release.ps1+++ /dev/null@@ -1,59 +0,0 @@-param(- [Parameter(Mandatory = $true)][string]$OneFile,- [Parameter(Mandatory = $true)][string]$FolderZip,- [Parameter(Mandatory = $true)][string]$FolderExecutable-)--$ErrorActionPreference = 'Stop'--# Signing is deliberately opt-in. A release must never claim to be signed when-# the maintainer has not configured a certificate in the repository secrets.-$encoded = [Environment]::GetEnvironmentVariable('WINDOWS_CODESIGN_PFX_B64')-if ([string]::IsNullOrWhiteSpace($encoded)) {- Write-Host 'Authenticode signing is not configured; retaining unsigned build.'- exit 0-}-$password = [Environment]::GetEnvironmentVariable('WINDOWS_CODESIGN_PFX_PASSWORD')-if ($null -eq $password) { $password = '' }-$timestamp = [Environment]::GetEnvironmentVariable('WINDOWS_CODESIGN_TIMESTAMP_URL')-if ([string]::IsNullOrWhiteSpace($timestamp)) { $timestamp = 'http://timestamp.digicert.com' }--$kits = Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\bin'-$signtool = Get-ChildItem -Path $kits -Filter signtool.exe -File -Recurse -ErrorAction SilentlyContinue |- Where-Object { $_.FullName -match '\\x64\\signtool\.exe$' } |- Sort-Object FullName -Descending | Select-Object -First 1-if ($null -eq $signtool) {- $signtool = Get-ChildItem -Path $kits -Filter signtool.exe -File -Recurse -ErrorAction SilentlyContinue |- Sort-Object FullName -Descending | Select-Object -First 1-}-if ($null -eq $signtool) { throw 'Authenticode signing is configured, but signtool.exe is unavailable on the runner.' }--$pfx = Join-Path $env:RUNNER_TEMP 'freevideo-signing.pfx'-[IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($encoded))--function Sign-Executable([string]$Path) {- if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "Executable is missing: $Path" }- $signArgs = @('sign', '/fd', 'SHA256', '/td', 'SHA256', '/tr', $timestamp,- '/f', $pfx, '/p', $password, '/d', 'FreeVideo', '/du', 'https://www.flashml.ai/', $Path)- & $signtool.FullName @signArgs- if ($LASTEXITCODE -ne 0) { throw "signtool failed for $Path (exit $LASTEXITCODE)" }- & $signtool.FullName verify /pa /all $Path- if ($LASTEXITCODE -ne 0) { throw "signtool verification failed for $Path (exit $LASTEXITCODE)" }-}--Sign-Executable $OneFile-Sign-Executable $FolderExecutable--# The ZIP itself cannot carry an Authenticode signature. Sign the executable-# inside it, then recreate the archive before hashes, scanning, and publishing.-$unpacked = Join-Path $env:RUNNER_TEMP 'freevideo-signed-folder'-Remove-Item -LiteralPath $unpacked -Recurse -Force -ErrorAction SilentlyContinue-Expand-Archive -LiteralPath $FolderZip -DestinationPath $unpacked -Force-$folderExe = Join-Path $unpacked 'FreeVideo\FreeVideo.exe'-Sign-Executable $folderExe-$folderHash = (Get-FileHash -LiteralPath $folderExe -Algorithm SHA256).Hash.ToLowerInvariant()-Set-Content -LiteralPath (Join-Path $unpacked 'FreeVideo\SHA256SUMS.txt') `- -Value ($folderHash + ' FreeVideo.exe') -Encoding ascii-Remove-Item -LiteralPath $FolderZip -Force-Compress-Archive -Path (Join-Path $unpacked 'FreeVideo') -DestinationPath $FolderZip -CompressionLevel Optimal-Write-Host 'Authenticode signatures applied to the one-file launcher and folder launcher.'diff --git a/scripts/verify_windows_release.ps1 b/scripts/verify_windows_release.ps1new file mode 100644index 0000000..61e765f--- /dev/null+++ b/scripts/verify_windows_release.ps1@@ -0,0 +1,23 @@+param(+ [Parameter(Mandatory = $true)][string[]]$Signed,+ [Parameter(Mandatory = $true)][string]$FolderDist+)++$ErrorActionPreference = 'Stop'++foreach ($path in $Signed) {+ $signature = Get-AuthenticodeSignature -LiteralPath $path+ if ($signature.Status -ne 'Valid') { throw "$path is not validly signed: $($signature.Status) $($signature.StatusMessage)" }+ if ($signature.SignerCertificate.Subject -notmatch 'CN=FlashML LLC') { throw "Unexpected signer for ${path}: $($signature.SignerCertificate.Subject)" }+ if ($null -eq $signature.TimeStamperCertificate) { throw "Signature has no timestamp: $path" }+ Write-Host "signed $path as $($signature.SignerCertificate.Subject), timestamped by $($signature.TimeStamperCertificate.Subject)"+}++# The ZIP cannot carry a signature and was built before its executable was signed. Rebuild it around the signed executable, with the same archiver as build_windows.py.+$folder = Join-Path $FolderDist 'FreeVideo'+$executable = Join-Path $folder 'FreeVideo.exe'+$hash = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash.ToLowerInvariant()+[IO.File]::WriteAllText((Join-Path $folder 'SHA256SUMS.txt'), $hash + " FreeVideo.exe`n")+python -c "import shutil, sys; shutil.make_archive(sys.argv[1], 'zip', root_dir=sys.argv[2], base_dir='FreeVideo')" (Join-Path $FolderDist 'FreeVideo-Windows-folder') $FolderDist+if ($LASTEXITCODE -ne 0) { throw 'Could not rebuild the folder ZIP' }+Write-Host "rebuilt $(Join-Path $FolderDist 'FreeVideo-Windows-folder.zip')"