Add complete per-user Companion installer and Windows qualification evidence

This commit is contained in:
nick 2026-11-05 22:43:10 +00:00
parent 6cdb49c08a
commit 97f5d99023
4 changed files with 412 additions and 0 deletions

View File

@ -0,0 +1,128 @@
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$PackagePath,
[string]$OutputDirectory=(Join-Path $env:USERPROFILE 'Downloads\PlotDirectorCompanion-1.0.0.10'),
[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.'}
$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.'}
New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
$output=(Resolve-Path $OutputDirectory).Path
$work=Join-Path $output 'build'
New-Item -ItemType Directory -Path $work -Force | Out-Null
# Reuse the tray's existing P branding for setup, shortcuts and Apps & Features.
Add-Type -AssemblyName System.Drawing
$bitmap=[Drawing.Bitmap]::new(64,64);$graphics=[Drawing.Graphics]::FromImage($bitmap)
$graphics.Clear([Drawing.Color]::Transparent);$graphics.SmoothingMode='AntiAlias'
$brush=[Drawing.SolidBrush]::new([Drawing.Color]::FromArgb(116,67,46));$graphics.FillEllipse($brush,1,1,62,62)
$font=[Drawing.Font]::new('Segoe UI',35,[Drawing.FontStyle]::Bold,[Drawing.GraphicsUnit]::Pixel)
$format=[Drawing.StringFormat]::new();$format.Alignment='Center';$format.LineAlignment='Center'
$graphics.DrawString('P',$font,[Drawing.Brushes]::White,[Drawing.RectangleF]::new(0,0,64,64),$format)
$icon=[Drawing.Icon]::FromHandle($bitmap.GetHicon());$iconPath=Join-Path $work 'PlotDirector.ico';$stream=[IO.File]::Create($iconPath);$icon.Save($stream);$stream.Dispose();$graphics.Dispose();$font.Dispose();$brush.Dispose();$bitmap.Dispose()
$installer=New-Object -ComObject WindowsInstaller.Installer
function Invoke-Com($object,[string]$name,[object[]]$arguments){$values=@(foreach($value in $arguments){if($null -eq $value){$null}else{$value.PSObject.BaseObject}});$object.GetType().InvokeMember($name,[Reflection.BindingFlags]::InvokeMethod,$null,$object,$values)}
function Set-Com($object,[string]$name,[object[]]$arguments){$values=@(foreach($value in $arguments){if($null -eq $value){$null}else{$value.PSObject.BaseObject}});$object.GetType().InvokeMember($name,[Reflection.BindingFlags]::SetProperty,$null,$object,$values)}
$msi=Join-Path $output 'PlotDirectorCompanion.msi'
if(Test-Path $msi){throw "Output already exists: $msi. Choose an empty output directory."}
$database=Invoke-Com $installer 'OpenDatabase' @($msi,3)
function Import-Table([string]$name,[string[]]$columns,[string[]]$types,[string[]]$keys,[object[]]$rows){
$lines=@(($columns -join "`t"),($types -join "`t"),((@($name)+$keys) -join "`t"))
foreach($row in $rows){$lines+=(@($row) -join "`t")}
[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}'
Import-Table Property @('Property','Value') @('s72','l0') @('Property') @(
,@('ProductCode',$product); ,@('ProductVersion','1.0.10'); ,@('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')
)
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)
$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'}
$identity=[Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes('PlotDirector.Companion/'+$folder+'/'+$file.Name))
$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)
$featureRows+=,@('Complete',$component);$ddf+=('"'+$file.FullName+'" '+$id)
if($file.Name -eq 'PlotDirector.Companion.Agent.exe'){$agentFile=$id}
}
# Registry is a separate component so Windows Installer owns removal and rollback.
$componentRows+=,@('Registration','{73926FA6-015D-4B48-885D-C17EAA64AC15}','INSTALLDIR','260','','RegManifest')
$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 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'
Import-Table Registry @('Registry','Root','Key','Name','Value','Component_') @('s72','i2','l255','L255','L0','s72') @('Registry') @(
,@('RegManifest','1',$key,'Manifest','file:///[INSTALLDIR]PlotDirector.WordAddIn.vsto|vstolocal','Registration');
,@('RegLoad','1',$key,'LoadBehavior','#3','Registration'); ,@('RegName','1',$key,'FriendlyName','PlotDirector Word Companion','Registration');
,@('RegDescription','1',$key,'Description','PlotDirector by Nick Beckley','Registration');
,@('RegVersion','1','Software\PlotDirector\Companion','InstalledVersion',$package.version,'Registration')
)
$shortcutColumns=@('Shortcut','Directory_','Name','Component_','Target','Arguments','Description','Hotkey','Icon_','IconIndex','ShowCmd','WkDir')
$shortcutTypes=@('s72','s72','l128','s72','s255','S255','L255','I2','S72','I2','I2','S72')
Import-Table Shortcut $shortcutColumns $shortcutTypes @('Shortcut') @(
,@('OpenCompanion','MENUFOLDER','PDCOMP~1|PlotDirector Companion','Registration',('[#'+$agentFile+']'),'--open','Open PlotDirector Companion','','PlotDirectorIcon','0','1','AGENTDIR');
,@('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'))
$actions=@(
,@('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');
,@('RegisterUser','','6000'); ,@('RegisterProduct','','6100'); ,@('PublishFeatures','','6300'); ,@('PublishProduct','','6400'); ,@('InstallFinalize','','6600')
)
Import-Table InstallExecuteSequence @('Action','Condition','Sequence') @('s72','S255','I2') @('Action') $actions
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.'))
[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){
$sql=if($table -eq '_Streams'){'INSERT INTO `_Streams` (`Name`, `Data`) VALUES (?, ?)'}else{'INSERT INTO `Icon` (`Name`, `Data`) VALUES (?, ?)'}
$view=Invoke-Com $database 'OpenView' @($sql);$record=Invoke-Com $installer 'CreateRecord' @(2)
$null=Set-Com $record 'StringData' @(1,$name);$null=Invoke-Com $record 'SetStream' @(2,$file);$null=Invoke-Com $view 'Execute' @($record);$null=Invoke-Com $view 'Close' @()
}
$view=Invoke-Com $database 'OpenView' @('CREATE TABLE `Icon` (`Name` CHAR(72) NOT NULL, `Data` OBJECT NOT NULL PRIMARY KEY `Name`)');$null=Invoke-Com $view 'Execute' @();$null=Invoke-Com $view 'Close' @()
Insert-Stream '_Streams' 'payload.cab' (Join-Path $work 'payload.cab')
Insert-Stream 'Icon' 'PlotDirectorIcon' $iconPath
$summary=$database.GetType().InvokeMember('SummaryInformation',[Reflection.BindingFlags]::GetProperty,$null,$database,@(20))
# Word-count bit 8 declares a limited-privilege package; bit 2 means compressed.
# Omitting bit 8 prompts for elevation even when ALLUSERS is empty.
foreach($entry in @(@(1,1252),@(2,'Installation Database'),@(3,'PlotDirector Companion'),@(4,'Nick Beckley'),@(7,'x64;1033'),@(9,('{'+[guid]::NewGuid().ToString().ToUpperInvariant()+'}')),@(14,500),@(15,10),@(18,'PlotDirector Companion packaging'))){$null=Set-Com $summary 'Property' $entry}
$null=Invoke-Com $summary 'Persist' @();$null=Invoke-Com $database 'Commit' @()
[Runtime.InteropServices.Marshal]::FinalReleaseComObject($summary) | Out-Null
[Runtime.InteropServices.Marshal]::FinalReleaseComObject($database) | Out-Null
$view=$null;$record=$null;$summary=$null;$database=$null;$installer=$null
[GC]::Collect();[GC]::WaitForPendingFinalizers();[GC]::Collect()
$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'))
$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')
Write-Output "Complete installer: $setup"

