Force local Companion payload installation across advertised upgrades

This commit is contained in:
nick 2026-11-06 19:54:57 +00:00
parent 7311764739
commit 661fdf6650
7 changed files with 111 additions and 12 deletions

View File

@ -56,7 +56,7 @@ Import-Table Property @('Property','Value') @('s72','l0') @('Property') @(
,@('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;NEWERPRODUCTS')
,@('MSIINSTALLPERUSER','1'); ,@('ADDLOCAL','Complete'); ,@('SecureCustomProperties','OLDPRODUCTS;NEWERPRODUCTS')
)
Import-Table Directory @('Directory','Directory_Parent','DefaultDir') @('s72','S72','l255') @('Directory') @(
,@('TARGETDIR','','SourceDir'); ,@('LocalAppDataFolder','TARGETDIR','.'); ,@('ProgramsDir','LocalAppDataFolder','Programs');
@ -83,7 +83,7 @@ $componentRows+=,@('Registration','{73926FA6-015D-4B48-885D-C17EAA64AC15}','INST
$featureRows+=,@('Complete','Registration')
Import-Table Component @('Component','ComponentId','Directory_','Attributes','Condition','KeyPath') @('s72','S38','s72','i2','S255','S72') @('Component') $componentRows
Import-Table File @('File','Component_','FileName','FileSize','Version','Language','Attributes','Sequence') @('s72','s72','l255','i4','S72','S20','I2','i4') @('File') $fileRows
Import-Table Feature @('Feature','Feature_Parent','Title','Description','Display','Level','Directory_','Attributes') @('s38','S38','L64','L255','I2','i2','S72','i2') @('Feature') @(,@('Complete','','PlotDirector Companion','Word add-in and tray Companion','1','1','INSTALLDIR','0'))
Import-Table Feature @('Feature','Feature_Parent','Title','Description','Display','Level','Directory_','Attributes') @('s38','S38','L64','L255','I2','i2','S72','i2') @('Feature') @(,@('Complete','','PlotDirector Companion','Word add-in and tray Companion','1','1','INSTALLDIR','24'))
Import-Table FeatureComponents @('Feature_','Component_') @('s38','s72') @('Feature_','Component_') $featureRows
Import-Table Media @('DiskId','LastSequence','DiskPrompt','Cabinet','VolumeLabel','Source') @('i2','i4','L64','S255','S32','S72') @('DiskId') @(,@('1',[string]$sequence,'','#payload.cab','',''))
$key='Software\Microsoft\Office\Word\Addins\PlotDirector.WordAddIn'
@ -101,11 +101,11 @@ Import-Table Shortcut $shortcutColumns $shortcutTypes @('Shortcut') @(
)
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,'',$release.msiVersion,'','1','ALL','OLDPRODUCTS');
,@($upgrade,'',$release.msiVersion,'','0','ALL','OLDPRODUCTS');
,@($upgrade,$release.msiVersion,'','','2','','NEWERPRODUCTS')
)
$actions=@(
,@('FindRelatedProducts','','25'); ,@('LaunchConditions','','100'); ,@('ValidateProductID','','700'); ,@('CostInitialize','','800'); ,@('FileCost','','900'); ,@('CostFinalize','','1000'); ,@('MigrateFeatureStates','','1200');
,@('FindRelatedProducts','','25'); ,@('LaunchConditions','','100'); ,@('ValidateProductID','','700'); ,@('CostInitialize','','800'); ,@('FileCost','','900'); ,@('CostFinalize','','1000');
,@('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');
@ -153,8 +153,9 @@ internal static class SetupRelease {
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'))
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 'UpgradePolicy.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;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')
$installerCommit=(& git -C $repo rev-parse HEAD).Trim()
@{version=$package.version;msiVersion=$release.msiVersion;applicationCommit=$package.commit;installerCommit=$installerCommit;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"

View File

@ -30,6 +30,13 @@ public static class CompanionInstallerInventory
[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);
[DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern uint MsiQueryFeatureStateEx(string product, string sid, uint context, string feature, out int state);
public static int FeatureState(CompanionInstalledProduct product, string feature)
{
int state; uint status = MsiQueryFeatureStateEx(product.ProductCode, product.UserSid, product.Context, feature, out state);
if (status != 0) throw new Win32Exception((int)status, "Cannot read Companion MSI feature state.");
return state;
}
public static CompanionInstalledProduct[] Product(string code)
{
var result = new List<CompanionInstalledProduct>();

View File

@ -43,6 +43,14 @@ 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.
- The complete desktop feature is explicitly selected with `ADDLOCAL=Complete`,
marked DisallowAdvertise/UIDisallowAbsent, and never inherits old feature states.
Version10 can have an advertised MSI feature despite physical version10 files.
Migrating that state registered version12 without copying its files; the
`Test-UpgradeRegression.ps1` negative control rejects the original faulty MSI.
Registered-but-advertised version12 is handled by the same-product repair path.
Strict post-install file-version checks remain and now log both detected versions;
native feature state must also be Local (3), not Advertised (1).
- 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;

View File

@ -21,7 +21,6 @@ internal static class Setup
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern int GetCurrentPackageFullName(ref int length, StringBuilder name);
[DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern uint MsiInstallProduct(string package, string properties);
[DllImport("msi.dll")] private static extern uint MsiSetInternalUI(uint level, IntPtr parent);
[DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern int MsiQueryProductState(string product);
[DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern uint MsiEnableLog(uint mode, string path, uint attributes);
[STAThread] private static int Main(string[] args)
{
@ -50,7 +49,8 @@ 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);
var family = CompanionInstallerInventory.Family(SetupRelease.UpgradeCode);
CompanionInstallerInventory.RequireCurrentUser(family, 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);
@ -62,8 +62,10 @@ internal static class Setup
using (var file = File.Create(msi)) source.CopyTo(file);
MsiSetInternalUI(3, IntPtr.Zero);
MsiEnableLog(0x1fff, Path.Combine(state, "windows-installer.log"), 0);
var properties = "ALLUSERS=\"\" MSIINSTALLPERUSER=1 REBOOT=ReallySuppress REINSTALLMODE=vamus";
if (MsiQueryProductState(SetupRelease.ProductCode) == 5) properties += " REINSTALL=ALL";
// An advertised/partially registered same-version product also needs
// repair, even though registration alone does not prove local files.
var properties = CompanionUpgradePolicy.InstallProperties(family.Any(p => p.ProductCode == SetupRelease.ProductCode));
Write("MSI install properties=" + properties);
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);
@ -74,7 +76,14 @@ internal static class Setup
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");
if (FileVersionInfo.GetVersionInfo(Path.Combine(home, "PlotDirector.WordAddIn.dll")).FileVersion != Version || FileVersionInfo.GetVersionInfo(agent).FileVersion != Version) throw new InvalidDataException("Installed component version mismatch.");
var wordVersion = FileVersionInfo.GetVersionInfo(Path.Combine(home, "PlotDirector.WordAddIn.dll")).FileVersion;
var agentVersion = FileVersionInfo.GetVersionInfo(agent).FileVersion;
Write("Word add-in detected=" + wordVersion + "; expected=" + Version);
Write("Tray executable detected=" + agentVersion + "; expected=" + Version);
CompanionUpgradePolicy.VerifyVersions(Version, wordVersion, agentVersion);
int featureState = CompanionInstallerInventory.FeatureState(installed[0], "Complete");
Write("MSI feature Complete state=" + featureState + "; required Local=3");
if (featureState != 3) throw new InvalidDataException("Companion MSI feature is not installed locally. Detected state " + featureState + "; required Local=3. Retain the setup log.");
// The supported VSTO installer performs signature/trust validation. No inclusion
// list, certificate store, policy or Office resiliency setting is changed here.
int trust = Run(VstoInstaller(), "/Install \"" + manifest + "\"", false);

View File

@ -105,7 +105,7 @@ $sequence=@{};foreach($row in $tables.InstallExecuteSequence){$sequence[$row.Act
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 ($older.Count -eq 1 -and $older[0].VersionMax -eq '1.0.12' -and [int]$older[0].Attributes -eq 0 -and $older[0].Remove -eq 'ALL') 'Upgrade range includes version10 without migrating advertised feature state'
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

View File

@ -0,0 +1,54 @@
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$FailedSetupDirectory,
[Parameter(Mandatory)][string]$CorrectedSetupDirectory,
[Parameter(Mandatory)][string]$ReportPath
)
$ErrorActionPreference='Stop'
$checks=[Collections.Generic.List[string]]::new()
function Assert-Upgrade([bool]$condition,[string]$message){if(!$condition){throw "Upgrade regression failed: $message"};$checks.Add($message)}
function Com($object,[string]$member,[object[]]$arguments,[switch]$Property){$values=@(foreach($v in $arguments){$v.PSObject.BaseObject});$flags=if($Property){[Reflection.BindingFlags]::GetProperty}else{[Reflection.BindingFlags]::InvokeMethod};$object.GetType().InvokeMember($member,$flags,$null,$object,$values)}
function Rows($database,[string]$table){
$view=Com $database 'OpenView' @('SELECT * FROM `'+$table+'`');$null=Com $view 'Execute' @()
$columns=Com $view 'ColumnInfo' @(0) -Property;$count=Com $columns 'FieldCount' @() -Property;$rows=@()
while($null -ne ($record=Com $view 'Fetch' @())){$row=[ordered]@{};for($i=1;$i -le $count;$i++){$row[(Com $columns 'StringData' @($i) -Property)]=Com $record 'StringData' @($i) -Property};$rows+=,[pscustomobject]$row}
$null=Com $view 'Close' @();return $rows
}
function Authoring($installer,[string]$path){
# OpenDatabase mode0 only. Never open an installation session or execute actions.
$db=Com $installer 'OpenDatabase' @($path,0)
$properties=@{};foreach($row in @(Rows $db 'Property')){$properties[$row.Property]=$row.Value}
$features=@(Rows $db 'Feature');$upgrade=@(Rows $db 'Upgrade');$sequence=@(Rows $db 'InstallExecuteSequence')
$problems=[Collections.Generic.List[string]]::new()
if($properties.ADDLOCAL -ne 'Complete'){$problems.Add('No explicit local Complete feature selection')}
if(@($features | Where-Object {$_.Feature -eq 'Complete' -and ([int]$_.Attributes -band 8) -eq 8 -and ([int]$_.Attributes -band 16) -eq 16 -and [int]$_.Level -gt 0}).Count -ne 1){$problems.Add('Complete can be advertised or absent')}
if(@($upgrade | Where-Object {([int]$_.Attributes -band 1) -ne 0}).Count){$problems.Add('Old advertised feature state is eligible for migration')}
if(@($sequence | Where-Object Action -eq 'MigrateFeatureStates').Count){$problems.Add('MigrateFeatureStates action is scheduled')}
return @{problems=@($problems);properties=$properties;files=@(Rows $db 'File');components=@(Rows $db 'FeatureComponents')}
}
$fixture=Get-Content -Raw (Join-Path $PSScriptRoot 'Fixtures\Advertised-Version10-Upgrade.log')
Assert-Upgrade ($fixture -match "setting feature 'Complete' to 'Advertise'" -and $fixture -match 'Request: Null; Action: Null') 'Regression fixture records the real advertised-feature/no-file-action failure'
$installer=New-Object -ComObject WindowsInstaller.Installer
$failed=Authoring $installer (Join-Path $FailedSetupDirectory 'PlotDirectorCompanion.msi')
$corrected=Authoring $installer (Join-Path $CorrectedSetupDirectory 'PlotDirectorCompanion.msi')
Assert-Upgrade ($failed.problems.Count -eq 4) 'Negative control: original released version12 MSI fails all four local-install invariants'
Assert-Upgrade ($corrected.problems.Count -eq 0) 'Corrected MSI cannot inherit the recorded advertised feature selection'
Assert-Upgrade ($failed.properties.ProductCode -eq $corrected.properties.ProductCode -and $corrected.properties.ProductVersion -eq '1.0.12') 'Existing partially registered version12 remains repairable under the same product identity'
$exe=Join-Path $CorrectedSetupDirectory 'PlotDirectorCompanionSetup.exe'
$assembly=[Reflection.Assembly]::Load([IO.File]::ReadAllBytes($exe))
$policy=$assembly.GetType('CompanionUpgradePolicy',$true)
foreach($scenario in @(@{name='version10 advertised-feature major upgrade';registered=$false},@{name='partially registered version12 repair';registered=$true})){
# Invoke only the compiled pure policy, never Setup.Main or any MSI API action.
$properties=[string]$policy.GetMethod('InstallProperties').Invoke($null,@([bool]$scenario.registered))
Assert-Upgrade ($properties -match '(^| )ADDLOCAL=Complete( |$)' -and $properties -match 'REINSTALLMODE=vamus' -and $properties -notmatch 'ADVERTISE=') "Compiled bootstrapper requests local files: $($scenario.name)"
Assert-Upgrade (($properties -match 'REINSTALL=ALL') -eq [bool]$scenario.registered) "Compiled bootstrapper chooses correct repair mode: $($scenario.name)"
}
foreach($versions in @(@{word='1.0.0.10';agent='1.0.0.10'},@{word='1.0.0.12';agent='1.0.0.10'},@{word='1.0.0.10';agent='1.0.0.12'})){
$message=$null;try{$policy.GetMethod('VerifyVersions').Invoke($null,@('1.0.0.12',$versions.word,$versions.agent))}catch{$message=$_.Exception.InnerException.Message}
Assert-Upgrade ($message -like '*Expected 1.0.0.12*' -and $message.Contains('Word add-in detected '+$versions.word) -and $message.Contains('tray executable detected '+$versions.agent)) "Strict check rejects and diagnoses old/mixed files: $($versions.word) / $($versions.agent)"
}
$null=$policy.GetMethod('VerifyVersions').Invoke($null,@('1.0.0.12','1.0.0.12','1.0.0.12'));$checks.Add('Strict check accepts matching version12 files')
$required=@('PlotDirector.WordAddIn.dll','PlotDirector.Companion.Agent.exe')
foreach($name in $required){$file=@($corrected.files | Where-Object {($_.FileName -split '\|')[-1] -eq $name});Assert-Upgrade ($file.Count -eq 1 -and @($corrected.components | Where-Object {$_.Component_ -eq $file[0].Component_ -and $_.Feature_ -eq 'Complete'}).Count -eq 1) "Required file belongs to the locally selected Complete feature: $name"}
@{passed=$checks;rejectedOriginalAuthoring=$failed.problems;correctedSetupSha256=(Get-FileHash $exe).Hash;scope='Read-only MSI tables and compiled pure policy only. No installed upgrade was executed.'} | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $ReportPath -Encoding UTF8
Write-Output "PASS exact advertised-feature upgrade regression: $($checks.Count) assertions; original package rejected, corrected package accepted without installation."

View File

@ -0,0 +1,20 @@
using System;
using System.IO;
// Pure bootstrapper contract, shared with the upgrade regression. The complete
// desktop application must be installed locally, never advertised on demand.
public static class CompanionUpgradePolicy
{
public static string InstallProperties(bool alreadyRegistered)
{
string properties = "ALLUSERS=\"\" MSIINSTALLPERUSER=1 REBOOT=ReallySuppress ADDLOCAL=Complete REINSTALLMODE=vamus";
return alreadyRegistered ? properties + " REINSTALL=ALL" : properties;
}
public static void VerifyVersions(string expected, string wordVersion, string agentVersion)
{
if (wordVersion != expected || agentVersion != expected)
throw new InvalidDataException("Installed component version mismatch. Expected " + expected +
"; Word add-in detected " + (wordVersion ?? "missing") +
"; tray executable detected " + (agentVersion ?? "missing") + ". Retain the setup log; no trust or Office repair was attempted.");
}
}