feat(packaging): add TPK1 self-extracting payload format

Installer payload appended to the setup program: JSON manifest (components,
files with size/SHA-256/offsets/mtime, shortcuts, file types) plus deflate or
stored entries and a 64-byte footer with the manifest hash. The reader finds
the footer before an Authenticode table, validates every offset, rejects
unsafe paths and bounds inflation by the declared size; the writer is
deterministic, deduplicates identical content and strips a signed stub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:56:37 +00:00
1 parent c40b6a7cd3
commit d79ab1e41b
12 files changed
+1488

No files matched your search

@@ -0,0 +1,130 @@
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
using Titano.Core.Packaging;
using Titano.Testing;
namespace Titano.Core.Tests.Packaging;
/// <summary>Synthetic stubs, component trees and hand-made installers for the packaging tests.</summary>
internal sealed class PackagingFixture(TestContext context)
{
public static readonly DateTime FixedTime = new(2026, 3, 14, 15, 9, 26, DateTimeKind.Utc);
private static readonly byte[] CraftStub = [(byte)'M', (byte)'Z', 1, 2, 3, 4, 5, 6, 7, 8, 9];
public string Root { get; } = context.CreateTempDirectory("packaging");
/// <summary>A setup "program": any bytes work, the format does not interpret the stub unless it is a PE.</summary>
public string Stub(int length = 4096)
{
var path = Path.Combine(Root, "Titano.Setup.exe");
var bytes = new byte[length];
new Random(7).NextBytes(bytes);
"MZ"u8.CopyTo(bytes);
File.WriteAllBytes(path, bytes);
return path;
}
/// <summary>Creates <paramref name="files"/> (payload path → content) under a new folder with a fixed mtime.</summary>
public string Folder(string name, params (string Path, byte[] Content)[] files)
{
var dir = Path.Combine(Root, name);
Directory.CreateDirectory(dir);
foreach (var (relative, content) in files)
{
var path = Path.Combine(dir, relative.Replace('/', Path.DirectorySeparatorChar));
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllBytes(path, content);
File.SetLastWriteTimeUtc(path, FixedTime);
}
return dir;
}
public static byte[] Text(string s, int repeat = 1) => Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat(s, repeat)));
public static byte[] Random(int length, int seed)
{
var bytes = new byte[length];
new Random(seed).NextBytes(bytes);
return bytes;
}
public static PayloadSource Source(params PayloadComponentSource[] components) => new()
{
Product = "Titano",
Version = "1.2.3",
Components = components,
};
public string Pack(string stub, PayloadSource source, string name = "Titano-Setup.exe")
{
var output = Path.Combine(Root, "out", name);
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
PayloadWriter.Write(stub, source, output);
return output;
}
/// <summary>
/// A minimal PE32+ header (no sections) followed by filler, with an optional certificate table at the end the
/// way signtool lays it out: 8-byte aligned, pointed at by the security data directory.
/// </summary>
public static byte[] PortableExecutable(int fillerLength, byte[]? certificate = null)
{
const int peOffset = 0x80;
const int optionalHeaderSize = 240;
var headerLength = peOffset + 4 + 20 + optionalHeaderSize;
var image = new byte[headerLength + fillerLength];
"MZ"u8.CopyTo(image);
BinaryPrimitives.WriteInt32LittleEndian(image.AsSpan(0x3C), peOffset);
"PE\0\0"u8.CopyTo(image.AsSpan(peOffset));
var coff = image.AsSpan(peOffset + 4);
BinaryPrimitives.WriteUInt16LittleEndian(coff, 0x8664);
BinaryPrimitives.WriteUInt16LittleEndian(coff[16..], optionalHeaderSize);
BinaryPrimitives.WriteUInt16LittleEndian(coff[18..], 0x0022);
var optional = image.AsSpan(peOffset + 24);
BinaryPrimitives.WriteUInt16LittleEndian(optional, 0x20B);
BinaryPrimitives.WriteUInt32LittleEndian(optional[32..], 0x1000); // SectionAlignment
BinaryPrimitives.WriteUInt32LittleEndian(optional[36..], 0x200); // FileAlignment
BinaryPrimitives.WriteUInt32LittleEndian(optional[108..], 16); // NumberOfRvaAndSizes
new Random(3).NextBytes(image.AsSpan(headerLength));
return certificate is null ? image : Sign(image, certificate);
}
/// <summary>Appends a certificate table and points the security directory at it, as signtool does.</summary>
public static byte[] Sign(byte[] file, byte[] certificate)
{
var aligned = (file.Length + 7) / 8 * 8;
var signed = new byte[aligned + certificate.Length];
file.CopyTo(signed, 0);
certificate.CopyTo(signed, aligned);
var entry = SecurityDirectoryOffset(signed);
BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(entry), (uint)aligned);
BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(entry + 4), (uint)certificate.Length);
return signed;
}
/// <summary>File offset of the security data directory entry of an image built by <see cref="PortableExecutable"/>.</summary>
public static int SecurityDirectoryOffset(byte[] image) =>
BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(0x3C)) + 4 + 20 + 112 + 4 * 8;
/// <summary>Assembles an installer by hand from a manifest and data region, bypassing the writer's checks.</summary>
public string Craft(PayloadManifest manifest, byte[] data, string name = "crafted.exe")
{
var stub = CraftStub;
var json = manifest.ToJsonBytes();
using var ms = new MemoryStream();
ms.Write(stub);
ms.Write(json);
ms.Write(data);
ms.Write(new byte[(8 - ms.Length % 8) % 8]);
var footer = new byte[PayloadFormat.FooterLength];
new PayloadFooter(stub.Length, json.Length, data.Length, SHA256.HashData(json)).WriteTo(footer);
ms.Write(footer);
var path = Path.Combine(Root, name);
File.WriteAllBytes(path, ms.ToArray());
return path;
}
public static string Sha256(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content));
}
@@ -0,0 +1,213 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Packaging;
using Titano.Testing;
namespace Titano.Core.Tests.Packaging;
public sealed class PayloadIntegrityTests(TestContext context)
{
private readonly PackagingFixture _fx = new(context);
private (string Installer, long PayloadOffset, byte[] Bytes) PackSample()
{
var app = _fx.Folder("app",
("Titano.exe", PackagingFixture.Text("program ", 3000)),
("noise.bin", PackagingFixture.Random(40_000, 5)),
("docs/readme.txt", PackagingFixture.Text("read me ", 200)));
var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)));
using var reader = PayloadReader.Open(installer);
return (installer, reader.PayloadOffset, File.ReadAllBytes(installer));
}
[Test]
public void TamperedManifestIsRejected()
{
var (installer, offset, bytes) = PackSample();
// Flip the first letter of "Titano" in "product":"Titano".
var at = Array.IndexOf(bytes, (byte)'T', (int)offset);
bytes[at] = (byte)'X';
File.WriteAllBytes(installer, bytes);
var ex = Assert.Throws<PayloadException>(() => PayloadReader.Open(installer));
Assert.Equal(PayloadError.Corrupt, ex.Error);
Assert.Contains("SHA-256", ex.Message);
}
[Test]
public void TamperedFooterHashIsRejected()
{
var (installer, _, bytes) = PackSample();
bytes[^1] ^= 0x5A;
File.WriteAllBytes(installer, bytes);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void FooterPointingOutsideTheFileIsRejected()
{
var (installer, _, bytes) = PackSample();
BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(bytes.Length - PayloadFormat.FooterLength + 16), long.MaxValue - 3);
File.WriteAllBytes(installer, bytes);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void CorruptStoredEntryFailsItsHash()
{
var (installer, _, bytes) = PackSample();
PayloadFile noise;
long dataOffset;
using (var reader = PayloadReader.Open(installer))
{
noise = reader.Manifest.Files.Single(f => f.Path == "noise.bin");
dataOffset = DataOffset(bytes, reader.PayloadOffset);
}
Assert.Equal(PayloadCompression.Stored, noise.Compression);
bytes[dataOffset + noise.Offset + 1234] ^= 0xFF;
File.WriteAllBytes(installer, bytes);
using var tampered = PayloadReader.Open(installer);
var ex = Assert.Throws<PayloadException>(() => tampered.Extract([noise], context.CreateTempDirectory()));
Assert.Equal(PayloadError.Corrupt, ex.Error);
Assert.Contains("noise.bin", ex.Message);
}
[Test]
public void EveryCorruptPayloadByteIsDetectedOrHarmless()
{
var (installer, offset, original) = PackSample();
var expected = new Dictionary<string, byte[]>
{
["Titano.exe"] = PackagingFixture.Text("program ", 3000),
["noise.bin"] = PackagingFixture.Random(40_000, 5),
["docs/readme.txt"] = PackagingFixture.Text("read me ", 200),
};
var step = Math.Max(1, (int)((original.Length - offset) / 150));
for (var at = offset; at < original.Length; at += step)
{
var bytes = (byte[])original.Clone();
bytes[at] ^= 0xFF;
File.WriteAllBytes(installer, bytes);
var target = context.CreateTempDirectory("fuzz");
try
{
using var reader = PayloadReader.Open(installer);
reader.Extract(reader.Manifest.Files, target);
foreach (var (path, content) in expected)
Assert.BytesEqual(content, File.ReadAllBytes(Path.Combine(target, path.Replace('/', Path.DirectorySeparatorChar))), $"flip at {at} produced wrong {path}");
}
catch (PayloadException)
{
// Detected: the expected outcome for almost every byte.
}
}
}
[Test]
public void TruncatedInstallersFailCleanly()
{
var (installer, _, original) = PackSample();
var lengths = new List<int> { 0, 1, 7, PayloadFormat.FooterLength - 1, PayloadFormat.FooterLength, original.Length - 1, original.Length - PayloadFormat.FooterLength };
for (var n = 97; n < original.Length; n += original.Length / 60) lengths.Add(n);
foreach (var length in lengths)
{
File.WriteAllBytes(installer, original.AsSpan(0, length).ToArray());
var ex = Assert.Throws<PayloadException>(() => PayloadReader.Open(installer), $"truncated to {length}");
Assert.True(ex.Error is PayloadError.NotFound or PayloadError.Corrupt, $"truncated to {length}: {ex.Error}");
}
}
[Test]
public void MissingFileIsReportedAsNotFound() =>
Assert.Equal(PayloadError.NotFound, Assert.Throws<PayloadException>(() => PayloadReader.Open(Path.Combine(_fx.Root, "nope.exe"))).Error);
[Theory]
[Case("../evil.txt")]
[Case("a/../../evil.txt")]
[Case("/etc/passwd")]
[Case("C:/Windows/evil.dll")]
[Case("sub\\evil.txt")]
[Case("file.txt:stream")]
public void ManifestPathEscapingTheTargetIsRejected(string path)
{
var content = PackagingFixture.Text("x");
var manifest = new PayloadManifest
{
Product = "Titano",
Version = "1.0.0",
Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano", DefaultSelected = true, EstimatedSize = 1 }],
Files = [new PayloadFile { Path = path, Component = "Titano", Size = 1, Sha256 = PackagingFixture.Sha256(content), Compression = PayloadCompression.Stored, Offset = 0, Length = 1 }],
};
var installer = _fx.Craft(manifest, content);
Assert.Equal(PayloadError.UnsafePath, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void DeclaredSizeBeyondTheDeflateLimitIsRejectedUpFront()
{
var manifest = new PayloadManifest
{
Product = "Titano",
Version = "1.0.0",
Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano" }],
Files = [new PayloadFile { Path = "bomb.bin", Component = "Titano", Size = 1L << 40, Sha256 = new string('0', 64), Compression = PayloadCompression.Deflate, Offset = 0, Length = 16 }],
};
var installer = _fx.Craft(manifest, new byte[16]);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void EntryInflatingPastItsDeclaredSizeStopsAtTheLimit()
{
var zeros = new byte[4 << 20];
using var compressed = new MemoryStream();
using (var deflate = new DeflateStream(compressed, CompressionLevel.SmallestSize, leaveOpen: true)) deflate.Write(zeros);
var data = compressed.ToArray();
var manifest = new PayloadManifest
{
Product = "Titano",
Version = "1.0.0",
Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano" }],
Files = [new PayloadFile { Path = "bomb.bin", Component = "Titano", Size = 1000, Sha256 = PackagingFixture.Sha256(new byte[1000]), Compression = PayloadCompression.Deflate, Offset = 0, Length = data.Length }],
};
using var reader = PayloadReader.Open(_fx.Craft(manifest, data));
var target = context.CreateTempDirectory();
var ex = Assert.Throws<PayloadException>(() => reader.Extract(reader.Manifest.Files, target));
Assert.Contains("larger", ex.Message);
Assert.True(new FileInfo(Path.Combine(target, "bomb.bin")).Length <= 1000);
}
[Test]
public void SignedStubLosesItsSignatureAndSignedInstallerStillOpens()
{
var stubBytes = PackagingFixture.PortableExecutable(5000, certificate: PackagingFixture.Random(1500, 9));
var stub = Path.Combine(_fx.Root, "signed-stub.exe");
File.WriteAllBytes(stub, stubBytes);
var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 50)));
var installer = _fx.Pack(stub, PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)));
var packed = File.ReadAllBytes(installer);
var entry = PackagingFixture.SecurityDirectoryOffset(packed);
Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(packed.AsSpan(entry)), "stub signature directory cleared");
// Sign the whole installer the way signtool does, then read it back.
File.WriteAllBytes(installer, PackagingFixture.Sign(packed, PackagingFixture.Random(2048, 4)));
using var reader = PayloadReader.Open(installer);
Assert.Equal((long)(stubBytes.Length - 1500), reader.PayloadOffset);
var target = context.CreateTempDirectory();
reader.Extract(reader.Manifest.Files, target);
Assert.BytesEqual(PackagingFixture.Text("app", 50), File.ReadAllBytes(Path.Combine(target, "Titano.exe")));
var copy = Path.Combine(target, "Uninstall Titano.exe");
reader.WriteStub(copy);
var copied = File.ReadAllBytes(copy);
Assert.Equal(reader.PayloadOffset, (long)copied.Length);
Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(copied.AsSpan(entry)), "uninstaller signature directory cleared");
}
private static long DataOffset(byte[] installer, long payloadOffset)
{
var footer = installer.AsSpan(installer.Length - PayloadFormat.FooterLength);
return payloadOffset + BinaryPrimitives.ReadInt64LittleEndian(footer[16..]);
}
}
@@ -0,0 +1,60 @@
using Titano.Core.Packaging;
using Titano.Testing;
namespace Titano.Core.Tests.Packaging;
public sealed class PayloadPathTests(TestContext context)
{
[Theory]
[Case("Titano.exe")]
[Case("lib/deep/file.dll")]
[Case("città/日本語 ✓.txt")]
[Case(".hidden")]
[Case("CONFIG.SYS")]
[Case("console.log")]
public void AcceptsCanonicalRelativePaths(string path) => Assert.True(PayloadPath.IsValid(path), path);
[Theory]
[Case("")]
[Case("..")]
[Case("../x")]
[Case("a/../b")]
[Case("a/./b")]
[Case("a//b")]
[Case("/rooted")]
[Case("trailing/")]
[Case("C:/x")]
[Case("a\\b")]
[Case("a:stream")]
[Case("con")]
[Case("aux.txt")]
[Case("COM1")]
[Case("lpt9.log")]
[Case("dot.")]
[Case("space ")]
[Case("tab\tname")]
[Case("star*")]
public void RejectsUnsafePaths(string path) => Assert.False(PayloadPath.IsValid(path), path);
[Test]
public void RejectsOverlongPaths()
{
Assert.False(PayloadPath.IsValid(new string('a', 256)));
Assert.False(PayloadPath.IsValid(string.Join('/', Enumerable.Repeat("abcdefghij", 100))));
}
[Test]
public void ResolveStaysInsideTheRoot()
{
var root = context.CreateTempDirectory();
Assert.Equal(Path.Combine(root, "a", "b.txt"), PayloadPath.Resolve(root, "a/b.txt"));
Assert.Equal(PayloadError.UnsafePath, Assert.Throws<PayloadException>(() => PayloadPath.Resolve(root, "../b.txt")).Error);
}
[Test]
public void ConvertsNativeSeparators()
{
Assert.Equal("a/b/c.txt", PayloadPath.FromRelative("a\\b\\c.txt"));
Assert.Throws<PayloadException>(() => PayloadPath.FromRelative("..\\c.txt"));
}
}
@@ -0,0 +1,172 @@
using Titano.Core.Packaging;
using Titano.Testing;
namespace Titano.Core.Tests.Packaging;
public sealed class PayloadRoundTripTests(TestContext context)
{
private readonly PackagingFixture _fx = new(context);
[Test]
public void ExtractsNestedEmptyUnicodeAndIncompressibleFilesExactly()
{
var files = new (string Path, byte[] Content)[]
{
("Titano.exe", PackagingFixture.Text("MZ program body ", 4000)),
("lib/deep/er/still/config.json", PackagingFixture.Text("{\"a\":1}", 50)),
("empty.txt", []),
("città/日本語 ✓.txt", PackagingFixture.Text("ciao 世界 ", 300)),
("media/noise.bin", PackagingFixture.Random(3 << 20, seed: 11)),
};
var app = _fx.Folder("app", files);
var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)));
using var reader = PayloadReader.Open(installer);
var manifest = reader.Manifest;
Assert.Equal("Titano", manifest.Product);
Assert.Equal("1.2.3", manifest.Version);
Assert.Count(files.Length, manifest.Files);
Assert.Equal(files.Sum(f => (long)f.Content.Length), manifest.Components[0].EstimatedSize);
Assert.Equal(PayloadCompression.Stored, manifest.Files.Single(f => f.Path == "media/noise.bin").Compression);
Assert.Equal(PayloadCompression.Deflate, manifest.Files.Single(f => f.Path == "Titano.exe").Compression);
var empty = manifest.Files.Single(f => f.Path == "empty.txt");
Assert.Equal(0L, empty.Length);
var target = context.CreateTempDirectory("extract");
reader.Extract(manifest.FilesFor(["Titano"]), target);
foreach (var (relative, content) in files)
{
var path = Path.Combine(target, relative.Replace('/', Path.DirectorySeparatorChar));
Assert.BytesEqual(content, File.ReadAllBytes(path), relative);
Assert.Equal(PackagingFixture.FixedTime, File.GetLastWriteTimeUtc(path), relative);
}
}
[Test]
public void ReportsProgressUpToTheTotalSize()
{
var app = _fx.Folder("app", ("a.bin", PackagingFixture.Random(9 << 20, 1)), ("b.txt", PackagingFixture.Text("b", 10)));
var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)));
using var reader = PayloadReader.Open(installer);
var reports = new List<PayloadProgress>();
reader.Extract(reader.Manifest.Files, context.CreateTempDirectory(), new SyncProgress<PayloadProgress>(reports.Add));
Assert.True(reports.Count >= 3);
Assert.Monotonic(reports.Select(r => (double)r.Done));
Assert.Equal(reports[^1].Total, reports[^1].Done);
Assert.Equal((9L << 20) + 10, reports[^1].Total);
}
[Test]
public void IdenticalInputsProduceIdenticalInstallers()
{
var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 999)), ("sub/z.txt", PackagingFixture.Text("z")), ("sub/a.txt", PackagingFixture.Text("a")));
var up = _fx.Folder("uploader", ("Titano.Uploader.exe", PackagingFixture.Text("uploader", 500)));
var stub = _fx.Stub();
var source = PackagingFixture.Source(
new PayloadComponentSource("Titano", "Titano", true, app),
new PayloadComponentSource("Uploader", "Titano Uploader", false, up));
var first = _fx.Pack(stub, source, "first.exe");
var second = _fx.Pack(stub, source, "second.exe");
Assert.BytesEqual(File.ReadAllBytes(first), File.ReadAllBytes(second));
Assert.Equal(0L, new FileInfo(first).Length % PayloadFormat.Alignment);
}
[Test]
public void SharedFilesAreStoredOnceAndInstalledOnce()
{
var shared = PackagingFixture.Text("shared runtime ", 2000);
var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 100)), ("runtime.dll", shared));
var up = _fx.Folder("uploader", ("Titano.Uploader.exe", PackagingFixture.Text("up", 100)), ("runtime.dll", shared));
var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(
new PayloadComponentSource("Titano", "Titano", true, app),
new PayloadComponentSource("Uploader", "Uploader", true, up)));
using var reader = PayloadReader.Open(installer);
var copies = reader.Manifest.Files.Where(f => f.Path == "runtime.dll").ToList();
Assert.Count(2, copies);
Assert.Equal(copies[0].Offset, copies[1].Offset);
var both = reader.Manifest.FilesFor(["Titano", "Uploader"]);
Assert.Count(3, both);
Assert.Count(2, reader.Manifest.FilesFor(["uploader"]));
Assert.Throws<ArgumentException>(() => reader.Manifest.FilesFor(["Server"]));
}
[Test]
public void DifferentContentAtTheSamePathAcrossComponentsIsRejected()
{
var app = _fx.Folder("app", ("same.dll", PackagingFixture.Text("one")));
var up = _fx.Folder("uploader", ("same.dll", PackagingFixture.Text("two")));
var ex = Assert.Throws<PayloadException>(() => _fx.Pack(_fx.Stub(), PackagingFixture.Source(
new PayloadComponentSource("Titano", "Titano", true, app),
new PayloadComponentSource("Uploader", "Uploader", true, up))));
Assert.Equal(PayloadError.Corrupt, ex.Error);
}
[Test]
public void ShortcutsAndAssociationsSurviveTheRoundTrip()
{
var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app")));
var source = new PayloadSource
{
Product = "Titano",
Version = "2.0.0-beta.1",
Components = [new PayloadComponentSource("Titano", "Titano", true, app)],
Shortcuts = [new PayloadShortcut { Component = "Titano", Name = "Titano", Target = "Titano.exe", StartMenu = true, Desktop = true }],
Associations = [new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" }],
};
using var reader = PayloadReader.Open(_fx.Pack(_fx.Stub(), source));
var shortcut = reader.Manifest.Shortcuts.Single();
Assert.True(shortcut.Desktop && shortcut.StartMenu);
Assert.Equal("Titano.exe", shortcut.Target);
Assert.Equal("Titano.Project", reader.Manifest.Associations.Single().ProgId);
}
[Test]
public void ShortcutToAFileOutsideItsComponentIsRejected()
{
var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app")));
var source = new PayloadSource
{
Product = "Titano",
Version = "1.0.0",
Components = [new PayloadComponentSource("Titano", "Titano", true, app)],
Shortcuts = [new PayloadShortcut { Component = "Titano", Name = "Missing", Target = "Missing.exe", StartMenu = true }],
};
Assert.Throws<PayloadException>(() => _fx.Pack(_fx.Stub(), source));
}
[Test]
public void StubCopyEndsAtThePayload()
{
var stub = _fx.Stub(10_000);
var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 10)));
using var reader = PayloadReader.Open(_fx.Pack(stub, PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app))));
Assert.Equal(10_000L, reader.PayloadOffset);
var copy = Path.Combine(context.CreateTempDirectory(), "Uninstall Titano.exe");
reader.WriteStub(copy);
Assert.BytesEqual(File.ReadAllBytes(stub), File.ReadAllBytes(copy));
Assert.Equal(PayloadError.NotFound, Assert.Throws<PayloadException>(() => PayloadReader.Open(copy)).Error);
}
[Test]
public void OutputInsideAComponentFolderIsRefused()
{
var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app")));
Assert.Throws<ArgumentException>(() => PayloadWriter.Write(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)), Path.Combine(app, "setup.exe")));
}
[Test]
public void AnInstallerCannotBeUsedAsStub()
{
var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app")));
var source = PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app));
var installer = _fx.Pack(_fx.Stub(), source);
Assert.Throws<ArgumentException>(() => _fx.Pack(installer, source, "nested.exe"));
}
/// <summary>Synchronous <see cref="IProgress{T}"/> (Progress&lt;T&gt; posts to the thread pool).</summary>
private sealed class SyncProgress<T>(Action<T> report) : IProgress<T>
{
public void Report(T value) => report(value);
}
}