View File

@ -0,0 +1,83 @@
# Complete Windows installation qualification — 2026-11-05
## Delivered installation
- Distributable: `C:\Users\Nick\Downloads\PlotDirectorCompanionSetup.exe`.
- EXE SHA-256: `9526E3781EB2EF9936132786E1E2242633349933A553E93E7A7D0B038160A7FF`.
- Application source: `6cdb49c08a74852d5089be8a40c07309543954d1`.
- VSTO and tray executable file versions: **1.0.0.10**.
- All 17 installed runtime files match the original complete signed package by
SHA-256. Symbols were excluded from the MSI; application binaries were not changed.
- Installed under `%LOCALAPPDATA%\Programs\PlotDirector Companion`, including Agent.
- Windows Installer product `{98F46939-764D-407F-BD1F-1D88315D010A}`. MSI's three-part
ProductVersion is `1.0.10`; application versions retain `1.0.0.10`.
- Native `MsiEnumProductsEx` reports context **2 (per-user unmanaged)** and Nick's
actual SID, rather than Codex's packaged registry view. Windows Settings has a
standard MSI uninstall entry for PlotDirector Companion.
## Causes and correction
1. Earlier installation scripts ran inside Codex's MSIX environment. Its private
HKCU registration and LocalAppData staging were visible to tool-launched Word,
while normal Word retained version 1.0.0.6, LoadBehavior 2. The bootstrapper now
targets normal Windows before installation; the final proof is normal Word UI.
2. Normal Windows retained an exact PlotDirector 1.0.0.6 VSTA Solutions record but
no matching cached deployment. Its supported VSTO uninstall returned -401. After
export and removal of that single orphan, the unchanged 1.0.0.10 manifests moved
past HRESULT 0x800736B3 to normal trust approval. No global cache was cleared.
3. A `.vsto` manifest was being presented as a complete installer. It did not supply
a conventional tray installation, shortcuts or unified uninstall. The new EXE
embeds a signed CAB/MSI covering both components and invokes existing VSTO tools
for normal signature/trust validation.
Both original manifest signatures passed SDK mage verification. All referenced
manifest file sizes and SHA-256 digests matched. ClickOnce verbose logging was
temporarily enabled for diagnosis and its prior values restored. A deployment-mode
experiment was rejected; the delivered package retains the original signed VSTO
manifests unchanged.
The first MSI trial omitted the limited-privilege summary bit and requested consent.
That packaging flag was corrected (summary value 10). Same-version repair also
required `REINSTALLMODE=vamus` to recache the updated MSI. These trials are not the
distributable linked above. No Visual Studio, Office, runtime, trust-store or
security-policy repair was performed.
## Actual user-session evidence
- Final setup log: 22:32:58 Windows Installer result 0; 22:33:10 VSTO result 0;
both installed, with final file verification and launch successful.
- Normal Word displayed only **Local Companion: connected** and **Open Companion**.
- Blank Word PID 2456 was closed normally; process absence was checked. Normal Word
PID 34232 then opened the existing eight-word synthetic recovery document. The
PlotDirector ribbon remained enabled and connected after this restart.
- Open Companion activated the installed tray control centre. No manuscript was
opened, edited, saved or uploaded during this qualification.
- Tray PID 36036 runs from the installed Programs directory. Duplicate EXE launch
and the actual installed Startup shortcut retained this same single PID.
- User explicitly confirmed the round P notification-area icon visible.
- Tray UI showed Word connected, Development online, authentication verified and AI
configured. The user completed browser approval; no credential was automated.
- The existing synthetic document's remembered authorised book restored after
reopening. Explicit local Detect Chapters found **Chapter One, eight words**.
No analysis/upload or paid AI request was made.
- Current-user Start menu and Startup shortcuts point to the installed executable;
the former passes `--open`, the latter starts the tray without opening its window.
- Restarting the whole laptop was not performed. Startup configuration and actual
shortcut launch were checked instead. Authentication tokens are memory-only in
this version, so a future tray/Windows restart requires sign-in again.
Evidence JSON/logs and prior registration exports are retained under
`C:\Users\Nick\Downloads\PlotDirectorWordCompanion\InstallationRecovery` and
`%LOCALAPPDATA%\PlotDirector\InstallerBackup`. No secrets are copied into this report.
## Build and scope
- Complete solution `dotnet build PlotLine.slnx -c Release`: passed, zero warnings
and errors. An initial no-restore attempt lacked the new Windows target assets;
normal restore/build resolved that build-only issue.
- Focused `--native-companion` and `--native-tray` executable harness checks: passed.
- Setup C# compilation, signed MSI creation and installed integration checks passed.
- New packaging sources and this evidence exist only in the existing isolated
detached worktree based on the required SHA. No new branch, force-push, server
deployment, application refactor, database change or production action occurred.
- The shared checkout's existing solution-file edit remains untouched.

