using System.Buffers.Binary;
namespace Titano.Core.Packaging;
///
/// The TPK1 self-extracting layout: [setup stub][manifest JSON][entry data][zero padding][footer], optionally
/// followed by an Authenticode certificate table that signtool appends when the installer is signed.
/// The footer is 64 bytes, little-endian: magic "TPK1END\0" · payload offset (int64, absolute offset of the
/// manifest) · manifest length (int64) · data length (int64) · SHA-256 of the manifest bytes (32 bytes).
/// Entry offsets in the manifest are relative to the first byte after the manifest. Padding aligns the end of the
/// footer to 8 bytes so a signature can be appended without signtool inserting bytes of its own.
///
public static class PayloadFormat
{
public const int FooterLength = 64;
public const int Alignment = 8;
public const int ManifestFormatVersion = 1;
/// Upper bound for the manifest; a larger value in a footer means corruption.
public const int MaxManifestLength = 64 << 20;
/// Deflate cannot expand data by more than about 1032:1; larger declared sizes are rejected up front.
public const int MaxDeflateRatio = 1032;
public static ReadOnlySpan Magic => "TPK1END\0"u8;
}
/// Decoded TPK1 footer.
internal readonly record struct PayloadFooter(long PayloadOffset, long ManifestLength, long DataLength, byte[] ManifestHash)
{
public void WriteTo(Span destination)
{
PayloadFormat.Magic.CopyTo(destination);
BinaryPrimitives.WriteInt64LittleEndian(destination[8..], PayloadOffset);
BinaryPrimitives.WriteInt64LittleEndian(destination[16..], ManifestLength);
BinaryPrimitives.WriteInt64LittleEndian(destination[24..], DataLength);
ManifestHash.CopyTo(destination[32..]);
}
/// Parses a footer; false when the magic does not match.
public static bool TryParse(ReadOnlySpan source, out PayloadFooter footer)
{
footer = default;
if (source.Length < PayloadFormat.FooterLength || !source[..8].SequenceEqual(PayloadFormat.Magic)) return false;
footer = new PayloadFooter(
BinaryPrimitives.ReadInt64LittleEndian(source[8..]),
BinaryPrimitives.ReadInt64LittleEndian(source[16..]),
BinaryPrimitives.ReadInt64LittleEndian(source[24..]),
source.Slice(32, 32).ToArray());
return true;
}
}