Files
Dj GilcreaseandClaude Fable 5.1 c953fe3995 feat: add msi support (#1097)
* chore(deps): add go-msi and go-pkcs12

go.digitalxero.dev/go-msi is the pure-Go Windows Installer database
writer, validator, reader and Authenticode signer behind the new msi
packager; go-pkcs12 becomes a direct dependency for the signing tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Hnro326ZTAu2EqUTGGkCB

* feat: add msi support

Adds an `msi` packager that writes a real Windows Installer database with
the pure-Go go-msi library: contents are mapped onto the standard Windows
folders (everything else under the product's Program Files folder), root
metadata (description, homepage, license, vendor/maintainer, scripts) is
reused where MSI has a place for it, and advertised shortcuts, Windows
services, registry values, per-user installs and Authenticode signing are
exposed under `msi:`.

Every release replaces older installs of the same upgrade code in place:
the upgrade code and component GUIDs are derived from identities that
survive releases, while the product code follows the full version. A
version Windows Installer cannot represent is an error rather than a
silently clamped (and colliding) one.

Maintainer scripts run as elevated deferred custom actions embedded in the
package so they work before any file is installed and after every file is
removed; they are extracted to a randomly named, freshly created file
since the SYSTEM temp directory is world-writable.

Unit tests build real packages, run go-msi's ICE validator and assert on
the decoded tables; golden GUIDs pin the derivation contract. The
acceptance suite installs, exercises, upgrades and removes the package
with msiexec on a Windows runner and proves a failing script rolls back.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Hnro326ZTAu2EqUTGGkCB

* ci: validate nfpm-signed MSI on real Windows

Build and Authenticode-sign the MSI on Linux with nfpm's pure-Go signer
and a throwaway openssl certificate, then validate the signature with the
real Windows trust stack (Get-AuthenticodeSignature, signtool verify) and
install, exercise and remove it with msiexec on a Windows runner. The
unsigned msi-windows-install job remains as the control.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Hnro326ZTAu2EqUTGGkCB

* chore(deps): update go-msi to latest main

* Revert "chore(deps): update go-msi to latest main"

This reverts commit 05aaa91684.

* ci: integrate MSI validation with merge queue checks

* fix(msi): decode quoted maintainer names

* fix: preserve address-only maintainer fallback

* fix(msi): update go-msi and support explicit file versions

Pin the latest upstream fixes for string references, column limits, and PE version detection. Expose per-destination file version overrides so intentionally unversioned Go binaries can still be packaged, and update fixtures, docs, and schema.

* chore(deps): pin go-msi v0.5.1 release

* fix(msi): Correct downgrade removal and shortcut resources

Match Windows destinations without case sensitivity, reuse PE icon streams by source and target extension, and cover newer products in downgrade removal ranges.

Add table regressions, native icon extraction and ICE50 checks, and Windows downgrade acceptance with distinct payloads. Run MSI installation checks on pull requests.

See #1097

* test(msi): Correct native icon extraction assertions

Distinguish one RT_GROUP_ICON resource from the two extracted icon handles requested from the Windows shell. Preserve checks for both handles and cover malformed resource directories and extensionless icon targets.

See #1097

* fix(msi): Adopt go-msi v0.5.2 and reject install-path aliases

Use the released dependency fixes for downgrade sequencing, non-elevating per-user packages, and lossless non-ASCII summary metadata. Preserve the explicit removal rule for allowed downgrades.

Reject duplicate resolved installation targets while preserving GUID identities. Add downstream table regressions and native silent-downgrade and standard-user Unicode/script verification.

See #1097

* fix(msi): Adopt go-msi v0.5.3 and close authoring gaps

* test(msi): Normalize redirected native install paths

* fix(msi): Preserve upgrade targets and release artifacts

* fix(msi): Adopt go-msi v0.5.5 signing and AppSearch fixes

* fix(msi): expand remaining strings and prove hook rollback

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-11 02:25:17 +00:00

189 lines
7.2 KiB
Go

package msi
import (
"bytes"
"encoding/base64"
"encoding/binary"
"fmt"
"os"
"path/filepath"
"strings"
"unicode/utf16"
"unicode/utf8"
"github.com/goreleaser/nfpm/v2"
"go.digitalxero.dev/go-msi"
)
// maxScriptSize bounds the size of an embedded maintainer script.
//
// The script travels base64-encoded inside a PowerShell bootstrap that is
// itself UTF-16LE + base64 encoded into the custom action command line, so
// every script byte costs 4/3 * 2 * 4/3 = 3.56 command-line characters on top
// of the fixed ~1,200-character bootstrap. Windows caps a command line at
// 32,767 characters; an 8 KiB script lands around 30,300, leaving headroom for
// the bootstrap to grow (TestScriptCommandLineFitsCommandLine guards it).
//
// The CustomAction.Target column is declared 255 characters wide in the MSI
// schema. Windows Installer stores and runs longer values fine (the Windows
// acceptance job proves it), but strict validators such as msival2 report the
// overflow as ICE03 "string overflow"; embedding the script is worth that
// warning because it is the only way the hooks can run before any package
// file exists (preinstall) or after every file is gone (postremove).
const maxScriptSize = 8 * 1024
// scriptExtensions maps a supported script extension to the PowerShell
// expression the bootstrap uses to run the extracted script.
// nolint: gochecknoglobals
var scriptExtensions = map[string]string{
".ps1": "& powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $f",
".bat": "& cmd.exe /c $f",
".cmd": "& cmd.exe /c $f",
}
// scriptHooks returns the root maintainer scripts mapped to their MSI custom
// action identity and InstallExecuteSequence schedule. "NOT Installed" runs the
// install hooks on fresh install and on the new product during a major upgrade
// (deb preinst/postinst semantics); "NOT UPGRADINGPRODUCTCODE" keeps the old
// product's remove hooks from firing while it is being replaced.
func scriptHooks(info *nfpm.Info) []struct {
field string
path string
caID string
before bool
anchor string
condition string
} {
const removeCondition = `REMOVE="ALL" AND NOT UPGRADINGPRODUCTCODE`
return []struct {
field string
path string
caID string
before bool
anchor string
condition string
}{
{"preinstall", info.Scripts.PreInstall, "NfpmPreInstall", true, "InstallFiles", "NOT Installed"},
{"postinstall", info.Scripts.PostInstall, "NfpmPostInstall", false, "InstallFiles", "NOT Installed"},
{"preremove", info.Scripts.PreRemove, "NfpmPreRemove", true, "RemoveFiles", removeCondition},
{"postremove", info.Scripts.PostRemove, "NfpmPostRemove", false, "RemoveFiles", removeCondition},
}
}
// addScripts turns the root maintainer scripts into deferred custom actions.
// They run elevated for per-machine installs and with the user's privileges
// for non-elevating per-user installs. Failures roll back the transaction,
// including on uninstall, matching dpkg/rpm strictness.
func addScripts(b msi.PackageBuilder, info *nfpm.Info) error {
for _, h := range scriptHooks(info) {
if h.path == "" {
continue
}
cmd, err := scriptCommandLine(h.caID, h.path, is64bit(info.Arch))
if err != nil {
return fmt.Errorf("package scripts.%s: %w", h.field, err)
}
ca := b.CustomAction(h.caID).
EXEFromDirectory("TARGETDIR", cmd).
Deferred().NoImpersonate().HideTarget()
if h.before {
ca.ScheduleBefore(msi.InstallExecuteSequence, h.anchor, h.condition)
} else {
ca.ScheduleAfter(msi.InstallExecuteSequence, h.anchor, h.condition)
}
}
return nil
}
// scriptCommandLine embeds the script file into a self-deleting PowerShell
// bootstrap and returns the full custom action command line. The script bytes
// travel base64 inside the bootstrap because the payload must run at points
// where no package file is on disk yet (preinstall) or anymore (postremove).
//
// A per-machine custom action runs as SYSTEM, whose temp directory
// (C:\Windows\Temp) lets any local user pre-create files; a per-user action
// instead runs with user privileges. The extracted script must not have
// a predictable name and must never be written over an existing file: the
// name gets a CSPRNG-backed random component and the file is opened with
// CreateNew, which fails (and rolls the install back) if the path exists.
func scriptCommandLine(caID, path string, is64 bool) (string, error) {
script, err := os.ReadFile(path)
if err != nil {
return "", err
}
run, ok := scriptExtensions[strings.ToLower(filepath.Ext(path))]
if !ok {
return "", fmt.Errorf("%q: msi scripts must be .ps1, .bat, or .cmd", path)
}
if strings.EqualFold(filepath.Ext(path), ".ps1") {
// Windows PowerShell 5.1 reads BOM-less files using the machine ANSI
// code page. Treat BOM-less input as UTF-8 and mark it explicitly;
// preserve existing UTF-8/UTF-16/UTF-32 BOMs and their original bytes.
hasBOM := bytes.HasPrefix(script, []byte{0xef, 0xbb, 0xbf}) ||
bytes.HasPrefix(script, []byte{0xff, 0xfe}) ||
bytes.HasPrefix(script, []byte{0xfe, 0xff}) ||
bytes.HasPrefix(script, []byte{0, 0, 0xfe, 0xff})
if !hasBOM {
if !utf8.Valid(script) {
return "", fmt.Errorf("%q: BOM-less PowerShell hooks must be valid UTF-8; add an encoding BOM for other supported encodings", path)
}
script = append([]byte{0xef, 0xbb, 0xbf}, script...)
}
}
bootstrap := fmt.Sprintf(
"$f = Join-Path $env:TEMP ('nfpm_%s_' + [IO.Path]::GetRandomFileName() + '%s')\n"+
"$s = [IO.File]::Open($f, 'CreateNew')\n"+
"try { $b = [Convert]::FromBase64String('%s'); $s.Write($b, 0, $b.Length) } finally { $s.Dispose() }\n"+
"try { %s; exit $LASTEXITCODE }\n"+
"finally { Remove-Item -Force $f -ErrorAction SilentlyContinue }",
caID, strings.ToLower(filepath.Ext(path)),
base64.StdEncoding.EncodeToString(script), run,
)
// -EncodedCommand takes base64 of the UTF-16LE bootstrap. [System64Folder]
// is a Formatted property; deferred action targets are formatted at script
// generation time, when properties are still available.
folder := "[System64Folder]"
if !is64 {
folder = "[SystemFolder]"
}
return fmt.Sprintf(
`"%sWindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand %s`,
folder, base64.StdEncoding.EncodeToString(utf16le(bootstrap)),
), nil
}
// validateScripts checks the root maintainer scripts against MSI constraints:
// supported interpreter extensions and the embeddable size limit.
func validateScripts(info *nfpm.Info) error {
for _, h := range scriptHooks(info) {
if h.path == "" {
continue
}
if _, ok := scriptExtensions[strings.ToLower(filepath.Ext(h.path))]; !ok {
return fmt.Errorf("package scripts.%s %q: msi scripts must be .ps1, .bat, or .cmd", h.field, h.path)
}
st, err := os.Stat(h.path)
if err != nil {
return fmt.Errorf("package scripts.%s: %w", h.field, err)
}
if st.Size() > maxScriptSize {
return fmt.Errorf(
"package scripts.%s %q is %d bytes; msi embeds scripts in the install command line and supports at most %d bytes",
h.field, h.path, st.Size(), maxScriptSize,
)
}
}
return nil
}
func utf16le(s string) []byte {
codes := utf16.Encode([]rune(s))
b := make([]byte, len(codes)*2)
for i, c := range codes {
binary.LittleEndian.PutUint16(b[i*2:], c)
}
return b
}