View File

@ -0,0 +1,54 @@
# Complete per-user Windows installer (1.0.0.10 recovery)
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`.
Build with existing Windows tooling, without launching Visual Studio:
```powershell
.\Build-Setup.ps1 -PackagePath '<validated complete signed developer package>' `
-OutputDirectory '<new output directory>' -CertificateThumbprint '<existing certificate>'
```
The builder verifies the payload inventory and both VSTO signatures, creates an
embedded CAB/MSI with Windows Installer's existing COM API and makecab, and compiles
the bootstrapper with the installed .NET Framework compiler. It installs no tools.
The existing developer certificate signs the MSI and EXE. A local developer
certificate is not a public distribution certificate: normal VSTO trust approval is
still required. Setup never writes certificate trust, inclusion lists or security
policy. Missing Framework 4.8, VSTO or .NET 10 x64 Windows Desktop prerequisites
produce a specific error; they are not installed or repaired automatically.
## Installation contract
- Per-user MSI, no ALLUSERS property; limited-privilege summary flag, compressed CAB.
- `%LOCALAPPDATA%\Programs\PlotDirector Companion` contains VSTO and `Agent`.
- Start menu opens the control centre; the current user's Startup shortcut starts
the same tray executable without opening its window at Windows sign-in.
- Word's manifest points to the installed signed manifest with `|vstolocal` and
LoadBehavior 3, preserving the existing registered-DLL hash resolver.
- The bootstrapper detects a packaged execution context and launches itself through
Win32_Process as the same user in normal Windows before touching installation
state. It never treats a private HKCU view as installation proof.
- Close Word first. Setup stops only this session's existing Companion agent from
LocalAppData; it never terminates Word or Visual Studio.
- Existing registration and exact-product VSTA metadata are exported under
`%LOCALAPPDATA%\PlotDirector\InstallerBackup\<timestamp>`.
- Previous exact PlotDirector VSTO deployments use the supported VSTO uninstaller.
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.
- 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.
- Authentication tokens in version 1.0.0.10 are memory-only. Restarting the agent
requires normal Development browser approval again. Document associations remain
inside their documents; the installer neither opens nor saves documents.
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.
Do not reboot the author's laptop as a test; inspect and launch the installed
Startup shortcut and report that actual reboot has not been exercised.

