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,214 @@
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
namespace Titano.Core.Packaging;
/// <summary>How an entry's bytes are stored in the data region.</summary>
public enum PayloadCompression
{
Stored,
Deflate,
}
/// <summary>Describes everything a TPK1 installer carries: product, components, files, shortcuts and file types.</summary>
public sealed partial class PayloadManifest
{
public int FormatVersion { get; init; } = PayloadFormat.ManifestFormatVersion;
public required string Product { get; init; }
public required string Version { get; init; }
public List<PayloadComponent> Components { get; init; } = [];
public List<PayloadFile> Files { get; init; } = [];
public List<PayloadShortcut> Shortcuts { get; init; } = [];
public List<PayloadAssociation> Associations { get; init; } = [];
/// <summary>The component with <paramref name="id"/> (ordinal, case-insensitive), or null.</summary>
public PayloadComponent? FindComponent(string id) =>
Components.FirstOrDefault(c => c.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
/// <summary>
/// Files installed by the given components, one entry per path in manifest order. A path shared by several
/// components (identical content, enforced by <see cref="Validate"/>) is listed once.
/// </summary>
public IReadOnlyList<PayloadFile> FilesFor(IEnumerable<string> componentIds)
{
var selected = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var id in componentIds)
{
var component = FindComponent(id) ?? throw new ArgumentException($"Unknown component '{id}'.", nameof(componentIds));
selected.Add(component.Id);
}
var seen = new HashSet<string>(PayloadPath.Comparer);
var result = new List<PayloadFile>();
foreach (var file in Files)
{
if (selected.Contains(file.Component) && seen.Add(file.Path)) result.Add(file);
}
return result;
}
/// <summary>Rejects manifests that are inconsistent with themselves or with a data region of <paramref name="dataLength"/> bytes.</summary>
public void Validate(long dataLength)
{
if (FormatVersion != PayloadFormat.ManifestFormatVersion) Fail($"unsupported manifest format {FormatVersion}");
if (!PayloadPath.IsValidSegment(Product) || Product.Length > 100) Fail("invalid product name");
if (string.IsNullOrWhiteSpace(Version) || Version.Length > 64) Fail("invalid version");
if (Components.Count == 0) Fail("no components");
var componentIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var c in Components)
{
if (c is null || !IdentifierRegex().IsMatch(c.Id)) Fail("invalid component id");
if (!componentIds.Add(c.Id)) Fail($"duplicate component {c.Id}");
if (string.IsNullOrWhiteSpace(c.DisplayName) || c.DisplayName.Length > 100) Fail($"invalid display name for {c.Id}");
if (c.EstimatedSize < 0) Fail($"negative size for {c.Id}");
}
var perComponent = new HashSet<(string, string)>();
var byPath = new Dictionary<string, PayloadFile>(PayloadPath.Comparer);
foreach (var f in Files)
{
if (f is null) Fail("empty file entry");
if (!PayloadPath.IsValid(f.Path)) throw new PayloadException(PayloadError.UnsafePath, $"Unsafe payload path '{f.Path}'.");
if (!componentIds.Contains(f.Component)) Fail($"{f.Path} belongs to an unknown component");
if (!perComponent.Add((f.Component.ToUpperInvariant(), f.Path.ToUpperInvariant()))) Fail($"duplicate file {f.Path}");
if (f.Size < 0 || f.Offset < 0 || f.Length < 0 || f.Offset > dataLength || f.Length > dataLength - f.Offset)
Fail($"{f.Path} lies outside the data region");
if (!Sha256Regex().IsMatch(f.Sha256)) Fail($"{f.Path} has no valid SHA-256");
switch (f.Compression)
{
case PayloadCompression.Stored when f.Length != f.Size:
Fail($"{f.Path}: stored length differs from size");
break;
case PayloadCompression.Deflate when f.Size / PayloadFormat.MaxDeflateRatio > f.Length:
Fail($"{f.Path}: declared size exceeds the deflate limit");
break;
case PayloadCompression.Stored or PayloadCompression.Deflate:
break;
default:
Fail($"{f.Path}: unknown compression");
break;
}
if (byPath.TryGetValue(f.Path, out var other) && (other.Size != f.Size || !other.Sha256.Equals(f.Sha256, StringComparison.Ordinal)))
Fail($"{f.Path} differs between components {other.Component} and {f.Component}");
byPath.TryAdd(f.Path, f);
}
foreach (var s in Shortcuts)
{
if (s is null || !PayloadPath.IsValidSegment(s.Name)) Fail("invalid shortcut name");
if (!OwnsFile(s.Component, s.Target)) Fail($"shortcut {s.Name} targets a file outside its component");
}
foreach (var a in Associations)
{
if (a is null || !ExtensionRegex().IsMatch(a.Extension)) Fail("invalid file extension");
if (!ProgIdRegex().IsMatch(a.ProgId) || a.ProgId.Length > 39) Fail($"invalid ProgID for {a.Extension}");
if (string.IsNullOrWhiteSpace(a.Description) || a.Description.Length > 100) Fail($"invalid description for {a.Extension}");
if (!OwnsFile(a.Component, a.Target)) Fail($"{a.Extension} opens a file outside its component");
}
bool OwnsFile(string? component, string? path) =>
component is not null && path is not null && perComponent.Contains((component.ToUpperInvariant(), path.ToUpperInvariant()));
}
/// <summary>Serializes with a fixed property order and no whitespace, so identical inputs give identical bytes.</summary>
public byte[] ToJsonBytes() => JsonSerializer.SerializeToUtf8Bytes(this, PayloadJson.Default.PayloadManifest);
/// <summary>Parses manifest bytes; malformed JSON is reported as <see cref="PayloadError.Corrupt"/>.</summary>
public static PayloadManifest Parse(ReadOnlySpan<byte> json)
{
try
{
return JsonSerializer.Deserialize(json, PayloadJson.Default.PayloadManifest)
?? throw new PayloadException(PayloadError.Corrupt, "The installer manifest is empty.");
}
catch (JsonException ex)
{
throw new PayloadException(PayloadError.Corrupt, "The installer manifest is not valid JSON.", ex);
}
}
[DoesNotReturn]
private static void Fail(string reason) => throw new PayloadException(PayloadError.Corrupt, "Invalid installer manifest: " + reason + ".");
[GeneratedRegex("^[A-Za-z][A-Za-z0-9]{0,63}$")]
internal static partial Regex IdentifierRegex();
[GeneratedRegex("^[0-9a-f]{64}$")]
private static partial Regex Sha256Regex();
[GeneratedRegex(@"^\.[A-Za-z0-9]{1,16}$")]
private static partial Regex ExtensionRegex();
[GeneratedRegex(@"^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z0-9]+)+$")]
private static partial Regex ProgIdRegex();
}
/// <summary>A selectable part of the product (Titano, Uploader, Server).</summary>
public sealed class PayloadComponent
{
public required string Id { get; init; }
public required string DisplayName { get; init; }
public bool DefaultSelected { get; init; }
/// <summary>Installed size in bytes (sum of the component's files).</summary>
public long EstimatedSize { get; init; }
}
/// <summary>One installed file and where its bytes live in the data region.</summary>
public sealed class PayloadFile
{
/// <summary>Canonical relative path (<see cref="PayloadPath"/>).</summary>
public required string Path { get; init; }
public required string Component { get; init; }
public long Size { get; init; }
/// <summary>Lower-case hex SHA-256 of the uncompressed content.</summary>
public required string Sha256 { get; init; }
public PayloadCompression Compression { get; init; }
/// <summary>Offset of the stored bytes, relative to the start of the data region.</summary>
public long Offset { get; init; }
/// <summary>Number of stored (possibly compressed) bytes.</summary>
public long Length { get; init; }
/// <summary>Last write time, Unix epoch seconds (UTC).</summary>
public long ModifiedUnixSeconds { get; init; }
}
/// <summary>A shortcut to one of a component's files, created in the Start menu and/or on the desktop.</summary>
public sealed class PayloadShortcut
{
public required string Component { get; init; }
/// <summary>File name of the shortcut without <c>.lnk</c>.</summary>
public required string Name { get; init; }
/// <summary>Payload path of the program the shortcut opens.</summary>
public required string Target { get; init; }
public bool StartMenu { get; init; }
public bool Desktop { get; init; }
}
/// <summary>A file type registered to open with one of a component's programs (<c>"target" "%1"</c>).</summary>
public sealed class PayloadAssociation
{
public required string Component { get; init; }
/// <summary>Extension including the dot, e.g. <c>.titano</c>.</summary>
public required string Extension { get; init; }
public required string ProgId { get; init; }
/// <summary>File type name shown by Explorer.</summary>
public required string Description { get; init; }
/// <summary>Payload path of the program that opens the file.</summary>
public required string Target { get; init; }
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, RespectNullableAnnotations = true)]
[JsonSerializable(typeof(PayloadManifest))]
internal sealed partial class PayloadJson : JsonSerializerContext;