diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Build-Setup.ps1 b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Build-Setup.ps1 index 2a0482ef..4b7522d0 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Build-Setup.ps1 +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Build-Setup.ps1 @@ -1,17 +1,28 @@ [CmdletBinding()] param( [Parameter(Mandatory)][string]$PackagePath, - [string]$OutputDirectory=(Join-Path $env:USERPROFILE 'Downloads\PlotDirectorCompanion-1.0.0.10'), + [string]$OutputDirectory, + [string]$ExpectedSourceCommit, [Parameter(Mandatory)][string]$CertificateThumbprint ) $ErrorActionPreference='Stop' . (Join-Path $PSScriptRoot '..\DeveloperPackage.ps1') $package=Test-DeveloperPackage $PackagePath -if($package.version -ne '1.0.0.10' -or $package.commit -ne '6cdb49c08a74852d5089be8a40c07309543954d1'){throw 'This recovery installer requires the exact qualified 1.0.0.10 payload.'} +$release=Get-Content -Raw (Join-Path $PSScriptRoot 'Release.json') | ConvertFrom-Json +$repo=(Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path +if(!$ExpectedSourceCommit){$ExpectedSourceCommit=(& git -C $repo rev-parse HEAD).Trim();if($LASTEXITCODE -ne 0){throw 'Cannot read the exact setup source revision.'}} +if($ExpectedSourceCommit -notmatch '^[0-9a-f]{40}$' -or $package.version -ne $release.version -or $package.commit -ne $ExpectedSourceCommit){throw 'Release version or exact package source SHA does not match the requested version12 build.'} +Invoke-Checked git @('-C',$repo,'merge-base','--is-ancestor',$release.atlasBaseline,$package.commit) +if($release.productCode -eq $release.baselineProductCode -or $release.upgradeCode -ne '{641A087B-9779-458C-B290-BCBBAD49319A}'){throw 'Version12 requires a new major-upgrade ProductCode and the established UpgradeCode.'} +foreach($relative in @('PlotDirector.WordAddIn.dll','Agent\PlotDirector.Companion.Agent.exe')){ + if([Diagnostics.FileVersionInfo]::GetVersionInfo((Join-Path $PackagePath $relative)).FileVersion -ne $release.version){throw "Wrong application bytes/version: $relative"} +} $mage='C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\mage.exe' foreach($manifest in @('PlotDirector.WordAddIn.vsto','PlotDirector.WordAddIn.dll.manifest')){Invoke-Checked $mage @('-Verify',(Join-Path $PackagePath $manifest))} $cert=Get-Item "Cert:\CurrentUser\My\$CertificateThumbprint" if(!$cert.HasPrivateKey -or $cert.NotAfter -lt (Get-Date)){throw 'An existing valid signing certificate with private key is required.'} +if(!$OutputDirectory){$OutputDirectory=Join-Path (Get-DownloadsFolder) "PlotDirectorCompanion-$($release.version)-$($package.commit.Substring(0,8))"} +if((Test-Path $OutputDirectory) -and @(Get-ChildItem -LiteralPath $OutputDirectory -Force).Count -gt 0){throw 'Setup output must be a new empty directory. The version10 baseline is never overwritten.'} New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null $output=(Resolve-Path $OutputDirectory).Path $work=Join-Path $output 'build' @@ -39,28 +50,31 @@ function Import-Table([string]$name,[string[]]$columns,[string[]]$types,[string[ [IO.File]::WriteAllLines((Join-Path $work "$name.idt"),$lines,[Text.Encoding]::ASCII) $null=Invoke-Com $database 'Import' @($work,"$name.idt") } -$product='{98F46939-764D-407F-BD1F-1D88315D010A}' -$upgrade='{641A087B-9779-458C-B290-BCBBAD49319A}' +$product=$release.productCode +$upgrade=$release.upgradeCode Import-Table Property @('Property','Value') @('s72','l0') @('Property') @( - ,@('ProductCode',$product); ,@('ProductVersion','1.0.10'); ,@('ProductLanguage','1033'); ,@('ProductName','PlotDirector Companion'); + ,@('ProductCode',$product); ,@('ProductVersion',$release.msiVersion); ,@('ProductLanguage','1033'); ,@('ProductName','PlotDirector Companion'); ,@('Manufacturer','Nick Beckley'); ,@('UpgradeCode',$upgrade); ,@('COMPANIONVERSION',$package.version); ,@('SOURCECOMMIT',$package.commit); ,@('ARPPRODUCTICON','PlotDirectorIcon'); ,@('ARPURLINFOABOUT','https://dev.plotdirector.com/'); ,@('ARPNOMODIFY','1'); ,@('ARPNOREPAIR','1'); - ,@('MSIINSTALLPERUSER','1'); ,@('SecureCustomProperties','OLDPRODUCTS') + ,@('MSIINSTALLPERUSER','1'); ,@('SecureCustomProperties','OLDPRODUCTS;NEWERPRODUCTS') ) Import-Table Directory @('Directory','Directory_Parent','DefaultDir') @('s72','S72','l255') @('Directory') @( ,@('TARGETDIR','','SourceDir'); ,@('LocalAppDataFolder','TARGETDIR','.'); ,@('ProgramsDir','LocalAppDataFolder','Programs'); ,@('INSTALLDIR','ProgramsDir','PDCOMP~1|PlotDirector Companion'); ,@('AGENTDIR','INSTALLDIR','Agent'); ,@('ProgramMenuFolder','TARGETDIR','.'); ,@('MENUFOLDER','ProgramMenuFolder','PDCOMP~1|PlotDirector Companion'); ,@('StartupFolder','TARGETDIR','.') ) -$payload=@(Get-ChildItem $PackagePath -File | Where-Object {$_.Extension -notin @('.pdb') -and $_.Name -ne 'package.json'} | Sort-Object Name)+@(Get-ChildItem (Join-Path $PackagePath 'Agent') -File | Where-Object {$_.Extension -ne '.pdb'} | Sort-Object Name) +$payload=@(Get-ChildItem $PackagePath -File | Where-Object {$_.Extension -ne '.pdb'} | Sort-Object Name)+@(Get-ChildItem (Join-Path $PackagePath 'Agent') -File | Where-Object {$_.Extension -ne '.pdb'} | Sort-Object Name) $componentRows=@();$fileRows=@();$featureRows=@();$ddf=@('.OPTION EXPLICIT','.Set CabinetNameTemplate=payload.cab',('.Set DiskDirectoryTemplate="'+$work+'"'),('.Set RptFileName="'+(Join-Path $work 'payload.rpt')+'"'),('.Set InfFileName="'+(Join-Path $work 'payload.inf')+'"'),'.Set CompressionType=MSZIP','.Set Cabinet=on','.Set Compress=on','.Set MaxDiskSize=0') $sequence=0;$agentFile=$null foreach($file in $payload){ - $sequence++;$id='F'+$sequence.ToString('000');$component='C'+$sequence.ToString('000');$folder=if($file.Directory.Name -eq 'Agent'){'AGENTDIR'}else{'INSTALLDIR'} + $sequence++;$folder=if($file.Directory.Name -eq 'Agent'){'AGENTDIR'}else{'INSTALLDIR'} $identity=[Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes('PlotDirector.Companion/'+$folder+'/'+$file.Name)) + $suffix=[Convert]::ToHexString($identity)[0..23] -join '';$id='F'+$suffix;$component='C'+$suffix $componentGuid=[guid]::new([byte[]]$identity[0..15]) $componentRows+=,@($component,('{'+$componentGuid.ToString().ToUpperInvariant()+'}'),$folder,'256','',$id) - $fileRows+=,@($id,$component,('PD'+$sequence.ToString('000')+'.DAT|'+$file.Name),[string]$file.Length,'','','16384',[string]$sequence) + $fileVersion=[Diagnostics.FileVersionInfo]::GetVersionInfo($file.FullName).FileVersion + if($fileVersion -notmatch '^\d+\.\d+\.\d+\.\d+$'){$fileVersion=''} + $fileRows+=,@($id,$component,('PD'+$sequence.ToString('000')+'.DAT|'+$file.Name),[string]$file.Length,$fileVersion,'','16384',[string]$sequence) $featureRows+=,@('Complete',$component);$ddf+=('"'+$file.FullName+'" '+$id) if($file.Name -eq 'PlotDirector.Companion.Agent.exe'){$agentFile=$id} } @@ -86,9 +100,12 @@ Import-Table Shortcut $shortcutColumns $shortcutTypes @('Shortcut') @( ,@('StartCompanion','StartupFolder','PDCOMP~1|PlotDirector Companion','Registration',('[#'+$agentFile+']'),'','PlotDirector tray Companion','','PlotDirectorIcon','0','1','AGENTDIR') ) Import-Table RemoveFile @('FileKey','Component_','FileName','DirProperty','InstallMode') @('s72','s72','L255','s72','i2') @('FileKey') @(,@('RemoveMenu','Registration','','MENUFOLDER','2')) -Import-Table Upgrade @('UpgradeCode','VersionMin','VersionMax','Language','Attributes','Remove','ActionProperty') @('s38','S20','S20','S255','i4','S255','s72') @('UpgradeCode','VersionMin','VersionMax','Language','Attributes') @(,@($upgrade,'','1.0.10','','1','ALL','OLDPRODUCTS')) +Import-Table Upgrade @('UpgradeCode','VersionMin','VersionMax','Language','Attributes','Remove','ActionProperty') @('s38','S20','S20','S255','i4','S255','s72') @('UpgradeCode','VersionMin','VersionMax','Language','Attributes') @( + ,@($upgrade,'',$release.msiVersion,'','1','ALL','OLDPRODUCTS'); + ,@($upgrade,$release.msiVersion,'','','2','','NEWERPRODUCTS') +) $actions=@( - ,@('FindRelatedProducts','','25'); ,@('LaunchConditions','','100'); ,@('ValidateProductID','','700'); ,@('CostInitialize','','800'); ,@('FileCost','','900'); ,@('CostFinalize','','1000'); + ,@('FindRelatedProducts','','25'); ,@('LaunchConditions','','100'); ,@('ValidateProductID','','700'); ,@('CostInitialize','','800'); ,@('FileCost','','900'); ,@('CostFinalize','','1000'); ,@('MigrateFeatureStates','','1200'); ,@('InstallValidate','','1400'); ,@('InstallInitialize','','1500'); ,@('RemoveExistingProducts','OLDPRODUCTS','1510'); ,@('ProcessComponents','','1600'); ,@('UnpublishFeatures','','1800'); ,@('RemoveShortcuts','','3200'); ,@('RemoveRegistryValues','','3300'); ,@('RemoveFiles','','3500'); ,@('RemoveFolders','','3600'); ,@('CreateFolders','','3700'); ,@('InstallFiles','','4000'); ,@('CreateShortcuts','','4500'); ,@('WriteRegistryValues','','5000'); @@ -98,7 +115,10 @@ Import-Table InstallExecuteSequence @('Action','Condition','Sequence') @('s72',' Import-Table InstallUISequence @('Action','Condition','Sequence') @('s72','S255','I2') @('Action') @( ,@('FindRelatedProducts','','25'); ,@('CostInitialize','','800'); ,@('FileCost','','900'); ,@('CostFinalize','','1000'); ,@('ExecuteAction','','1300') ) -Import-Table LaunchCondition @('Condition','Description') @('s255','l255') @('Condition') @(,@('NOT ALLUSERS','PlotDirector Companion must be installed for the current Windows user only.')) +Import-Table LaunchCondition @('Condition','Description') @('s255','l255') @('Condition') @( + ,@('NOT ALLUSERS','PlotDirector Companion must be installed for the current Windows user only.'); + ,@('Installed OR NOT NEWERPRODUCTS','A newer PlotDirector Companion is installed. Downgrade was refused.') +) [IO.File]::WriteAllLines((Join-Path $work 'payload.ddf'),$ddf,[Text.Encoding]::ASCII) Invoke-Checked makecab.exe @('/F',(Join-Path $work 'payload.ddf')) function Insert-Stream([string]$table,[string]$name,[string]$file){ @@ -121,8 +141,20 @@ $view=$null;$record=$null;$summary=$null;$database=$null;$installer=$null $signature=Set-AuthenticodeSignature -FilePath $msi -Certificate $cert -HashAlgorithm SHA256 if(!$signature.SignerCertificate -or $signature.SignerCertificate.Thumbprint -ne $cert.Thumbprint -or $signature.Status -notin @('Valid','UnknownError','NotTrusted')){throw "MSI signing failed: $($signature.StatusMessage)"} $setup=Join-Path $output 'PlotDirectorCompanionSetup.exe' -Invoke-Checked 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe' @('/nologo','/target:winexe','/platform:x64',('/win32icon:'+$iconPath),('/out:'+$setup),('/resource:'+$msi+',Companion.msi'),'/reference:System.Windows.Forms.dll','/reference:System.Management.dll',(Join-Path $PSScriptRoot 'Setup.cs')) +$generated=Join-Path $work 'SetupRelease.g.cs' +@" +using System.Reflection; +[assembly: AssemblyVersion("$($release.version)")] +[assembly: AssemblyFileVersion("$($release.version)")] +internal static class SetupRelease { + internal const string Version = "$($release.version)"; + internal const string MsiVersion = "$($release.msiVersion)"; + internal const string ProductCode = "$product"; + internal const string UpgradeCode = "$upgrade"; +} +"@ | Set-Content $generated -Encoding UTF8 +Invoke-Checked 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe' @('/nologo','/target:winexe','/platform:x64',('/win32icon:'+$iconPath),('/win32manifest:'+(Join-Path $PSScriptRoot 'Setup.manifest')),('/out:'+$setup),('/resource:'+$msi+',Companion.msi'),'/reference:System.Windows.Forms.dll','/reference:System.Management.dll',$generated,(Join-Path $PSScriptRoot 'InstallerInventory.cs'),(Join-Path $PSScriptRoot 'Setup.cs')) $signature=Set-AuthenticodeSignature -FilePath $setup -Certificate $cert -HashAlgorithm SHA256 if(!$signature.SignerCertificate -or $signature.SignerCertificate.Thumbprint -ne $cert.Thumbprint -or $signature.Status -notin @('Valid','UnknownError','NotTrusted')){throw "Setup signing failed: $($signature.StatusMessage)"} -@{version=$package.version;applicationCommit=$package.commit;payloadPackage=(Resolve-Path $PackagePath).Path;setupSha256=(Get-FileHash $setup).Hash;msiSha256=(Get-FileHash $msi).Hash;productCode=$product;upgradeCode=$upgrade;builtUtc=[DateTime]::UtcNow.ToString('o')} | ConvertTo-Json | Set-Content (Join-Path $output 'setup-evidence.json') +@{version=$package.version;msiVersion=$release.msiVersion;applicationCommit=$package.commit;atlasBaseline=$release.atlasBaseline;payloadPackage=(Resolve-Path $PackagePath).Path;setupSha256=(Get-FileHash $setup).Hash;msiSha256=(Get-FileHash $msi).Hash;productCode=$product;upgradeCode=$upgrade;builtUtc=[DateTime]::UtcNow.ToString('o')} | ConvertTo-Json | Set-Content (Join-Path $output 'setup-evidence.json') Write-Output "Complete installer: $setup" diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Inspect-UserInstallation.ps1 b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Inspect-UserInstallation.ps1 new file mode 100644 index 00000000..cafe93ab --- /dev/null +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Inspect-UserInstallation.ps1 @@ -0,0 +1,39 @@ +[CmdletBinding()] +param([Parameter(Mandatory)][string]$OutputPath) +$ErrorActionPreference='Stop' +Add-Type -Path (Join-Path $PSScriptRoot 'InstallerInventory.cs') +$identity=[Security.Principal.WindowsIdentity]::GetCurrent() +$session=[Diagnostics.Process]::GetCurrentProcess().SessionId +$release=Get-Content -Raw (Join-Path $PSScriptRoot 'Release.json') | ConvertFrom-Json +$local=[Environment]::GetFolderPath('LocalApplicationData') +$installRoot=Join-Path $local 'Programs\PlotDirector Companion' +$family=@([CompanionInstallerInventory]::Family($release.upgradeCode)) +$baseline=@([CompanionInstallerInventory]::Product($release.baselineProductCode)) +$current=@([CompanionInstallerInventory]::Product($release.productCode)) +$ancestry=@();$next=$PID +for($depth=0;$depth -lt 8 -and $next;$depth++){ + $process=Get-CimInstance Win32_Process -Filter "ProcessId=$next" + if(!$process){break} + $ancestry+=@{id=$process.ProcessId;parent=$process.ParentProcessId;name=$process.Name;path=$process.ExecutablePath} + $next=$process.ParentProcessId +} +$explorer=@(Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object SessionId -eq $session | ForEach-Object { + $owner=Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid + @{id=$_.ProcessId;session=$_.SessionId;sid=$owner.Sid;matchesCurrentUser=$owner.Sid -eq $identity.User.Value} +}) +$registration=Get-ItemProperty 'HKCU:\Software\Microsoft\Office\Word\Addins\PlotDirector.WordAddIn' -ErrorAction SilentlyContinue | Select-Object Manifest,LoadBehavior,FriendlyName,Description +$files=@(if(Test-Path $installRoot){Get-ChildItem $installRoot -File -Recurse | ForEach-Object { + @{relative=$_.FullName.Substring($installRoot.Length+1);length=$_.Length;sha256=(Get-FileHash $_.FullName).Hash;version=[Diagnostics.FileVersionInfo]::GetVersionInfo($_.FullName).FileVersion} +}}) +$theme=Get-ItemPropertyValue 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name AppsUseLightTheme -ErrorAction SilentlyContinue +$snapshot=@{ + checkedUtc=[DateTime]::UtcNow.ToString('o');identity=$identity.Name;sid=$identity.User.Value;session=$session;profile=$env:USERPROFILE;localAppData=$local + packageIdentity=[CompanionInstallerInventory]::CurrentPackage();signedInUser=(Get-CimInstance Win32_ComputerSystem).UserName;ancestry=$ancestry;explorer=$explorer + baselineProducts=$baseline;candidateProducts=$current;family=$family;registration=$registration;installedFiles=$files;appsUseLightTheme=$theme + word=@(Get-Process WINWORD -ErrorAction SilentlyContinue | Select-Object Id,SessionId,Path) + agent=@(Get-Process PlotDirector.Companion.Agent -ErrorAction SilentlyContinue | Select-Object Id,SessionId,Path) + stateDirectoryExists=Test-Path (Join-Path $local 'PlotDirector\Companion');backupDirectoryExists=Test-Path (Join-Path $local 'PlotDirector\InstallerBackup') + startupShortcutExists=Test-Path (Join-Path ([Environment]::GetFolderPath('Startup')) 'PlotDirector Companion.lnk') + menuShortcutExists=Test-Path (Join-Path ([Environment]::GetFolderPath('Programs')) 'PlotDirector Companion\PlotDirector Companion.lnk') +} +$snapshot | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $OutputPath -Encoding UTF8 diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/InstallerInventory.cs b/PlotDirector.NativeCompanion/WindowsValidation/Setup/InstallerInventory.cs new file mode 100644 index 00000000..859fd51d --- /dev/null +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/InstallerInventory.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; + +// Read-only native MSI inventory. Also used by unattended qualification; never +// enumerate Win32_Product, execute an MSI action, or infer context from HKCU alone. +public sealed class CompanionInstalledProduct +{ + public string ProductCode { get; set; } + public uint Context { get; set; } + public string UserSid { get; set; } + public string Version { get; set; } + public string LocalPackage { get; set; } +} +public static class CompanionInstallerInventory +{ + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern int GetCurrentPackageFullName(ref int length, StringBuilder name); + public static string CurrentPackage() + { + int size = 0; int status = GetCurrentPackageFullName(ref size, null); + if (status == 15700) return null; + if (status != 122) throw new Win32Exception(status); + var value = new StringBuilder(size); status = GetCurrentPackageFullName(ref size, value); + if (status != 0) throw new Win32Exception(status); + return value.ToString(); + } + [DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern uint MsiEnumProductsEx(string product, string sid, uint context, uint index, StringBuilder code, out uint installedContext, StringBuilder user, ref uint size); + [DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern uint MsiGetProductInfoEx(string product, string sid, uint context, string property, StringBuilder value, ref uint size); + [DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern uint MsiEnumRelatedProducts(string upgrade, uint reserved, uint index, StringBuilder code); + public static CompanionInstalledProduct[] Product(string code) + { + var result = new List(); + for (uint index = 0; ; index++) + { + var product = new StringBuilder(39); var sid = new StringBuilder(256); uint size = 256, context; + uint status = MsiEnumProductsEx(code, null, 7, index, product, out context, sid, ref size); + if (status == 259) break; + if (status != 0) throw new Win32Exception((int)status, "Cannot enumerate Companion MSI context."); + string user = context == 4 ? null : sid.ToString(); + result.Add(new CompanionInstalledProduct { ProductCode = product.ToString(), Context = context, UserSid = user, Version = Info(product.ToString(), user, context, "VersionString"), LocalPackage = Info(product.ToString(), user, context, "LocalPackage") }); + } + return result.ToArray(); + } + private static string Info(string code, string sid, uint context, string property) + { + uint size = 0; uint status = MsiGetProductInfoEx(code, sid, context, property, null, ref size); + if (status != 234 && status != 0) throw new Win32Exception((int)status, "Cannot read Companion MSI " + property); + var value = new StringBuilder((int)size + 1); size++; + status = MsiGetProductInfoEx(code, sid, context, property, value, ref size); + if (status != 0) throw new Win32Exception((int)status, "Cannot read Companion MSI " + property); + return value.ToString(); + } + public static CompanionInstalledProduct[] Family(string upgrade) + { + var result = new List(); + for (uint index = 0; ; index++) + { + var code = new StringBuilder(39); uint status = MsiEnumRelatedProducts(upgrade, 0, index, code); + if (status == 259) break; + if (status != 0) throw new Win32Exception((int)status, "Cannot enumerate Companion upgrade family."); + result.AddRange(Product(code.ToString())); + } + return result.ToArray(); + } + public static void RequireCurrentUser(CompanionInstalledProduct[] products, string newestVersion) + { + string sid = WindowsIdentity.GetCurrent().User.Value; + foreach (var product in products) + { + if (product.Context != 2 || product.UserSid != sid) throw new InvalidOperationException("Companion is not installed in this user's unmanaged MSI context. No installation was changed."); + if (new Version(product.Version) > new Version(newestVersion)) throw new InvalidOperationException("A newer Companion is installed. Downgrade was refused before changing it."); + } + } +} diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/README.md b/PlotDirector.NativeCompanion/WindowsValidation/Setup/README.md index def3a0b0..12e40602 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Setup/README.md +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/README.md @@ -1,14 +1,17 @@ -# Complete per-user Windows installer (1.0.0.10 recovery) +# Complete per-user Windows installer — version12 candidate Run **PlotDirectorCompanionSetup.exe** from normal File Explorer after closing Word. It contains the MSI and both application components; no adjacent payload folder is -needed. The application payload remains exactly source commit -`6cdb49c08a74852d5089be8a40c07309543954d1`, version `1.0.0.10`. +needed. `Release.json` deliberately selects application **1.0.0.12**, MSI **1.0.12**, +and Atlas baseline `be88c1d068a4c384c5db348238ac78704b6f73e9`. The exact clean +build SHA must match `package.json` and `-ExpectedSourceCommit` (defaults to HEAD). +This is a packaging candidate, not a claim of installed Windows acceptance. Build with existing Windows tooling, without launching Visual Studio: ```powershell .\Build-Setup.ps1 -PackagePath '' ` + -ExpectedSourceCommit '' ` -OutputDirectory '' -CertificateThumbprint '' ``` @@ -40,6 +43,19 @@ produce a specific error; they are not installed or repaired automatically. Only its `-401` (not installed) result permits removing that exported orphaned PlotDirector VSTA record. Other products and ClickOnce caches are untouched. - Re-running setup uses Windows Installer recaching/repair for this product. +- Version12 has new ProductCode `{0B1E8E22-FCF5-4D9C-99A1-5D0F4BD3210C}` and the + same UpgradeCode `{641A087B-9779-458C-B290-BCBBAD49319A}`. Older family products + below MSI 1.0.12, including qualified 1.0.10, are major-upgrade candidates; + removal is inside the MSI transaction before copying files. A separate detect-only + range and launch condition reject newer versions. Same-version12 is a repair. +- File/component identifiers derive from target-relative paths; existing component + GUIDs remain identical to the qualified version10 MSI. The independent + `Test-SetupPackage.ps1` reads the MSI/CAB, verifies every payload hash, component + GUID, upgrade boundary, shortcut, sequence and per-user flag without running it. +- The bootstrapper queries the native MSI inventory before and after installation, + refusing machine/other-user context or newer versions before any mutation. It + has an explicit asInvoker execution manifest and uses generated version constants + from the same Release.json as the MSI builder. - Windows Settings > Apps > **PlotDirector Companion** uses the MSI uninstall path for the installed files, registration and shortcuts. Existing application state, document metadata, manuscripts and retained backups are not MSI components. @@ -47,6 +63,21 @@ produce a specific error; they are not installed or repaired automatically. requires normal Development browser approval again. Document associations remain inside their documents; the installer neither opens nor saves documents. +For unattended qualification, do not execute Setup, VSTOInstaller, msiexec, the +installed tray or Word. `Inspect-UserInstallation.ps1` uses only read-only supported +queries; its local JSON contains personal identity/profile data and must not be +published. It does not use Win32_Product, launch applications or change the theme. +`Update-WordCompanion.ps1 -NoSync` may build a clean local qualification commit after +the caller safely fetches/fast-forwards; it still requires the tracked remote tip +to be an ancestor and never reconciles divergent history. This permits validation +before publishing a packaging commit. Its single build/test run supplies reusable +evidence for both handover prompts, including native-import and Intent assessment. + +The original version10 installer and `Qualification-2026-11-05.md` are the recovery +baseline. Never overwrite that EXE or relabel its payload as version12. Actual +upgrade, uninstall/rollback and Word/visual acceptance require the separately +authorised manual checklist; static MSI inspection does not qualify those actions. + An MSI result of zero is only a packaging result. Acceptance additionally requires normal Word's minimal ribbon, Open Companion activation, connected IPC, exact installed payload hashes/version, tray visibility and a real Word close/reopen. diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json new file mode 100644 index 00000000..8d5c1c9f --- /dev/null +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Release.json @@ -0,0 +1,9 @@ +{ + "version": "1.0.0.12", + "msiVersion": "1.0.12", + "productCode": "{0B1E8E22-FCF5-4D9C-99A1-5D0F4BD3210C}", + "upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}", + "atlasBaseline": "be88c1d068a4c384c5db348238ac78704b6f73e9", + "baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}", + "baselineSetupSha256": "9526E3781EB2EF9936132786E1E2242633349933A553E93E7A7D0B038160A7FF" +} diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Setup.cs b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Setup.cs index ec5f94bf..5aeba14d 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Setup.cs +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Setup.cs @@ -13,11 +13,9 @@ using Microsoft.Win32; [assembly: AssemblyTitle("PlotDirector Companion Setup")] [assembly: AssemblyCompany("Nick Beckley")] [assembly: AssemblyProduct("PlotDirector Companion")] -[assembly: AssemblyVersion("1.0.0.10")] -[assembly: AssemblyFileVersion("1.0.0.10")] internal static class Setup { - private const string Version = "1.0.0.10"; + private const string Version = SetupRelease.Version; private const string AddinKey = @"Software\Microsoft\Office\Word\Addins\PlotDirector.WordAddIn"; private static string log; [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern int GetCurrentPackageFullName(ref int length, StringBuilder name); @@ -52,6 +50,7 @@ internal static class Setup Write("PlotDirector Companion " + Version + "; normal Windows user=" + Environment.UserName); if (Process.GetProcessesByName("WINWORD").Length != 0) throw new InvalidOperationException("Save your work and close Word normally, then run setup again. Word was not terminated."); CheckPrerequisites(); + CompanionInstallerInventory.RequireCurrentUser(CompanionInstallerInventory.Family(SetupRelease.UpgradeCode), SetupRelease.MsiVersion); if (!args.Contains("--install") && MessageBox.Show("Install PlotDirector Companion " + Version + " for your Windows account?\n\nIncludes the Word add-in, tray application, Start menu shortcut and launch at Windows sign-in. No manuscripts or application data will be removed.", "PlotDirector Companion Setup", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) return 2; StopOwnAgent(); BackupRegistration(state); @@ -64,10 +63,14 @@ internal static class Setup MsiSetInternalUI(3, IntPtr.Zero); MsiEnableLog(0x1fff, Path.Combine(state, "windows-installer.log"), 0); var properties = "ALLUSERS=\"\" MSIINSTALLPERUSER=1 REBOOT=ReallySuppress REINSTALLMODE=vamus"; - if (MsiQueryProductState("{98F46939-764D-407F-BD1F-1D88315D010A}") == 5) properties += " REINSTALL=ALL"; + if (MsiQueryProductState(SetupRelease.ProductCode) == 5) properties += " REINSTALL=ALL"; uint code = MsiInstallProduct(msi, properties); Write("Windows Installer result=" + code); if (code != 0 && code != 3010) throw new InvalidOperationException("Windows Installer failed with code " + code + ". See " + log); + var installed = CompanionInstallerInventory.Product(SetupRelease.ProductCode); + CompanionInstallerInventory.RequireCurrentUser(installed, SetupRelease.MsiVersion); + if (installed.Length != 1 || installed[0].Version != SetupRelease.MsiVersion) throw new InvalidOperationException("Installed MSI identity/version does not match this user's package. Stop and retain the setup log."); + Write("Verified MSI context=2 and current-user SID; product=" + SetupRelease.ProductCode); var home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "PlotDirector Companion"); var manifest = Path.Combine(home, "PlotDirector.WordAddIn.vsto"); var agent = Path.Combine(home, "Agent", "PlotDirector.Companion.Agent.exe"); diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Setup.manifest b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Setup.manifest new file mode 100644 index 00000000..789887e6 --- /dev/null +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Setup.manifest @@ -0,0 +1,7 @@ + + + + + + + diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Setup/Test-SetupPackage.ps1 b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Test-SetupPackage.ps1 new file mode 100644 index 00000000..981cca2b --- /dev/null +++ b/PlotDirector.NativeCompanion/WindowsValidation/Setup/Test-SetupPackage.ps1 @@ -0,0 +1,117 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$PackagePath, + [Parameter(Mandatory)][string]$SetupDirectory, + [Parameter(Mandatory)][string]$BaselineMsi, + [Parameter(Mandatory)][string]$ReportPath +) +$ErrorActionPreference='Stop' +. (Join-Path $PSScriptRoot '..\DeveloperPackage.ps1') +$package=Test-DeveloperPackage $PackagePath +$release=Get-Content -Raw (Join-Path $PSScriptRoot 'Release.json') | ConvertFrom-Json +$evidence=Get-Content -Raw (Join-Path $SetupDirectory 'setup-evidence.json') | ConvertFrom-Json +$passed=[Collections.Generic.List[string]]::new() +function Assert-Package([bool]$condition,[string]$message){if(!$condition){throw "Package qualification failed: $message"};$passed.Add($message)} +function Invoke-Com($object,[string]$name,[object[]]$arguments){$values=@(foreach($v in $arguments){if($null -eq $v){$null}else{$v.PSObject.BaseObject}});$object.GetType().InvokeMember($name,[Reflection.BindingFlags]::InvokeMethod,$null,$object,$values)} +function Get-Com($object,[string]$name,[object[]]$arguments){$values=@(foreach($v in $arguments){$v.PSObject.BaseObject});$object.GetType().InvokeMember($name,[Reflection.BindingFlags]::GetProperty,$null,$object,$values)} +function Read-Table($database,[string]$table){ + if($table -notmatch '^[A-Za-z]+$'){throw 'Unexpected table name'} + $view=Invoke-Com $database 'OpenView' @('SELECT * FROM `'+$table+'`');$null=Invoke-Com $view 'Execute' @() + $columns=Get-Com $view 'ColumnInfo' @(0);$count=$columns.FieldCount;$rows=@() + while($null -ne ($record=Invoke-Com $view 'Fetch' @())){ + $row=[ordered]@{};for($i=1;$i -le $count;$i++){$row[(Get-Com $columns 'StringData' @($i))]=Get-Com $record 'StringData' @($i)} + $rows+=,[pscustomobject]$row + } + $null=Invoke-Com $view 'Close' @();return $rows +} +# These APIs read the CAB and native EXE manifest as data. No MSI action, +# executable entry point, DllMain, Word, tray activation or installer is run. +Add-Type @' +using System;using System.IO;using System.Runtime.InteropServices;using System.Text; +public static class CompanionPackageStreams { + [DllImport("msi.dll",CharSet=CharSet.Unicode)]static extern uint MsiOpenDatabase(string file,IntPtr persist,out IntPtr db); + [DllImport("msi.dll",CharSet=CharSet.Unicode)]static extern uint MsiDatabaseOpenView(IntPtr db,string sql,out IntPtr view); + [DllImport("msi.dll")]static extern uint MsiViewExecute(IntPtr view,IntPtr record); + [DllImport("msi.dll")]static extern uint MsiViewFetch(IntPtr view,out IntPtr record); + [DllImport("msi.dll")]static extern uint MsiRecordReadStream(IntPtr record,uint field,byte[] data,ref uint size); + [DllImport("msi.dll")]static extern uint MsiCloseHandle(IntPtr handle); + [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr LoadLibraryEx(string file,IntPtr reserved,uint flags); + [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)]static extern IntPtr FindResource(IntPtr module,IntPtr name,IntPtr type); + [DllImport("kernel32.dll")]static extern IntPtr LoadResource(IntPtr module,IntPtr resource); + [DllImport("kernel32.dll")]static extern IntPtr LockResource(IntPtr resource); + [DllImport("kernel32.dll")]static extern uint SizeofResource(IntPtr module,IntPtr resource); + [DllImport("kernel32.dll")]static extern bool FreeLibrary(IntPtr module); + static void Check(uint result){if(result!=0)throw new System.ComponentModel.Win32Exception((int)result);} + public static void Cabinet(string file,string destination){IntPtr db=IntPtr.Zero,view=IntPtr.Zero,record=IntPtr.Zero;try{Check(MsiOpenDatabase(file,IntPtr.Zero,out db));Check(MsiDatabaseOpenView(db,"SELECT `Data` FROM `_Streams` WHERE `Name`='payload.cab'",out view));Check(MsiViewExecute(view,IntPtr.Zero));Check(MsiViewFetch(view,out record));using(var output=File.Create(destination)){var buffer=new byte[65536];while(true){uint size=(uint)buffer.Length;Check(MsiRecordReadStream(record,1,buffer,ref size));if(size==0)break;output.Write(buffer,0,(int)size);}}}finally{if(record!=IntPtr.Zero)MsiCloseHandle(record);if(view!=IntPtr.Zero)MsiCloseHandle(view);if(db!=IntPtr.Zero)MsiCloseHandle(db);}} + public static string Manifest(string file){var module=LoadLibraryEx(file,IntPtr.Zero,0x22);if(module==IntPtr.Zero)throw new System.ComponentModel.Win32Exception();try{var resource=FindResource(module,(IntPtr)1,(IntPtr)24);if(resource==IntPtr.Zero)throw new InvalidDataException("Missing setup execution-level manifest.");var data=LockResource(LoadResource(module,resource));var bytes=new byte[SizeofResource(module,resource)];Marshal.Copy(data,bytes,0,bytes.Length);return Encoding.UTF8.GetString(bytes);}finally{FreeLibrary(module);}} +} +'@ +$verify=Join-Path $SetupDirectory 'verification' +if(Test-Path $verify){throw 'Verification output already exists; reuse the existing report instead of repeating qualification.'} +New-Item -ItemType Directory -Path $verify | Out-Null +$msi=Join-Path $SetupDirectory 'PlotDirectorCompanion.msi';$exe=Join-Path $SetupDirectory 'PlotDirectorCompanionSetup.exe' +Assert-Package ($package.version -eq $release.version -and $evidence.applicationCommit -eq $package.commit) 'Exact version12 payload source and setup evidence agree' +Assert-Package ((Get-FileHash $exe).Hash -eq $evidence.setupSha256 -and (Get-FileHash $msi).Hash -eq $evidence.msiSha256) 'Final EXE and MSI hashes agree with build evidence' +$assembly=[Reflection.Assembly]::Load([IO.File]::ReadAllBytes($exe)) +Assert-Package ($assembly.GetName().Version.ToString() -eq $release.version -and [Diagnostics.FileVersionInfo]::GetVersionInfo($exe).FileVersion -eq $release.version) 'Bootstrapper assembly and file versions are 1.0.0.12' +$embedded=Join-Path $verify 'embedded.msi';$source=$assembly.GetManifestResourceStream('Companion.msi');$dest=[IO.File]::Create($embedded);try{$source.CopyTo($dest)}finally{$source.Dispose();$dest.Dispose()} +Assert-Package ((Get-FileHash $embedded).Hash -eq (Get-FileHash $msi).Hash) 'EXE embeds the exact signed MSI with no external payload dependency' +[xml]$manifest=[CompanionPackageStreams]::Manifest($exe) +Assert-Package ($manifest.SelectSingleNode('//*[local-name()="requestedExecutionLevel"]').level -eq 'asInvoker') 'Setup has an explicit asInvoker execution manifest' +$signatures=@(foreach($file in @($exe,$msi)){ + $signature=Get-AuthenticodeSignature $file + Assert-Package ($signature.SignerCertificate.Thumbprint -eq $package.certificateThumbprint) "$(Split-Path $file -Leaf) uses the existing developer signer" + Assert-Package ($signature.Status -eq 'Valid' -or ($signature.Status -in @('UnknownError','NotTrusted') -and $signature.StatusMessage -match 'not trusted|untrusted')) "$(Split-Path $file -Leaf) signature is valid or limited solely by developer trust" + @{file=Split-Path $file -Leaf;status=[string]$signature.Status;message=$signature.StatusMessage;thumbprint=$signature.SignerCertificate.Thumbprint} +}) +$installer=New-Object -ComObject WindowsInstaller.Installer +$database=Invoke-Com $installer 'OpenDatabase' @($msi,0);$baseline=Invoke-Com $installer 'OpenDatabase' @($BaselineMsi,0) +$tables=@{};foreach($table in @('Property','File','Component','Directory','Registry','Shortcut','Upgrade','InstallExecuteSequence','InstallUISequence','Media','RemoveFile','LaunchCondition','Feature','FeatureComponents')){$tables[$table]=@(Read-Table $database $table)} +$properties=@{};foreach($row in $tables.Property){$properties[$row.Property]=$row.Value} +$oldProperties=@{};foreach($row in @(Read-Table $baseline 'Property')){$oldProperties[$row.Property]=$row.Value} +Assert-Package ($properties.ProductVersion -eq '1.0.12' -and $properties.COMPANIONVERSION -eq '1.0.0.12' -and $properties.SOURCECOMMIT -eq $package.commit) 'MSI version and source metadata match the final application' +Assert-Package ($properties.ProductCode -eq $release.productCode -and $properties.ProductCode -ne $oldProperties.ProductCode -and $properties.UpgradeCode -eq $oldProperties.UpgradeCode) 'Major upgrade changes ProductCode and preserves the qualified version10 UpgradeCode' +Assert-Package (!$properties.ContainsKey('ALLUSERS') -and $properties.MSIINSTALLPERUSER -eq '1' -and @($tables.LaunchCondition | Where-Object Condition -eq 'NOT ALLUSERS').Count -eq 1) 'MSI is authored strictly per-user' +$summary=Get-Com $database 'SummaryInformation' @(0) +Assert-Package (([int](Get-Com $summary 'Property' @(15)) -band 10) -eq 10 -and (Get-Com $summary 'Property' @(7)) -eq 'x64;1033') 'MSI summary is compressed x64 and requires no elevated privileges' +Assert-Package (@($tables.Directory | Where-Object {$_.Directory -eq 'INSTALLDIR' -and $_.Directory_Parent -eq 'ProgramsDir' -and $_.DefaultDir -like '*PlotDirector Companion'}).Count -eq 1) 'Install root remains current-user LocalAppData Programs' +$components=@{};foreach($row in $tables.Component){$components[$row.Component]=$row} +$oldComponents=@{};foreach($row in @(Read-Table $baseline 'Component')){$oldComponents[$row.Component]=$row} +$oldPaths=@{};foreach($row in @(Read-Table $baseline 'File')){$component=$oldComponents[$row.Component_];$oldPaths[$component.Directory_+'/'+($row.FileName -split '\|')[-1]]=$component.ComponentId} +$cab=Join-Path $verify 'payload.cab';[CompanionPackageStreams]::Cabinet($msi,$cab) +$expanded=Join-Path $verify 'cab';New-Item -ItemType Directory -Path $expanded | Out-Null +Invoke-Checked expand.exe @('-F:*',$cab,$expanded) +$installed=@();$agentId=$null +foreach($file in $tables.File){ + $component=$components[$file.Component_];$name=($file.FileName -split '\|')[-1] + Assert-Package ($component.Directory_ -in @('INSTALLDIR','AGENTDIR')) "Payload directory is application-only: $name" + $relative=if($component.Directory_ -eq 'AGENTDIR'){'Agent/'+$name}else{$name} + $expected=Join-Path $PackagePath $relative;$actual=Join-Path $expanded $file.File + Assert-Package ((Test-Path $expected) -and (Get-FileHash $actual).Hash -eq (Get-FileHash $expected).Hash) "Embedded CAB hash matches verified payload: $relative" + Assert-Package ((Get-Item $actual).Length -eq [long]$file.FileSize) "MSI file size matches payload: $relative" + $logical=$component.Directory_+'/'+$name + if($oldPaths.ContainsKey($logical)){Assert-Package ($component.ComponentId -eq $oldPaths[$logical]) "Component GUID remains stable from version10: $relative"} + $installed+=@{path=$relative;sha256=(Get-FileHash $actual).Hash;componentId=$component.ComponentId;fileId=$file.File} + if($relative -eq 'Agent/PlotDirector.Companion.Agent.exe'){$agentId=$file.File} +} +$expectedRuntime=@($package.files | Where-Object {$_.path -notlike '*.pdb'}).Count+1 +Assert-Package ($installed.Count -eq $expectedRuntime -and @(Get-ChildItem $expanded -File).Count -eq $installed.Count) 'CAB includes the complete runtime inventory plus package.json, without symbols or extra state' +$registry=$tables.Registry +Assert-Package (@($registry | Where-Object {$_.Root -ne '1' -or $_.Key -notin @('Software\Microsoft\Office\Word\Addins\PlotDirector.WordAddIn','Software\PlotDirector\Companion')}).Count -eq 0) 'All MSI registry writes are limited to exact Companion HKCU keys' +Assert-Package (@($registry | Where-Object {$_.Name -eq 'Manifest' -and $_.Value -eq 'file:///[INSTALLDIR]PlotDirector.WordAddIn.vsto|vstolocal'}).Count -eq 1 -and @($registry | Where-Object {$_.Name -eq 'LoadBehavior' -and $_.Value -eq '#3'}).Count -eq 1) 'Word registration uses signed local manifest and LoadBehavior3' +Assert-Package ($tables.Shortcut.Count -eq 2 -and @($tables.Shortcut | Where-Object {$_.Target -ne ('[#'+$agentId+']') -or $_.Directory_ -notin @('MENUFOLDER','StartupFolder')}).Count -eq 0) 'Start-menu and Startup shortcuts target the installed tray executable' +Assert-Package (@($tables.RemoveFile | Where-Object {$_.DirProperty -ne 'MENUFOLDER' -or $_.FileName -or $_.InstallMode -ne '2'}).Count -eq 0) 'Uninstall cleanup excludes user state, documents, credentials and logs' +$sequence=@{};foreach($row in $tables.InstallExecuteSequence){$sequence[$row.Action]=[int]$row.Sequence} +Assert-Package ($sequence.InstallInitialize -lt $sequence.RemoveExistingProducts -and $sequence.RemoveExistingProducts -lt $sequence.InstallFiles -and $sequence.InstallFiles -lt $sequence.InstallFinalize) 'Older MSI removal is transactional and precedes new files' +Assert-Package (@(@('RemoveFiles','RemoveRegistryValues','RemoveShortcuts','RegisterProduct','PublishProduct') | Where-Object {!$sequence.ContainsKey($_)}).Count -eq 0) 'Standard MSI installation and unified removal actions are present' +$older=@($tables.Upgrade | Where-Object ActionProperty -eq 'OLDPRODUCTS');$newer=@($tables.Upgrade | Where-Object ActionProperty -eq 'NEWERPRODUCTS') +Assert-Package ($older.Count -eq 1 -and $older[0].VersionMax -eq '1.0.12' -and [int]$older[0].Attributes -eq 1 -and $older[0].Remove -eq 'ALL') 'Upgrade range includes version10 and excludes same-version repair' +Assert-Package ($newer.Count -eq 1 -and $newer[0].VersionMin -eq '1.0.12' -and [int]$newer[0].Attributes -eq 2 -and @($tables.LaunchCondition | Where-Object Condition -eq 'Installed OR NOT NEWERPRODUCTS').Count -eq 1) 'Newer versions are detected without removal and blocked from downgrade' +$runtime=Get-Content -Raw (Join-Path $PackagePath 'Agent\PlotDirector.Companion.Agent.runtimeconfig.json') | ConvertFrom-Json +$deps=Get-Content -Raw (Join-Path $PackagePath 'Agent\PlotDirector.Companion.Agent.deps.json') | ConvertFrom-Json +Assert-Package ($runtime.runtimeOptions.tfm -eq 'net10.0' -and @($runtime.runtimeOptions.frameworks | Where-Object name -eq 'Microsoft.WindowsDesktop.App').Count -eq 1 -and $deps.runtimeTarget.name -like '*/win-x64') 'Tray depends on existing .NET10 Windows Desktop x64 runtime' +$sourceCode=Get-Content -Raw (Join-Path $PSScriptRoot 'Setup.cs') +Assert-Package ($sourceCode.Contains('GetCurrentPackageFullName') -and $sourceCode.Contains('Win32_Process') -and $sourceCode.Contains('CompanionInstallerInventory.RequireCurrentUser') -and $sourceCode.Contains('product != "PlotDirector.WordAddIn"') -and $sourceCode.Contains('if (result == -401)')) 'Bootstrapper retains normal-user escape, native context checks and exact-product stale metadata handling' +$result=@{version=$release.version;sourceCommit=$package.commit;passed=$passed;installedInventory=$installed;signatures=$signatures;msiProperties=$properties;upgrade=$tables.Upgrade;executeSequence=$tables.InstallExecuteSequence;manual='Installation, upgrade/uninstall/rollback, trust, Word restart, visual/theme/DPI/accessibility and author workflow acceptance not performed.'} +$result | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $ReportPath -Encoding UTF8 +Write-Output "PASS package qualification: $($passed.Count) assertions; neither installer nor application was executed." diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1 b/PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1 index 65fee876..69279157 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1 +++ b/PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1 @@ -1,5 +1,5 @@ [CmdletBinding()] -param([string]$CertificateThumbprint) +param([string]$CertificateThumbprint,[switch]$NoSync) $ErrorActionPreference='Stop' if($env:OS -ne 'Windows_NT'){throw 'Run this command on Windows. It never installs the add-in.'} . (Join-Path $PSScriptRoot 'DeveloperPackage.ps1') @@ -13,10 +13,16 @@ try { $scriptHash=(Get-FileHash -Algorithm SHA256 -LiteralPath $PSCommandPath).Hash $remote=(& git config --get "branch.$sharedBranch.remote").Trim() if($LASTEXITCODE -ne 0 -or !$remote -or $remote -eq '.'){throw 'The shared branch must have an external tracking remote configured. No remote was guessed.'} - Invoke-Checked git @('fetch',$remote) - $ahead=(& git rev-list --left-right --count "HEAD...$remote/$sharedBranch") -split '\s+' - if($LASTEXITCODE -ne 0 -or [int]$ahead[0] -gt 0){throw 'Local commits are not on the shared remote branch. Push/reconcile them safely before updating.'} - Invoke-Checked git @('merge','--ff-only',"$remote/$sharedBranch") + if($NoSync){ + # Build a clean local qualification commit after the caller has safely fetched. + # Local packaging fixes must be tested before publication, not pushed to pass this gate. + Invoke-Checked git @('merge-base','--is-ancestor',"$remote/$sharedBranch",'HEAD') + }else{ + Invoke-Checked git @('fetch',$remote) + $ahead=(& git rev-list --left-right --count "HEAD...$remote/$sharedBranch") -split '\s+' + if($LASTEXITCODE -ne 0 -or [int]$ahead[0] -gt 0){throw 'Local commits are not on the shared remote branch. Push/reconcile them safely before updating.'} + Invoke-Checked git @('merge','--ff-only',"$remote/$sharedBranch") + } if((Get-FileHash -Algorithm SHA256 -LiteralPath $PSCommandPath).Hash -ne $scriptHash){& $PSCommandPath @PSBoundParameters;return} Invoke-Checked git @('merge-base','--is-ancestor','726a3d5','HEAD') $commit=(& git rev-parse HEAD).Trim();if($LASTEXITCODE -ne 0){throw 'Cannot read commit SHA.'} @@ -45,9 +51,18 @@ try { Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion-http') Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-workflow') Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-tray') + Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-import') + Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--intent-assessment') # Office Clean unregisters the installed add-in. Build signed outputs without that target or F5 registration. Invoke-Checked $msbuild @('PlotDirector.NativeCompanion\Vsto\PlotDirector.WordAddIn.csproj','/restore','/t:Build;VisualStudioForApplicationsBuild','/p:Configuration=Release','/p:PrepareForRunDependsOn=CopyFilesToOutputDirectory','/p:SignManifests=true',"/p:ManifestCertificateThumbprint=$CertificateThumbprint","/p:ApplicationVersion=$version") $bin=Join-Path $repo 'PlotDirector.NativeCompanion\Vsto\bin\Release' + # Office's development-manifest target substitutes AssemblyName as publisher. + # Set the existing release publisher without changing the product identity, + # recompute the application-manifest digest with SHA256, then re-sign normally. + $mage=Join-Path ${env:ProgramFiles(x86)} 'Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\mage.exe' + if(!(Test-Path $mage)){throw 'Existing SDK mage was not found. No SDK was installed.'} + Invoke-Checked $mage @('-Update',(Join-Path $bin 'PlotDirector.WordAddIn.vsto'),'-AppManifest',(Join-Path $bin 'PlotDirector.WordAddIn.dll.manifest'),'-Publisher','Nick Beckley','-Algorithm','sha256RSA') + Invoke-Checked $mage @('-Sign',(Join-Path $bin 'PlotDirector.WordAddIn.vsto'),'-CertHash',$CertificateThumbprint,'-Algorithm','sha256RSA') $staging=$output+'.preparing-'+[guid]::NewGuid().ToString('N') New-Item -ItemType Directory -Path $staging -Force | Out-Null Copy-Item -Path (Join-Path $bin '*') -Destination $staging -Recurse @@ -61,5 +76,5 @@ try { New-Item -ItemType Directory -Path (Split-Path $settings) -Force | Out-Null @{certificateThumbprint=$CertificateThumbprint} | ConvertTo-Json | Set-Content -LiteralPath $settings -Encoding UTF8 Write-Output "Build and tests passed. Version: $version; Git SHA: $commit; Package: $output" - Write-Output "Not installed. Close Word, then run: & '$PSScriptRoot\Install-WordCompanion.ps1' -PackagePath '$output' -StopAgent" + Write-Output "Not installed. Prepare the unified EXE/MSI with Setup\Build-Setup.ps1. Installation and Word acceptance require a separately authorised interactive window." } finally {Pop-Location}