View File

@ -0,0 +1,147 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
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 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);
[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)
{
Application.EnableVisualStyles();
try
{
// A packaged caller's HKCU/LocalAppData writes are invisible to normal Word.
// WMI launches the same installer as the same user outside that package view.
int length = 0;
if (GetCurrentPackageFullName(ref length, null) != 15700)
{
using (var process = new ManagementClass("Win32_Process"))
using (var input = process.GetMethodParameters("Create"))
using (var startup = new ManagementClass("Win32_ProcessStartup").CreateInstance())
{
startup["ShowWindow"] = (ushort)0;
input["CommandLine"] = "\"" + Assembly.GetExecutingAssembly().Location + "\" --install";
input["ProcessStartupInformation"] = startup;
using (var result = process.InvokeMethod("Create", input, null))
if ((uint)result["ReturnValue"] != 0) throw new InvalidOperationException("Cannot start setup in normal Windows. Run this EXE from File Explorer.");
}
return 0;
}
var state = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PlotDirector", "InstallerBackup", DateTime.Now.ToString("yyyyMMdd-HHmmss"));
Directory.CreateDirectory(state); log = Path.Combine(state, "setup.log");
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();
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);
RemoveOldDeployment(state);
var cache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PlotDirector", "Setup", Version);
Directory.CreateDirectory(cache);
var msi = Path.Combine(cache, "PlotDirectorCompanion.msi");
using (var source = Assembly.GetExecutingAssembly().GetManifestResourceStream("Companion.msi"))
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("{98F46939-764D-407F-BD1F-1D88315D010A}") == 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 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.");
// 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);
Write("VSTO installer result=" + trust);
if (trust != 0) throw new InvalidOperationException("VSTO installation/trust failed with exit code " + trust + ". Both components are staged; rerun setup after resolving this specific error. No system repair was attempted.");
using (var key = Registry.CurrentUser.OpenSubKey(AddinKey, true))
{
key.SetValue("Manifest", new Uri(manifest).AbsoluteUri + "|vstolocal"); key.SetValue("LoadBehavior", 3, RegistryValueKind.DWord);
}
var settings = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PlotDirector", "Companion");
Directory.CreateDirectory(settings);
// Only migrate an existing server preference, never credentials or diagnostic logs.
var oldSettings = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", "OpenAI.Codex_2p2nqsd0c76g0", "LocalCache", "Local", "PlotDirector", "Companion", "server-url.txt");
if (!File.Exists(Path.Combine(settings, "server-url.txt")) && File.Exists(oldSettings)) File.Copy(oldSettings, Path.Combine(settings, "server-url.txt"));
Process.Start(new ProcessStartInfo(agent, "--open") { UseShellExecute = true });
Write("Installed both components; Word restart verification still required.");
MessageBox.Show("PlotDirector Companion " + Version + " is installed.\n\nOpen Word and choose PlotDirector > Open Companion.\nThe tray app also starts at Windows sign-in.\n\nUninstall using Windows Settings > Apps > PlotDirector Companion. Your application state and documents are retained.", "PlotDirector Companion Setup", MessageBoxButtons.OK, MessageBoxIcon.Information);
return 0;
}
catch (Exception ex) { if (log != null) Write(ex.ToString()); MessageBox.Show(ex.Message, "PlotDirector Companion Setup — stopped", MessageBoxButtons.OK, MessageBoxIcon.Error); return 1; }
}
private static void CheckPrerequisites()
{
if (!Environment.Is64BitOperatingSystem) throw new InvalidOperationException("This package requires 64-bit Windows. No prerequisites were installed.");
using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"))
if (key == null || Convert.ToInt32(key.GetValue("Release", 0)) < 528040) throw new InvalidOperationException(".NET Framework 4.8 is required. No installation or repair was attempted.");
var desktop = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "dotnet", "shared", "Microsoft.WindowsDesktop.App");
if (!Directory.Exists(desktop) || !Directory.GetDirectories(desktop, "10.*").Any()) throw new InvalidOperationException("The existing .NET 10 Windows Desktop x64 runtime is required. No runtime was installed.");
if (!File.Exists(VstoInstaller())) throw new InvalidOperationException("The VSTO Runtime is required. No Office or runtime repair was attempted.");
}
private static string VstoInstaller() { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles), @"Microsoft Shared\VSTO\10.0\VSTOInstaller.exe"); }
private static int Run(string exe, string arguments, bool hidden)
{ using (var p = Process.Start(new ProcessStartInfo(exe, arguments) { UseShellExecute = false, CreateNoWindow = hidden, WindowStyle = hidden ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal })) { p.WaitForExit(); return p.ExitCode; } }
private static void Write(string message) { File.AppendAllText(log, DateTime.UtcNow.ToString("o") + " " + message + Environment.NewLine); }
private static void StopOwnAgent()
{
foreach (var p in Process.GetProcessesByName("PlotDirector.Companion.Agent")) using (p)
{
if (p.SessionId != Process.GetCurrentProcess().SessionId) continue;
var path = p.MainModule.FileName;
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar;
if (!path.StartsWith(local, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("A Companion agent is running from another location. Exit it using its tray menu and rerun setup.");
Write("Stopping this session's Companion for upgrade: " + path); p.Kill(); if (!p.WaitForExit(5000)) throw new InvalidOperationException("Companion did not stop.");
}
}
private static void BackupRegistration(string state)
{
using (var key = Registry.CurrentUser.OpenSubKey(AddinKey))
if (key != null) Run(Path.Combine(Environment.SystemDirectory, "reg.exe"), "export \"HKCU\\" + AddinKey + "\" \"" + Path.Combine(state, "word-registration.reg") + "\" /y", true);
}
private static void RemoveOldDeployment(string state)
{
const string root = @"Software\Microsoft\VSTA\Solutions";
using (var solutions = Registry.CurrentUser.OpenSubKey(root, true))
{
if (solutions == null) return;
foreach (var name in solutions.GetSubKeyNames())
{
string url, product, subscription;
using (var key = solutions.OpenSubKey(name)) { url = key.GetValue("Url") as string; product = key.GetValue("ProductName") as string; subscription = key.GetValue("SubscriptionID") as string; }
if (product != "PlotDirector.WordAddIn" || subscription == null || !subscription.StartsWith("PlotDirector.WordAddIn.vsto,", StringComparison.Ordinal)) continue;
Uri uri; if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || !uri.IsFile || Path.GetFileName(uri.LocalPath) != "PlotDirector.WordAddIn.vsto") throw new InvalidOperationException("Unexpected prior Companion deployment. No other deployment was changed.");
var backup = Path.Combine(state, "vsta-" + name + ".reg");
if (Run(Path.Combine(Environment.SystemDirectory, "reg.exe"), "export \"HKCU\\" + root + "\\" + name + "\" \"" + backup + "\" /y", true) != 0) throw new IOException("Cannot back up previous Companion deployment.");
int result = Run(VstoInstaller(), "/Uninstall \"" + url + "\" /Silent", true); Write("Previous exact Companion uninstall=" + result);
// -401 means no cached deployment exists. Retain exported metadata and
// remove only that orphan, which otherwise triggers ERROR_SXS_ASSEMBLY_NOT_FOUND.
if (result == -401) solutions.DeleteSubKeyTree(name, false);
else if (result != 0) throw new InvalidOperationException("Previous Companion uninstall failed: " + result + ". Backup retained; unrelated ClickOnce applications were not changed.");
}
}
}
}