From e74a334cefaaf1ed2625798c309b6025b9bc7738 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 15:22:18 -0500 Subject: [PATCH 01/22] feat: read the plugin hub's catalog and download from it with a size cap --- .../Plugins/HubCatalogJsonTests.cs | 105 +++++++++ .../Plugins/HubHttpTests.cs | 43 ++++ .../Data/LocalDataPaths.cs | 12 + .../Plugins/Hub/HubAddresses.cs | 20 ++ .../Plugins/Hub/HubCatalog.cs | 29 +++ .../Plugins/Hub/HubCatalogJson.cs | 212 ++++++++++++++++++ .../Plugins/Hub/HubHttp.cs | 41 ++++ .../Plugins/Hub/HubLimits.cs | 16 ++ .../Plugins/PluginManifestReader.cs | 35 ++- 9 files changed, 501 insertions(+), 12 deletions(-) create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalog.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/HubLimits.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs new file mode 100644 index 0000000..f4689ba --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs @@ -0,0 +1,105 @@ +using System.Text.Json.Nodes; +using FourFoldAccountManager.Core.Overlay; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubCatalogJsonTests +{ + private const string Commit = "0123456789abcdef0123456789abcdef01234567"; + private static readonly string Hash = new('a', 64); + + private static HubPlugin Plugin(string id = "cody.goal-tracker") => new( + id, "Goal tracker", "Goals", "1.2.0", "cody", "Tracks a level goal.", + [new Uri("https://example.com")], false, [new HubCard("Goal", OverlayAddOnScope.Account)], + new Uri("https://github.com/cody/goal-tracker"), Commit, "2026-10-09", 18234, Hash); + + [Fact] + public void AWrittenCatalogReadsBackTheSame() + { + var written = HubCatalogJson.Write(new HubCatalog([Plugin()], [new HubRemoval("x.y", "Broken.")])); + + var read = HubCatalogJson.Parse(written)!; + + var plugin = Assert.Single(read.Plugins); + var expected = Plugin(); + Assert.Equal(expected.Id, plugin.Id); + Assert.Equal(expected.Name, plugin.Name); + Assert.Equal(expected.ShortLabel, plugin.ShortLabel); + Assert.Equal(expected.Version, plugin.Version); + Assert.Equal(expected.Author, plugin.Author); + Assert.Equal(expected.Description, plugin.Description); + Assert.Equal(expected.Sites, plugin.Sites); + Assert.Equal(expected.AnySite, plugin.AnySite); + Assert.Equal(expected.Cards, plugin.Cards); + Assert.Equal(expected.Repository, plugin.Repository); + Assert.Equal(expected.Commit, plugin.Commit); + Assert.Equal(expected.Reviewed, plugin.Reviewed); + Assert.Equal(expected.Size, plugin.Size); + Assert.Equal(expected.Sha256, plugin.Sha256); + Assert.Equal([new HubRemoval("x.y", "Broken.")], read.Removed); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("not json")] + [InlineData("[]")] + [InlineData("{}")] + [InlineData("{\"version\":2,\"plugins\":[]}")] + [InlineData("{\"version\":\"1\"}")] + public void ACatalogThatCannotBeUsedReadsAsNothing(string? json) => Assert.Null(HubCatalogJson.Parse(json)); + + [Fact] + public void AnOversizedCatalogReadsAsNothing() => + Assert.Null(HubCatalogJson.Parse( + "{\"version\":1,\"pad\":\"" + new string('x', HubLimits.MaximumCatalogBytes) + "\"}")); + + [Theory] + [InlineData("id", "\"../evil\"")] + [InlineData("id", "\"nul.tools\"")] + [InlineData("id", "7")] + [InlineData("commit", "\"abc\"")] + [InlineData("commit", "\"0123456789ABCDEF0123456789ABCDEF01234567\"")] + [InlineData("commit", "\"../../0123456789abcdef0123456789abcdef0123\"")] + [InlineData("sha256", "\"zz\"")] + [InlineData("size", "0")] + [InlineData("size", "99999999")] + [InlineData("size", "\"1\"")] + [InlineData("repository", "\"https://evil.example/cody/goal-tracker\"")] + [InlineData("repository", "\"https://github.com/cody/goal-tracker/tree/main\"")] + [InlineData("name", "\"Goal\\u202Etracker\"")] + [InlineData("name", "\"\"")] + [InlineData("version", "\"1.2\"")] + [InlineData("sites", "[\"http://example.com\"]")] + [InlineData("sites", "[\"https://localhost\"]")] + [InlineData("sites", "[\"https://a\\u200Db.example\"]")] + [InlineData("cards", "[{\"name\":\"Goal\",\"scope\":\"everywhere\"}]")] + public void ABadEntryIsSkippedAndTheOthersLoad(string property, string value) + { + var catalog = JsonNode.Parse(HubCatalogJson.Write(new HubCatalog([Plugin("good.plugin")], [])))!; + var bad = JsonNode.Parse(HubCatalogJson.Write(new HubCatalog([Plugin("bad.plugin")], [])))!["plugins"]![0]! + .DeepClone(); + bad[property] = JsonNode.Parse(value); + catalog["plugins"]!.AsArray().Insert(0, bad); + + var read = HubCatalogJson.Parse(catalog.ToJsonString()); + + Assert.Equal("good.plugin", Assert.Single(read!.Plugins).Id); + } + + [Fact] + public void APulledPluginIsNeverAlsoListedAndAPullSurvivesABadReason() + { + var catalog = JsonNode.Parse( + HubCatalogJson.Write(new HubCatalog([Plugin("pulled.plugin"), Plugin("kept.plugin")], [])))!; + catalog["removed"] = JsonNode.Parse( + "[{\"id\":\"pulled.plugin\",\"reason\":\"Bad\\u202Ereason\"},{\"id\":\"../x\",\"reason\":\"ignored\"}]"); + + var read = HubCatalogJson.Parse(catalog.ToJsonString())!; + + Assert.Equal("kept.plugin", Assert.Single(read.Plugins).Id); + Assert.Equal([new HubRemoval("pulled.plugin", string.Empty)], read.Removed); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs new file mode 100644 index 0000000..c8ce1f6 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs @@ -0,0 +1,43 @@ +using System.Net; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubHttpTests +{ + // No Content-Length, so only counting the bytes as they arrive can stop an oversized download. + private sealed class UnknownLengthContent(byte[] body) : HttpContent + { + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => + stream.WriteAsync(body).AsTask(); + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + } + + private sealed class FixedHandler(byte[] body) : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new UnknownLengthContent(body), + RequestMessage = request + }); + } + + [Fact] + public async Task ADownloadLargerThanTheLimitIsRefused() + { + using var atLimit = new HttpClient(new FixedHandler(new byte[100])); + using var overLimit = new HttpClient(new FixedHandler(new byte[101])); + var uri = new Uri("https://example.com/file"); + + Assert.Equal(100, (await HubHttp.DownloadAsync(atLimit, uri, 100, CancellationToken.None))!.Length); + Assert.Null(await HubHttp.DownloadAsync(overLimit, uri, 100, CancellationToken.None)); + } +} diff --git a/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs b/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs index dde8b50..8b244c6 100644 --- a/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs +++ b/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs @@ -19,6 +19,9 @@ public LocalDataPaths(string? root = null) DevPluginsRoot = Path.Combine(DataRoot, "dev-plugins"); PluginDataRoot = Path.Combine(DataRoot, "plugin-data"); PluginWebViewUserDataRoot = Path.Combine(DataRoot, "PluginWebView2"); + HubPluginsRoot = Path.Combine(DataRoot, "plugins"); + HubCatalogFilePath = Path.Combine(DataRoot, "hub", "catalog.json"); + HubInstalledFilePath = Path.Combine(DataRoot, "hub", "installed.json"); } public string DataRoot { get; } @@ -41,4 +44,13 @@ public LocalDataPaths(string? root = null) // The plugin browser's own data folder, separate from the game profiles in WebViewUserDataRoot. public string PluginWebViewUserDataRoot { get; } + + // Plugins installed from the hub, one folder per plugin id. + public string HubPluginsRoot { get; } + + // The last good copy of the hub's catalog, so installed plugins work offline. + public string HubCatalogFilePath { get; } + + // Which hub plugins are installed, and at which reviewed commit. + public string HubInstalledFilePath { get; } } diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs new file mode 100644 index 0000000..7111714 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs @@ -0,0 +1,20 @@ +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// Where the hub lives. Every address is built here from fixed parts plus an id and a commit that were already +// validated (PluginManifestReader.IsValidId, HubCatalogJson.IsCommit); nothing is ever taken from the catalog as a URL. +public static class HubAddresses +{ + public const string Repository = "CodySimonds65/FourFoldAccountManager-plugin-hub"; + + private const string ReleaseBase = "https://github.com/" + Repository + "/releases/download/catalog/"; + + public static Uri Catalog { get; } = new(ReleaseBase + "catalog.json"); + + public static string PackageName(string id, string commit) => $"{id}-{commit}.zip"; + + public static Uri Package(string id, string commit) => new(ReleaseBase + PackageName(id, commit)); + + // GitHub's zip of a repository at one commit. repository is https://github.com//. + public static Uri RepositoryArchive(Uri repository, string commit) => + new($"https://codeload.github.com{repository.AbsolutePath}/zip/{commit}"); +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalog.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalog.cs new file mode 100644 index 0000000..76aa9fe --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalog.cs @@ -0,0 +1,29 @@ +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +public sealed record HubCard(string Name, OverlayAddOnScope Scope); + +// One listed plugin: what the hub page shows, and the reviewed commit, size and hash of its package. +public sealed record HubPlugin( + string Id, + string Name, + string ShortLabel, + string Version, + string Author, + string Description, + IReadOnlyList Sites, + // Already the combined answer: the maintainers cleared it and the plugin's plugin.json asks for it. + bool AnySite, + IReadOnlyList Cards, + Uri Repository, + string Commit, + // yyyy-MM-dd, or empty when the catalog's value couldn't be read. + string Reviewed, + long Size, + string Sha256); + +// A plugin the maintainers pulled, and why. +public sealed record HubRemoval(string Id, string Reason); + +public sealed record HubCatalog(IReadOnlyList Plugins, IReadOnlyList Removed); diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs new file mode 100644 index 0000000..6485a5d --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs @@ -0,0 +1,212 @@ +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// Reads and writes the hub's catalog.json. Reading never throws: the file comes from the network, so an entry that +// breaks a rule is skipped, and a catalog that can't be used at all reads as null. +public static partial class HubCatalogJson +{ + public const int Version = 1; + + [GeneratedRegex(@"^[0-9a-f]{40}\z")] + private static partial Regex CommitRegex(); + + [GeneratedRegex(@"^[0-9a-f]{64}\z")] + private static partial Regex Sha256Regex(); + + [GeneratedRegex(@"^https://github\.com/[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}\z")] + private static partial Regex RepositoryRegex(); + + // A full commit id in lowercase: never a branch, a tag or a short id. + public static bool IsCommit([NotNullWhen(true)] string? value) => value is not null && CommitRegex().IsMatch(value); + + public static bool IsSha256([NotNullWhen(true)] string? value) => value is not null && Sha256Regex().IsMatch(value); + + // Exactly https://github.com//. + public static bool TryParseRepository(string? value, out Uri repository) + { + repository = null!; + if (value is null || !RepositoryRegex().IsMatch(value) || + value.EndsWith("/.", StringComparison.Ordinal) || value.EndsWith("/..", StringComparison.Ordinal)) + { + return false; + } + + repository = new Uri(value); + return true; + } + + public static HubCatalog? Parse(string? json) + { + if (json is null || json.Length > HubLimits.MaximumCatalogBytes) + { + return null; + } + + try + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("version", out var version) || version.ValueKind != JsonValueKind.Number || + !version.TryGetInt32(out var number) || number != Version) + { + return null; + } + + var removed = new List(); + if (root.TryGetProperty("removed", out var removedElement) && removedElement.ValueKind == JsonValueKind.Array) + { + foreach (var item in removedElement.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.Object || + PluginManifestReader.Text(item, "id") is not { } id || !PluginManifestReader.IsValidId(id) || + removed.Any(other => other.Id == id)) + { + continue; + } + + // A pull must never be lost over its wording: a reason that can't be shown is dropped, not the pull. + var reason = PluginManifestReader.Text(item, "reason") ?? string.Empty; + removed.Add(new HubRemoval( + id, reason.Length > 200 || PluginText.HasUnsafeCharacter(reason) ? string.Empty : reason)); + } + } + + var plugins = new List(); + if (root.TryGetProperty("plugins", out var pluginsElement) && pluginsElement.ValueKind == JsonValueKind.Array) + { + foreach (var item in pluginsElement.EnumerateArray().Take(HubLimits.MaximumCatalogPlugins)) + { + if (TryReadPlugin(item) is { } plugin && plugins.All(other => other.Id != plugin.Id) && + removed.All(other => other.Id != plugin.Id)) + { + plugins.Add(plugin); + } + } + } + + return new HubCatalog(Array.AsReadOnly(plugins.ToArray()), Array.AsReadOnly(removed.ToArray())); + } + catch (Exception exception) when (exception is JsonException or InvalidOperationException) + { + return null; + } + } + + public static string Write(HubCatalog catalog) => JsonSerializer.Serialize( + new + { + version = Version, + plugins = catalog.Plugins.Select(plugin => new + { + id = plugin.Id, + name = plugin.Name, + shortLabel = plugin.ShortLabel, + version = plugin.Version, + author = plugin.Author, + description = plugin.Description, + sites = plugin.Sites.Select(site => site.GetLeftPart(UriPartial.Authority)), + anySite = plugin.AnySite, + cards = plugin.Cards.Select(card => new + { + name = card.Name, + scope = card.Scope == OverlayAddOnScope.Account ? "account" : "global" + }), + repository = plugin.Repository.AbsoluteUri, + commit = plugin.Commit, + reviewed = plugin.Reviewed, + size = plugin.Size, + sha256 = plugin.Sha256 + }), + removed = catalog.Removed.Select(removal => new { id = removal.Id, reason = removal.Reason }) + }, + AtomicJsonFile.Options); + + private static HubPlugin? TryReadPlugin(JsonElement item) + { + try + { + if (item.ValueKind != JsonValueKind.Object) + { + return null; + } + + var id = PluginManifestReader.Text(item, "id"); + var version = PluginManifestReader.Text(item, "version"); + var commit = PluginManifestReader.Text(item, "commit"); + var sha256 = PluginManifestReader.Text(item, "sha256"); + var description = PluginManifestReader.Text(item, "description") ?? string.Empty; + if (!PluginManifestReader.IsValidId(id) || !PluginManifestReader.IsVersion(version) || + !PluginManifestReader.InRange(PluginManifestReader.Text(item, "name"), 1, 40, out var name) || + !PluginManifestReader.InRange(PluginManifestReader.Text(item, "shortLabel"), 1, 8, out var shortLabel) || + !PluginManifestReader.InRange(PluginManifestReader.Text(item, "author"), 1, 40, out var author) || + description.Length > 200 || + new[] { name, shortLabel, author, description }.Any(PluginText.HasUnsafeCharacter) || + !PluginManifestReader.TryReadSites(item, out var sites, out _) || + !TryParseRepository(PluginManifestReader.Text(item, "repository"), out var repository) || + !IsCommit(commit) || !IsSha256(sha256) || + !item.TryGetProperty("size", out var sizeElement) || sizeElement.ValueKind != JsonValueKind.Number || + !sizeElement.TryGetInt64(out var size) || size < 1 || size > HubLimits.MaximumPackageBytes || + !TryReadCards(item, out var cards)) + { + return null; + } + + var reviewed = PluginManifestReader.Text(item, "reviewed"); + return new HubPlugin( + id, name, shortLabel, version, author, description, sites, + item.TryGetProperty("anySite", out var anySite) && anySite.ValueKind == JsonValueKind.True, + cards, repository, commit, + DateOnly.TryParseExact(reviewed, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _) + ? reviewed! + : string.Empty, + size, sha256); + } + catch (Exception) + { + // A host name Uri refuses, say. One bad entry never costs the rest of the catalog. + return null; + } + } + + private static bool TryReadCards(JsonElement item, out IReadOnlyList cards) + { + cards = []; + if (!item.TryGetProperty("cards", out var element) || element.ValueKind == JsonValueKind.Null) + { + return true; + } + + if (element.ValueKind != JsonValueKind.Array || element.GetArrayLength() > 6) + { + return false; + } + + var result = new List(); + foreach (var card in element.EnumerateArray()) + { + if (card.ValueKind != JsonValueKind.Object) + { + return false; + } + + var scope = PluginManifestReader.Text(card, "scope"); + if (!PluginManifestReader.InRange(PluginManifestReader.Text(card, "name"), 1, 24, out var name) || + PluginText.HasUnsafeCharacter(name) || scope is not ("account" or "global")) + { + return false; + } + + result.Add(new HubCard(name, scope == "account" ? OverlayAddOnScope.Account : OverlayAddOnScope.Global)); + } + + cards = Array.AsReadOnly(result.ToArray()); + return true; + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs new file mode 100644 index 0000000..53f3830 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs @@ -0,0 +1,41 @@ +namespace FourFoldAccountManager.Core.Plugins.Hub; + +public static class HubHttp +{ + // Downloads a file of at most maximumBytes over https. Null when the request fails, ends anywhere but https, or + // the file is larger. The bytes are counted as they arrive, since a response needn't say how long it is. + public static async Task DownloadAsync( + HttpClient http, Uri uri, long maximumBytes, CancellationToken cancellationToken) + { + try + { + using var response = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + if (!response.IsSuccessStatusCode || + response.RequestMessage?.RequestUri?.Scheme != Uri.UriSchemeHttps || + response.Content.Headers.ContentLength > maximumBytes) + { + return null; + } + + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await stream.ReadAsync(chunk, cancellationToken)) > 0) + { + if (buffer.Length + read > maximumBytes) + { + return null; + } + + buffer.Write(chunk, 0, read); + } + + return buffer.ToArray(); + } + catch (Exception exception) when (exception is HttpRequestException or IOException or TaskCanceledException) + { + return null; + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubLimits.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubLimits.cs new file mode 100644 index 0000000..7a01a1c --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubLimits.cs @@ -0,0 +1,16 @@ +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// The size limits the hub tool enforces when it builds a package and the app enforces again when it installs one. +public static class HubLimits +{ + public const int MaximumCatalogBytes = 1024 * 1024; + + public const int MaximumCatalogPlugins = 2000; + + public const int MaximumPackageFiles = 500; + + public const long MaximumUnpackedBytes = 5 * 1024 * 1024; + + // A package is a zip of at most MaximumUnpackedBytes, so an honest one is never larger than this. + public const long MaximumPackageBytes = 6 * 1024 * 1024; +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index 7f0d4b2..3aea421 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using System.Diagnostics.CodeAnalysis; using System.Text.Json; using System.Text.RegularExpressions; using FourFoldAccountManager.Core.Overlay; @@ -32,6 +33,21 @@ public static partial class PluginManifestReader [GeneratedRegex("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$")] private static partial Regex DeviceNameRegex(); + // True for an id the reader accepts: the pattern, no Windows device name first, and a usable host label. + public static bool IsValidId([NotNullWhen(true)] string? id) + { + if (id is null || id.Length > 64 || !IdRegex().IsMatch(id) || DeviceNameRegex().IsMatch(id[..id.IndexOf('.')])) + { + return false; + } + + var label = id.Replace(".", "--"); + return label.Length <= 63 && !label.StartsWith("xn--", StringComparison.OrdinalIgnoreCase); + } + + public static bool IsVersion([NotNullWhen(true)] string? version) => + version is not null && VersionRegex().IsMatch(version); + // Reads and validates /plugin.json. Every rejection carries a reason an author can act on, and a file the // reader can't make sense of for any other reason (one that vanishes mid-read, a host name Uri refuses) is // rejected too: this never throws. @@ -81,18 +97,13 @@ private static PluginManifestResult ReadManifest(string folder) } var id = Text(root, "id"); - if (id is null || id.Length > 64 || !IdRegex().IsMatch(id)) - { - return Reject("The id must look like author.plugin-name (lowercase letters, digits, dots and dashes)."); - } - - if (DeviceNameRegex().IsMatch(id[..id.IndexOf('.')])) + if (id is not null && id.Length <= 64 && IdRegex().IsMatch(id) && + DeviceNameRegex().IsMatch(id[..id.IndexOf('.')])) { return Reject("The id can't start with a Windows device name such as nul, con or com1."); } - var label = id.Replace(".", "--"); - if (label.Length > 63 || label.StartsWith("xn--", StringComparison.OrdinalIgnoreCase)) + if (!IsValidId(id)) { return Reject("The id must look like author.plugin-name (lowercase letters, digits, dots and dashes)."); } @@ -108,7 +119,7 @@ private static PluginManifestResult ReadManifest(string folder) } var version = Text(root, "version"); - if (version is null || !VersionRegex().IsMatch(version)) + if (!IsVersion(version)) { return Reject("The version must look like 1.0.0."); } @@ -182,12 +193,12 @@ private static PluginManifestResult ReadManifest(string folder) private static PluginManifestResult Reject(string reason) => new(null, reason); - private static string? Text(JsonElement root, string property) => + internal static string? Text(JsonElement root, string property) => root.TryGetProperty(property, out var element) && element.ValueKind == JsonValueKind.String ? element.GetString()?.Trim() : null; - private static bool InRange(string? value, int minimum, int maximum, out string result) + internal static bool InRange(string? value, int minimum, int maximum, out string result) { result = value ?? string.Empty; return result.Length >= minimum && result.Length <= maximum; @@ -207,7 +218,7 @@ private static bool IsSmallPng(string path) BinaryPrimitives.ReadUInt32BigEndian(header[20..]) is >= 1 and <= 256; } - private static bool TryReadSites(JsonElement root, out IReadOnlyList sites, out string error) + internal static bool TryReadSites(JsonElement root, out IReadOnlyList sites, out string error) { sites = []; error = "Each site must look like https://example.com, with no path, and can't be an IP address or a local network name."; From 93e0719321a0e6cc6da71722e9f9d1816757b92c Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 15:25:20 -0500 Subject: [PATCH 02/22] feat: build, verify and safely unpack plugin packages --- .../Plugins/PluginPackageTests.cs | 107 ++++++++++++++++++ .../Plugins/Hub/PluginPackage.cs | 85 ++++++++++++++ .../Plugins/Hub/SafeArchive.cs | 76 +++++++++++++ .../Plugins/PluginFileServer.cs | 3 + 4 files changed, 271 insertions(+) create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs new file mode 100644 index 0000000..3b55727 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs @@ -0,0 +1,107 @@ +using System.IO.Compression; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginPackageTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "fourfold-package-" + Guid.NewGuid().ToString("N")); + + public PluginPackageTests() => Directory.CreateDirectory(_root); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + private static byte[] Zip(params (string Name, byte[] Content)[] entries) => Zip(null, entries); + + private static byte[] Zip(Action? configure, params (string Name, byte[] Content)[] entries) + { + using var buffer = new MemoryStream(); + using (var archive = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (var (name, content) in entries) + { + var entry = archive.CreateEntry(name); + configure?.Invoke(entry); + using var stream = entry.Open(); + stream.Write(content); + } + } + + return buffer.ToArray(); + } + + [Fact] + public void APackageThatDoesNotMatchTheCatalogIsRefused() + { + var package = Zip(("plugin.json", "{}"u8.ToArray())); + var hash = PluginPackage.Sha256(package); + + Assert.True(PluginPackage.Matches(package, package.Length, hash)); + Assert.False(PluginPackage.Matches(package, package.Length + 1, hash)); + Assert.False(PluginPackage.Matches(package, package.Length, new string('0', 64))); + Assert.False(PluginPackage.Matches([.. package, 0], package.Length, hash)); + } + + [Theory] + [InlineData("../evil.txt")] + [InlineData("a/../../evil.txt")] + [InlineData("/evil.txt")] + [InlineData("C:/evil.txt")] + [InlineData("./evil.txt")] + public void AnEntryThatEscapesTheFolderIsRefused(string name) + { + var target = Path.Combine(_root, "inner", "plugin"); + + Assert.Throws( + () => PluginPackage.Extract(Zip((name, new byte[] { 1 })), target)); + + Assert.Empty(Directory.EnumerateFiles(_root, "evil.txt", SearchOption.AllDirectories)); + } + + [Fact] + public void TooManyFilesOrTooMuchDataIsRefused() + { + var many = Enumerable.Range(0, HubLimits.MaximumPackageFiles + 1) + .Select(index => ($"file{index}.txt", new byte[] { 1 })) + .ToArray(); + Assert.Throws(() => PluginPackage.Extract(Zip(many), Path.Combine(_root, "many"))); + + // Zeros compress to almost nothing, so the package is small and only the unpacked size gives it away. + var large = Zip(("big.txt", new byte[HubLimits.MaximumUnpackedBytes + 1])); + Assert.True(large.Length < 100_000); + Assert.Throws(() => PluginPackage.Extract(large, Path.Combine(_root, "large"))); + } + + [Fact] + public void ALinkInAnArchiveIsRefused() + { + // A Unix symbolic link: file type 0xA in the mode bits a zip keeps in the high half of this field. + var package = Zip( + entry => entry.ExternalAttributes = unchecked((int)0xA1FF0000), ("link.txt", "target"u8.ToArray())); + + Assert.Throws(() => PluginPackage.Extract(package, Path.Combine(_root, "link"))); + } + + [Fact] + public void BuildLeavesOutFilesFourFoldDoesNotServeAndIsRepeatable() + { + var plugin = Path.Combine(_root, "plugin"); + Directory.CreateDirectory(Path.Combine(plugin, ".github")); + Directory.CreateDirectory(Path.Combine(plugin, "img")); + foreach (var name in new[] + { + "plugin.json", "index.html", "README.md", ".gitignore", "tool.exe", ".github/ci.yml", "img/a.png" + }) + { + File.WriteAllText(Path.Combine(plugin, name), name); + } + + var first = PluginPackage.Build(plugin); + var second = PluginPackage.Build(plugin); + + using var archive = new ZipArchive(new MemoryStream(first)); + Assert.Equal(["img/a.png", "index.html", "plugin.json"], archive.Entries.Select(entry => entry.FullName)); + Assert.Equal(first, second); + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs new file mode 100644 index 0000000..7902921 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs @@ -0,0 +1,85 @@ +using System.IO.Compression; +using System.Security.Cryptography; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// A plugin as the hub ships it: a zip of plugin.json and the files FourFold serves. +public static class PluginPackage +{ + private static readonly DateTimeOffset EntryTime = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); + + // Builds the package for the plugin in folder. README, LICENSE, dot-files and other file types are left out. The + // same files always give the same bytes. Throws InvalidDataException when the plugin is past the limits or + // contains a link. + public static byte[] Build(string folder) + { + var files = new List<(string Name, string Path)>(); + Collect(folder, string.Empty, files); + files.Sort((left, right) => string.CompareOrdinal(left.Name, right.Name)); + if (files.Count > HubLimits.MaximumPackageFiles) + { + throw new InvalidDataException($"A plugin can have at most {HubLimits.MaximumPackageFiles} files."); + } + + if (files.Sum(file => new FileInfo(file.Path).Length) > HubLimits.MaximumUnpackedBytes) + { + throw new InvalidDataException("A plugin's files can be at most 5 MB together."); + } + + using var buffer = new MemoryStream(); + using (var archive = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (var (name, path) in files) + { + var entry = archive.CreateEntry(name, CompressionLevel.Optimal); + entry.LastWriteTime = EntryTime; + using var output = entry.Open(); + output.Write(File.ReadAllBytes(path)); + } + } + + return buffer.ToArray(); + } + + public static string Sha256(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes)); + + // Whether a downloaded package is the one the catalog names. + public static bool Matches(byte[] package, long size, string sha256) => + package.LongLength == size && string.Equals(Sha256(package), sha256, StringComparison.Ordinal); + + // Unpacks a package into targetFolder. Throws InvalidDataException or IOException when it breaks a rule; the + // caller deletes the folder. + public static void Extract(byte[] package, string targetFolder) + { + using var stream = new MemoryStream(package); + SafeArchive.Extract( + stream, targetFolder, HubLimits.MaximumPackageFiles, HubLimits.MaximumUnpackedBytes, stripTopFolder: false); + } + + private static void Collect(string folder, string prefix, List<(string Name, string Path)> files) + { + foreach (var path in Directory.EnumerateFileSystemEntries(folder)) + { + var name = Path.GetFileName(path); + var attributes = File.GetAttributes(path); + if (attributes.HasFlag(FileAttributes.ReparsePoint)) + { + throw new InvalidDataException("A plugin can't contain links."); + } + + if (name.StartsWith('.')) + { + continue; + } + + if (attributes.HasFlag(FileAttributes.Directory)) + { + Collect(path, prefix + name + "/", files); + } + else if (prefix + name == "plugin.json" || PluginFileServer.IsServed(name)) + { + files.Add((prefix + name, path)); + } + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs new file mode 100644 index 0000000..1e442ca --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs @@ -0,0 +1,76 @@ +using System.IO.Compression; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// Unpacks a zip that came from the network. Anything that could write outside the target folder, or fill the disk, +// throws InvalidDataException before it is written. The caller deletes the target folder when this throws. +public static class SafeArchive +{ + // stripTopFolder drops each entry's first path part, for GitHub's repository zips, which wrap everything in one + // "-" folder. + public static void Extract(Stream zip, string targetFolder, int maximumFiles, long maximumBytes, bool stripTopFolder) + { + using var archive = new ZipArchive(zip, ZipArchiveMode.Read, leaveOpen: true); + Directory.CreateDirectory(targetFolder); + var files = 0; + long bytes = 0; + var buffer = new byte[81920]; + foreach (var entry in archive.Entries) + { + var name = entry.FullName; + if (name.EndsWith('/')) + { + continue; + } + + // A Unix symbolic link is stored as a file whose mode bits say "link". + if (((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000) + { + throw new InvalidDataException("The archive contains a link."); + } + + var parts = name.Split('/'); + if (name.Contains('\\') || name.Contains(':') || + parts.Any(part => part.Length == 0 || part is "." or "..")) + { + throw new InvalidDataException("The archive contains a path that isn't allowed."); + } + + if (stripTopFolder) + { + if (parts.Length == 1) + { + continue; + } + + parts = parts[1..]; + } + + if (!PluginPaths.TryResolveInside(targetFolder, string.Join('/', parts), out var path)) + { + throw new InvalidDataException("The archive contains a path that isn't allowed."); + } + + if (++files > maximumFiles) + { + throw new InvalidDataException("The archive has too many files."); + } + + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using var input = entry.Open(); + using var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write); + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + { + // Counted as it is written: the size an entry declares can lie. + bytes += read; + if (bytes > maximumBytes) + { + throw new InvalidDataException("The archive is too large."); + } + + output.Write(buffer, 0, read); + } + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs b/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs index f823c57..76232d7 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs @@ -21,6 +21,9 @@ public static class PluginFileServer [".woff2"] = "font/woff2" }; + // Whether a file of this name is a type FourFold serves; the hub packages only these. + public static bool IsServed(string path) => ContentTypes.ContainsKey(Path.GetExtension(path)); + public static bool TryResolve(PluginManifest manifest, string urlPath, out string filePath, out string contentType) { filePath = string.Empty; From 8cf4d27a80263ac67a65aad9342484fbfce6e1bc Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 15:29:51 -0500 Subject: [PATCH 03/22] feat: decide which hub plugins may run, and install, update and remove them on disk --- .../Plugins/HubPolicyTests.cs | 112 +++++++++++ .../Plugins/HubStoreTests.cs | 116 +++++++++++ .../Plugins/Hub/HubPolicy.cs | 102 ++++++++++ .../Plugins/Hub/HubStore.cs | 187 ++++++++++++++++++ .../Plugins/PluginLayoutPolicy.cs | 5 +- .../Plugins/PluginTrust.cs | 4 +- 6 files changed, 522 insertions(+), 4 deletions(-) create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs new file mode 100644 index 0000000..98c01c4 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs @@ -0,0 +1,112 @@ +using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubPolicyTests +{ + private const string CommitA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string CommitB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + + private static HubPlugin Listed(string id, string commit, bool anySite = false) => new( + id, "Name", "Short", "1.0.0", "author", "", [], anySite, [], + new Uri("https://github.com/author/repo"), commit, "2026-10-09", 100, new string('a', 64)); + + [Fact] + public void APulledOrUnlistedPluginNeverLoads() + { + var catalog = new HubCatalog( + [Listed("kept.plugin", CommitA)], + [new HubRemoval("pulled.plugin", "Sent data away."), new HubRemoval("quiet.plugin", "")]); + HubInstalled[] installed = + [ + new("kept.plugin", CommitA), new("pulled.plugin", CommitA), new("quiet.plugin", CommitA), + new("gone.plugin", CommitA) + ]; + + var loads = HubPolicy.Loads(catalog, installed, id => id); + + Assert.Equal("kept.plugin", Assert.Single(loads).Id); + Assert.Null(HubPolicy.PulledReason(catalog, "kept.plugin")); + Assert.Equal("Sent data away.", HubPolicy.PulledReason(catalog, "pulled.plugin")); + Assert.Equal(HubPolicy.RemovedReason, HubPolicy.PulledReason(catalog, "quiet.plugin")); + Assert.Equal(HubPolicy.UnlistedReason, HubPolicy.PulledReason(catalog, "gone.plugin")); + } + + [Fact] + public void AnyWebsiteNeedsTheCatalogsClearanceForTheInstalledCommit() + { + var catalog = new HubCatalog( + [ + Listed("cleared.plugin", CommitA, anySite: true), Listed("plain.plugin", CommitA), + Listed("updating.plugin", CommitB, anySite: true) + ], + []); + HubInstalled[] installed = + [new("cleared.plugin", CommitA), new("plain.plugin", CommitA), new("updating.plugin", CommitA)]; + + // The update that was cleared isn't installed yet, so the old code doesn't get the clearance early. + Assert.Equal( + [PluginTrust.Verified, PluginTrust.Standard, PluginTrust.Standard], + HubPolicy.Loads(catalog, installed, id => id).Select(load => load.Trust)); + Assert.Equal("updating.plugin", Assert.Single(HubPolicy.Updates(catalog, installed)).Id); + + // No catalog at all (a first start offline): everything installed still runs, with its declared sites only. + var offline = HubPolicy.Loads(null, installed, id => id); + Assert.Equal(3, offline.Count); + Assert.All(offline, load => Assert.Equal(PluginTrust.Standard, load.Trust)); + Assert.Empty(HubPolicy.Updates(null, installed)); + } + + [Fact] + public void ADevPluginReplacesTheHubPluginOfTheSameId() + { + HubLoad[] loads = + [ + new("cody.goal-tracker", "a", CommitA, PluginTrust.Standard), + new("other.plugin", "b", CommitA, PluginTrust.Standard) + ]; + + Assert.Equal( + "other.plugin", + Assert.Single(HubPolicy.Visible(loads, new HashSet { "cody.goal-tracker" })).Id); + Assert.Equal(2, HubPolicy.Visible(loads, new HashSet()).Count); + } + + [Fact] + public void UninstallingRemovesThePluginsCardsAndIdsFromSettings() + { + var accountId = Guid.NewGuid(); + var settings = PanelSettings.Default with + { + PluginOrder = ["xp-tracker", "cody.goal-tracker", "other.plugin"], + DisabledPlugins = ["cody.goal-tracker"], + OpenPlugin = "cody.goal-tracker", + OverlayCards = + [ + new OverlayCardPlacement(OverlayAddOnKind.Plugin, accountId, true, null) + { + PluginCard = "cody.goal-tracker/goal" + }, + // Another plugin whose id merely starts the same way keeps its card. + new OverlayCardPlacement(OverlayAddOnKind.Plugin, null, true, null) + { + PluginCard = "cody.goal-tracker-two/goal" + }, + new OverlayCardPlacement(OverlayAddOnKind.Xp, accountId, true, null) + ] + }; + + var next = HubPolicy.WithUninstalled(settings, "cody.goal-tracker"); + + Assert.Equal(["xp-tracker", "other.plugin"], next.PluginOrder); + Assert.Empty(next.DisabledPlugins); + Assert.Null(next.OpenPlugin); + Assert.Equal( + [null, "cody.goal-tracker-two/goal"], + next.OverlayCards.Select(card => card.PluginCard).OrderBy(card => card)); + Assert.Same(next, HubPolicy.WithUninstalled(next, "cody.goal-tracker")); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs new file mode 100644 index 0000000..b188485 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs @@ -0,0 +1,116 @@ +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubStoreTests : IDisposable +{ + private const string CommitA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string CommitB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "fourfold-hub-" + Guid.NewGuid().ToString("N")); + private readonly LocalDataPaths _paths; + private readonly HubStore _store; + + public HubStoreTests() + { + Directory.CreateDirectory(_root); + _paths = new LocalDataPaths(Path.Combine(_root, "data")); + _store = new HubStore(_paths); + } + + public void Dispose() => Directory.Delete(_root, recursive: true); + + // A real package for a small plugin, and the catalog record that names it. + private (HubPlugin Plugin, byte[] Package) Build(string id, string version, string commit, string page = "

v

") + { + var source = Path.Combine(_root, "source-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(source); + File.WriteAllText( + Path.Combine(source, "plugin.json"), + $$"""{"id":"{{id}}","name":"Goal tracker","shortLabel":"Goals","version":"{{version}}","author":"cody","apiVersion":1,"panel":"index.html"}"""); + File.WriteAllText(Path.Combine(source, "index.html"), page); + var package = PluginPackage.Build(source); + return ( + new HubPlugin( + id, "Goal tracker", "Goals", version, "cody", "", [], false, [], + new Uri("https://github.com/cody/goal-tracker"), commit, "2026-10-09", package.Length, + PluginPackage.Sha256(package)), + package); + } + + private async Task InstallAsync(HubPlugin plugin, byte[] package) + { + Assert.Null(_store.Stage(plugin, package, out var staging)); + await _store.CommitAsync(plugin, staging, CancellationToken.None); + } + + [Fact] + public async Task AFailedUpdateKeepsTheInstalledVersion() + { + var (first, firstPackage) = Build("cody.goal-tracker", "1.0.0", CommitA, "

one

"); + await InstallAsync(first, firstPackage); + + // A download that was tampered with never gets as far as a folder. + var (second, secondPackage) = Build("cody.goal-tracker", "1.1.0", CommitB, "

two

"); + secondPackage[^1] ^= 0xFF; + Assert.NotNull(_store.Stage(second, secondPackage, out _)); + + // A swap that fails halfway puts the old version back. + await Assert.ThrowsAnyAsync( + () => _store.CommitAsync(second, Path.Combine(_root, "missing"), CancellationToken.None)); + + Assert.Equal("

one

", File.ReadAllText(Path.Combine(_store.FolderOf("cody.goal-tracker"), "index.html"))); + Assert.Equal([new HubInstalled("cody.goal-tracker", CommitA)], _store.LoadInstalled()); + Assert.True(_store.IsIntact("cody.goal-tracker")); + Assert.Empty(Directory.GetDirectories(_paths.HubPluginsRoot, ".*")); + } + + [Fact] + public void APackageForADifferentPluginOrVersionIsRefused() + { + var (plugin, package) = Build("cody.goal-tracker", "1.0.0", CommitA); + + Assert.NotNull(_store.Stage(plugin with { Id = "other.plugin" }, package, out _)); + Assert.NotNull(_store.Stage(plugin with { Version = "9.9.9" }, package, out _)); + Assert.Empty(Directory.GetDirectories(_paths.HubPluginsRoot)); + + Assert.Null(_store.Stage(plugin, package, out var staging)); + Assert.True(File.Exists(Path.Combine(staging, "plugin.json"))); + } + + [Fact] + public async Task UninstallRemovesTheFilesTheSavedSettingsAndTheRecord() + { + var (goal, goalPackage) = Build("cody.goal-tracker", "1.0.0", CommitA); + var (other, otherPackage) = Build("other.plugin", "1.0.0", CommitA); + await InstallAsync(goal, goalPackage); + await InstallAsync(other, otherPackage); + Directory.CreateDirectory(_paths.PluginDataRoot); + var saved = Path.Combine(_paths.PluginDataRoot, "cody.goal-tracker.json"); + File.WriteAllText(saved, "{}"); + + await _store.UninstallAsync("cody.goal-tracker", CancellationToken.None); + + Assert.False(Directory.Exists(_store.FolderOf("cody.goal-tracker"))); + Assert.False(File.Exists(saved)); + Assert.Equal([new HubInstalled("other.plugin", CommitA)], _store.LoadInstalled()); + Assert.True(_store.IsIntact("other.plugin")); + } + + [Fact] + public async Task ALockedRecordIsNotReadAsNothingInstalled() + { + var (plugin, package) = Build("cody.goal-tracker", "1.0.0", CommitA); + await InstallAsync(plugin, package); + + using (new FileStream(_paths.HubInstalledFilePath, FileMode.Open, FileAccess.Read, FileShare.None)) + { + // Reading it as empty would make the next install write a record that forgets this plugin. + Assert.ThrowsAny(() => _store.LoadInstalled()); + } + + Assert.Equal([new HubInstalled("cody.goal-tracker", CommitA)], _store.LoadInstalled()); + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs new file mode 100644 index 0000000..685f1b4 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs @@ -0,0 +1,102 @@ +using FourFoldAccountManager.Core.Models; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// A plugin installed from the hub, at the commit that was reviewed. +public sealed record HubInstalled(string Id, string Commit); + +// An installed plugin that may run, and with what trust. +public sealed record HubLoad(string Id, string Folder, string Commit, PluginTrust Trust); + +// The decisions about hub plugins that need no files and no network. +public static class HubPolicy +{ + public const string UnlistedReason = "This plugin is no longer on the hub."; + + public const string RemovedReason = "This plugin was removed from the hub."; + + // Why an installed plugin may not run, or null when it may. A plugin the catalog doesn't list at all counts as + // pulled, so a mistake on the hub's side stops a plugin and never leaves an unlisted one running. With no catalog + // yet, nothing is known to be pulled. + public static string? PulledReason(HubCatalog? catalog, string id) + { + if (catalog is null || catalog.Plugins.Any(plugin => plugin.Id == id)) + { + return null; + } + + var removal = catalog.Removed.FirstOrDefault(removed => removed.Id == id); + return removal is null ? UnlistedReason : removal.Reason.Length > 0 ? removal.Reason : RemovedReason; + } + + // The installed plugins that may run. A plugin gets any-website trust only when the catalog clears the exact + // commit that is installed: with no catalog, or while a cleared update is still to be installed, it gets its + // declared sites only. + public static IReadOnlyList Loads( + HubCatalog? catalog, IReadOnlyList installed, Func folderOf) => + installed + .Where(plugin => PulledReason(catalog, plugin.Id) is null) + .Select(plugin => + { + var listed = catalog?.Plugins.FirstOrDefault(candidate => candidate.Id == plugin.Id); + return new HubLoad( + plugin.Id, folderOf(plugin.Id), plugin.Commit, + listed is { AnySite: true } && listed.Commit == plugin.Commit + ? PluginTrust.Verified + : PluginTrust.Standard); + }) + .ToArray(); + + // While developer mode has a plugin with the same id in the dev folder, that copy runs instead of the hub's. + public static IReadOnlyList Visible(IReadOnlyList loads, IReadOnlySet devIds) => + loads.Where(load => !devIds.Contains(load.Id)).ToArray(); + + // Listed plugins whose reviewed commit differs from the one installed. + public static IReadOnlyList Updates(HubCatalog? catalog, IReadOnlyList installed) => + catalog is null + ? [] + : catalog.Plugins + .Where(plugin => installed.Any(other => other.Id == plugin.Id && other.Commit != plugin.Commit)) + .ToArray(); + + // Forgets an uninstalled plugin in saved settings: its cards, its place in the strip, and its switch. Returns the + // same instance when there was nothing to forget, so callers can skip the save. + public static PanelSettings WithUninstalled(PanelSettings settings, string id) + { + var cardPrefix = id + "/"; + var cards = settings.OverlayCards + .Where(card => card.PluginCard?.StartsWith(cardPrefix, StringComparison.Ordinal) != true) + .ToArray(); + var order = settings.PluginOrder.Where(other => other != id).ToArray(); + var disabled = settings.DisabledPlugins.Where(other => other != id).ToArray(); + if (cards.Length == settings.OverlayCards.Count && order.Length == settings.PluginOrder.Count && + disabled.Length == settings.DisabledPlugins.Count && settings.OpenPlugin != id) + { + return settings; + } + + return settings with + { + OverlayCards = Array.AsReadOnly(cards), + PluginOrder = Array.AsReadOnly(order), + DisabledPlugins = Array.AsReadOnly(disabled), + OpenPlugin = settings.OpenPlugin == id ? null : settings.OpenPlugin + }; + } + + // The hub page's list: installed plugins first, then by name. An empty query matches everything. + public static IReadOnlyList Search( + IReadOnlyList plugins, string? query, IReadOnlySet installed) + { + var text = query?.Trim() ?? string.Empty; + return plugins + .Where(plugin => text.Length == 0 || + plugin.Name.Contains(text, StringComparison.OrdinalIgnoreCase) || + plugin.Author.Contains(text, StringComparison.OrdinalIgnoreCase) || + plugin.Description.Contains(text, StringComparison.OrdinalIgnoreCase)) + .OrderBy(plugin => installed.Contains(plugin.Id) ? 0 : 1) + .ThenBy(plugin => plugin.Name, StringComparer.OrdinalIgnoreCase) + .ThenBy(plugin => plugin.Id, StringComparer.Ordinal) + .ToArray(); + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs new file mode 100644 index 0000000..0f17cb6 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs @@ -0,0 +1,187 @@ +using System.Text.Json; +using FourFoldAccountManager.Core.Data; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// What the hub keeps on disk: each installed plugin's folder, the record of what is installed, and the last good +// catalog. Nothing here talks to the network or to a running plugin. +public sealed class HubStore(LocalDataPaths paths) +{ + public string FolderOf(string id) => Path.Combine(paths.HubPluginsRoot, id); + + // False when a crash mid-install left the record without its files; the next hub check installs it again. + public bool IsIntact(string id) => File.Exists(Path.Combine(FolderOf(id), "plugin.json")); + + // No file means nothing is installed, and a file that isn't JSON reads the same way. A file that exists but can't + // be opened throws, so a locked record is never mistaken for "nothing installed" and then written over. + public IReadOnlyList LoadInstalled() + { + if (!File.Exists(paths.HubInstalledFilePath)) + { + return []; + } + + List? records; + try + { + records = JsonSerializer.Deserialize>( + File.ReadAllText(paths.HubInstalledFilePath), AtomicJsonFile.Options); + } + catch (JsonException) + { + return []; + } + + return (records ?? []) + .Where(record => record is not null && PluginManifestReader.IsValidId(record.Id) && + HubCatalogJson.IsCommit(record.Commit)) + .Select(record => record!) + .DistinctBy(record => record.Id) + .ToArray(); + } + + public HubCatalog? LoadCatalog() + { + try + { + return File.Exists(paths.HubCatalogFilePath) + ? HubCatalogJson.Parse(File.ReadAllText(paths.HubCatalogFilePath)) + : null; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + } + + public async Task SaveCatalogAsync(string json, CancellationToken cancellationToken) + { + Directory.CreateDirectory(Path.GetDirectoryName(paths.HubCatalogFilePath)!); + var temporary = paths.HubCatalogFilePath + ".tmp"; + await File.WriteAllTextAsync(temporary, json, cancellationToken); + File.Move(temporary, paths.HubCatalogFilePath, overwrite: true); + } + + // Checks a downloaded package and unpacks it into a staging folder beside the installed plugins. Returns the + // reason it was refused, or null. Nothing that is installed is touched. + public string? Stage(HubPlugin plugin, byte[] package, out string stagingFolder) + { + stagingFolder = Path.Combine(paths.HubPluginsRoot, ".staging-" + Guid.NewGuid().ToString("N")); + if (!PluginPackage.Matches(package, plugin.Size, plugin.Sha256)) + { + return "The download didn't match the hub's record."; + } + + try + { + PluginPackage.Extract(package, stagingFolder); + } + catch (Exception exception) when (exception is InvalidDataException or IOException or UnauthorizedAccessException) + { + TryDeleteFolder(stagingFolder); + return "The package isn't valid."; + } + + // The hash matched, but it must also be the plugin the user asked for. + var manifest = PluginManifestReader.Read(stagingFolder).Manifest; + if (manifest is null || manifest.Id != plugin.Id || manifest.Version != plugin.Version) + { + TryDeleteFolder(stagingFolder); + return "The package isn't the plugin the hub listed."; + } + + return null; + } + + // Puts a staged plugin in place and records it. If the swap or the record fails, the version that was installed + // before is back in place when this throws. + public async Task CommitAsync(HubPlugin plugin, string stagingFolder, CancellationToken cancellationToken) + { + // Read before anything moves: a record that can't be read stops the install here. + var records = LoadInstalled(); + var target = FolderOf(plugin.Id); + var previous = Path.Combine(paths.HubPluginsRoot, ".old-" + Guid.NewGuid().ToString("N")); + var hadPrevious = Directory.Exists(target); + if (hadPrevious) + { + Directory.Move(target, previous); + } + + try + { + Directory.Move(stagingFolder, target); + try + { + await SaveInstalledAsync( + records.Where(record => record.Id != plugin.Id) + .Append(new HubInstalled(plugin.Id, plugin.Commit)) + .ToArray(), + cancellationToken); + } + catch + { + Directory.Move(target, stagingFolder); + throw; + } + } + catch + { + if (hadPrevious) + { + Directory.Move(previous, target); + } + + throw; + } + + TryDeleteFolder(previous); + } + + // The record goes first, so a crash partway leaves files nothing points at, never a record without its files. + public async Task UninstallAsync(string id, CancellationToken cancellationToken) + { + await SaveInstalledAsync(LoadInstalled().Where(record => record.Id != id).ToArray(), cancellationToken); + if (Directory.Exists(FolderOf(id))) + { + Directory.Delete(FolderOf(id), recursive: true); + } + + var saved = Path.Combine(paths.PluginDataRoot, id + ".json"); + if (File.Exists(saved)) + { + File.Delete(saved); + } + } + + // Removes folders a crash left behind mid-install. An installed plugin's folder never starts with a dot. + public void CleanUp() + { + if (!Directory.Exists(paths.HubPluginsRoot)) + { + return; + } + + foreach (var folder in Directory.GetDirectories(paths.HubPluginsRoot, ".*")) + { + TryDeleteFolder(folder); + } + } + + private Task SaveInstalledAsync(IReadOnlyList records, CancellationToken cancellationToken) => + AtomicJsonFile.WriteAsync(paths.HubInstalledFilePath, records, cancellationToken); + + private static void TryDeleteFolder(string folder) + { + try + { + if (Directory.Exists(folder)) + { + Directory.Delete(folder, recursive: true); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // CleanUp tries again at the next start. + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs index 6a582b0..7df82cb 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs @@ -4,7 +4,8 @@ namespace FourFoldAccountManager.Core.Plugins; public static class PluginLayoutPolicy { - public const int MaximumIds = 64; + // Room for the built-in plugins plus every hub plugin a user is likely to install. + public const int MaximumIds = 256; // Known plugins in saved order; a known plugin missing from the saved order goes last, in the order given. public static IReadOnlyList Ordered(PanelSettings settings, IReadOnlyList known) @@ -92,7 +93,7 @@ public static PanelSettings WithOpened(PanelSettings settings, string id) => public static PanelSettings WithClosed(PanelSettings settings) => settings.PluginsSidebarExpanded ? settings with { PluginsSidebarExpanded = false } : settings; - // Load-time cleanup: blank ids and repeats go (the first wins), and at most 64 ids stay. + // Load-time cleanup: blank ids and repeats go (the first wins), and at most 256 ids stay. public static IReadOnlyList CleanIds(IReadOnlyList? ids) => Array.AsReadOnly((ids ?? Array.Empty()) .Where(id => !string.IsNullOrWhiteSpace(id)) diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs b/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs index f877690..0544d79 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs @@ -2,12 +2,12 @@ namespace FourFoldAccountManager.Core.Plugins; public enum PluginTrust { - // Declared sites only; anySite in the manifest is ignored. + // A hub plugin without that clearance: declared sites only; anySite in the manifest is ignored. Standard, // Loaded from the dev plugins folder: the manifest is honored as written. Developer, - // Reviewed and signed by FourFold's maintainers (part 3): anySite is honored. + // Listed on the hub and cleared by the maintainers for any website: anySite is honored. Verified } From 2b24a923874a5b86a455905770c96fddf1e85a5e Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 15:35:18 -0500 Subject: [PATCH 04/22] feat: add the hub tool that checks a submission and builds the catalog --- FourFoldAccountManager.sln | 15 ++ .../Plugins/HubSubmissionTests.cs | 127 ++++++++++++++ .../Plugins/Hub/HubEntry.cs | 96 ++++++++++ .../Plugins/Hub/HubSubmission.cs | 166 ++++++++++++++++++ .../Plugins/PluginNetworkPolicy.cs | 3 + .../FourFoldAccountManager.HubTool.csproj | 15 ++ src/FourFoldAccountManager.HubTool/Program.cs | 151 ++++++++++++++++ 7 files changed, 573 insertions(+) create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/HubEntry.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs create mode 100644 src/FourFoldAccountManager.HubTool/FourFoldAccountManager.HubTool.csproj create mode 100644 src/FourFoldAccountManager.HubTool/Program.cs diff --git a/FourFoldAccountManager.sln b/FourFoldAccountManager.sln index ed69279..fca42bf 100644 --- a/FourFoldAccountManager.sln +++ b/FourFoldAccountManager.sln @@ -17,6 +17,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FourFoldAccountManager.Lead EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FourFoldAccountManager.Desktop.Tests", "src\FourFoldAccountManager.Desktop.Tests\FourFoldAccountManager.Desktop.Tests.csproj", "{B1001A02-C503-4CC9-9BF3-473EE45297D0}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FourFoldAccountManager.HubTool", "src\FourFoldAccountManager.HubTool\FourFoldAccountManager.HubTool.csproj", "{4C1F820F-039F-4288-9458-F78626241946}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -99,6 +101,18 @@ Global {B1001A02-C503-4CC9-9BF3-473EE45297D0}.Release|x64.Build.0 = Release|Any CPU {B1001A02-C503-4CC9-9BF3-473EE45297D0}.Release|x86.ActiveCfg = Release|Any CPU {B1001A02-C503-4CC9-9BF3-473EE45297D0}.Release|x86.Build.0 = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|x64.ActiveCfg = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|x64.Build.0 = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|x86.ActiveCfg = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|x86.Build.0 = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|Any CPU.Build.0 = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|x64.ActiveCfg = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|x64.Build.0 = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|x86.ActiveCfg = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -110,5 +124,6 @@ Global {8DC5AD11-A59F-445F-84AC-D10C5F7A9C17} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {B3971592-86AD-488E-85E2-8C9F87A41670} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {B1001A02-C503-4CC9-9BF3-473EE45297D0} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {4C1F820F-039F-4288-9458-F78626241946} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} EndGlobalSection EndGlobal diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs new file mode 100644 index 0000000..2923db3 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs @@ -0,0 +1,127 @@ +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubSubmissionTests : IDisposable +{ + private const string CommitA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string CommitB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + private const string GoodEntry = + "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\"}"; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "fourfold-submit-" + Guid.NewGuid().ToString("N")); + + public HubSubmissionTests() => Directory.CreateDirectory(_root); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + private string Repository(string id, string version, bool anySite = false, string folder = "") + { + var root = Path.Combine(_root, "repo-" + Guid.NewGuid().ToString("N")); + var plugin = Path.Combine(root, folder); + Directory.CreateDirectory(plugin); + File.WriteAllText( + Path.Combine(plugin, "plugin.json"), + $$"""{"id":"{{id}}","name":"Goal tracker","shortLabel":"Goals","version":"{{version}}","author":"cody","apiVersion":1,"panel":"index.html","anySite":{{(anySite ? "true" : "false")}}}"""); + File.WriteAllText(Path.Combine(plugin, "index.html"), "

hello

"); + File.WriteAllText(Path.Combine(root, "README.md"), "not shipped"); + return root; + } + + private static HubEntry Entry(string commit = CommitA, string path = "", bool anySite = false) => + new("cody.goal-tracker", new Uri("https://github.com/cody/goal-tracker"), commit, path, anySite); + + [Theory] + [InlineData("Not An Id.json", GoodEntry)] + [InlineData("cody.goal-tracker.txt", GoodEntry)] + [InlineData("cody.goal-tracker.json", "not json")] + [InlineData("cody.goal-tracker.json", "[]")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://gitlab.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"main\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"aaaaaaa\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":\"../other\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":\"/abs\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"anySite\":\"yes\"}")] + public void AnEntryThatBreaksARuleIsRejected(string fileName, string json) + { + var (entry, error) = HubEntryReader.Read(fileName, json); + + Assert.Null(entry); + Assert.False(string.IsNullOrEmpty(error)); + } + + [Fact] + public void AGoodEntryIsRead() + { + var (entry, error) = HubEntryReader.Read( + "cody.goal-tracker.json", + "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + + "\",\"path\":\"samples/goal-tracker\",\"anySite\":true}"); + + Assert.Null(error); + Assert.Equal(Entry(path: "samples/goal-tracker", anySite: true), entry); + } + + [Fact] + public void ASubmissionMustMatchItsEntry() + { + // The plugin.json names another plugin than the file is named for. + Assert.NotNull(HubSubmission.Check(Entry(), Repository("other.plugin", "1.0.0"), null, "2026-10-09").Error); + // The entry clears any website, but the plugin never asked for it. + Assert.NotNull( + HubSubmission.Check(Entry(anySite: true), Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09").Error); + // The folder the entry names isn't in the repository. + Assert.NotNull( + HubSubmission.Check(Entry(path: "plugin"), Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09").Error); + + var good = HubSubmission.Check( + Entry(path: "plugin", anySite: true), Repository("cody.goal-tracker", "1.0.0", anySite: true, folder: "plugin"), + null, "2026-10-09"); + + Assert.Null(good.Error); + Assert.True(good.Plugin!.AnySite); + Assert.Equal("2026-10-09", good.Plugin.Reviewed); + Assert.True(PluginPackage.Matches(good.Package!, good.Plugin.Size, good.Plugin.Sha256)); + } + + [Fact] + public void AnUpdateMustRaiseTheVersion() + { + var listed = HubSubmission.Check(Entry(), Repository("cody.goal-tracker", "1.2.0"), null, "2026-10-01").Plugin!; + var current = new HubCatalog([listed], []); + + Assert.NotNull( + HubSubmission.Check(Entry(CommitB), Repository("cody.goal-tracker", "1.2.0"), current, "2026-10-09").Error); + Assert.NotNull( + HubSubmission.Check(Entry(CommitB), Repository("cody.goal-tracker", "1.1.9"), current, "2026-10-09").Error); + Assert.Null( + HubSubmission.Check(Entry(CommitB), Repository("cody.goal-tracker", "1.10.0"), current, "2026-10-09").Error); + } + + [Fact] + public void AnUnchangedEntryKeepsItsRecordWithoutBeingFetchedAgain() + { + var listed = HubSubmission.Check(Entry(), Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-01").Plugin!; + + // The author's repository may be gone by now; an unchanged entry must not need it. + var build = HubSubmission.BuildCatalog( + [Entry()], [], new HubCatalog([listed], []), _ => throw new InvalidOperationException("fetched again")); + + Assert.Empty(build.Errors); + Assert.Empty(build.Packages); + Assert.Same(listed, Assert.Single(build.Catalog!.Plugins)); + } + + [Fact] + public void APluginCannotBeBothListedAndRemoved() + { + var build = HubSubmission.BuildCatalog( + [Entry()], [new HubRemoval("cody.goal-tracker", "Pulled.")], null, + entry => HubSubmission.Check(entry, Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09")); + + Assert.Null(build.Catalog); + Assert.Single(build.Errors); + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubEntry.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubEntry.cs new file mode 100644 index 0000000..4d3b364 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubEntry.cs @@ -0,0 +1,96 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// One file in the hub repository's plugins folder: which repository and commit to list, and whether the maintainers +// cleared the plugin for any website. The plugin's id is the file's name. +public sealed record HubEntry(string Id, Uri Repository, string Commit, string Path, bool AnySite); + +public static partial class HubEntryReader +{ + [GeneratedRegex(@"^[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*\z")] + private static partial Regex PathRegex(); + + // fileName is the entry's file name, ".json". Every rejection carries a reason an author can act on. + public static (HubEntry? Entry, string? Error) Read(string fileName, string json) + { + var id = fileName.EndsWith(".json", StringComparison.Ordinal) ? fileName[..^5] : null; + if (!PluginManifestReader.IsValidId(id)) + { + return (null, "The file must be named .json, for example cody.goal-tracker.json."); + } + + try + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return (null, "The entry must be a JSON object."); + } + + if (!HubCatalogJson.TryParseRepository(PluginManifestReader.Text(root, "repository"), out var repository)) + { + return (null, "\"repository\" must look like https://github.com/owner/repo."); + } + + var commit = PluginManifestReader.Text(root, "commit"); + if (!HubCatalogJson.IsCommit(commit)) + { + return (null, "\"commit\" must be a full 40-character commit in lowercase, not a branch or a tag."); + } + + var path = PluginManifestReader.Text(root, "path") ?? string.Empty; + if (path.Length > 0 && (!PathRegex().IsMatch(path) || path.Split('/').Any(part => part is "." or ".."))) + { + return (null, "\"path\" must be a folder inside the repository, written with forward slashes."); + } + + var hasAnySite = root.TryGetProperty("anySite", out var anySite); + if (hasAnySite && anySite.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) + { + return (null, "\"anySite\" must be true or false."); + } + + return (new HubEntry(id, repository, commit, path, hasAnySite && anySite.ValueKind == JsonValueKind.True), null); + } + catch (JsonException) + { + return (null, "The entry isn't valid JSON."); + } + } + + public static (IReadOnlyList? Removed, string? Error) ReadRemoved(string json) + { + try + { + using var document = JsonDocument.Parse(json); + if (document.RootElement.ValueKind != JsonValueKind.Array) + { + return (null, "removed.json must be a list."); + } + + var result = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + var isObject = item.ValueKind == JsonValueKind.Object; + var id = isObject ? PluginManifestReader.Text(item, "id") : null; + var reason = isObject ? PluginManifestReader.Text(item, "reason") : null; + if (!PluginManifestReader.IsValidId(id) || reason is null || reason.Length is 0 or > 200 || + PluginText.HasUnsafeCharacter(reason) || result.Any(other => other.Id == id)) + { + return (null, "Each removed.json line needs a plugin \"id\" (once) and a \"reason\" of 1 to 200 characters."); + } + + result.Add(new HubRemoval(id, reason)); + } + + return (result, null); + } + catch (JsonException) + { + return (null, "removed.json isn't valid JSON."); + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs new file mode 100644 index 0000000..a27a3b5 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs @@ -0,0 +1,166 @@ +using System.IO.Compression; +using System.Text; +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +public sealed record HubCheckResult(string? Error, HubPlugin? Plugin, byte[]? Package); + +// The catalog a publish run would upload, the packages that are new in it, and what stopped it. +public sealed record HubBuild( + HubCatalog? Catalog, IReadOnlyList<(string Name, byte[] Bytes)> Packages, IReadOnlyList Errors); + +// What the hub repository's workflows check before a plugin is listed. The plugin's code is never run. +public static class HubSubmission +{ + // Checks one entry against its repository, unpacked at the entry's commit in repositoryFolder, and builds its + // package. today is the review date recorded for it (yyyy-MM-dd). + public static HubCheckResult Check(HubEntry entry, string repositoryFolder, HubCatalog? current, string today) + { + var folder = repositoryFolder; + if (entry.Path.Length > 0 && + (!PluginPaths.TryResolveInside(repositoryFolder, entry.Path, out folder) || !Directory.Exists(folder))) + { + return Fail($"The repository has no folder \"{entry.Path}\" at that commit."); + } + + var read = PluginManifestReader.Read(folder); + if (read.Manifest is not { } manifest) + { + return Fail(read.Error ?? "plugin.json couldn't be read."); + } + + if (manifest.Id != entry.Id) + { + return Fail($"The file is named for \"{entry.Id}\", but plugin.json says \"{manifest.Id}\"."); + } + + if (entry.AnySite && !manifest.AnySite) + { + return Fail("\"anySite\" is true in the entry, but the plugin's plugin.json doesn't ask for it."); + } + + var listed = current?.Plugins.FirstOrDefault(plugin => plugin.Id == entry.Id); + if (listed is not null && listed.Commit != entry.Commit && !IsNewer(manifest.Version, listed.Version)) + { + return Fail( + $"An update must raise the version: the hub lists {listed.Version} and plugin.json says {manifest.Version}."); + } + + byte[] package; + try + { + package = PluginPackage.Build(folder); + } + catch (InvalidDataException exception) + { + return Fail(exception.Message); + } + + if (package.LongLength > HubLimits.MaximumPackageBytes) + { + return Fail("The package is too large."); + } + + return new HubCheckResult( + null, + new HubPlugin( + manifest.Id, manifest.Name, manifest.ShortLabel, manifest.Version, manifest.Author, manifest.Description, + manifest.Sites, entry.AnySite && manifest.AnySite, + manifest.Cards.Select(card => new HubCard(card.Name, card.Scope)).ToArray(), + entry.Repository, entry.Commit, today, package.LongLength, PluginPackage.Sha256(package)), + package); + + static HubCheckResult Fail(string reason) => new(reason, null, null); + } + + // Builds the catalog for every entry. An entry whose commit and clearance are unchanged keeps its record and its + // published package, so a listed plugin survives its author deleting the repository; only new and changed entries + // go through check. One failure means no catalog. + public static HubBuild BuildCatalog( + IReadOnlyList entries, + IReadOnlyList removed, + HubCatalog? current, + Func check) + { + var errors = new List(); + var plugins = new List(); + var packages = new List<(string Name, byte[] Bytes)>(); + foreach (var entry in entries.OrderBy(entry => entry.Id, StringComparer.Ordinal)) + { + if (removed.Any(removal => removal.Id == entry.Id)) + { + errors.Add($"{entry.Id}: a plugin can't be both listed and in removed.json."); + continue; + } + + if (current?.Plugins.FirstOrDefault(plugin => plugin.Id == entry.Id) is { } listed && + listed.Commit == entry.Commit && listed.AnySite == entry.AnySite) + { + plugins.Add(listed); + continue; + } + + var result = check(entry); + if (result.Error is not null) + { + errors.Add($"{entry.Id}: {result.Error}"); + continue; + } + + plugins.Add(result.Plugin!); + packages.Add((HubAddresses.PackageName(entry.Id, entry.Commit), result.Package!)); + } + + return new HubBuild(errors.Count == 0 ? new HubCatalog(plugins, removed) : null, packages, errors); + } + + // What a reviewer needs to see for one entry, as Markdown for the check's summary page. + public static string Summary( + string fileName, HubEntry? entry, string? error, HubPlugin? plugin, byte[]? package, HubCatalog? current) + { + var text = new StringBuilder().AppendLine($"### {fileName}").AppendLine(); + if (error is not null || entry is null || plugin is null || package is null) + { + return text.AppendLine($"**Not accepted:** {error}").ToString(); + } + + var contact = plugin.AnySite ? "any website (cleared by this entry)" + : plugin.Sites.Count == 0 ? "no websites" + : string.Join(", ", plugin.Sites.Select(PluginNetworkPolicy.SiteLabel)); + var cards = plugin.Cards.Count == 0 + ? "none" + : string.Join(", ", plugin.Cards.Select(card => + $"{Cell(card.Name)} ({(card.Scope == OverlayAddOnScope.Account ? "per account" : "global")})")); + text.AppendLine("| | |") + .AppendLine("|---|---|") + .AppendLine($"| Name | {Cell(plugin.Name)} ({Cell(plugin.ShortLabel)}) |") + .AppendLine($"| Author | {Cell(plugin.Author)} |") + .AppendLine($"| Version | {plugin.Version} |") + .AppendLine($"| Description | {Cell(plugin.Description)} |") + .AppendLine($"| Can contact | {contact} |") + .AppendLine($"| Cards | {cards} |") + .AppendLine($"| Package | {plugin.Size} bytes |") + .AppendLine(); + + var listed = current?.Plugins.FirstOrDefault(other => other.Id == plugin.Id); + var repository = entry.Repository.AbsoluteUri; + text.AppendLine(listed is null + ? $"New plugin. Review the code: {repository}/tree/{entry.Commit}{(entry.Path.Length > 0 ? "/" + entry.Path : "")}" + : $"Update from {listed.Version}. Review the changes: {repository}/compare/{listed.Commit}...{entry.Commit}"); + text.AppendLine().AppendLine("Files in the package:").AppendLine(); + using var archive = new ZipArchive(new MemoryStream(package)); + foreach (var file in archive.Entries) + { + text.AppendLine($"- `{file.FullName}` ({file.Length} bytes)"); + } + + return text.ToString(); + + // Plugin text goes into a Markdown table, so a pipe or a line break in it must not break the row. + static string Cell(string value) => value.Replace("|", "\\|").Replace("\r", " ").Replace("\n", " "); + } + + private static bool IsNewer(string version, string than) => + System.Version.TryParse(version, out var left) && System.Version.TryParse(than, out var right) && left > right; +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs index 8c53e73..268de4f 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs @@ -27,6 +27,9 @@ public static bool IsPluginHost(string host) name.EndsWith("." + OriginSuffix, StringComparison.OrdinalIgnoreCase); } + // How a site is shown to a user or a reviewer: its real (xn--) host name, with the port when it isn't 443. + public static string SiteLabel(Uri site) => site.IsDefaultPort ? site.IdnHost : $"{site.IdnHost}:{site.Port}"; + public static bool AllowsAnySite(PluginManifest manifest, PluginTrust trust) => manifest.AnySite && trust is (PluginTrust.Developer or PluginTrust.Verified); diff --git a/src/FourFoldAccountManager.HubTool/FourFoldAccountManager.HubTool.csproj b/src/FourFoldAccountManager.HubTool/FourFoldAccountManager.HubTool.csproj new file mode 100644 index 0000000..ce87d9d --- /dev/null +++ b/src/FourFoldAccountManager.HubTool/FourFoldAccountManager.HubTool.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0 + enable + enable + false + + + + + + + diff --git a/src/FourFoldAccountManager.HubTool/Program.cs b/src/FourFoldAccountManager.HubTool/Program.cs new file mode 100644 index 0000000..7d76f37 --- /dev/null +++ b/src/FourFoldAccountManager.HubTool/Program.cs @@ -0,0 +1,151 @@ +using System.Globalization; +using FourFoldAccountManager.Core.Plugins.Hub; + +// The plugin hub's command-line tool. The hub repository's workflows run it; it never runs a plugin's code. +// check --hub --entry plugins/.json [--catalog ] [--work ] [--summary ] [--source ] +// publish --hub --out [--catalog ] [--work ] [--source ] +// --catalog is the catalog that is live now, when there is one. --source uses a local folder as the repository +// instead of downloading it, for trying the tool by hand. +const long MaximumRepositoryBytes = 50L * 1024 * 1024; + +if (args.Length == 0 || args[0] is not ("check" or "publish") || args.Length % 2 == 0) +{ + Console.Error.WriteLine("Usage: check --hub --entry [...] | publish --hub --out [...]"); + return 2; +} + +var options = new Dictionary(StringComparer.Ordinal); +for (var index = 1; index + 1 < args.Length; index += 2) +{ + options[args[index]] = args[index + 1]; +} + +var hub = Option("--hub") ?? "."; +var work = Option("--work") ?? Path.Combine(Path.GetTempPath(), "fourfold-hub-" + Guid.NewGuid().ToString("N")); +var current = Option("--catalog") is { } catalogPath && File.Exists(catalogPath) + ? HubCatalogJson.Parse(File.ReadAllText(catalogPath)) + : null; +var today = DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); +using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) }; +http.DefaultRequestHeaders.UserAgent.ParseAdd("FourFoldAccountManager-HubTool"); + +if (args[0] == "check") +{ + var entryFile = Path.Combine(hub, Option("--entry") ?? string.Empty); + var fileName = Path.GetFileName(entryFile); + var (entry, error) = File.Exists(entryFile) + ? HubEntryReader.Read(fileName, File.ReadAllText(entryFile)) + : (null, "The entry file doesn't exist."); + var (removed, removedError) = ReadRemoved(); + error ??= removedError; + if (error is null && removed!.Any(removal => removal.Id == entry!.Id)) + { + error = "This plugin is in removed.json. Take it out of that file to list it again."; + } + + HubCheckResult? result = null; + if (error is null) + { + result = await CheckAsync(entry!); + error = result.Error; + } + + var summary = HubSubmission.Summary(fileName, entry, error, result?.Plugin, result?.Package, current); + Console.WriteLine(summary); + if (Option("--summary") is { } summaryFile) + { + File.AppendAllText(summaryFile, summary + Environment.NewLine); + } + + return error is null ? 0 : 1; +} + +var outFolder = Option("--out") ?? "out"; +Directory.CreateDirectory(outFolder); +var entries = new List(); +var problems = new List(); +var pluginsFolder = Path.Combine(hub, "plugins"); +foreach (var file in Directory.Exists(pluginsFolder) ? Directory.GetFiles(pluginsFolder, "*.json") : []) +{ + var (entry, error) = HubEntryReader.Read(Path.GetFileName(file), File.ReadAllText(file)); + if (entry is null) + { + problems.Add($"{Path.GetFileName(file)}: {error}"); + } + else + { + entries.Add(entry); + } +} + +var (pulled, pulledError) = ReadRemoved(); +if (pulledError is not null) +{ + problems.Add(pulledError); +} + +var build = problems.Count > 0 + ? new HubBuild(null, [], problems) + : HubSubmission.BuildCatalog(entries, pulled!, current, entry => CheckAsync(entry).GetAwaiter().GetResult()); +foreach (var problem in build.Errors) +{ + Console.Error.WriteLine(problem); +} + +if (build.Catalog is null) +{ + return 1; +} + +foreach (var (name, bytes) in build.Packages) +{ + File.WriteAllBytes(Path.Combine(outFolder, name), bytes); +} + +File.WriteAllText(Path.Combine(outFolder, "catalog.json"), HubCatalogJson.Write(build.Catalog)); +Console.WriteLine( + $"{build.Catalog.Plugins.Count} plugin(s) listed, {build.Packages.Count} new package(s), {build.Catalog.Removed.Count} removed."); +return 0; + +string? Option(string name) => options.GetValueOrDefault(name); + +(IReadOnlyList? Removed, string? Error) ReadRemoved() +{ + var path = Path.Combine(hub, "removed.json"); + return File.Exists(path) ? HubEntryReader.ReadRemoved(File.ReadAllText(path)) : ([], null); +} + +// Gets the entry's repository at its commit onto disk, then checks the plugin in it. +async Task CheckAsync(HubEntry entry) +{ + if (Option("--source") is { } source) + { + return HubSubmission.Check(entry, source, current, today); + } + + var bytes = await HubHttp.DownloadAsync( + http, HubAddresses.RepositoryArchive(entry.Repository, entry.Commit), MaximumRepositoryBytes, CancellationToken.None); + if (bytes is null) + { + return new HubCheckResult( + "The repository couldn't be downloaded at that commit. It must be public and under 50 MB.", null, null); + } + + var folder = Path.Combine(work, entry.Id); + try + { + if (Directory.Exists(folder)) + { + Directory.Delete(folder, recursive: true); + } + + using var stream = new MemoryStream(bytes); + SafeArchive.Extract(stream, folder, maximumFiles: 20_000, maximumBytes: 200L * 1024 * 1024, stripTopFolder: true); + } + catch (Exception exception) when (exception is InvalidDataException or IOException or UnauthorizedAccessException) + { + return new HubCheckResult("The repository's archive couldn't be unpacked: " + exception.Message, null, null); + } + + return HubSubmission.Check(entry, folder, current, today); +} From c028c8a72e6ff8c884b0397ae036b71058a18a18 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 15:39:49 -0500 Subject: [PATCH 05/22] fix: read a hostile hub catalog quickly and strictly, and check hub addresses at the source --- .../Plugins/HubCatalogJsonTests.cs | 68 ++++++++++++++++++ .../Plugins/HubHttpTests.cs | 33 +++++++++ .../Plugins/Hub/HubAddresses.cs | 15 ++-- .../Plugins/Hub/HubCatalogJson.cs | 69 ++++++++++++++----- .../Plugins/Hub/HubHttp.cs | 6 +- .../Plugins/PluginManifestReader.cs | 2 +- 6 files changed, 170 insertions(+), 23 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs index f4689ba..4839890 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs @@ -1,5 +1,6 @@ using System.Text.Json.Nodes; using FourFoldAccountManager.Core.Overlay; +using FourFoldAccountManager.Core.Plugins; using FourFoldAccountManager.Core.Plugins.Hub; using Xunit; @@ -49,8 +50,75 @@ public void AWrittenCatalogReadsBackTheSame() [InlineData("{}")] [InlineData("{\"version\":2,\"plugins\":[]}")] [InlineData("{\"version\":\"1\"}")] + [InlineData("{\"version\":1,\"plugins\":\"x\"}")] + [InlineData("{\"version\":1,\"removed\":{}}")] + [InlineData("{\"version\":1,\"removed\":\"x\",\"plugins\":[]}")] public void ACatalogThatCannotBeUsedReadsAsNothing(string? json) => Assert.Null(HubCatalogJson.Parse(json)); + [Fact] + public void AMissingOrNullListReadsAsEmpty() + { + var read = HubCatalogJson.Parse("{\"version\":1,\"plugins\":null}")!; + + Assert.Empty(read.Plugins); + Assert.Empty(read.Removed); + } + + [Fact] + public void ARawLoneSurrogateReadsAsNothingNotAnException() => + Assert.Null(HubCatalogJson.Parse("{\"version\":1,\"pad\":\"\ud800\"}")); + + [Fact] + public void AnEscapedLoneSurrogateCostsOnlyItsOwnItem() + { + var read = HubCatalogJson.Parse( + "{\"version\":1,\"plugins\":[]," + + "\"removed\":[{\"id\":\"pulled.plugin\",\"reason\":\"\\ud800\"}," + + "{\"id\":\"\\ud800\",\"reason\":\"x\"}," + + "{\"id\":\"other.plugin\",\"reason\":\"Gone.\"}]}")!; + + Assert.Equal([new HubRemoval("pulled.plugin", string.Empty), new HubRemoval("other.plugin", "Gone.")], read.Removed); + } + + [Fact] + public void ACatalogThatStartsWithAByteOrderMarkStillReads() => + Assert.Single(HubCatalogJson.Parse("\uFEFF" + HubCatalogJson.Write(new HubCatalog([Plugin()], [])))!.Plugins); + + [Fact] + public void ASecondEntryWithTheSameIdIsDropped() + { + var catalog = JsonNode.Parse(HubCatalogJson.Write(new HubCatalog([Plugin()], [])))!; + var second = catalog["plugins"]![0]!.DeepClone(); + second["commit"] = new string('b', 40); + catalog["plugins"]!.AsArray().Add(second); + + var read = HubCatalogJson.Parse(catalog.ToJsonString())!; + + Assert.Equal(Commit, Assert.Single(read.Plugins).Commit); + } + + [Fact] + public void AnAddressIsNeverBuiltFromAnUncheckedIdCommitOrRepository() + { + var repository = new Uri("https://github.com/cody/goal-tracker"); + + Assert.Throws(() => HubAddresses.PackageName("../evil", Commit)); + Assert.Throws(() => HubAddresses.Package("cody.goal-tracker", "main")); + Assert.Throws(() => HubAddresses.RepositoryArchive(repository, "main")); + Assert.Throws( + () => HubAddresses.RepositoryArchive(new Uri("https://evil.example/cody/goal-tracker"), Commit)); + Assert.Throws( + () => HubAddresses.RepositoryArchive(new Uri("https://github.com/cody/goal-tracker/tree/main"), Commit)); + Assert.EndsWith($"/cody.goal-tracker-{Commit}.zip", HubAddresses.Package("cody.goal-tracker", Commit).AbsoluteUri); + Assert.Equal( + $"https://codeload.github.com/cody/goal-tracker/zip/{Commit}", + HubAddresses.RepositoryArchive(repository, Commit).AbsoluteUri); + } + + [Fact] + public void AVersionWithATrailingNewlineIsNotAVersion() => + Assert.False(PluginManifestReader.IsVersion("1.2.0\n")); + [Fact] public void AnOversizedCatalogReadsAsNothing() => Assert.Null(HubCatalogJson.Parse( diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs index c8ce1f6..c4c5c5a 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs @@ -40,4 +40,37 @@ public async Task ADownloadLargerThanTheLimitIsRefused() Assert.Equal(100, (await HubHttp.DownloadAsync(atLimit, uri, 100, CancellationToken.None))!.Length); Assert.Null(await HubHttp.DownloadAsync(overLimit, uri, 100, CancellationToken.None)); } + + // What a handler that decompresses throws on a corrupt body. + private sealed class CorruptContent : HttpContent + { + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => + throw new InvalidDataException("The archive entry was compressed using an unsupported compression method."); + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + } + + private sealed class CorruptHandler : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new CorruptContent(), + RequestMessage = request + }); + } + + [Fact] + public async Task ACorruptBodyIsRefusedNotThrown() + { + using var http = new HttpClient(new CorruptHandler()); + + Assert.Null(await HubHttp.DownloadAsync( + http, new Uri("https://example.com/file"), 100, CancellationToken.None)); + } } diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs index 7111714..e17b8a5 100644 --- a/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs @@ -1,7 +1,8 @@ namespace FourFoldAccountManager.Core.Plugins.Hub; -// Where the hub lives. Every address is built here from fixed parts plus an id and a commit that were already -// validated (PluginManifestReader.IsValidId, HubCatalogJson.IsCommit); nothing is ever taken from the catalog as a URL. +// Where the hub lives. Every address is built here from fixed parts plus an id, a commit and (for an archive) a +// repository, and all three are checked here, the last stop before a request: a bad one throws ArgumentException. +// Nothing is ever taken from the catalog as a URL. public static class HubAddresses { public const string Repository = "CodySimonds65/FourFoldAccountManager-plugin-hub"; @@ -10,11 +11,17 @@ public static class HubAddresses public static Uri Catalog { get; } = new(ReleaseBase + "catalog.json"); - public static string PackageName(string id, string commit) => $"{id}-{commit}.zip"; + public static string PackageName(string id, string commit) => + PluginManifestReader.IsValidId(id) && HubCatalogJson.IsCommit(commit) + ? $"{id}-{commit}.zip" + : throw new ArgumentException("The id must be a valid plugin id and the commit a full lowercase commit id."); public static Uri Package(string id, string commit) => new(ReleaseBase + PackageName(id, commit)); // GitHub's zip of a repository at one commit. repository is https://github.com//. public static Uri RepositoryArchive(Uri repository, string commit) => - new($"https://codeload.github.com{repository.AbsolutePath}/zip/{commit}"); + HubCatalogJson.TryParseRepository(repository.AbsoluteUri, out _) && HubCatalogJson.IsCommit(commit) + ? new Uri($"https://codeload.github.com{repository.AbsolutePath}/zip/{commit}") + : throw new ArgumentException( + "The repository must be https://github.com// and the commit a full lowercase commit id."); } diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs index 6485a5d..00b31c8 100644 --- a/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs @@ -50,41 +50,39 @@ public static bool TryParseRepository(string? value, out Uri repository) try { - using var document = JsonDocument.Parse(json); + // A byte order mark is no part of the JSON, and some editors add one. + using var document = JsonDocument.Parse(json.TrimStart('\uFEFF')); var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("version", out var version) || version.ValueKind != JsonValueKind.Number || - !version.TryGetInt32(out var number) || number != Version) + !version.TryGetInt32(out var number) || number != Version || + !TryGetList(root, "removed", out var removedElement) || + !TryGetList(root, "plugins", out var pluginsElement)) { return null; } + // Sets, not lists: a catalog can hold tens of thousands of ids, and a list scan per id takes seconds. var removed = new List(); - if (root.TryGetProperty("removed", out var removedElement) && removedElement.ValueKind == JsonValueKind.Array) + var removedIds = new HashSet(StringComparer.Ordinal); + if (removedElement.ValueKind == JsonValueKind.Array) { foreach (var item in removedElement.EnumerateArray()) { - if (item.ValueKind != JsonValueKind.Object || - PluginManifestReader.Text(item, "id") is not { } id || !PluginManifestReader.IsValidId(id) || - removed.Any(other => other.Id == id)) + if (TryReadRemoval(item) is { } removal && removedIds.Add(removal.Id)) { - continue; + removed.Add(removal); } - - // A pull must never be lost over its wording: a reason that can't be shown is dropped, not the pull. - var reason = PluginManifestReader.Text(item, "reason") ?? string.Empty; - removed.Add(new HubRemoval( - id, reason.Length > 200 || PluginText.HasUnsafeCharacter(reason) ? string.Empty : reason)); } } var plugins = new List(); - if (root.TryGetProperty("plugins", out var pluginsElement) && pluginsElement.ValueKind == JsonValueKind.Array) + var pluginIds = new HashSet(StringComparer.Ordinal); + if (pluginsElement.ValueKind == JsonValueKind.Array) { foreach (var item in pluginsElement.EnumerateArray().Take(HubLimits.MaximumCatalogPlugins)) { - if (TryReadPlugin(item) is { } plugin && plugins.All(other => other.Id != plugin.Id) && - removed.All(other => other.Id != plugin.Id)) + if (TryReadPlugin(item) is { } plugin && !removedIds.Contains(plugin.Id) && pluginIds.Add(plugin.Id)) { plugins.Add(plugin); } @@ -93,12 +91,51 @@ public static bool TryParseRepository(string? value, out Uri repository) return new HubCatalog(Array.AsReadOnly(plugins.ToArray()), Array.AsReadOnly(removed.ToArray())); } - catch (Exception exception) when (exception is JsonException or InvalidOperationException) + catch (Exception exception) when (exception is JsonException or InvalidOperationException or ArgumentException) { return null; } } + // A missing or null list reads as an empty one. Any other type makes the catalog unusable: reading it as empty + // would drop the pulls, and the app would replace a good cached copy that still carries them. + private static bool TryGetList(JsonElement root, string name, out JsonElement list) + { + list = default; + return !root.TryGetProperty(name, out list) || list.ValueKind is JsonValueKind.Null or JsonValueKind.Array; + } + + private static HubRemoval? TryReadRemoval(JsonElement item) + { + string id; + try + { + if (item.ValueKind != JsonValueKind.Object || + PluginManifestReader.Text(item, "id") is not { } text || !PluginManifestReader.IsValidId(text)) + { + return null; + } + + id = text; + } + catch (Exception exception) when (exception is InvalidOperationException or ArgumentException) + { + return null; + } + + // A pull must never be lost over its wording: a reason that can't be read or shown is dropped, not the pull. + try + { + var reason = PluginManifestReader.Text(item, "reason") ?? string.Empty; + return new HubRemoval( + id, reason.Length > 200 || PluginText.HasUnsafeCharacter(reason) ? string.Empty : reason); + } + catch (Exception exception) when (exception is InvalidOperationException or ArgumentException) + { + return new HubRemoval(id, string.Empty); + } + } + public static string Write(HubCatalog catalog) => JsonSerializer.Serialize( new { diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs index 53f3830..a17ea3e 100644 --- a/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs @@ -3,7 +3,8 @@ namespace FourFoldAccountManager.Core.Plugins.Hub; public static class HubHttp { // Downloads a file of at most maximumBytes over https. Null when the request fails, ends anywhere but https, or - // the file is larger. The bytes are counted as they arrive, since a response needn't say how long it is. + // the file is larger; a cancelled or corrupt download also gives null. The bytes are counted as they arrive, since + // a response needn't say how long it is. public static async Task DownloadAsync( HttpClient http, Uri uri, long maximumBytes, CancellationToken cancellationToken) { @@ -33,7 +34,8 @@ public static class HubHttp return buffer.ToArray(); } - catch (Exception exception) when (exception is HttpRequestException or IOException or TaskCanceledException) + catch (Exception exception) when ( + exception is HttpRequestException or IOException or InvalidDataException or OperationCanceledException) { return null; } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index 3aea421..a99b937 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -25,7 +25,7 @@ public static partial class PluginManifestReader [GeneratedRegex("^" + CardIdPattern + @"\z")] private static partial Regex CardIdRegex(); - [GeneratedRegex(@"^[0-9]+\.[0-9]+\.[0-9]+$")] + [GeneratedRegex(@"^[0-9]+\.[0-9]+\.[0-9]+\z")] private static partial Regex VersionRegex(); // Windows treats these names as devices whatever follows the dot, so a plugin called nul.tools would get a storage From 51c1bfd57f36fe5df1f116a3428f937d0773dba6 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 15:43:34 -0500 Subject: [PATCH 06/22] feat: open links only on a plugin's declared sites, and mark community panels with a bar --- .../Plugins/PluginApiTests.cs | 50 +++++++++++-- .../Plugins/Web/CommunityPluginManager.cs | 4 +- .../Plugins/Web/PluginApi.cs | 8 +++ .../Plugins/Web/WebPlugin.cs | 71 ++++++++++++++++--- 4 files changed, 114 insertions(+), 19 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs index 703a24d..f77e2b0 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs @@ -19,20 +19,24 @@ public sealed class PluginApiTests : IDisposable private readonly FakeHost _host = new(); private readonly ManualTimeProvider _clock = new(); private readonly PluginCardStore _cards = new(); + private readonly PluginManifest _manifest; private readonly PluginHttpFetcher _http; private readonly PluginApi _api; public PluginApiTests() { - var manifest = new PluginManifest( - PluginId, "Goal tracker", "Goals", "1.0.0", "Cody", "Tracks goals.", 1, "index.html", null, [], false, + _manifest = new PluginManifest( + PluginId, "Goal tracker", "Goals", "1.0.0", "Cody", "Tracks goals.", 1, "index.html", null, + [new Uri("https://example.com")], false, [ new PluginCardManifest("goal", "Goal", OverlayAddOnScope.Account), new PluginCardManifest("summary", "Summary", OverlayAddOnScope.Global) ]) { Folder = _folder }; _host.Accounts = [new PluginAccountInfo(KnownAccount, "Main", "Cody", true)]; - _http = new PluginHttpFetcher(manifest, PluginTrust.Standard); - _api = new PluginApi(manifest, _host, new PluginStorage(Path.Combine(_folder, "storage.json")), _http, _cards, _clock); + _http = new PluginHttpFetcher(_manifest, PluginTrust.Standard); + _api = new PluginApi( + _manifest, PluginTrust.Standard, _host, new PluginStorage(Path.Combine(_folder, "storage.json")), _http, + _cards, _clock); } public void Dispose() @@ -45,7 +49,7 @@ public void Dispose() } [Fact] - public async Task OpenExternalOnlyOpensPublicHttpsLinks() + public async Task OpenExternalOnlyOpensPublicHttpsLinksOnDeclaredSites() { _host.PanelShowing = true; @@ -60,6 +64,16 @@ public async Task OpenExternalOnlyOpensPublicHttpsLinks() Assert.Equal("invalid-argument", ErrorCode(await Call("openExternal", new { url }))); } + // The plugin declares example.com and nothing else. Its own address, and another plugin's, are never sites. + foreach (var url in new[] + { + "https://example.org/", "https://sub.example.com/", "https://example.com:8443/", + "https://cody--goal-tracker.fourfoldplugin/", "https://other--plugin.fourfoldplugin/" + }) + { + Assert.Equal("site-not-allowed", ErrorCode(await Call("openExternal", new { url }))); + } + Assert.Empty(_host.Opened); var opened = await Call("openExternal", new { url = "https://example.com/page" }); @@ -68,6 +82,26 @@ public async Task OpenExternalOnlyOpensPublicHttpsLinks() Assert.Equal(new Uri("https://example.com/page"), Assert.Single(_host.Opened)); } + [Fact] + public async Task OnlyAPluginClearedForAnyWebsiteCanOpenLinksAnywhere() + { + _host.PanelShowing = true; + var asking = _manifest with { AnySite = true }; + var notCleared = new PluginApi( + asking, PluginTrust.Standard, _host, new PluginStorage(Path.Combine(_folder, "a.json")), _http, _cards, _clock); + var cleared = new PluginApi( + asking, PluginTrust.Verified, _host, new PluginStorage(Path.Combine(_folder, "b.json")), _http, _cards, _clock); + var link = new { url = "https://example.org/" }; + + // Asking for any website in plugin.json isn't enough; the hub must have cleared it. + Assert.Equal("site-not-allowed", ErrorCode(await Call(notCleared, "openExternal", link))); + Assert.Empty(_host.Opened); + + Assert.Null(ErrorCode(await Call(cleared, "openExternal", link))); + Assert.Equal(new Uri("https://example.org/"), Assert.Single(_host.Opened)); + Assert.Equal("invalid-argument", ErrorCode(await Call(cleared, "openExternal", new { url = "https://localhost/" }))); + } + [Fact] public async Task OpenExternalNeedsTheShowingPanelAndIsRateLimited() { @@ -203,9 +237,11 @@ public async Task StorageWritesAreRateLimited() Assert.Null(ErrorCode(await Call("storage.set", new { key = "k", value = 1 }))); } - private async Task Call(string method, object parameters) + private Task Call(string method, object parameters) => Call(_api, method, parameters); + + private static async Task Call(PluginApi api, string method, object parameters) { - var reply = await _api.HandleAsync(JsonSerializer.Serialize(new { id = 1, method, @params = parameters })); + var reply = await api.HandleAsync(JsonSerializer.Serialize(new { id = 1, method, @params = parameters })); Assert.NotNull(reply); return JsonDocument.Parse(reply).RootElement; } diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs index c6af14a..7f0736b 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs @@ -158,7 +158,9 @@ changedFolders is not null && WebPlugin webPlugin; try { - webPlugin = new WebPlugin(manifest, PluginTrust.Developer, _browser, _parkingHost, _host, _cards, _paths); + webPlugin = new WebPlugin( + manifest, PluginTrust.Developer, _browser, _parkingHost, _host, _cards, + new PluginStorage(Path.Combine(_paths.PluginDataRoot, manifest.Id + ".json"))); } catch (Exception) { diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs index 1f43b54..bc5ffb5 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs @@ -9,6 +9,7 @@ namespace FourFoldAccountManager.Desktop.Plugins.Web; // message gets an error reply (or none) and never throws into the app. internal sealed class PluginApi( PluginManifest manifest, + PluginTrust trust, IPluginHostData host, PluginStorage storage, PluginHttpFetcher http, @@ -284,6 +285,13 @@ private void OpenExternal(string url) throw new PluginApiException("invalid-argument", "Only https links can be opened."); } + // A plugin can send the user only where it may go itself: the sites it declared, or anywhere once the hub has + // cleared it for any website. That list is what the hub shows and what was reviewed. + if (PluginNetworkPolicy.IsPluginHost(uri.IdnHost) || !PluginNetworkPolicy.IsAllowed(uri, manifest, trust)) + { + throw new PluginApiException("site-not-allowed", "A plugin can only open links on the sites it declares."); + } + if (!host.IsPanelShowing(manifest.Id)) { throw new PluginApiException("unavailable", "A link can only be opened while the plugin's panel is showing."); diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs index 2cd2e81..d4e75f0 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs @@ -3,7 +3,6 @@ using System.Text.Json; using System.Windows; using System.Windows.Controls; -using FourFoldAccountManager.Core.Data; using FourFoldAccountManager.Core.Plugins; using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.Wpf; @@ -71,16 +70,14 @@ public WebPlugin( Panel parkingHost, IPluginHostData host, PluginCardStore cards, - LocalDataPaths paths) + PluginStorage storage) { Manifest = manifest; _trust = trust; _browser = browser; _parkingHost = parkingHost; _http = new PluginHttpFetcher(manifest, trust); - _api = new PluginApi( - manifest, host, new PluginStorage(Path.Combine(paths.PluginDataRoot, manifest.Id + ".json")), _http, cards, - TimeProvider.System); + _api = new PluginApi(manifest, trust, host, storage, _http, cards, TimeProvider.System); _contentSecurityPolicy = PluginNetworkPolicy.BuildContentSecurityPolicy(manifest, trust); // A plugin with no icon image shows the default Segoe glyph, a puzzle piece. Descriptor = new PluginDescriptor(manifest.Id, manifest.Name, manifest.ShortLabel, "\uEA86", [], []) @@ -88,11 +85,10 @@ public WebPlugin( Cards = manifest.Cards.Select(card => new PluginCardDescriptor(card.Id, card.Name, card.Scope)).ToArray(), IconPath = manifest.Icon is null ? null : Path.Combine(manifest.Folder, manifest.Icon), Badge = trust == PluginTrust.Developer ? "DEV" : null, - // IdnHost, so a look-alike Unicode host name shows as its real xn-- form. - Detail = PluginNetworkPolicy.AllowsAnySite(manifest, trust) ? "Can contact: any website" - : manifest.Sites.Count == 0 ? "Can contact: no websites" - : "Can contact: " + string.Join(", ", manifest.Sites.Select(site => - site.IsDefaultPort ? site.IdnHost : $"{site.IdnHost}:{site.Port}")) + Detail = $"by {manifest.Author}\n" + + (PluginNetworkPolicy.AllowsAnySite(manifest, trust) ? "Can contact: any website" + : manifest.Sites.Count == 0 ? "Can contact: no websites" + : "Can contact: " + string.Join(", ", manifest.Sites.Select(PluginNetworkPolicy.SiteLabel))) }; var reload = new Button { Content = "Reload", Height = 30, Padding = new Thickness(12, 0, 12, 0) }; @@ -110,7 +106,60 @@ public WebPlugin( } }; _viewHost.Children.Add(_stoppedNotice); - _root = new Border { BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(9), Child = _viewHost }; + // Everything in the page below is drawn by the plugin, so this bar, drawn by FourFold, says whose page it is. + var barName = new TextBlock + { + Text = manifest.Name, + FontSize = 11, + FontWeight = FontWeights.SemiBold, + VerticalAlignment = VerticalAlignment.Center, + TextTrimming = TextTrimming.CharacterEllipsis + }; + var barAuthor = new TextBlock + { + Text = "by " + manifest.Author, + FontSize = 11, + Margin = new Thickness(6, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center, + TextTrimming = TextTrimming.CharacterEllipsis + }; + barAuthor.SetResourceReference(TextBlock.ForegroundProperty, "Brush.TextMuted"); + var barTagText = new TextBlock + { + Text = trust == PluginTrust.Developer ? "DEV" : "COMMUNITY", + FontSize = 9, + FontWeight = FontWeights.Bold + }; + barTagText.SetResourceReference(TextBlock.ForegroundProperty, "Brush.TextMuted"); + var barTag = new Border + { + Child = barTagText, + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(3), + Padding = new Thickness(5, 0, 5, 0), + Margin = new Thickness(8, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center + }; + barTag.SetResourceReference(Border.BorderBrushProperty, "Brush.BorderStrong"); + DockPanel.SetDock(barTag, Dock.Right); + DockPanel.SetDock(barName, Dock.Left); + var bar = new Border + { + Height = 24, + Padding = new Thickness(9, 0, 9, 0), + BorderThickness = new Thickness(0, 0, 0, 1), + CornerRadius = new CornerRadius(8, 8, 0, 0), + Child = new DockPanel { Children = { barTag, barName, barAuthor } } + }; + bar.SetResourceReference(Border.BackgroundProperty, "Brush.SurfaceRaised"); + bar.SetResourceReference(Border.BorderBrushProperty, "Brush.Border"); + var layout = new Grid(); + layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + layout.RowDefinitions.Add(new RowDefinition()); + layout.Children.Add(bar); + Grid.SetRow(_viewHost, 1); + layout.Children.Add(_viewHost); + _root = new Border { BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(9), Child = layout }; _root.SetResourceReference(Border.BackgroundProperty, "Brush.Surface"); _root.SetResourceReference(Border.BorderBrushProperty, "Brush.Border"); // The view lives in the panel while the panel is on screen, and in the parking host the rest of the time. A web From 554158dfbe1af71e4dc0619c1ca4ae81baa7232d Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:01:01 -0500 Subject: [PATCH 07/22] feat: run installed hub plugins beside dev plugins, each starting on its own --- .../Plugins/Web/CommunityPluginManager.cs | 267 ++++++++++++------ .../Plugins/Web/PluginBrowser.cs | 34 +++ 2 files changed, 222 insertions(+), 79 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs index 7f0736b..52cfcce 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs @@ -4,13 +4,14 @@ using FourFoldAccountManager.Core.Data; using FourFoldAccountManager.Core.Models; using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; namespace FourFoldAccountManager.Desktop.Plugins.Web; public sealed record RejectedPlugin(string FolderName, string Reason); -// Loads community plugins from the dev plugins folder while developer mode is on, runs the ones that are switched on, -// and reloads a plugin when its files change. Create and use it on the UI thread. +// Runs community plugins from two places: the plugins installed from the hub, and, while developer mode is on, the +// dev plugins folder (reloading a plugin when its files change). Create and use it on the UI thread. public sealed class CommunityPluginManager : IDisposable { private readonly LocalDataPaths _paths; @@ -21,10 +22,19 @@ public sealed class CommunityPluginManager : IDisposable private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher; private readonly DispatcherTimer _reloadTimer; private readonly HashSet _changedFolders = new(StringComparer.OrdinalIgnoreCase); - private readonly List _plugins = []; + private readonly List _dev = []; + private readonly List _hub = []; + private readonly Dictionary _hubLoadOf = []; private readonly List _rejected = []; + + // One settings store per plugin id, so a hub plugin, its update and a dev copy of it never write the same file + // from two stores. + private readonly Dictionary _storages = new(StringComparer.Ordinal); + private IReadOnlyList _hubLoads = []; private FileSystemWatcher? _watcher; private bool _disposed; + private string? _folderError; + private string? _startError; private PanelSettings _settings = PanelSettings.Default; public CommunityPluginManager(LocalDataPaths paths, IPluginHostData host, Panel parkingHost, PluginCardStore cards) @@ -48,18 +58,19 @@ public CommunityPluginManager(LocalDataPaths paths, IPluginHostData host, Panel }; } - public IReadOnlyList Plugins => _plugins; + // Dev-folder plugins first, then hub plugins. + public IReadOnlyList Plugins => [.. _dev, .. _hub]; public IReadOnlyList Rejected => _rejected; - // Set when the dev folder can't be read or the plugin browser can't start; the plugin list shows it. - public string? StartupError { get; private set; } + // Set when the dev folder can't be read or a plugin can't start; the plugin list shows it. + public string? StartupError => _folderError ?? _startError; // Raised when the set of plugins, or whether one is running, changed. public event Action? Changed; - // Matches what is loaded and running to the settings. Never throws: a folder that can't be read, or a plugin that - // can't start, is reported through StartupError. + // Matches the dev-folder plugins, and what is running, to the settings. Never throws: a folder that can't be + // read, or a plugin that can't start, is reported through StartupError. public async Task ApplyAsync(PanelSettings settings) { // A click while the window is closing must not build new web views. @@ -71,32 +82,30 @@ public async Task ApplyAsync(PanelSettings settings) _settings = settings; if (!settings.PluginDeveloperMode) { - var hadState = _plugins.Count > 0 || _rejected.Count > 0 || StartupError is not null; - UnloadAll(); - StartupError = null; - if (hadState) + if (_dev.Count > 0 || _rejected.Count > 0 || _watcher is not null || _folderError is not null) { + UnloadDev(); + _folderError = null; + // A hub plugin that a dev copy was standing in for comes back. + ReconcileHub(); Changed?.Invoke(); } - - return; } - - if (_watcher is null) + else if (_watcher is null) { try { Directory.CreateDirectory(_paths.DevPluginsRoot); Rescan(changedFolders: null); StartWatching(); + _folderError = null; } catch (Exception) { AbandonLoad(); - Changed?.Invoke(); - return; } + ReconcileHub(); Changed?.Invoke(); } @@ -106,9 +115,47 @@ public async Task ApplyAsync(PanelSettings settings) } } + // The installed hub plugins that may run. Never throws. + public async Task SetHubPluginsAsync(IReadOnlyList loads) + { + if (_disposed) + { + return; + } + + _hubLoads = loads; + ReconcileHub(); + Changed?.Invoke(); + if (await SyncRunningAsync()) + { + Changed?.Invoke(); + } + } + + // Stops a hub plugin and lets go of its folder, before the folder is swapped or deleted. It stays unloaded until + // the next SetHubPluginsAsync. + public void Unload(string id) + { + // After Dispose the plugins are gone for good; reconciling would load the other hub plugins again. + if (_disposed) + { + return; + } + + _hubLoads = _hubLoads.Where(load => load.Id != id).ToArray(); + ReconcileHub(); + Changed?.Invoke(); + } + + // After an uninstall deleted the plugin's settings file: the store that cached it must not write it back. + public void Forget(string id) => _storages.Remove(id); + + public Task ClearBrowserDataAsync(string id) => + _browser.ClearOriginAsync(_parkingHost, PluginNetworkPolicy.Origin(id)); + public void PostEvent(string name, object? data) { - foreach (var plugin in _plugins) + foreach (var plugin in Plugins) { plugin.PostEvent(name, data); } @@ -117,7 +164,77 @@ public void PostEvent(string name, object? data) public void Dispose() { _disposed = true; - UnloadAll(); + UnloadDev(); + foreach (var plugin in _hub) + { + plugin.Dispose(); + } + + _hub.Clear(); + _hubLoadOf.Clear(); + } + + // Makes the loaded hub plugins match the loads that may run and aren't stood in for by a dev plugin. A load whose + // folder, commit or trust changed is a different load, so its plugin is replaced. + private void ReconcileHub() + { + var wanted = HubPolicy.Visible(_hubLoads, _dev.Select(plugin => plugin.Manifest.Id).ToHashSet(StringComparer.Ordinal)); + foreach (var plugin in _hub.ToArray()) + { + if (!wanted.Contains(_hubLoadOf[plugin])) + { + plugin.Dispose(); + _hub.Remove(plugin); + _hubLoadOf.Remove(plugin); + } + } + + foreach (var load in wanted) + { + if (_hubLoadOf.ContainsValue(load)) + { + continue; + } + + // An install that was damaged on disk simply doesn't load; the next hub check installs it again. + var manifest = PluginManifestReader.Read(load.Folder).Manifest; + if (manifest is null || manifest.Id != load.Id) + { + continue; + } + + try + { + var plugin = Create(manifest, load.Trust); + _hub.Add(plugin); + _hubLoadOf[plugin] = load; + } + catch (Exception) + { + // One plugin that can't be loaded must never take the others down. + } + } + } + + private WebPlugin Create(PluginManifest manifest, PluginTrust trust) + { + if (!_storages.TryGetValue(manifest.Id, out var storage)) + { + storage = new PluginStorage(Path.Combine(_paths.PluginDataRoot, manifest.Id + ".json")); + _storages[manifest.Id] = storage; + } + + var plugin = new WebPlugin(manifest, trust, _browser, _parkingHost, _host, _cards, storage); + // A plugin stops or restarts by itself (a flood, a crash, its Reload button). That can happen inside a web view + // event or mid-start, and Changed re-renders the sidebar, so it is raised later. + plugin.RunningChanged += () => _dispatcher.BeginInvoke(() => + { + if (!_disposed) + { + Changed?.Invoke(); + } + }); + return plugin; } // Re-reads the dev folder. A plugin whose folder is in changedFolders (or every plugin, when it is null) is @@ -127,12 +244,16 @@ private void Rescan(IReadOnlySet? changedFolders) var folders = Directory.Exists(_paths.DevPluginsRoot) ? Directory.GetDirectories(_paths.DevPluginsRoot).OrderBy(folder => folder, StringComparer.OrdinalIgnoreCase).ToArray() : []; - var kept = _plugins + var kept = _dev .Where(plugin => folders.Contains(plugin.Manifest.Folder, StringComparer.OrdinalIgnoreCase) && changedFolders is not null && !changedFolders.Contains(Path.GetFileName(plugin.Manifest.Folder))) .ToList(); - Unload(_plugins.Except(kept).ToArray()); + foreach (var plugin in _dev.Except(kept).ToArray()) + { + plugin.Dispose(); + } + _rejected.Clear(); foreach (var folder in folders) { @@ -155,92 +276,52 @@ changedFolders is not null && continue; } - WebPlugin webPlugin; try { - webPlugin = new WebPlugin( - manifest, PluginTrust.Developer, _browser, _parkingHost, _host, _cards, - new PluginStorage(Path.Combine(_paths.PluginDataRoot, manifest.Id + ".json"))); + kept.Add(Create(manifest, PluginTrust.Developer)); } catch (Exception) { // One folder that can't be loaded must never take the others down. _rejected.Add(new RejectedPlugin(folderName, "The plugin couldn't be loaded.")); - continue; } - - // A plugin stops or restarts by itself (a flood, a crash, its Reload button). That can happen inside a web - // view event or while SyncRunningAsync is mid-loop, and Changed re-renders the sidebar, so it is raised later. - webPlugin.RunningChanged += () => _dispatcher.BeginInvoke(() => - { - if (!_disposed) - { - Changed?.Invoke(); - } - }); - kept.Add(webPlugin); } - _plugins.Clear(); - _plugins.AddRange(kept.OrderBy(plugin => plugin.Manifest.Folder, StringComparer.OrdinalIgnoreCase)); + _dev.Clear(); + _dev.AddRange(kept.OrderBy(plugin => plugin.Manifest.Folder, StringComparer.OrdinalIgnoreCase)); } - private void Unload(IReadOnlyList plugins) + private void UnloadDev() { - foreach (var plugin in plugins) + StopWatching(); + foreach (var plugin in _dev) { plugin.Dispose(); - _plugins.Remove(plugin); } - } - private void UnloadAll() - { - StopWatching(); - Unload(_plugins.ToArray()); + _dev.Clear(); _rejected.Clear(); } - // The dev folder can't be read or watched. Nothing stays half-loaded, and the next apply tries again. + // The dev folder can't be read or watched. No dev plugin stays half-loaded, and the next apply tries again. private void AbandonLoad() { - UnloadAll(); - StartupError = "The dev plugins folder couldn't be read."; + UnloadDev(); + _folderError = "The dev plugins folder couldn't be read."; } // Starts switched-on plugins and stops switched-off ones. Returns whether anything changed. private async Task SyncRunningAsync() { - var changed = StartupError is not null; - StartupError = null; - foreach (var plugin in _plugins.ToArray()) + var changed = _startError is not null; + _startError = null; + var starts = new List>(); + foreach (var plugin in Plugins) { - // A reload or developer mode switching off during an earlier await disposed this one. - if (!_plugins.Contains(plugin)) - { - continue; - } - var shouldRun = PluginLayoutPolicy.IsEnabled(_settings, plugin.Descriptor.Id); if (shouldRun && !plugin.IsRunning) { - try - { - await plugin.StartAsync(); - // The user may have switched it off while it was starting. - if (plugin.IsRunning && !PluginLayoutPolicy.IsEnabled(_settings, plugin.Descriptor.Id)) - { - plugin.Stop(); - } - - // A start that was abandoned (the plugin was stopped meanwhile) returns normally, so ask the plugin. - changed |= plugin.IsRunning; - } - catch (Exception) - { - StartupError = "Community plugins couldn't start."; - changed = true; - } + starts.Add(StartAsync(plugin)); } else if (!shouldRun && plugin.IsRunning) { @@ -249,9 +330,37 @@ private async Task SyncRunningAsync() } } + // Side by side, so one plugin that hangs while starting can't hold up the rest. + foreach (var started in await Task.WhenAll(starts)) + { + changed |= started; + } + return changed; } + // Starts one plugin. A plugin disposed meanwhile (a reload, an update, developer mode switching off) refuses to + // start, and one that was abandoned mid-start returns normally, so the answer is whether it is running now. + private async Task StartAsync(WebPlugin plugin) + { + try + { + await plugin.StartAsync(); + // The user may have switched it off while it was starting. + if (plugin.IsRunning && !PluginLayoutPolicy.IsEnabled(_settings, plugin.Descriptor.Id)) + { + plugin.Stop(); + } + + return plugin.IsRunning; + } + catch (Exception) + { + _startError = "Community plugins couldn't start."; + return true; + } + } + private void StartWatching() { var watcher = new FileSystemWatcher(_paths.DevPluginsRoot) @@ -334,10 +443,10 @@ private async Task ReloadChangedAsync() { // A tick on the UI thread must never take the app down, whatever state the folder was left in. AbandonLoad(); - Changed?.Invoke(); - return; } + // A dev plugin that appeared or went away changes which hub plugins it stands in for. + ReconcileHub(); // Before the plugins start, so the strip never shows the ones that were just disposed. Changed?.Invoke(); await SyncRunningAsync(); diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs index 33b7447..e41d08e 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs @@ -1,6 +1,9 @@ using System.IO; +using System.Text.Json; +using System.Windows.Controls; using FourFoldAccountManager.Core.Data; using Microsoft.Web.WebView2.Core; +using Microsoft.Web.WebView2.Wpf; namespace FourFoldAccountManager.Desktop.Plugins.Web; @@ -30,4 +33,35 @@ public async Task GetEnvironmentAsync() throw; } } + + // Removes everything the plugin browser stored for one plugin's address (cookies, IndexedDB, caches), after the + // plugin is uninstalled. It needs a web view to ask through, so it borrows a blank one for a moment. Best effort: + // data left behind takes disk space and nothing else. + public async Task ClearOriginAsync(Panel parkingHost, Uri origin) + { + // No plugin has ever run, so there is nothing to clear and no reason to start a browser. + if (!Directory.Exists(paths.PluginWebViewUserDataRoot)) + { + return; + } + + var view = new WebView2CompositionControl(); + parkingHost.Children.Add(view); + try + { + await view.EnsureCoreWebView2Async(await GetEnvironmentAsync()); + await view.CoreWebView2.CallDevToolsProtocolMethodAsync( + "Storage.clearDataForOrigin", + JsonSerializer.Serialize(new { origin = origin.GetLeftPart(UriPartial.Authority), storageTypes = "all" })); + } + catch (Exception) + { + // Left behind; see above. + } + finally + { + parkingHost.Children.Remove(view); + view.Dispose(); + } + } } From 6a0c6f7931c75e4adf41008ab80c75e6c35976ad Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:10:23 -0500 Subject: [PATCH 08/22] fix: keep hub installs and their record safe from corrupt files, races and half-finished swaps --- .../Plugins/HubPolicyTests.cs | 7 + .../Plugins/HubStoreTests.cs | 175 ++++++++++++++- .../Plugins/Hub/HubPolicy.cs | 24 +- .../Plugins/Hub/HubStore.cs | 211 +++++++++++++----- 4 files changed, 353 insertions(+), 64 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs index 98c01c4..33c3e99 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs @@ -33,6 +33,12 @@ public void APulledOrUnlistedPluginNeverLoads() Assert.Equal("Sent data away.", HubPolicy.PulledReason(catalog, "pulled.plugin")); Assert.Equal(HubPolicy.RemovedReason, HubPolicy.PulledReason(catalog, "quiet.plugin")); Assert.Equal(HubPolicy.UnlistedReason, HubPolicy.PulledReason(catalog, "gone.plugin")); + + // A pull wins even when a hand-built catalog also lists the plugin. + var both = new HubCatalog( + [Listed("both.plugin", CommitA, anySite: true)], [new HubRemoval("both.plugin", "Pulled after listing.")]); + Assert.Equal("Pulled after listing.", HubPolicy.PulledReason(both, "both.plugin")); + Assert.Empty(HubPolicy.Loads(both, [new HubInstalled("both.plugin", CommitA)], id => id)); } [Fact] @@ -104,6 +110,7 @@ public void UninstallingRemovesThePluginsCardsAndIdsFromSettings() Assert.Equal(["xp-tracker", "other.plugin"], next.PluginOrder); Assert.Empty(next.DisabledPlugins); Assert.Null(next.OpenPlugin); + Assert.False(next.PluginsSidebarExpanded); Assert.Equal( [null, "cody.goal-tracker-two/goal"], next.OverlayCards.Select(card => card.PluginCard).OrderBy(card => card)); diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs index b188485..fe9402e 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs @@ -46,14 +46,21 @@ private async Task InstallAsync(HubPlugin plugin, byte[] package) await _store.CommitAsync(plugin, staging, CancellationToken.None); } + private string[] DotFolders() => + Directory.GetDirectories(_paths.HubPluginsRoot, ".*").Select(folder => Path.GetFileName(folder)).ToArray(); + [Fact] public async Task AFailedUpdateKeepsTheInstalledVersion() { var (first, firstPackage) = Build("cody.goal-tracker", "1.0.0", CommitA, "

one

"); await InstallAsync(first, firstPackage); - // A download that was tampered with never gets as far as a folder. + // An intact package still has to be the one the catalog records, by hash and by size. var (second, secondPackage) = Build("cody.goal-tracker", "1.1.0", CommitB, "

two

"); + Assert.NotNull(_store.Stage(second with { Sha256 = new string('0', 64) }, secondPackage, out _)); + Assert.NotNull(_store.Stage(second with { Size = second.Size + 1 }, secondPackage, out _)); + + // A download that was tampered with never gets as far as a folder. secondPackage[^1] ^= 0xFF; Assert.NotNull(_store.Stage(second, secondPackage, out _)); @@ -64,7 +71,28 @@ await Assert.ThrowsAnyAsync( Assert.Equal("

one

", File.ReadAllText(Path.Combine(_store.FolderOf("cody.goal-tracker"), "index.html"))); Assert.Equal([new HubInstalled("cody.goal-tracker", CommitA)], _store.LoadInstalled()); Assert.True(_store.IsIntact("cody.goal-tracker")); - Assert.Empty(Directory.GetDirectories(_paths.HubPluginsRoot, ".*")); + Assert.Empty(DotFolders()); + } + + [Fact] + public async Task AFailedRecordSaveKeepsTheInstalledVersion() + { + var (first, firstPackage) = Build("cody.goal-tracker", "1.0.0", CommitA, "

one

"); + await InstallAsync(first, firstPackage); + var (second, secondPackage) = Build("cody.goal-tracker", "1.1.0", CommitB, "

two

"); + Assert.Null(_store.Stage(second, secondPackage, out var staging)); + + // Readable, so the record loads, but it can't be swapped: the save fails after the folders were exchanged. + using (new FileStream(_paths.HubInstalledFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + await Assert.ThrowsAnyAsync( + () => _store.CommitAsync(second, staging, CancellationToken.None)); + } + + Assert.Equal("

one

", File.ReadAllText(Path.Combine(_store.FolderOf("cody.goal-tracker"), "index.html"))); + Assert.Equal([new HubInstalled("cody.goal-tracker", CommitA)], _store.LoadInstalled()); + Assert.True(_store.IsIntact("cody.goal-tracker")); + Assert.Empty(DotFolders()); } [Fact] @@ -74,6 +102,10 @@ public void APackageForADifferentPluginOrVersionIsRefused() Assert.NotNull(_store.Stage(plugin with { Id = "other.plugin" }, package, out _)); Assert.NotNull(_store.Stage(plugin with { Version = "9.9.9" }, package, out _)); + + // The sites the hub page showed, and any-website clearance, must match what the package's plugin.json asks for. + Assert.NotNull(_store.Stage(plugin with { Sites = [new Uri("https://example.org")] }, package, out _)); + Assert.NotNull(_store.Stage(plugin with { AnySite = true }, package, out _)); Assert.Empty(Directory.GetDirectories(_paths.HubPluginsRoot)); Assert.Null(_store.Stage(plugin, package, out var staging)); @@ -97,6 +129,7 @@ public async Task UninstallRemovesTheFilesTheSavedSettingsAndTheRecord() Assert.False(File.Exists(saved)); Assert.Equal([new HubInstalled("other.plugin", CommitA)], _store.LoadInstalled()); Assert.True(_store.IsIntact("other.plugin")); + Assert.Empty(DotFolders()); } [Fact] @@ -113,4 +146,142 @@ public async Task ALockedRecordIsNotReadAsNothingInstalled() Assert.Equal([new HubInstalled("cody.goal-tracker", CommitA)], _store.LoadInstalled()); } + + [Fact] + public async Task ACorruptRecordIsRebuiltFromTheInstalledFolders() + { + var (first, firstPackage) = Build("cody.goal-tracker", "1.0.0", CommitA); + var (second, secondPackage) = Build("other.plugin", "1.0.0", CommitA); + var (third, thirdPackage) = Build("third.plugin", "1.0.0", CommitB); + await InstallAsync(first, firstPackage); + await InstallAsync(second, secondPackage); + Assert.True(HubCatalogJson.IsCommit(HubStore.UnknownCommit)); + + // Leftovers and a folder that isn't a whole plugin are not mistaken for installed plugins. + Directory.CreateDirectory(Path.Combine(_paths.HubPluginsRoot, ".staging-x")); + Directory.CreateDirectory(Path.Combine(_paths.HubPluginsRoot, "broken.plugin")); + + foreach (var damaged in new[] { "{ not json", "", "null", """[{"id":5}]""" }) + { + File.WriteAllText(_paths.HubInstalledFilePath, damaged); + Assert.Equal( + [new HubInstalled("cody.goal-tracker", HubStore.UnknownCommit), new HubInstalled("other.plugin", HubStore.UnknownCommit)], + _store.LoadInstalled()); + } + + // The next install keeps the others instead of writing a record that forgets them. + File.WriteAllText(_paths.HubInstalledFilePath, "{ not json"); + await InstallAsync(third, thirdPackage); + + Assert.Equal( + [ + new HubInstalled("cody.goal-tracker", HubStore.UnknownCommit), + new HubInstalled("other.plugin", HubStore.UnknownCommit), + new HubInstalled("third.plugin", CommitB) + ], + _store.LoadInstalled()); + + // A missing record is still just "nothing installed", not a reason to guess from the folders. + File.Delete(_paths.HubInstalledFilePath); + Assert.Empty(_store.LoadInstalled()); + } + + [Fact] + public async Task InstallsAtTheSameTimeAreAllRecorded() + { + var staged = new List<(HubPlugin Plugin, string Staging)>(); + for (var number = 1; number <= 8; number++) + { + var (plugin, package) = Build($"cody.plugin-{number}", "1.0.0", CommitA); + Assert.Null(_store.Stage(plugin, package, out var staging)); + staged.Add((plugin, staging)); + } + + await Task.WhenAll(staged.Select(item => + Task.Run(() => _store.CommitAsync(item.Plugin, item.Staging, CancellationToken.None)))); + + Assert.Equal( + staged.Select(item => item.Plugin.Id).Order(StringComparer.Ordinal), + _store.LoadInstalled().Select(record => record.Id).Order(StringComparer.Ordinal)); + Assert.All(staged, item => Assert.True(_store.IsIntact(item.Plugin.Id))); + } + + [Fact] + public async Task CleanUpRemovesOnlyLeftovers() + { + var (plugin, package) = Build("cody.goal-tracker", "1.0.0", CommitA); + await InstallAsync(plugin, package); + foreach (var leftover in new[] { ".staging-x", ".trash-y" }) + { + Directory.CreateDirectory(Path.Combine(_paths.HubPluginsRoot, leftover)); + File.WriteAllText(Path.Combine(_paths.HubPluginsRoot, leftover, "file.txt"), "x"); + } + + // A set-aside copy of a plugin that still has its folder is only a leftover. + var setAside = Path.Combine(_paths.HubPluginsRoot, ".old-cody.goal-tracker-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(setAside); + + _store.CleanUp(); + + Assert.Empty(DotFolders()); + Assert.True(_store.IsIntact("cody.goal-tracker")); + Assert.Equal([new HubInstalled("cody.goal-tracker", CommitA)], _store.LoadInstalled()); + } + + [Fact] + public async Task CleanUpPutsBackAPluginAfterACrashMidSwap() + { + var (plugin, package) = Build("cody.goal-tracker", "1.0.0", CommitA, "

one

"); + await InstallAsync(plugin, package); + + // The state a crash leaves between the two moves of an update: the old folder set aside, the new one not in place. + Directory.Move( + _store.FolderOf("cody.goal-tracker"), + Path.Combine(_paths.HubPluginsRoot, ".old-cody.goal-tracker-" + Guid.NewGuid().ToString("N"))); + Assert.False(_store.IsIntact("cody.goal-tracker")); + + _store.CleanUp(); + + Assert.True(_store.IsIntact("cody.goal-tracker")); + Assert.Equal("

one

", File.ReadAllText(Path.Combine(_store.FolderOf("cody.goal-tracker"), "index.html"))); + Assert.Empty(DotFolders()); + } + + [Fact] + public async Task TheSavedCatalogIsReadBack() + { + var plugin = new HubPlugin( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "cody", "", [], false, [], + new Uri("https://github.com/cody/goal-tracker"), CommitA, "2026-10-09", 100, new string('a', 64)); + var catalog = new HubCatalog([plugin], [new HubRemoval("pulled.plugin", "Sent data away.")]); + Assert.Null(_store.LoadCatalog()); + + await _store.SaveCatalogAsync(HubCatalogJson.Write(catalog), CancellationToken.None); + + var loaded = _store.LoadCatalog(); + Assert.NotNull(loaded); + var listed = Assert.Single(loaded.Plugins); + Assert.Equal((plugin.Id, plugin.Commit, plugin.Sha256), (listed.Id, listed.Commit, listed.Sha256)); + Assert.Equal(new HubRemoval("pulled.plugin", "Sent data away."), Assert.Single(loaded.Removed)); + } + + [Fact] + public async Task AnIdThatIsNotAPluginIdNeverReachesTheDisk() + { + var (plugin, package) = Build("cody.goal-tracker", "1.0.0", CommitA); + await InstallAsync(plugin, package); + var victim = Path.Combine(_paths.DataRoot, "victim"); + Directory.CreateDirectory(victim); + File.WriteAllText(Path.Combine(victim, "keep.txt"), "x"); + + Assert.Throws(() => _store.FolderOf("../victim")); + Assert.Throws(() => _store.FolderOf("..\\victim")); + Assert.Throws(() => _store.IsIntact("../victim")); + await Assert.ThrowsAsync( + () => _store.UninstallAsync("../victim", CancellationToken.None)); + + Assert.True(File.Exists(Path.Combine(victim, "keep.txt"))); + Assert.Equal([new HubInstalled("cody.goal-tracker", CommitA)], _store.LoadInstalled()); + Assert.True(_store.IsIntact("cody.goal-tracker")); + } } diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs index 685f1b4..f3fc40b 100644 --- a/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs @@ -15,18 +15,23 @@ public static class HubPolicy public const string RemovedReason = "This plugin was removed from the hub."; - // Why an installed plugin may not run, or null when it may. A plugin the catalog doesn't list at all counts as - // pulled, so a mistake on the hub's side stops a plugin and never leaves an unlisted one running. With no catalog - // yet, nothing is known to be pulled. + // Why an installed plugin may not run, or null when it may. A removal wins even when the catalog also lists the id, + // and a plugin the catalog doesn't list at all counts as pulled, so a mistake on the hub's side stops a plugin and + // never leaves an unlisted one running. With no catalog yet, nothing is known to be pulled. public static string? PulledReason(HubCatalog? catalog, string id) { - if (catalog is null || catalog.Plugins.Any(plugin => plugin.Id == id)) + if (catalog is null) { return null; } var removal = catalog.Removed.FirstOrDefault(removed => removed.Id == id); - return removal is null ? UnlistedReason : removal.Reason.Length > 0 ? removal.Reason : RemovedReason; + if (removal is not null) + { + return removal.Reason.Length > 0 ? removal.Reason : RemovedReason; + } + + return catalog.Plugins.Any(plugin => plugin.Id == id) ? null : UnlistedReason; } // The installed plugins that may run. A plugin gets any-website trust only when the catalog clears the exact @@ -59,8 +64,9 @@ catalog is null .Where(plugin => installed.Any(other => other.Id == plugin.Id && other.Commit != plugin.Commit)) .ToArray(); - // Forgets an uninstalled plugin in saved settings: its cards, its place in the strip, and its switch. Returns the - // same instance when there was nothing to forget, so callers can skip the save. + // Forgets an uninstalled plugin in saved settings: its cards, its place in the strip, and its switch. When it was + // the open plugin the panel closes, as when it is switched off. Returns the same instance when there was nothing + // to forget, so callers can skip the save. public static PanelSettings WithUninstalled(PanelSettings settings, string id) { var cardPrefix = id + "/"; @@ -75,12 +81,14 @@ public static PanelSettings WithUninstalled(PanelSettings settings, string id) return settings; } + var wasOpen = settings.OpenPlugin == id; return settings with { OverlayCards = Array.AsReadOnly(cards), PluginOrder = Array.AsReadOnly(order), DisabledPlugins = Array.AsReadOnly(disabled), - OpenPlugin = settings.OpenPlugin == id ? null : settings.OpenPlugin + OpenPlugin = wasOpen ? null : settings.OpenPlugin, + PluginsSidebarExpanded = !wasOpen && settings.PluginsSidebarExpanded }; } diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs index 0f17cb6..0428432 100644 --- a/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs @@ -1,3 +1,4 @@ +using System.Text; using System.Text.Json; using FourFoldAccountManager.Core.Data; @@ -7,13 +8,30 @@ namespace FourFoldAccountManager.Core.Plugins.Hub; // catalog. Nothing here talks to the network or to a running plugin. public sealed class HubStore(LocalDataPaths paths) { - public string FolderOf(string id) => Path.Combine(paths.HubPluginsRoot, id); + // Git's null id. A record rebuilt from the folders on disk can't know which commit they hold, so it names this + // one: it passes the commit check, never equals a commit the catalog lists (so it never earns any-website trust), + // and the next hub check sees a different commit and installs the plugin again, cleanly. + public static readonly string UnknownCommit = new('0', 40); - // False when a crash mid-install left the record without its files; the next hub check installs it again. - public bool IsIntact(string id) => File.Exists(Path.Combine(FolderOf(id), "plugin.json")); + private const string OldPrefix = ".old-"; - // No file means nothing is installed, and a file that isn't JSON reads the same way. A file that exists but can't - // be opened throws, so a locked record is never mistaken for "nothing installed" and then written over. + // Commit and uninstall each read the record, wait, then write it, so two at once would lose one of the writes. + private readonly SemaphoreSlim _gate = new(1, 1); + + // Throws for anything but a plugin id, so no caller can point this (or the recursive delete in UninstallAsync) at + // a folder outside the plugins folder. + public string FolderOf(string id) => PluginManifestReader.IsValidId(id) + ? Path.Combine(paths.HubPluginsRoot, id) + : throw new ArgumentException("That isn't a plugin id.", nameof(id)); + + // False when the folder is missing or broken: a crash mid-install left the record without its files, or a file the + // plugin needs is gone. The next hub check installs it again. + public bool IsIntact(string id) => PluginManifestReader.Read(FolderOf(id)).Manifest is not null; + + // No file means nothing is installed. A file that can't be read as a record (not JSON, empty, one wrong entry) is + // rebuilt from the plugin folders on disk, so a damaged record never makes the next install forget the others. A + // file that exists but can't be opened throws (IOException, or UnauthorizedAccessException when access is denied), + // so a locked record is never mistaken for "nothing installed" and then written over. public IReadOnlyList LoadInstalled() { if (!File.Exists(paths.HubInstalledFilePath)) @@ -29,15 +47,17 @@ public IReadOnlyList LoadInstalled() } catch (JsonException) { - return []; + records = null; } - return (records ?? []) - .Where(record => record is not null && PluginManifestReader.IsValidId(record.Id) && - HubCatalogJson.IsCommit(record.Commit)) - .Select(record => record!) - .DistinctBy(record => record.Id) - .ToArray(); + return records is null + ? RebuildFromFolders() + : records + .Where(record => record is not null && PluginManifestReader.IsValidId(record.Id) && + HubCatalogJson.IsCommit(record.Commit)) + .Select(record => record!) + .DistinctBy(record => record.Id) + .ToArray(); } public HubCatalog? LoadCatalog() @@ -54,11 +74,20 @@ public IReadOnlyList LoadInstalled() } } + // Written through to disk before it takes the final name, so a power cut can't leave a short file there. public async Task SaveCatalogAsync(string json, CancellationToken cancellationToken) { Directory.CreateDirectory(Path.GetDirectoryName(paths.HubCatalogFilePath)!); var temporary = paths.HubCatalogFilePath + ".tmp"; - await File.WriteAllTextAsync(temporary, json, cancellationToken); + await using (var stream = new FileStream( + temporary, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 16 * 1024, + FileOptions.Asynchronous | FileOptions.WriteThrough)) + { + await stream.WriteAsync(Encoding.UTF8.GetBytes(json), cancellationToken); + await stream.FlushAsync(cancellationToken); + stream.Flush(flushToDisk: true); + } + File.Move(temporary, paths.HubCatalogFilePath, overwrite: true); } @@ -82,9 +111,11 @@ public async Task SaveCatalogAsync(string json, CancellationToken cancellationTo return "The package isn't valid."; } - // The hash matched, but it must also be the plugin the user asked for. + // The hash matched, but it must also be the plugin the user asked for, asking for the websites the hub page + // showed: the catalog's sites are what the user saw, and the plugin.json is what the sandbox enforces. var manifest = PluginManifestReader.Read(stagingFolder).Manifest; - if (manifest is null || manifest.Id != plugin.Id || manifest.Version != plugin.Version) + if (manifest is null || manifest.Id != plugin.Id || manifest.Version != plugin.Version || + !manifest.Sites.ToHashSet().SetEquals(plugin.Sites) || (plugin.AnySite && !manifest.AnySite)) { TryDeleteFolder(stagingFolder); return "The package isn't the plugin the hub listed."; @@ -94,79 +125,151 @@ public async Task SaveCatalogAsync(string json, CancellationToken cancellationTo } // Puts a staged plugin in place and records it. If the swap or the record fails, the version that was installed - // before is back in place when this throws. + // before is back in place when this throws, and the staging folder is gone. public async Task CommitAsync(HubPlugin plugin, string stagingFolder, CancellationToken cancellationToken) { - // Read before anything moves: a record that can't be read stops the install here. - var records = LoadInstalled(); var target = FolderOf(plugin.Id); - var previous = Path.Combine(paths.HubPluginsRoot, ".old-" + Guid.NewGuid().ToString("N")); - var hadPrevious = Directory.Exists(target); - if (hadPrevious) - { - Directory.Move(target, previous); - } - + await _gate.WaitAsync(cancellationToken); try { - Directory.Move(stagingFolder, target); + // Read before anything moves: a record that can't be read stops the install here. + var records = LoadInstalled(); + // The id is in the name so CleanUp can put the folder back if a crash comes between the two moves. + var previous = Path.Combine(paths.HubPluginsRoot, $"{OldPrefix}{plugin.Id}-{Guid.NewGuid():N}"); + var hadPrevious = Directory.Exists(target); + if (hadPrevious) + { + Directory.Move(target, previous); + } + try { - await SaveInstalledAsync( - records.Where(record => record.Id != plugin.Id) - .Append(new HubInstalled(plugin.Id, plugin.Commit)) - .ToArray(), - cancellationToken); + Directory.Move(stagingFolder, target); + try + { + await SaveInstalledAsync( + records.Where(record => record.Id != plugin.Id) + .Append(new HubInstalled(plugin.Id, plugin.Commit)) + .ToArray(), + cancellationToken); + } + catch + { + Directory.Move(target, stagingFolder); + throw; + } } catch { - Directory.Move(target, stagingFolder); + // If putting the old version back fails, nothing below runs and the staged files stay. + if (hadPrevious) + { + Directory.Move(previous, target); + } + + TryDeleteFolder(stagingFolder); throw; } + + TryDeleteFolder(previous); } - catch + finally { - if (hadPrevious) - { - Directory.Move(previous, target); - } - - throw; + _gate.Release(); } - - TryDeleteFolder(previous); } - // The record goes first, so a crash partway leaves files nothing points at, never a record without its files. + // The record goes first, so a crash partway leaves files nothing points at, never a record without its files. The + // folder is renamed before it is deleted: a delete that fails partway then leaves a leftover CleanUp finishes at + // the next start, never a half-deleted plugin folder that could be loaded. public async Task UninstallAsync(string id, CancellationToken cancellationToken) { - await SaveInstalledAsync(LoadInstalled().Where(record => record.Id != id).ToArray(), cancellationToken); - if (Directory.Exists(FolderOf(id))) + var folder = FolderOf(id); + await _gate.WaitAsync(cancellationToken); + try { - Directory.Delete(FolderOf(id), recursive: true); - } + await SaveInstalledAsync(LoadInstalled().Where(record => record.Id != id).ToArray(), cancellationToken); + var saved = Path.Combine(paths.PluginDataRoot, id + ".json"); + if (File.Exists(saved)) + { + File.Delete(saved); + } - var saved = Path.Combine(paths.PluginDataRoot, id + ".json"); - if (File.Exists(saved)) + if (Directory.Exists(folder)) + { + var trash = Path.Combine(paths.HubPluginsRoot, ".trash-" + Guid.NewGuid().ToString("N")); + Directory.Move(folder, trash); + TryDeleteFolder(trash); + } + } + finally { - File.Delete(saved); + _gate.Release(); } } - // Removes folders a crash left behind mid-install. An installed plugin's folder never starts with a dot. + // Clears what a crash or a failed delete left behind. An installed plugin's folder never starts with a dot. A + // folder CommitAsync set aside is put back when the swap never finished and the plugin has no folder; otherwise it + // is deleted with the rest. Never throws: a plugins folder that can't be listed must not stop the hub starting. public void CleanUp() { - if (!Directory.Exists(paths.HubPluginsRoot)) + try + { + if (!Directory.Exists(paths.HubPluginsRoot)) + { + return; + } + + foreach (var folder in Directory.GetDirectories(paths.HubPluginsRoot, ".*")) + { + if (SetAsideId(Path.GetFileName(folder)) is { } id && !Directory.Exists(FolderOf(id))) + { + try + { + Directory.Move(folder, FolderOf(id)); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Kept, never deleted: it may be the only copy. The next start tries again. + } + + continue; + } + + TryDeleteFolder(folder); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { - return; + // The next start tries again. } + } - foreach (var folder in Directory.GetDirectories(paths.HubPluginsRoot, ".*")) + // The plugin id in ".old--<32 hex digits>", or null for any other name. + private static string? SetAsideId(string name) + { + if (!name.StartsWith(OldPrefix, StringComparison.Ordinal)) { - TryDeleteFolder(folder); + return null; } + + var rest = name[OldPrefix.Length..]; + return rest.Length > 33 && rest[^33] == '-' && Guid.TryParseExact(rest[^32..], "N", out _) && + PluginManifestReader.IsValidId(rest[..^33]) + ? rest[..^33] + : null; } + private IReadOnlyList RebuildFromFolders() => + !Directory.Exists(paths.HubPluginsRoot) + ? [] + : Directory.GetDirectories(paths.HubPluginsRoot) + .Select(folder => Path.GetFileName(folder)) + .Where(name => !name.StartsWith('.') && PluginManifestReader.IsValidId(name) && IsIntact(name)) + .Order(StringComparer.Ordinal) + .Select(name => new HubInstalled(name, UnknownCommit)) + .ToArray(); + private Task SaveInstalledAsync(IReadOnlyList records, CancellationToken cancellationToken) => AtomicJsonFile.WriteAsync(paths.HubInstalledFilePath, records, cancellationToken); From eb55bcdb8ce927761d8d6df2897fef2b34a92675 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:17:27 -0500 Subject: [PATCH 09/22] fix: bound how deep a package can nest, and keep packages to files every user can unpack --- .../Plugins/PluginPackageTests.cs | 93 +++++++++++++++++++ .../Plugins/Hub/PluginPackage.cs | 59 ++++++++++-- .../Plugins/Hub/SafeArchive.cs | 71 ++++++++++---- 3 files changed, 196 insertions(+), 27 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs index 3b55727..85b08b3 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs @@ -71,6 +71,99 @@ public void TooManyFilesOrTooMuchDataIsRefused() var large = Zip(("big.txt", new byte[HubLimits.MaximumUnpackedBytes + 1])); Assert.True(large.Length < 100_000); Assert.Throws(() => PluginPackage.Extract(large, Path.Combine(_root, "large"))); + + // Each entry is under the limit; only the total is over it. + var two = Zip(("a.txt", new byte[3 * 1024 * 1024]), ("b.txt", new byte[3 * 1024 * 1024])); + Assert.Throws(() => PluginPackage.Extract(two, Path.Combine(_root, "two"))); + } + + [Fact] + public void AnEntryNestedTooDeeplyIsRefused() + { + // Deleting a tree thousands of levels deep overflows the stack, so a deep entry must never be unpacked. + var name = string.Join('/', Enumerable.Repeat("a", 100)) + "/f.txt"; + var target = Path.Combine(_root, "deep"); + + Assert.Throws(() => PluginPackage.Extract(Zip((name, new byte[] { 1 })), target)); + + Assert.Empty(Directory.EnumerateFileSystemEntries(target)); + } + + [Fact] + public void AFileWhereAFolderAlreadyIsIsRefused() + { + using var package = new MemoryStream(Zip(("a/b.txt", new byte[] { 1 }), ("a", new byte[] { 1 }))); + + var exception = Assert.ThrowsAny( + () => SafeArchive.Extract( + package, Path.Combine(_root, "clash"), 500, HubLimits.MaximumUnpackedBytes, stripTopFolder: false)); + + Assert.IsNotType(exception); + } + + [Fact] + public void AFolderThatAlreadyHasFilesIsNotUnpackedInto() + { + var target = Path.Combine(_root, "taken"); + Directory.CreateDirectory(target); + File.WriteAllText(Path.Combine(target, "mine.txt"), "mine"); + + Assert.Throws(() => PluginPackage.Extract(Zip(("plugin.json", "{}"u8.ToArray())), target)); + + Assert.Equal(["mine.txt"], Directory.EnumerateFileSystemEntries(target).Select(path => Path.GetFileName(path))); + } + + [Fact] + public void LinksAndOddNamesAreSkippedOnlyWhenAsked() + { + var package = Zip( + entry => + { + if (entry.FullName == "link.txt") + { + entry.ExternalAttributes = unchecked((int)0xA1FF0000); + } + }, + ("link.txt", "target"u8.ToArray()), + ("a:b.txt", new byte[] { 1 }), + ("logs\\c.log", new byte[] { 1 }), + ("ok.txt", new byte[] { 1 })); + var skipped = Path.Combine(_root, "skipped"); + + using (var stream = new MemoryStream(package)) + { + SafeArchive.Extract( + stream, skipped, 500, HubLimits.MaximumUnpackedBytes, stripTopFolder: false, skipLinksAndOddNames: true); + } + + Assert.Equal(["ok.txt"], Directory.EnumerateFileSystemEntries(skipped).Select(path => Path.GetFileName(path))); + + using var strict = new MemoryStream(package); + Assert.Throws( + () => SafeArchive.Extract( + strict, Path.Combine(_root, "strict"), 500, HubLimits.MaximumUnpackedBytes, stripTopFolder: false)); + } + + [Fact] + public void APackageWithAFileFourFoldDoesNotServeIsRefusedBeforeAnythingIsWritten() + { + var package = Zip(("plugin.json", "{}"u8.ToArray()), ("run.exe", new byte[] { 1 })); + var target = Path.Combine(_root, "exe"); + + Assert.Throws(() => PluginPackage.Extract(package, target)); + + Assert.False(Directory.Exists(target)); + } + + [Fact] + public void FileNamesWindowsCannotUnpackAreFoundWhenBuilding() + { + Assert.Null(PluginPackage.UnpackableReason(["plugin.json", "index.html", "img/a.png", "img/b.png"])); + Assert.NotNull(PluginPackage.UnpackableReason(["a:b.png"])); + Assert.NotNull(PluginPackage.UnpackableReason(["what?.png"])); + Assert.NotNull(PluginPackage.UnpackableReason(["trail.png."])); + Assert.NotNull(PluginPackage.UnpackableReason(["dir /a.png"])); + Assert.NotNull(PluginPackage.UnpackableReason(["A.png", "a.png"])); } [Fact] diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs index 7902921..0dfda10 100644 --- a/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs @@ -9,13 +9,18 @@ public static class PluginPackage private static readonly DateTimeOffset EntryTime = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); // Builds the package for the plugin in folder. README, LICENSE, dot-files and other file types are left out. The - // same files always give the same bytes. Throws InvalidDataException when the plugin is past the limits or - // contains a link. + // same files always give the same bytes. Throws InvalidDataException when the plugin is past the limits, contains + // a link, or has a file name that Windows can't unpack. public static byte[] Build(string folder) { var files = new List<(string Name, string Path)>(); Collect(folder, string.Empty, files); files.Sort((left, right) => string.CompareOrdinal(left.Name, right.Name)); + if (UnpackableReason(files.ConvertAll(file => file.Name)) is { } reason) + { + throw new InvalidDataException(reason); + } + if (files.Count > HubLimits.MaximumPackageFiles) { throw new InvalidDataException($"A plugin can have at most {HubLimits.MaximumPackageFiles} files."); @@ -47,11 +52,49 @@ public static byte[] Build(string folder) public static bool Matches(byte[] package, long size, string sha256) => package.LongLength == size && string.Equals(Sha256(package), sha256, StringComparison.Ordinal); + // Why files with these names (paths inside a package, with '/') can't all be unpacked on Windows, or null. The hub + // tool runs on Linux, where Path.GetInvalidFileNameChars lists only '/' and NUL, so the Windows rules are written + // out here; without this a package would build fine and then be refused on a user's machine. + public static string? UnpackableReason(IReadOnlyList names) + { + var seen = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var name in names) + { + foreach (var part in name.Split('/')) + { + if (part.Any(character => char.IsControl(character) || "\\:<>\"|?*".Contains(character)) || + part.EndsWith('.') || part.EndsWith(' ')) + { + return $"{name} can't be unpacked on Windows: a file or folder name can't contain \\ : < > \" | ? * " + + "or a control character, or end with a dot or a space."; + } + } + + if (!seen.TryAdd(name, name)) + { + return $"{name} and {seen[name]} differ only by capital letters, which Windows can't tell apart."; + } + } + + return null; + } + // Unpacks a package into targetFolder. Throws InvalidDataException or IOException when it breaks a rule; the - // caller deletes the folder. + // caller deletes the folder. A package holds only plugin.json and the file types FourFold serves, as Build + // makes it; anything else, such as an .exe, is refused before a byte is written. public static void Extract(byte[] package, string targetFolder) { using var stream = new MemoryStream(package); + using (var archive = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true)) + { + if (archive.Entries.Any(entry => + !entry.FullName.EndsWith('/') && entry.FullName != "plugin.json" && + !PluginFileServer.IsServed(entry.FullName))) + { + throw new InvalidDataException("The package holds a file that FourFold doesn't serve."); + } + } + SafeArchive.Extract( stream, targetFolder, HubLimits.MaximumPackageFiles, HubLimits.MaximumUnpackedBytes, stripTopFolder: false); } @@ -61,15 +104,15 @@ private static void Collect(string folder, string prefix, List<(string Name, str foreach (var path in Directory.EnumerateFileSystemEntries(folder)) { var name = Path.GetFileName(path); - var attributes = File.GetAttributes(path); - if (attributes.HasFlag(FileAttributes.ReparsePoint)) + if (name.StartsWith('.')) { - throw new InvalidDataException("A plugin can't contain links."); + continue; } - if (name.StartsWith('.')) + var attributes = File.GetAttributes(path); + if (attributes.HasFlag(FileAttributes.ReparsePoint)) { - continue; + throw new InvalidDataException("A plugin can't contain links."); } if (attributes.HasFlag(FileAttributes.Directory)) diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs index 1e442ca..615a664 100644 --- a/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs @@ -6,10 +6,23 @@ namespace FourFoldAccountManager.Core.Plugins.Hub; // throws InvalidDataException before it is written. The caller deletes the target folder when this throws. public static class SafeArchive { + // Deleting a folder tree is recursive and overflows the stack when the tree is thousands of levels deep, which + // nothing can catch, so no entry may nest deeper than this. + private const int MaximumDepth = 64; + // stripTopFolder drops each entry's first path part, for GitHub's repository zips, which wrap everything in one - // "-" folder. - public static void Extract(Stream zip, string targetFolder, int maximumFiles, long maximumBytes, bool stripTopFolder) + // "-" folder. skipLinksAndOddNames skips links and names with a ':' or '\' instead of refusing the + // archive, for an author's whole repository, where such a file has nothing to do with the plugin. + public static void Extract( + Stream zip, string targetFolder, int maximumFiles, long maximumBytes, bool stripTopFolder, + bool skipLinksAndOddNames = false) { + // Callers unpack into a fresh folder; one with files in it could hold a link that leads somewhere else. + if (Directory.Exists(targetFolder) && Directory.EnumerateFileSystemEntries(targetFolder).Any()) + { + throw new IOException("The folder to unpack into isn't empty."); + } + using var archive = new ZipArchive(zip, ZipArchiveMode.Read, leaveOpen: true); Directory.CreateDirectory(targetFolder); var files = 0; @@ -23,19 +36,30 @@ public static void Extract(Stream zip, string targetFolder, int maximumFiles, lo continue; } - // A Unix symbolic link is stored as a file whose mode bits say "link". - if (((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000) + var parts = name.Split('/'); + if (parts.Length > MaximumDepth) { - throw new InvalidDataException("The archive contains a link."); + throw new InvalidDataException("The archive nests folders too deeply."); } - var parts = name.Split('/'); - if (name.Contains('\\') || name.Contains(':') || - parts.Any(part => part.Length == 0 || part is "." or "..")) + if (parts.Any(part => part.Length == 0 || part is "." or "..")) { throw new InvalidDataException("The archive contains a path that isn't allowed."); } + // A Unix symbolic link is stored as a file whose mode bits say "link". + var isLink = ((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000; + if (isLink || name.Contains('\\') || name.Contains(':')) + { + if (skipLinksAndOddNames) + { + continue; + } + + throw new InvalidDataException( + isLink ? "The archive contains a link." : "The archive contains a path that isn't allowed."); + } + if (stripTopFolder) { if (parts.Length == 1) @@ -56,20 +80,29 @@ public static void Extract(Stream zip, string targetFolder, int maximumFiles, lo throw new InvalidDataException("The archive has too many files."); } - Directory.CreateDirectory(Path.GetDirectoryName(path)!); - using var input = entry.Open(); - using var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write); - int read; - while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + try { - // Counted as it is written: the size an entry declares can lie. - bytes += read; - if (bytes > maximumBytes) + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using var input = entry.Open(); + using var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write); + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { - throw new InvalidDataException("The archive is too large."); - } + // Counted as it is written: the size an entry declares can lie. + bytes += read; + if (bytes > maximumBytes) + { + throw new InvalidDataException("The archive is too large."); + } - output.Write(buffer, 0, read); + output.Write(buffer, 0, read); + } + } + catch (UnauthorizedAccessException exception) + { + // A file where a folder is needed, or the reverse; callers expect only InvalidDataException or + // IOException from this method. + throw new IOException("The archive can't be unpacked: access to a path was denied.", exception); } } } From a8d96464cf5740c1afad0d84242bea6864adcb03 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:27:35 -0500 Subject: [PATCH 10/22] fix: make the hub tool refuse bad input loudly and tell the reviewer the truth --- .../Plugins/HubSubmissionTests.cs | 204 +++++++++++++++++- .../Plugins/Hub/HubEntry.cs | 25 ++- .../Plugins/Hub/HubSubmission.cs | 203 +++++++++++++++-- src/FourFoldAccountManager.HubTool/Program.cs | 204 +++++++++++------- 4 files changed, 527 insertions(+), 109 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs index 2923db3..f0ca5ef 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs @@ -16,16 +16,23 @@ public sealed class HubSubmissionTests : IDisposable public void Dispose() => Directory.Delete(_root, recursive: true); - private string Repository(string id, string version, bool anySite = false, string folder = "") + private string Repository( + string id, string version, bool anySite = false, string folder = "", string name = "Goal tracker", + string panel = "index.html", string? extraFile = null) { var root = Path.Combine(_root, "repo-" + Guid.NewGuid().ToString("N")); var plugin = Path.Combine(root, folder); Directory.CreateDirectory(plugin); File.WriteAllText( Path.Combine(plugin, "plugin.json"), - $$"""{"id":"{{id}}","name":"Goal tracker","shortLabel":"Goals","version":"{{version}}","author":"cody","apiVersion":1,"panel":"index.html","anySite":{{(anySite ? "true" : "false")}}}"""); - File.WriteAllText(Path.Combine(plugin, "index.html"), "

hello

"); + $$"""{"id":"{{id}}","name":"{{name}}","shortLabel":"Goals","version":"{{version}}","author":"cody","apiVersion":1,"panel":"{{panel}}","anySite":{{(anySite ? "true" : "false")}}}"""); + File.WriteAllText(Path.Combine(plugin, panel), "

hello

"); File.WriteAllText(Path.Combine(root, "README.md"), "not shipped"); + if (extraFile is not null) + { + File.WriteAllText(Path.Combine(plugin, extraFile), "

extra

"); + } + return root; } @@ -44,6 +51,12 @@ private static HubEntry Entry(string commit = CommitA, string path = "", bool an [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":\"../other\"}")] [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":\"/abs\"}")] [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"anySite\":\"yes\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":5}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":null}")] + // The same property twice reads as its last value, while a reviewer of the raw file sees the first. + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"anySite\":false,\"anySite\":true}")] + // A lone surrogate escape: JSON the reader can't hand back as text, which once crashed the tool. + [InlineData("cody.goal-tracker.json", "{\"repository\":\"\\ud800\",\"commit\":\"" + CommitA + "\"}")] public void AnEntryThatBreaksARuleIsRejected(string fileName, string json) { var (entry, error) = HubEntryReader.Read(fileName, json); @@ -124,4 +137,189 @@ public void APluginCannotBeBothListedAndRemoved() Assert.Null(build.Catalog); Assert.Single(build.Errors); } + + [Fact] + public void AnEntryPathPastTwoHundredCharactersIsRejected() + { + var (entry, error) = HubEntryReader.Read( + "cody.goal-tracker.json", + "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":\"" + + new string('a', 201) + "\"}"); + + Assert.Null(entry); + Assert.False(string.IsNullOrEmpty(error)); + } + + [Theory] + [InlineData("not json")] + [InlineData("{}")] + [InlineData("[{\"id\":\"cody.goal-tracker\"}]")] + [InlineData("[{\"id\":\"cody.goal-tracker\",\"reason\":\"a\"},{\"id\":\"cody.goal-tracker\",\"reason\":\"b\"}]")] + [InlineData("[{\"id\":\"cody.goal-tracker\",\"reason\":\"a\",\"reason\":\"b\"}]")] + [InlineData("[{\"id\":\"cody.goal-tracker\",\"reason\":\"\\ud800\"}]")] + [InlineData("[{\"id\":\"\\ud800\",\"reason\":\"a\"}]")] + public void ARemovedListThatBreaksARuleIsRejected(string json) + { + var (removed, error) = HubEntryReader.ReadRemoved(json); + + Assert.Null(removed); + Assert.False(string.IsNullOrEmpty(error)); + } + + [Fact] + public void AGoodRemovedListIsRead() + { + var (removed, error) = HubEntryReader.ReadRemoved("[{\"id\":\"cody.goal-tracker\",\"reason\":\"Pulled.\"}]"); + + Assert.Null(error); + Assert.Equal(new HubRemoval("cody.goal-tracker", "Pulled."), Assert.Single(removed!)); + } + + [Fact] + public void AnEntryClearsAnyWebsiteOnlyWhenItSaysSo() + { + // The plugin's plugin.json asks for any website, but the maintainers' entry doesn't clear it. + var plugin = HubSubmission.Check( + Entry(anySite: false), Repository("cody.goal-tracker", "1.0.0", anySite: true), null, "2026-10-09").Plugin!; + + Assert.False(plugin.AnySite); + } + + [Fact] + public void AVersionTooLargeToCompareIsRefused() + { + Assert.NotNull( + HubSubmission.Check(Entry(), Repository("cody.goal-tracker", "99999999999.0.0"), null, "2026-10-09").Error); + } + + [Fact] + public void APluginThatWouldNotInstallFromItsPackageIsRefused() + { + // The package leaves dot-files out, so this plugin would have no panel once a user installed it. + var result = HubSubmission.Check( + Entry(), Repository("cody.goal-tracker", "1.0.0", panel: ".index.html"), null, "2026-10-09"); + + Assert.NotNull(result.Error); + Assert.Null(result.Package); + } + + [Fact] + public void ARevokedClearanceIsCheckedAgainNotReused() + { + var cleared = HubSubmission.Check( + Entry(anySite: true), Repository("cody.goal-tracker", "1.0.0", anySite: true), null, "2026-10-01").Plugin!; + var current = new HubCatalog([cleared], []); + var checkedAgain = false; + + // Same commit, but the entry no longer clears any website: the listed record must not be kept as it is. + var build = HubSubmission.BuildCatalog( + [Entry(anySite: false)], [], current, + entry => + { + checkedAgain = true; + return HubSubmission.Check( + entry, Repository("cody.goal-tracker", "1.0.0", anySite: true), current, "2026-10-09"); + }); + + Assert.True(checkedAgain); + Assert.False(Assert.Single(build.Catalog!.Plugins).AnySite); + } + + [Fact] + public void AChangedRepositoryIsCheckedAgainNotReused() + { + var listed = HubSubmission.Check(Entry(), Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-01").Plugin!; + var moved = Entry() with { Repository = new Uri("https://github.com/someone-else/goal-tracker") }; + var checkedAgain = false; + + var build = HubSubmission.BuildCatalog( + [moved], [], new HubCatalog([listed], []), + entry => + { + checkedAgain = true; + return HubSubmission.Check(entry, Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09"); + }); + + Assert.True(checkedAgain); + Assert.Equal(moved.Repository, Assert.Single(build.Catalog!.Plugins).Repository); + } + + [Fact] + public void NoPackagesAreOfferedWhenThereIsNoCatalog() + { + var other = Entry() with { Id = "cody.other" }; + + var build = HubSubmission.BuildCatalog( + [Entry(), other], [], null, + entry => entry.Id == "cody.other" + ? new HubCheckResult("Refused.", null, null) + : HubSubmission.Check(entry, Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09")); + + Assert.Null(build.Catalog); + Assert.Empty(build.Packages); + Assert.Single(build.Errors); + } + + [Fact] + public void ACatalogTheAppWouldRefuseIsNotBuilt() + { + // The app reads at most 1 MB of catalog, so a larger one would leave the hub dead for every user. + var removals = Enumerable.Range(0, 6000) + .Select(number => new HubRemoval($"cody.pulled-{number}", new string('x', 200))) + .ToArray(); + + var build = HubSubmission.BuildCatalog([], removals, null, _ => throw new InvalidOperationException("no entries")); + + Assert.Null(build.Catalog); + Assert.Single(build.Errors); + } + + [Fact] + public void TheSummaryCannotBeSteeredByTheSubmission() + { + // A name that is a Markdown link, and a file name with a backtick (legal on Windows and Linux). + var result = HubSubmission.Check( + Entry(), Repository("cody.goal-tracker", "1.0.0", name: "[x](http://e)", extraFile: "a`b.html"), null, + "2026-10-09"); + Assert.Null(result.Error); + + var summary = HubSubmission.Summary( + "# [evil](http://e).json", Entry(), null, result.Plugin, result.Package, null); + + Assert.DoesNotMatch(@"(?.json". Every rejection carries a reason an author can act on. public static (HubEntry? Entry, string? Error) Read(string fileName, string json) { @@ -23,7 +27,7 @@ public static (HubEntry? Entry, string? Error) Read(string fileName, string json try { - using var document = JsonDocument.Parse(json); + using var document = JsonDocument.Parse(json, Options); var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object) { @@ -41,10 +45,18 @@ public static (HubEntry? Entry, string? Error) Read(string fileName, string json return (null, "\"commit\" must be a full 40-character commit in lowercase, not a branch or a tag."); } + const string PathError = + "\"path\" must be a folder inside the repository, written with forward slashes (at most 200 characters)."; var path = PluginManifestReader.Text(root, "path") ?? string.Empty; - if (path.Length > 0 && (!PathRegex().IsMatch(path) || path.Split('/').Any(part => part is "." or ".."))) + if (root.TryGetProperty("path", out var pathElement) && pathElement.ValueKind != JsonValueKind.String) + { + return (null, PathError); + } + + if (path.Length > 0 && + (path.Length > 200 || !PathRegex().IsMatch(path) || path.Split('/').Any(part => part is "." or ".."))) { - return (null, "\"path\" must be a folder inside the repository, written with forward slashes."); + return (null, PathError); } var hasAnySite = root.TryGetProperty("anySite", out var anySite); @@ -55,8 +67,9 @@ public static (HubEntry? Entry, string? Error) Read(string fileName, string json return (new HubEntry(id, repository, commit, path, hasAnySite && anySite.ValueKind == JsonValueKind.True), null); } - catch (JsonException) + catch (Exception exception) when (exception is JsonException or InvalidOperationException or ArgumentException) { + // InvalidOperationException: text with a lone surrogate escape (\ud800) is JSON the reader can't hand back. return (null, "The entry isn't valid JSON."); } } @@ -65,7 +78,7 @@ public static (IReadOnlyList? Removed, string? Error) ReadRemoved(st { try { - using var document = JsonDocument.Parse(json); + using var document = JsonDocument.Parse(json, Options); if (document.RootElement.ValueKind != JsonValueKind.Array) { return (null, "removed.json must be a list."); @@ -88,7 +101,7 @@ public static (IReadOnlyList? Removed, string? Error) ReadRemoved(st return (result, null); } - catch (JsonException) + catch (Exception exception) when (exception is JsonException or InvalidOperationException or ArgumentException) { return (null, "removed.json isn't valid JSON."); } diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs index a27a3b5..c225517 100644 --- a/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs @@ -13,6 +13,11 @@ public sealed record HubBuild( // What the hub repository's workflows check before a plugin is listed. The plugin's code is never run. public static class HubSubmission { + private const int MaximumListedFiles = 100; + + // Every character Markdown could act on in the summary. + private const string MarkdownCharacters = "\\`*_[]<>&|~!()#"; + // Checks one entry against its repository, unpacked at the entry's commit in repositoryFolder, and builds its // package. today is the review date recorded for it (yyyy-MM-dd). public static HubCheckResult Check(HubEntry entry, string repositoryFolder, HubCatalog? current, string today) @@ -40,6 +45,13 @@ public static HubCheckResult Check(HubEntry entry, string repositoryFolder, HubC return Fail("\"anySite\" is true in the entry, but the plugin's plugin.json doesn't ask for it."); } + // The reader accepts any digits, but a number past 2,147,483,647 can't be compared, so no update to it could + // ever pass the "must raise" rule below. + if (!System.Version.TryParse(manifest.Version, out _)) + { + return Fail("Each number in the version must be below 2147483647, for example 1.4.0."); + } + var listed = current?.Plugins.FirstOrDefault(plugin => plugin.Id == entry.Id); if (listed is not null && listed.Commit != entry.Commit && !IsNewer(manifest.Version, listed.Version)) { @@ -56,12 +68,21 @@ public static HubCheckResult Check(HubEntry entry, string repositoryFolder, HubC { return Fail(exception.Message); } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return Fail("The plugin's files couldn't be read."); + } if (package.LongLength > HubLimits.MaximumPackageBytes) { return Fail("The package is too large."); } + if (Unpackable(package, manifest) is { } unpackProblem) + { + return Fail(unpackProblem); + } + return new HubCheckResult( null, new HubPlugin( @@ -74,9 +95,49 @@ public static HubCheckResult Check(HubEntry entry, string repositoryFolder, HubC static HubCheckResult Fail(string reason) => new(reason, null, null); } - // Builds the catalog for every entry. An entry whose commit and clearance are unchanged keeps its record and its - // published package, so a listed plugin survives its author deleting the repository; only new and changed entries - // go through check. One failure means no catalog. + // The package is built from the author's folder, but what users get is what the app unpacks from it. Unpacks it the + // way the app does, into a throwaway folder, and returns why it wouldn't install as the same plugin, or null. A + // manifest whose panel is a dot-file, say, passes the folder's own check and then has no panel in the package. + private static string? Unpackable(byte[] package, PluginManifest manifest) + { + var staging = Path.Combine(Path.GetTempPath(), "fourfold-hub-check-" + Guid.NewGuid().ToString("N")); + try + { + PluginPackage.Extract(package, staging); + var unpacked = PluginManifestReader.Read(staging); + if (unpacked.Manifest is not { } installed) + { + return "Once packaged, the plugin can't be installed: " + unpacked.Error; + } + + return installed.Id == manifest.Id && installed.Version == manifest.Version + ? null + : "Once packaged, the plugin isn't the same id and version."; + } + catch (Exception exception) when (exception is InvalidDataException or IOException or UnauthorizedAccessException) + { + return "The package can't be unpacked: " + + (exception is InvalidDataException ? exception.Message : "a file couldn't be written."); + } + finally + { + try + { + if (Directory.Exists(staging)) + { + Directory.Delete(staging, recursive: true); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A leftover folder in the temporary folder costs nothing; it must not hide the result. + } + } + } + + // Builds the catalog for every entry. An entry whose repository, commit and clearance are unchanged keeps its + // record and its published package, so a listed plugin survives its author deleting the repository; only new and + // changed entries go through check. One failure means no catalog, and then no packages either. public static HubBuild BuildCatalog( IReadOnlyList entries, IReadOnlyList removed, @@ -95,7 +156,7 @@ public static HubBuild BuildCatalog( } if (current?.Plugins.FirstOrDefault(plugin => plugin.Id == entry.Id) is { } listed && - listed.Commit == entry.Commit && listed.AnySite == entry.AnySite) + listed.Commit == entry.Commit && listed.AnySite == entry.AnySite && listed.Repository == entry.Repository) { plugins.Add(listed); continue; @@ -112,32 +173,61 @@ public static HubBuild BuildCatalog( packages.Add((HubAddresses.PackageName(entry.Id, entry.Commit), result.Package!)); } - return new HubBuild(errors.Count == 0 ? new HubCatalog(plugins, removed) : null, packages, errors); + if (errors.Count > 0) + { + return new HubBuild(null, [], errors); + } + + // The app reads at most this much of a catalog and refuses a larger one, which would leave the hub dead for + // every user, so a catalog it would refuse is never built. The app counts characters and the download is capped + // in bytes, so both are checked. + var catalog = new HubCatalog(plugins, removed); + if (plugins.Count > HubLimits.MaximumCatalogPlugins) + { + errors.Add($"The catalog would list {plugins.Count} plugins, and FourFold reads at most {HubLimits.MaximumCatalogPlugins}."); + } + else + { + var json = HubCatalogJson.Write(catalog); + if (json.Length > HubLimits.MaximumCatalogBytes || Encoding.UTF8.GetByteCount(json) > HubLimits.MaximumCatalogBytes) + { + errors.Add($"The catalog would be larger than the {HubLimits.MaximumCatalogBytes} bytes FourFold reads."); + } + } + + return errors.Count == 0 ? new HubBuild(catalog, packages, errors) : new HubBuild(null, [], errors); } - // What a reviewer needs to see for one entry, as Markdown for the check's summary page. + // What a reviewer needs to see for one entry, as Markdown for the check's summary page. A maintainer reads this + // before merging, and most of it is a stranger's text: Plain makes each such value harmless, and every line starts + // with text written here, never with a stranger's value. public static string Summary( string fileName, HubEntry? entry, string? error, HubPlugin? plugin, byte[]? package, HubCatalog? current) { - var text = new StringBuilder().AppendLine($"### {fileName}").AppendLine(); + var text = new StringBuilder().AppendLine($"### {Plain(fileName)}").AppendLine(); if (error is not null || entry is null || plugin is null || package is null) { - return text.AppendLine($"**Not accepted:** {error}").ToString(); + return text.AppendLine($"**Not accepted:** {Plain(error ?? "The entry couldn't be checked.", 500)}").ToString(); } - var contact = plugin.AnySite ? "any website (cleared by this entry)" + if (plugin.AnySite) + { + text.AppendLine("**WARNING: this entry asks for ANY WEBSITE access. Merging it grants that.**").AppendLine(); + } + + var contact = plugin.AnySite ? "any website (requested by this entry)" : plugin.Sites.Count == 0 ? "no websites" : string.Join(", ", plugin.Sites.Select(PluginNetworkPolicy.SiteLabel)); var cards = plugin.Cards.Count == 0 ? "none" : string.Join(", ", plugin.Cards.Select(card => - $"{Cell(card.Name)} ({(card.Scope == OverlayAddOnScope.Account ? "per account" : "global")})")); + $"{Plain(card.Name)} ({(card.Scope == OverlayAddOnScope.Account ? "per account" : "global")})")); text.AppendLine("| | |") .AppendLine("|---|---|") - .AppendLine($"| Name | {Cell(plugin.Name)} ({Cell(plugin.ShortLabel)}) |") - .AppendLine($"| Author | {Cell(plugin.Author)} |") + .AppendLine($"| Name | {Plain(plugin.Name)} ({Plain(plugin.ShortLabel)}) |") + .AppendLine($"| Author | {Plain(plugin.Author)} |") .AppendLine($"| Version | {plugin.Version} |") - .AppendLine($"| Description | {Cell(plugin.Description)} |") + .AppendLine($"| Description | {Plain(plugin.Description, 200)} |") .AppendLine($"| Can contact | {contact} |") .AppendLine($"| Cards | {cards} |") .AppendLine($"| Package | {plugin.Size} bytes |") @@ -145,20 +235,93 @@ public static string Summary( var listed = current?.Plugins.FirstOrDefault(other => other.Id == plugin.Id); var repository = entry.Repository.AbsoluteUri; - text.AppendLine(listed is null - ? $"New plugin. Review the code: {repository}/tree/{entry.Commit}{(entry.Path.Length > 0 ? "/" + entry.Path : "")}" - : $"Update from {listed.Version}. Review the changes: {repository}/compare/{listed.Commit}...{entry.Commit}"); + var sameRepository = listed is not null && listed.Repository == entry.Repository; + text.AppendLine(sameRepository + ? $"Update from {listed!.Version}. Review the changes: {repository}/compare/{listed.Commit}...{entry.Commit}" + : $"{(listed is null ? "New plugin" : $"Update from {listed.Version}, from another repository")}. " + + $"Review the code: {repository}/tree/{entry.Commit}{(entry.Path.Length > 0 ? "/" + entry.Path : "")}"); + if (listed is not null) + { + // What an update escalates is what a reviewer must not miss, so it is spelled out, not left to the table. + var shown = plugin.Sites.Select(PluginNetworkPolicy.SiteLabel).ToArray(); + var before = listed.Sites.Select(PluginNetworkPolicy.SiteLabel).ToArray(); + var changes = new List(); + if (plugin.AnySite != listed.AnySite) + { + changes.Add(plugin.AnySite ? "Any-website access gained." : "Any-website access dropped."); + } + + if (shown.Except(before).ToArray() is { Length: > 0 } added) + { + changes.Add("Sites added: " + string.Join(", ", added) + "."); + } + + if (before.Except(shown).ToArray() is { Length: > 0 } removed) + { + changes.Add("Sites removed: " + string.Join(", ", removed) + "."); + } + + if (listed.Repository != plugin.Repository) + { + changes.Add($"Repository changed from {listed.Repository.AbsoluteUri} to {repository}."); + } + + if (listed.Author != plugin.Author) + { + changes.Add($"Author changed from {Plain(listed.Author)} to {Plain(plugin.Author)}."); + } + + text.AppendLine(); + if (changes.Count == 0) + { + text.AppendLine("No change to access, sites, repository or author."); + } + else + { + text.AppendLine("Changed:").AppendLine(); + foreach (var change in changes) + { + text.AppendLine("- " + change); + } + } + } + text.AppendLine().AppendLine("Files in the package:").AppendLine(); using var archive = new ZipArchive(new MemoryStream(package)); - foreach (var file in archive.Entries) + foreach (var file in archive.Entries.Take(MaximumListedFiles)) + { + text.AppendLine($"- {Plain(file.FullName)} ({file.Length} bytes)"); + } + + if (archive.Entries.Count > MaximumListedFiles) { - text.AppendLine($"- `{file.FullName}` ({file.Length} bytes)"); + text.AppendLine($"- \u2026and {archive.Entries.Count - MaximumListedFiles} more"); } return text.ToString(); + } + + // Text from a plugin, an entry or a repository, made safe to put in the summary, which GitHub draws as Markdown: + // anything that could start a new line or hide text (control, formatting and separator characters) becomes "?", + // every character Markdown could act on gets a backslash, and a long value is cut and ends in "...". + private static string Plain(string value, int maximum = 100) + { + var result = new StringBuilder(); + foreach (var rune in value.EnumerateRunes()) + { + var text = rune.ToString(); + var piece = PluginText.HasUnsafeCharacter(text) ? "?" + : rune.IsBmp && MarkdownCharacters.Contains((char)rune.Value) ? "\\" + text + : text; + if (result.Length + piece.Length > maximum) + { + return result.Append('\u2026').ToString(); + } + + result.Append(piece); + } - // Plugin text goes into a Markdown table, so a pipe or a line break in it must not break the row. - static string Cell(string value) => value.Replace("|", "\\|").Replace("\r", " ").Replace("\n", " "); + return result.ToString(); } private static bool IsNewer(string version, string than) => diff --git a/src/FourFoldAccountManager.HubTool/Program.cs b/src/FourFoldAccountManager.HubTool/Program.cs index 7d76f37..be2e6e0 100644 --- a/src/FourFoldAccountManager.HubTool/Program.cs +++ b/src/FourFoldAccountManager.HubTool/Program.cs @@ -1,124 +1,162 @@ using System.Globalization; using FourFoldAccountManager.Core.Plugins.Hub; -// The plugin hub's command-line tool. The hub repository's workflows run it; it never runs a plugin's code. +// The plugin hub's command-line tool. The hub repository's workflows run it; it never runs a plugin's code. Its input +// is untrusted: `check` reads an entry file and a repository from a stranger's pull request, so a bad input is refused +// with a reason, never a stack trace. Exit code 0 when all is well, 1 when something is refused, 2 for bad usage. // check --hub --entry plugins/.json [--catalog ] [--work ] [--summary ] [--source ] // publish --hub --out [--catalog ] [--work ] [--source ] -// --catalog is the catalog that is live now, when there is one. --source uses a local folder as the repository +// --hub, --entry (check) and --out (publish) have no defaults. --catalog is the catalog that is live now: it must +// exist and be readable, and leaving it out says there is none yet. --source uses a local folder as the repository // instead of downloading it, for trying the tool by hand. const long MaximumRepositoryBytes = 50L * 1024 * 1024; -if (args.Length == 0 || args[0] is not ("check" or "publish") || args.Length % 2 == 0) +string[] knownOptions = ["--hub", "--entry", "--catalog", "--work", "--summary", "--source", "--out"]; +var options = new Dictionary(StringComparer.Ordinal); +var wellFormed = args.Length % 2 == 1; +for (var index = 1; wellFormed && index + 1 < args.Length; index += 2) { - Console.Error.WriteLine("Usage: check --hub --entry [...] | publish --hub --out [...]"); - return 2; + wellFormed = knownOptions.Contains(args[index]); + options[args[index]] = args[index + 1]; } -var options = new Dictionary(StringComparer.Ordinal); -for (var index = 1; index + 1 < args.Length; index += 2) +if (args.Length == 0 || args[0] is not ("check" or "publish") || !wellFormed || !options.ContainsKey("--hub") || + !options.ContainsKey(args[0] == "check" ? "--entry" : "--out")) { - options[args[index]] = args[index + 1]; + Console.Error.WriteLine( + "Usage: check --hub --entry [--catalog ] [--work ] [--summary ] [--source ]" + + " | publish --hub --out [--catalog ] [--work ] [--source ]"); + return 2; } -var hub = Option("--hub") ?? "."; -var work = Option("--work") ?? Path.Combine(Path.GetTempPath(), "fourfold-hub-" + Guid.NewGuid().ToString("N")); -var current = Option("--catalog") is { } catalogPath && File.Exists(catalogPath) - ? HubCatalogJson.Parse(File.ReadAllText(catalogPath)) - : null; +var hub = options["--hub"]; +var work = options.GetValueOrDefault("--work") ?? Path.Combine(Path.GetTempPath(), "fourfold-hub-" + Guid.NewGuid().ToString("N")); var today = DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); +HubCatalog? current = null; using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) }; -http.DefaultRequestHeaders.UserAgent.ParseAdd("FourFoldAccountManager-HubTool"); -if (args[0] == "check") +try { - var entryFile = Path.Combine(hub, Option("--entry") ?? string.Empty); - var fileName = Path.GetFileName(entryFile); - var (entry, error) = File.Exists(entryFile) - ? HubEntryReader.Read(fileName, File.ReadAllText(entryFile)) - : (null, "The entry file doesn't exist."); - var (removed, removedError) = ReadRemoved(); - error ??= removedError; - if (error is null && removed!.Any(removal => removal.Id == entry!.Id)) + return await RunAsync(); +} +catch (Exception exception) +{ + // Whatever is in the input, the tool says one line and stops: no stack trace, no half-written result. + Console.Error.WriteLine("hubtool: " + exception.GetType().Name); + return 1; +} + +async Task RunAsync() +{ + http.DefaultRequestHeaders.UserAgent.ParseAdd("FourFoldAccountManager-HubTool"); + + // A catalog that is named but can't be used must stop the run: carrying on as if there were none would turn off + // the version rule and re-list everything from scratch. + if (options.GetValueOrDefault("--catalog") is { } catalogPath) { - error = "This plugin is in removed.json. Take it out of that file to list it again."; + current = File.Exists(catalogPath) ? HubCatalogJson.Parse(File.ReadAllText(catalogPath)) : null; + if (current is null) + { + return Refuse("--catalog must be the live catalog.json: a file that exists and that FourFold can read."); + } } - HubCheckResult? result = null; - if (error is null) + // A wrong --hub would read as "no plugins, nothing pulled": a publish would delist every plugin and un-pull every + // pulled one. + var removedFile = Path.Combine(hub, "removed.json"); + var pluginsFolder = Path.Combine(hub, "plugins"); + if (!Directory.Exists(pluginsFolder) || !File.Exists(removedFile)) { - result = await CheckAsync(entry!); - error = result.Error; + return Refuse("--hub must be the hub repository's folder, with a plugins folder and a removed.json file in it."); } - var summary = HubSubmission.Summary(fileName, entry, error, result?.Plugin, result?.Package, current); - Console.WriteLine(summary); - if (Option("--summary") is { } summaryFile) + var (removed, removedError) = HubEntryReader.ReadRemoved(File.ReadAllText(removedFile)); + if (args[0] == "check") { - File.AppendAllText(summaryFile, summary + Environment.NewLine); - } + var entryFile = Path.Combine(hub, options["--entry"]); + var fileName = Path.GetFileName(entryFile); + var (entry, error) = File.Exists(entryFile) + ? HubEntryReader.Read(fileName, File.ReadAllText(entryFile)) + : (null, "The entry file doesn't exist."); + error ??= removedError; + if (error is null && removed!.Any(removal => removal.Id == entry!.Id)) + { + error = "This plugin is in removed.json. Take it out of that file to list it again."; + } - return error is null ? 0 : 1; -} + HubCheckResult? result = null; + if (error is null) + { + result = await CheckAsync(entry!); + error = result.Error; + } -var outFolder = Option("--out") ?? "out"; -Directory.CreateDirectory(outFolder); -var entries = new List(); -var problems = new List(); -var pluginsFolder = Path.Combine(hub, "plugins"); -foreach (var file in Directory.Exists(pluginsFolder) ? Directory.GetFiles(pluginsFolder, "*.json") : []) -{ - var (entry, error) = HubEntryReader.Read(Path.GetFileName(file), File.ReadAllText(file)); - if (entry is null) + var summary = HubSubmission.Summary(fileName, entry, error, result?.Plugin, result?.Package, current); + Console.WriteLine(summary); + if (options.GetValueOrDefault("--summary") is { } summaryFile) + { + File.AppendAllText(summaryFile, summary + Environment.NewLine); + } + + return error is null ? 0 : 1; + } + + var entries = new List(); + var problems = new List(); + foreach (var file in Directory.GetFiles(pluginsFolder, "*.json")) { - problems.Add($"{Path.GetFileName(file)}: {error}"); + var (entry, error) = HubEntryReader.Read(Path.GetFileName(file), File.ReadAllText(file)); + if (entry is null) + { + problems.Add($"plugins/{Path.GetFileName(file)}: {error}"); + } + else + { + entries.Add(entry); + } } - else + + if (removedError is not null) { - entries.Add(entry); + problems.Add(removedError); } -} -var (pulled, pulledError) = ReadRemoved(); -if (pulledError is not null) -{ - problems.Add(pulledError); -} + var build = problems.Count > 0 + ? new HubBuild(null, [], problems) + : HubSubmission.BuildCatalog(entries, removed!, current, entry => CheckAsync(entry).GetAwaiter().GetResult()); + foreach (var problem in build.Errors) + { + Console.Error.WriteLine(problem); + } -var build = problems.Count > 0 - ? new HubBuild(null, [], problems) - : HubSubmission.BuildCatalog(entries, pulled!, current, entry => CheckAsync(entry).GetAwaiter().GetResult()); -foreach (var problem in build.Errors) -{ - Console.Error.WriteLine(problem); -} + if (build.Catalog is null) + { + return 1; + } -if (build.Catalog is null) -{ - return 1; -} + var outFolder = options["--out"]; + Directory.CreateDirectory(outFolder); + foreach (var (name, bytes) in build.Packages) + { + File.WriteAllBytes(Path.Combine(outFolder, name), bytes); + } -foreach (var (name, bytes) in build.Packages) -{ - File.WriteAllBytes(Path.Combine(outFolder, name), bytes); + File.WriteAllText(Path.Combine(outFolder, "catalog.json"), HubCatalogJson.Write(build.Catalog)); + Console.WriteLine( + $"{build.Catalog.Plugins.Count} plugin(s) listed, {build.Packages.Count} new package(s), {build.Catalog.Removed.Count} removed."); + return 0; } -File.WriteAllText(Path.Combine(outFolder, "catalog.json"), HubCatalogJson.Write(build.Catalog)); -Console.WriteLine( - $"{build.Catalog.Plugins.Count} plugin(s) listed, {build.Packages.Count} new package(s), {build.Catalog.Removed.Count} removed."); -return 0; - -string? Option(string name) => options.GetValueOrDefault(name); - -(IReadOnlyList? Removed, string? Error) ReadRemoved() +int Refuse(string reason) { - var path = Path.Combine(hub, "removed.json"); - return File.Exists(path) ? HubEntryReader.ReadRemoved(File.ReadAllText(path)) : ([], null); + Console.Error.WriteLine(reason); + return 1; } // Gets the entry's repository at its commit onto disk, then checks the plugin in it. async Task CheckAsync(HubEntry entry) { - if (Option("--source") is { } source) + if (options.GetValueOrDefault("--source") is { } source) { return HubSubmission.Check(entry, source, current, today); } @@ -140,11 +178,17 @@ async Task CheckAsync(HubEntry entry) } using var stream = new MemoryStream(bytes); - SafeArchive.Extract(stream, folder, maximumFiles: 20_000, maximumBytes: 200L * 1024 * 1024, stripTopFolder: true); + SafeArchive.Extract( + stream, folder, maximumFiles: 20_000, maximumBytes: 200L * 1024 * 1024, stripTopFolder: true, + skipLinksAndOddNames: true); } catch (Exception exception) when (exception is InvalidDataException or IOException or UnauthorizedAccessException) { - return new HubCheckResult("The repository's archive couldn't be unpacked: " + exception.Message, null, null); + // The message is shown only for an InvalidDataException, whose text is fixed; any other exception's text can + // carry the path of a file the stranger named. + return new HubCheckResult( + "The repository's archive couldn't be unpacked" + (exception is InvalidDataException ? ": " + exception.Message : "."), + null, null); } return HubSubmission.Check(entry, folder, current, today); From f28bd77de1ea97531b0f864687d8ca611868375f Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:32:09 -0500 Subject: [PATCH 11/22] fix: keep the author visible in the community bar, and open exactly the link that was checked --- .../Plugins/PluginDescriptor.cs | 3 ++- .../Plugins/PluginApiTests.cs | 4 +++- .../Plugins/Web/PluginApi.cs | 20 ++++++++++++++++--- .../Plugins/Web/WebPlugin.cs | 2 ++ 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs b/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs index bb4e3d4..33c036a 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs @@ -23,6 +23,7 @@ public sealed record PluginDescriptor( // A short tag beside the plugin's name in the plugin list, such as "DEV". public string? Badge { get; init; } - // One line under the plugin's name in the plugin list, such as the sites it can contact. + // Text under the plugin's name in the plugin list. A community plugin gives two lines: its author, then the sites + // it can contact. public string? Detail { get; init; } } diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs index f77e2b0..068e2c0 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs @@ -58,7 +58,9 @@ public async Task OpenExternalOnlyOpensPublicHttpsLinksOnDeclaredSites() "file:///C:/Windows/System32/calc.exe", "javascript:alert(1)", "http://example.com/", "https://localhost/", "https://192.168.1.1/", "https://printer.local/", "https://user@example.com/", "ms-settings:", - "not a url" + "not a url", + // An invalid international host name, for which reading the Uri's IdnHost throws. + "https://a\u200Db.example/" }) { Assert.Equal("invalid-argument", ErrorCode(await Call("openExternal", new { url }))); diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs index bc5ffb5..1779d7f 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs @@ -280,14 +280,14 @@ private void OpenExternal(string url) { // A "user@" prefix can make a link read as a trusted site while it goes somewhere else. if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps || - uri.UserInfo.Length > 0 || PluginNetworkPolicy.IsLocalHost(uri.IdnHost)) + uri.UserInfo.Length > 0 || TryGetIdnHost(uri) is not { } idnHost || PluginNetworkPolicy.IsLocalHost(idnHost)) { throw new PluginApiException("invalid-argument", "Only https links can be opened."); } // A plugin can send the user only where it may go itself: the sites it declared, or anywhere once the hub has // cleared it for any website. That list is what the hub shows and what was reviewed. - if (PluginNetworkPolicy.IsPluginHost(uri.IdnHost) || !PluginNetworkPolicy.IsAllowed(uri, manifest, trust)) + if (PluginNetworkPolicy.IsPluginHost(idnHost) || !PluginNetworkPolicy.IsAllowed(uri, manifest, trust)) { throw new PluginApiException("site-not-allowed", "A plugin can only open links on the sites it declares."); } @@ -305,6 +305,20 @@ private void OpenExternal(string url) } _lastOpened = now; - host.OpenInBrowser(uri); + // The browser gets the host as it was checked (its xn-- form), not a Unicode or fullwidth spelling of it. + host.OpenInBrowser(new UriBuilder(uri) { Host = idnHost }.Uri); + } + + // IdnHost throws for some invalid international host names; such a link is a bad argument, not a failure. + private static string? TryGetIdnHost(Uri uri) + { + try + { + return uri.IdnHost; + } + catch (UriFormatException) + { + return null; + } } } diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs index d4e75f0..666307b 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs @@ -112,6 +112,7 @@ public WebPlugin( Text = manifest.Name, FontSize = 11, FontWeight = FontWeights.SemiBold, + MaxWidth = 100, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis }; @@ -149,6 +150,7 @@ public WebPlugin( Padding = new Thickness(9, 0, 9, 0), BorderThickness = new Thickness(0, 0, 0, 1), CornerRadius = new CornerRadius(8, 8, 0, 0), + // The tag stays first, so it is measured first and can never be squeezed out. Child = new DockPanel { Children = { barTag, barName, barAuthor } } }; bar.SetResourceReference(Border.BackgroundProperty, "Brush.SurfaceRaised"); From d95264f2975a76a0ca02f495baa6ab808b5c31dd Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:39:04 -0500 Subject: [PATCH 12/22] fix: never start a hub plugin before the user's settings are known, and keep the plugin list calm and in order --- .../Plugins/Web/CommunityPluginManager.cs | 51 ++++++++++++++++--- .../Plugins/Web/PluginBrowser.cs | 13 +++-- 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs index 52cfcce..11278a9 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs @@ -33,10 +33,14 @@ public sealed class CommunityPluginManager : IDisposable private IReadOnlyList _hubLoads = []; private FileSystemWatcher? _watcher; private bool _disposed; + private bool _changedQueued; private string? _folderError; private string? _startError; private PanelSettings _settings = PanelSettings.Default; + // False until the first ApplyAsync: before that _settings is only the default, which switches everything on. + private bool _settingsGiven; + public CommunityPluginManager(LocalDataPaths paths, IPluginHostData host, Panel parkingHost, PluginCardStore cards) { _paths = paths; @@ -80,6 +84,7 @@ public async Task ApplyAsync(PanelSettings settings) } _settings = settings; + _settingsGiven = true; if (!settings.PluginDeveloperMode) { if (_dev.Count > 0 || _rejected.Count > 0 || _watcher is not null || _folderError is not null) @@ -150,8 +155,17 @@ public void Unload(string id) // After an uninstall deleted the plugin's settings file: the store that cached it must not write it back. public void Forget(string id) => _storages.Remove(id); - public Task ClearBrowserDataAsync(string id) => - _browser.ClearOriginAsync(_parkingHost, PluginNetworkPolicy.Origin(id)); + // Best effort, and bounded: an uninstall that awaits this must not hang if the borrowed web view never starts. + public async Task ClearBrowserDataAsync(string id) + { + if (_disposed) + { + return; + } + + await Task.WhenAny( + _browser.ClearOriginAsync(_parkingHost, PluginNetworkPolicy.Origin(id)), Task.Delay(TimeSpan.FromSeconds(10))); + } public void PostEvent(string name, object? data) { @@ -214,6 +228,12 @@ private void ReconcileHub() // One plugin that can't be loaded must never take the others down. } } + + // A replaced plugin was appended; the list keeps the order of the loads, so an update never moves a plugin. + var order = wanted.ToList(); + var ordered = _hub.OrderBy(plugin => order.IndexOf(_hubLoadOf[plugin])).ToArray(); + _hub.Clear(); + _hub.AddRange(ordered); } private WebPlugin Create(PluginManifest manifest, PluginTrust trust) @@ -226,14 +246,25 @@ private WebPlugin Create(PluginManifest manifest, PluginTrust trust) var plugin = new WebPlugin(manifest, trust, _browser, _parkingHost, _host, _cards, storage); // A plugin stops or restarts by itself (a flood, a crash, its Reload button). That can happen inside a web view - // event or mid-start, and Changed re-renders the sidebar, so it is raised later. - plugin.RunningChanged += () => _dispatcher.BeginInvoke(() => + // event or mid-start, and Changed re-renders the sidebar, so it is raised later, once for however many plugins + // changed in the meantime. + plugin.RunningChanged += () => { - if (!_disposed) + if (_changedQueued) { - Changed?.Invoke(); + return; } - }); + + _changedQueued = true; + _dispatcher.BeginInvoke(() => + { + _changedQueued = false; + if (!_disposed) + { + Changed?.Invoke(); + } + }); + }; return plugin; } @@ -313,6 +344,12 @@ private void AbandonLoad() // Starts switched-on plugins and stops switched-off ones. Returns whether anything changed. private async Task SyncRunningAsync() { + // Until the user's settings are known, a plugin they switched off could be started; ApplyAsync starts them all. + if (!_settingsGiven) + { + return false; + } + var changed = _startError is not null; _startError = null; var starts = new List>(); diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs index e41d08e..1d35eab 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs @@ -45,10 +45,11 @@ public async Task ClearOriginAsync(Panel parkingHost, Uri origin) return; } - var view = new WebView2CompositionControl(); - parkingHost.Children.Add(view); + WebView2CompositionControl? view = null; try { + view = new WebView2CompositionControl(); + parkingHost.Children.Add(view); await view.EnsureCoreWebView2Async(await GetEnvironmentAsync()); await view.CoreWebView2.CallDevToolsProtocolMethodAsync( "Storage.clearDataForOrigin", @@ -60,8 +61,12 @@ await view.CoreWebView2.CallDevToolsProtocolMethodAsync( } finally { - parkingHost.Children.Remove(view); - view.Dispose(); + // Null when the control could not even be created. + if (view is not null) + { + parkingHost.Children.Remove(view); + view.Dispose(); + } } } } From dafebb592f65623556c5023c09074b867f1cf880 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:43:06 -0500 Subject: [PATCH 13/22] feat: add the plugin hub page to the plugin panel --- .../Plugins/Hub/HubViewState.cs | 22 ++ .../Views/PluginSidebar.xaml.cs | 355 +++++++++++++++++- 2 files changed, 376 insertions(+), 1 deletion(-) create mode 100644 src/FourFoldAccountManager.Desktop/Plugins/Hub/HubViewState.cs diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Hub/HubViewState.cs b/src/FourFoldAccountManager.Desktop/Plugins/Hub/HubViewState.cs new file mode 100644 index 0000000..103b367 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Hub/HubViewState.cs @@ -0,0 +1,22 @@ +using FourFoldAccountManager.Core.Plugins.Hub; + +namespace FourFoldAccountManager.Desktop.Plugins.Hub; + +// An installed plugin the hub no longer lists, with the reason to show. +public sealed record HubPulledPlugin(string Id, string Name, string Reason); + +// Everything the hub page and the plugin list show about the hub. +public sealed record HubViewState( + bool Loading, + bool Unreachable, + IReadOnlyList Plugins, + IReadOnlySet Installed, + // Plugins being installed, updated or removed right now. + IReadOnlySet Busy, + // The reason a plugin's last install or removal failed, by plugin id. + IReadOnlyDictionary Errors, + IReadOnlyList Pulled) +{ + public static HubViewState Empty { get; } = new( + false, false, [], new HashSet(), new HashSet(), new Dictionary(), []); +} diff --git a/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs b/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs index 7652ea1..b7aa088 100644 --- a/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; @@ -5,8 +6,11 @@ using System.Windows.Media; using System.Windows.Media.Imaging; using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Overlay; using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; using FourFoldAccountManager.Desktop.Plugins; +using FourFoldAccountManager.Desktop.Plugins.Hub; using FourFoldAccountManager.Desktop.Plugins.Web; namespace FourFoldAccountManager.Desktop.Views; @@ -28,6 +32,12 @@ public partial class PluginSidebar : UserControl private string? _pressedId; private IReadOnlyList _rejected = []; private string? _communityError; + private HubViewState _hub = HubViewState.Empty; + private bool _showingHub; + private string? _hubExpandedId; + private Grid? _hubPage; + private TextBox? _hubSearch; + private StackPanel? _hubRows; public PluginSidebar() { @@ -43,6 +53,12 @@ public PluginSidebar() public event Action? OpenDevFolderRequested; // Opening the plugin list from a closed panel counts as opening the panel. public event Action? PanelOpenRequested; + // The hub page was opened; a good moment to check the hub. + public event Action? HubOpened; + public event Action? HubRetryRequested; + public event Action? HubInstallRequested; + public event Action? HubUninstallRequested; + public event Action? HubSourceRequested; // In the tools window the panel never closes, since a window that's just a strip would be odd. Moving between the // main window and the tools window starts from the plugin view, not the plugin list or a settings page. @@ -58,6 +74,7 @@ public bool StayOpen _stayOpen = value; _showingList = false; _settingsFor = null; + _showingHub = false; Render(_settings); } } @@ -75,6 +92,12 @@ public void SetCommunityState(IReadOnlyList rejected, string? st Render(_settings); } + public void SetHubState(HubViewState state) + { + _hub = state; + Render(_settings); + } + // True while this plugin's panel is the page on screen. public bool IsShowing(string pluginId) => IsVisible && !_showingList && ShownPlugin()?.Descriptor.Id == pluginId; @@ -158,7 +181,9 @@ private void RenderPage(IFourFoldPlugin? shown) PanelColumn.Width = !visible ? new GridLength(0) : _stayOpen ? new GridLength(1, GridUnitType.Star) : new GridLength(250); PanelGapColumn.Width = new GridLength(visible ? 6 : 0); - BackButton.Visibility = _showingList && _settingsFor is not null ? Visibility.Visible : Visibility.Collapsed; + BackButton.Visibility = _showingList && (_settingsFor is not null || _showingHub) + ? Visibility.Visible + : Visibility.Collapsed; // A plugin's panel carries its own header, so only the plugin list and settings pages get the host's. var showingPlugin = !_showingList && shown is not null; @@ -170,6 +195,12 @@ private void RenderPage(IFourFoldPlugin? shown) TitleText.Text = "Settings"; PageHost.Content = settingsPlugin.SettingsPage; } + else if (_showingList && _showingHub) + { + KickerText.Text = "PLUGINS"; + TitleText.Text = "Plugin hub"; + PageHost.Content = HubPage(); + } else if (_showingList) { KickerText.Text = "PLUGINS"; @@ -193,6 +224,21 @@ private void RenderPage(IFourFoldPlugin? shown) private UIElement BuildPluginList() { var list = new StackPanel(); + var hubButton = new Button + { + Content = "Plugin hub", + Height = 30, + Margin = new Thickness(0, 0, 0, 10), + Style = (Style)FindResource("AppButtonStyle") + }; + hubButton.Click += (_, _) => + { + _showingHub = true; + _hubExpandedId = null; + Render(_settings); + HubOpened?.Invoke(); + }; + list.Children.Add(hubButton); foreach (var descriptor in PluginLayoutPolicy.Ordered(_settings, Descriptors)) { var plugin = Find(descriptor.Id)!; @@ -267,6 +313,43 @@ private UIElement BuildPluginList() list.Children.Add(border); } + // An installed plugin the hub no longer lists: it can't run, so it has no switch, only its reason and a way out. + foreach (var pulled in _hub.Pulled) + { + var name = new TextBlock { Text = pulled.Name, VerticalAlignment = VerticalAlignment.Center }; + name.SetResourceReference(TextBlock.ForegroundProperty, "Brush.TextMuted"); + var uninstall = new Button + { + Content = "Uninstall", + Height = 26, + Padding = new Thickness(8, 0, 8, 0), + Margin = new Thickness(6, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center, + IsEnabled = !_hub.Busy.Contains(pulled.Id), + Style = (Style)FindResource("AppButtonStyle") + }; + AutomationProperties.SetName(uninstall, $"Uninstall {pulled.Name}"); + uninstall.Click += (_, _) => HubUninstallRequested?.Invoke(pulled.Id); + var row = new Grid(); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + row.Children.Add(CreateNameBlock( + name, null, "Removed from the hub. " + pulled.Reason, detailBrush: "Brush.Danger")); + Grid.SetColumn(uninstall, 1); + row.Children.Add(uninstall); + var border = new Border + { + Padding = new Thickness(10, 8, 10, 8), + Margin = new Thickness(0, 0, 0, 6), + CornerRadius = new CornerRadius(6), + BorderThickness = new Thickness(1), + Child = row + }; + border.SetResourceReference(Border.BackgroundProperty, "Brush.SurfaceRaised"); + border.SetResourceReference(Border.BorderBrushProperty, "Brush.Border"); + list.Children.Add(border); + } + if (_communityError is not null) { var error = new TextBlock { Text = _communityError, FontSize = 11, TextWrapping = TextWrapping.Wrap }; @@ -331,6 +414,273 @@ private UIElement BuildPluginList() }; } + // The hub page is built once and kept, so what is typed in the search box survives every refresh of the rows. + private UIElement HubPage() + { + if (_hubPage is null) + { + _hubSearch = new TextBox { Style = (Style)FindResource("InputStyle") }; + AutomationProperties.SetName(_hubSearch, "Search plugins"); + var hint = new TextBlock + { + Text = "Search plugins", + IsHitTestVisible = false, + Margin = new Thickness(10, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center + }; + hint.SetResourceReference(TextBlock.ForegroundProperty, "Brush.TextMuted"); + _hubSearch.TextChanged += (_, _) => + { + hint.Visibility = _hubSearch.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed; + RebuildHubRows(); + }; + var searchArea = new Grid { Margin = new Thickness(0, 0, 0, 8) }; + searchArea.Children.Add(_hubSearch); + searchArea.Children.Add(hint); + + _hubRows = new StackPanel(); + var scroll = new ScrollViewer + { + Content = _hubRows, + VerticalScrollBarVisibility = ScrollBarVisibility.Auto, + HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled + }; + Grid.SetRow(scroll, 1); + _hubPage = new Grid(); + _hubPage.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + _hubPage.RowDefinitions.Add(new RowDefinition()); + _hubPage.Children.Add(searchArea); + _hubPage.Children.Add(scroll); + } + + RebuildHubRows(); + return _hubPage; + } + + private void RebuildHubRows() + { + if (_hubRows is null || _hubSearch is null) + { + return; + } + + _hubRows.Children.Clear(); + if (_hub.Unreachable) + { + _hubRows.Children.Add(HubNote( + "The hub couldn't be reached. The plugins you have installed keep working.", "Brush.Danger")); + var retry = new Button + { + Content = "Try again", + Height = 28, + Padding = new Thickness(10, 0, 10, 0), + Margin = new Thickness(0, 6, 0, 10), + HorizontalAlignment = HorizontalAlignment.Left, + IsEnabled = !_hub.Loading, + Style = (Style)FindResource("AppButtonStyle") + }; + retry.Click += (_, _) => HubRetryRequested?.Invoke(); + _hubRows.Children.Add(retry); + } + + if (_hub.Plugins.Count == 0) + { + if (_hub.Loading) + { + _hubRows.Children.Add(HubNote("Loading the hub…", "Brush.TextMuted")); + } + else if (!_hub.Unreachable) + { + _hubRows.Children.Add(HubNote("The hub has no plugins yet.", "Brush.TextMuted")); + } + + return; + } + + var matches = HubPolicy.Search(_hub.Plugins, _hubSearch.Text, _hub.Installed); + if (matches.Count == 0) + { + _hubRows.Children.Add(HubNote("No plugins match.", "Brush.TextMuted")); + } + + foreach (var plugin in matches) + { + _hubRows.Children.Add(CreateHubRow(plugin)); + } + } + + // One small wrapping line of text. Everything from the catalog is shown this way: as plain text. + private static TextBlock HubNote(string text, string brush) + { + var note = new TextBlock { Text = text, FontSize = 11, Margin = new Thickness(0, 3, 0, 0), TextWrapping = TextWrapping.Wrap }; + note.SetResourceReference(TextBlock.ForegroundProperty, brush); + return note; + } + + private Border CreateHubRow(HubPlugin plugin) + { + var installed = _hub.Installed.Contains(plugin.Id); + var busy = _hub.Busy.Contains(plugin.Id); + var expanded = _hubExpandedId == plugin.Id; + void Toggle() + { + _hubExpandedId = expanded ? null : plugin.Id; + RebuildHubRows(); + } + + // The first letter of the name stands in for an icon; the plugin's own icon shows in the strip once installed. + var tileText = new TextBlock + { + Text = StringInfo.GetNextTextElement(plugin.Name).ToUpperInvariant(), + FontWeight = FontWeights.Bold, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + tileText.SetResourceReference(TextBlock.ForegroundProperty, "Brush.AccentGold"); + var tile = new Border + { + Width = 26, + Height = 26, + CornerRadius = new CornerRadius(5), + Margin = new Thickness(0, 0, 8, 0), + VerticalAlignment = VerticalAlignment.Top, + Child = tileText + }; + tile.SetResourceReference(Border.BackgroundProperty, "Brush.BorderStrong"); + + var text = new StackPanel(); + text.Children.Add(new TextBlock + { + Text = plugin.Name, + FontWeight = FontWeights.SemiBold, + TextWrapping = TextWrapping.Wrap + }); + text.Children.Add(HubNote($"by {plugin.Author} · v{plugin.Version}", "Brush.TextMuted")); + if (_hub.Errors.TryGetValue(plugin.Id, out var error)) + { + text.Children.Add(HubNote(error, "Brush.Danger")); + } + + if (expanded) + { + if (plugin.Description.Length > 0) + { + text.Children.Add(HubNote(plugin.Description, "Brush.TextSecondary")); + } + + // SiteLabel shows the real xn-- host name, so a look-alike Unicode host name can't pass for another site. + text.Children.Add(HubNote( + plugin.AnySite ? "Can contact: any website" + : plugin.Sites.Count == 0 ? "Can contact: no websites" + : "Can contact: " + string.Join(", ", plugin.Sites.Select(PluginNetworkPolicy.SiteLabel)), + "Brush.TextMuted")); + if (plugin.Cards.Count > 0) + { + text.Children.Add(HubNote( + "Adds cards: " + string.Join(", ", plugin.Cards.Select(card => + $"{card.Name} ({(card.Scope == OverlayAddOnScope.Account ? "per account" : "global")})")), + "Brush.TextMuted")); + } + + if (DateOnly.TryParseExact( + plugin.Reviewed, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var reviewed)) + { + text.Children.Add(HubNote( + "Reviewed " + reviewed.ToString("d MMM yyyy", CultureInfo.InvariantCulture), "Brush.TextMuted")); + } + } + + var actions = new WrapPanel { Margin = new Thickness(0, 6, 0, 0) }; + // A button as well as the row click, so the details can be opened from the keyboard. + var details = new Button + { + Content = expanded ? "Less" : "Details", + Height = 24, + Padding = new Thickness(8, 0, 8, 0), + Style = (Style)FindResource("AppButtonStyle") + }; + AutomationProperties.SetName(details, $"{plugin.Name} details"); + details.Click += (_, _) => Toggle(); + actions.Children.Add(details); + if (expanded) + { + var source = new Button + { + Content = "Source", + Height = 24, + Padding = new Thickness(8, 0, 8, 0), + Margin = new Thickness(6, 0, 0, 0), + Style = (Style)FindResource("AppButtonStyle") + }; + source.Click += (_, _) => HubSourceRequested?.Invoke(plugin.Repository); + actions.Children.Add(source); + if (installed) + { + var uninstall = new Button + { + Content = "Uninstall", + Height = 24, + Padding = new Thickness(8, 0, 8, 0), + Margin = new Thickness(6, 0, 0, 0), + IsEnabled = !busy, + Style = (Style)FindResource("AppButtonStyle") + }; + AutomationProperties.SetName(uninstall, $"Uninstall {plugin.Name}"); + uninstall.Click += (_, _) => HubUninstallRequested?.Invoke(plugin.Id); + actions.Children.Add(uninstall); + } + } + + text.Children.Add(actions); + Grid.SetColumn(text, 1); + + FrameworkElement action; + if (installed && !busy) + { + action = HubNote("Installed", "Brush.TextMuted"); + } + else + { + var install = new Button + { + Content = busy ? "Working…" : "Install", + Height = 26, + Padding = new Thickness(10, 0, 10, 0), + IsEnabled = !busy, + Style = (Style)FindResource("PrimaryButtonStyle") + }; + AutomationProperties.SetName(install, $"Install {plugin.Name}"); + install.Click += (_, _) => HubInstallRequested?.Invoke(plugin.Id); + action = install; + } + + action.Margin = new Thickness(8, 0, 0, 0); + action.VerticalAlignment = VerticalAlignment.Top; + Grid.SetColumn(action, 2); + + var row = new Grid(); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + row.Children.Add(tile); + row.Children.Add(text); + row.Children.Add(action); + var border = new Border + { + Padding = new Thickness(10, 8, 10, 8), + Margin = new Thickness(0, 0, 0, 6), + CornerRadius = new CornerRadius(6), + BorderThickness = new Thickness(1), + Cursor = Cursors.Hand, + Child = row + }; + border.SetResourceReference(Border.BackgroundProperty, "Brush.SurfaceRaised"); + border.SetResourceReference(Border.BorderBrushProperty, expanded ? "Brush.AccentGold" : "Brush.Border"); + // A button inside the row handles its own click, so this only sees clicks on the row itself. + border.MouseLeftButtonUp += (_, _) => Toggle(); + return border; + } + // A plugin list row's text: the name with an optional small tag beside it, and an optional line underneath. private static StackPanel CreateNameBlock(TextBlock name, string? badge, string? detail, string detailBrush) { @@ -433,6 +783,7 @@ private void PluginIcon_Click(string id) var wasShown = !_showingList && ReferenceEquals(ShownPlugin(), Find(id)); _showingList = false; _settingsFor = null; + _showingHub = false; if (wasShown) { // Clicking the lit icon closes the panel, except in the tools window. @@ -464,6 +815,7 @@ private void PluginListButton_Click(object sender, RoutedEventArgs e) _showingList = false; _settingsFor = null; + _showingHub = false; // Clicking the lit wrench closes the panel; the tools window goes back to the last plugin instead. if (_stayOpen) { @@ -477,6 +829,7 @@ private void PluginListButton_Click(object sender, RoutedEventArgs e) private void BackButton_Click(object sender, RoutedEventArgs e) { _settingsFor = null; + _showingHub = false; Render(_settings); } From b8a9097e014f05adc6699019a9d3964650048dd8 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:53:23 -0500 Subject: [PATCH 14/22] feat: check the plugin hub, and install, update and uninstall its plugins --- .../MainWindow.CommunityPlugins.cs | 14 + .../MainWindow.xaml.cs | 5 + .../Plugins/Hub/PluginHub.cs | 407 ++++++++++++++++++ 3 files changed, 426 insertions(+) create mode 100644 src/FourFoldAccountManager.Desktop/Plugins/Hub/PluginHub.cs diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs index 99f15a3..846aa3d 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs @@ -5,8 +5,10 @@ using FourFoldAccountManager.Core.Models; using FourFoldAccountManager.Core.Overlay; using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; using FourFoldAccountManager.Core.Timing; using FourFoldAccountManager.Desktop.Plugins; +using FourFoldAccountManager.Desktop.Plugins.Hub; using FourFoldAccountManager.Desktop.Plugins.Web; using FourFoldAccountManager.Desktop.Views; @@ -19,6 +21,7 @@ public partial class MainWindow : IPluginHostData private readonly Dictionary _postedXpUpdates = []; private CommunityPluginManager _communityPlugins = null!; + private PluginHub _pluginHub = null!; private string _postedAccounts = string.Empty; private System.Windows.Threading.DispatcherTimer? _pluginCardRefreshTimer; @@ -36,6 +39,17 @@ private void InitializeCommunityPlugins(LocalDataPaths paths) RefreshPluginSidebar(); RefreshTrackerRows(); }; + _pluginHub = new PluginHub(paths, _communityPlugins); + _pluginHub.Changed += () => PluginSidebar.SetHubState(_pluginHub.ViewState); + // An uninstalled plugin's cards, its place in the strip and its switch go from the saved settings too. + _pluginHub.Uninstalled += id => + _ = ApplyPluginChangeAsync(settings => HubPolicy.WithUninstalled(settings, id), refreshEffects: true); + PluginSidebar.HubOpened += () => _ = _pluginHub.RefreshAsync(userAsked: false); + PluginSidebar.HubRetryRequested += () => _ = _pluginHub.RefreshAsync(userAsked: true); + PluginSidebar.HubInstallRequested += id => _ = _pluginHub.InstallAsync(id); + PluginSidebar.HubUninstallRequested += id => _ = _pluginHub.UninstallAsync(id); + // The catalog reader only lets through https://github.com//, and OpenInBrowser opens https only. + PluginSidebar.HubSourceRequested += uri => ((IPluginHostData)this).OpenInBrowser(uri); _pluginCards.Changed += QueuePluginCardRefresh; _timer.StateChanged += () => _communityPlugins.PostEvent("timer.changed", null); PluginSidebar.DeveloperModeChangeRequested += on => diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs index 79c26ce..308e33f 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs @@ -331,6 +331,9 @@ private async void MainWindow_Loaded(object sender, RoutedEventArgs e) SetManagerEnabled(true); // Not awaited: a slow or stuck plugin start must never keep the manager disabled. _ = _communityPlugins.ApplyAsync(_panelSettings); + // After ApplyAsync: the manager starts no hub plugin until it has seen the user's settings, so a plugin + // they switched off is never started first. + _ = _pluginHub.StartAsync(); LayoutPicker.SelectedValue = _panelSettings.Layout; AccountsListBox.SelectedIndex = _accounts.Count > 0 ? 0 : -1; UpdateAccountActions(); @@ -3422,6 +3425,8 @@ private async void MainWindow_Closing(object? sender, System.ComponentModel.Canc // typed just before closing reaches disk instead of being lost. _plugins.XpCalc.View.FlushPendingTargetSave(); _pluginCardRefreshTimer?.Stop(); + // First, so a download that finishes now can't reach the plugins that are being disposed. + _pluginHub.Dispose(); _communityPlugins.Dispose(); try diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Hub/PluginHub.cs b/src/FourFoldAccountManager.Desktop/Plugins/Hub/PluginHub.cs new file mode 100644 index 0000000..0c6985d --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Hub/PluginHub.cs @@ -0,0 +1,407 @@ +using System.Net.Http; +using System.Text; +using System.Windows.Threading; +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; +using FourFoldAccountManager.Desktop.Plugins.Web; + +namespace FourFoldAccountManager.Desktop.Plugins.Hub; + +// The plugin hub as the app sees it: checks the catalog, installs and updates plugins, stops the ones that were +// pulled, and tells the plugin manager which installed plugins may run. Create and use it on the UI thread. Nothing +// here throws into the app: a failure leaves things as they were and shows in ViewState. +public sealed class PluginHub : IDisposable +{ + // A hub page that is opened again and again checks the hub at most this often. + private const long MinimumGapMilliseconds = 60_000; + + private const string RemoveFailed = "The plugin couldn't be removed."; + + private readonly HubStore _store; + private readonly CommunityPluginManager _manager; + private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(60) }; + private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromHours(6) }; + + // Start, refresh, install and uninstall run one at a time. Each swaps plugin folders and tells the manager what may + // run; interleaved, one would load a plugin from the folder another is replacing, or list one that is being removed. + private readonly SemaphoreSlim _gate = new(1, 1); + + // Plugins being installed, updated or removed, from the click until the operation ends, so a second click does + // nothing and the page shows the plugin as busy while it waits for its turn. + private readonly HashSet _busy = new(StringComparer.Ordinal); + private readonly Dictionary _errors = new(StringComparer.Ordinal); + private HubCatalog? _catalog; + private IReadOnlyList _installed = []; + private IReadOnlyList _pulled = []; + private bool _loading; + private bool _unreachable; + private bool _disposed; + private long? _lastCheck; + + public PluginHub(LocalDataPaths paths, CommunityPluginManager manager) + { + _store = new HubStore(paths); + _manager = manager; + _http.DefaultRequestHeaders.UserAgent.ParseAdd("FourFoldAccountManager"); + _timer.Tick += (_, _) => _ = RefreshAsync(userAsked: false); + } + + public event Action? Changed; + + // A plugin was uninstalled; its cards and ids should go from the saved settings. + public event Action? Uninstalled; + + public HubViewState ViewState => new( + _loading, + _unreachable, + _catalog?.Plugins ?? [], + _installed.Select(plugin => plugin.Id).ToHashSet(StringComparer.Ordinal), + new HashSet(_busy, StringComparer.Ordinal), + new Dictionary(_errors, StringComparer.Ordinal), + _pulled); + + // Reads what is installed and the last catalog from disk and starts the plugins that may run. The hub itself is + // contacted only when something is installed; otherwise not until the hub page is opened. + public Task StartAsync() => RunAsync(StartCoreAsync); + + // Downloads the catalog, installs approved updates, and stops plugins that were pulled. + public Task RefreshAsync(bool userAsked) + { + var askedAt = Environment.TickCount64; + return RunAsync(async () => + { + if (IsDue(userAsked, askedAt)) + { + await RefreshCoreAsync(); + } + }); + } + + public async Task InstallAsync(string id) + { + if (_disposed || _catalog?.Plugins.Any(plugin => plugin.Id == id) != true || !_busy.Add(id)) + { + return; + } + + _errors.Remove(id); + try + { + Notify(); + await RunAsync(async () => + { + // The catalog may have changed while this waited for its turn. + if (_catalog?.Plugins.FirstOrDefault(plugin => plugin.Id == id) is { } listed) + { + await InstallCoreAsync(listed); + PushLoads(); + } + }); + } + finally + { + _busy.Remove(id); + Notify(); + } + } + + public async Task UninstallAsync(string id) + { + if (_disposed || !_busy.Add(id)) + { + return; + } + + _errors.Remove(id); + try + { + Notify(); + await RunAsync(async () => + { + // Only a plugin the record holds is removed: an uninstall also deletes the plugin's saved settings. + if (_installed.Any(plugin => plugin.Id == id)) + { + await RemoveAsync(id); + PushLoads(); + } + }); + } + finally + { + _busy.Remove(id); + Notify(); + } + } + + // Doesn't wait for the gate: an operation that holds it finds _disposed set and stops at its next step, and the + // download it may be waiting on ends when the client is disposed. + public void Dispose() + { + _disposed = true; + _timer.Stop(); + _http.Dispose(); + } + + // Runs one operation with the gate held. An operation that gets its turn after Dispose does nothing. + private async Task RunAsync(Func operation) + { + await _gate.WaitAsync(); + try + { + if (!_disposed) + { + await operation(); + } + } + catch (Exception) + { + // Every operation records its own failures where the hub page can show them; this is the last stop, so + // nothing reaches the app. + } + finally + { + _gate.Release(); + } + } + + // A refresh that waited for its turn runs only if it is still due: a user's request is met by any check that came + // back after the request was made, and a routine one by a check within the last minute. + private bool IsDue(bool userAsked, long askedAt) => + _lastCheck is not { } last || + (userAsked ? last < askedAt : Environment.TickCount64 - last >= MinimumGapMilliseconds); + + // Gate held. + private async Task StartCoreAsync() + { + try + { + var (installed, catalog) = await Task.Run(() => + { + _store.CleanUp(); + return (_store.LoadInstalled(), _store.LoadCatalog()); + }); + if (_disposed) + { + return; + } + + _installed = installed; + _catalog = catalog; + PushLoads(); + if (_installed.Count > 0) + { + await RefreshCoreAsync(); + } + } + catch (Exception) + { + // The record of installed plugins can't be read right now. Hub plugins stay off for this session, and + // nothing is written over it. + } + } + + // Gate held. Loading is true only while this runs, not while a refresh waits for its turn. + private async Task RefreshCoreAsync() + { + _loading = true; + try + { + Notify(); + var bytes = await HubHttp.DownloadAsync( + _http, HubAddresses.Catalog, HubLimits.MaximumCatalogBytes, CancellationToken.None); + if (_disposed) + { + return; + } + + _lastCheck = Environment.TickCount64; + var text = bytes is null ? null : Encoding.UTF8.GetString(bytes); + if (HubCatalogJson.Parse(text) is not { } catalog) + { + // The last good catalog stays in use. + _unreachable = true; + return; + } + + _unreachable = false; + _catalog = catalog; + try + { + await _store.SaveCatalogAsync(text!, CancellationToken.None); + } + catch (Exception) + { + // Offline starts fall back to the older copy; the next check saves again. + } + + // Approved updates install without asking, and an install a crash left without its files is repaired. + var due = HubPolicy.Updates(catalog, _installed) + .Concat(catalog.Plugins.Where(plugin => + _installed.Any(other => other.Id == plugin.Id) && !_store.IsIntact(plugin.Id))) + .DistinctBy(plugin => plugin.Id) + .ToArray(); + foreach (var plugin in due) + { + if (_disposed) + { + return; + } + + // A plugin the user has already asked to install or remove is theirs to finish. + if (!_busy.Add(plugin.Id)) + { + continue; + } + + try + { + await InstallCoreAsync(plugin); + } + finally + { + _busy.Remove(plugin.Id); + Notify(); + } + } + + PushLoads(); + } + catch (Exception) + { + _unreachable = true; + } + finally + { + _loading = false; + Notify(); + } + } + + // Gate held, and the plugin's id is in _busy. Downloads, checks and installs one listed plugin over whatever + // version is there. A failure leaves the installed version in place and records a reason for the hub page. The + // caller loads the plugin again afterwards (PushLoads). + private async Task InstallCoreAsync(HubPlugin plugin) + { + _errors.Remove(plugin.Id); + try + { + Notify(); + var package = await HubHttp.DownloadAsync( + _http, HubAddresses.Package(plugin.Id, plugin.Commit), + Math.Min(plugin.Size, HubLimits.MaximumPackageBytes), CancellationToken.None); + if (_disposed) + { + return; + } + + if (package is null) + { + _errors[plugin.Id] = "The download failed."; + return; + } + + var (reason, staging) = await Task.Run(() => + { + var refused = _store.Stage(plugin, package, out var folder); + return (refused, folder); + }); + if (_disposed) + { + // The staging folder is left for the next start's CleanUp. + return; + } + + if (reason is not null) + { + _errors[plugin.Id] = reason; + return; + } + + // Nothing may be running from the folder while it is swapped. + _manager.Unload(plugin.Id); + await _store.CommitAsync(plugin, staging, CancellationToken.None); + _installed = _store.LoadInstalled(); + } + catch (Exception) + { + _errors[plugin.Id] = "The plugin couldn't be installed."; + } + } + + // Gate held, and the plugin's id is in _busy. The record is written first by the store, so a step that fails later + // still takes the plugin out of the record. What the manager runs and what the saved settings forget follow the + // record as it is now, not how the removal ended. + private async Task RemoveAsync(string id) + { + try + { + // Nothing may be running from the folder, or holding its settings file, while they are deleted. + _manager.Unload(id); + await _manager.ClearBrowserDataAsync(id); + await _store.UninstallAsync(id, CancellationToken.None); + } + catch (Exception) + { + _errors[id] = RemoveFailed; + } + finally + { + try + { + _installed = _store.LoadInstalled(); + } + catch (Exception) + { + // Whether the plugin is still recorded can't be told, so the page says it couldn't be removed. + _errors[id] = RemoveFailed; + } + } + + if (!_disposed && _installed.All(plugin => plugin.Id != id)) + { + _manager.Forget(id); + Uninstalled?.Invoke(id); + } + } + + // Gate held. Tells the manager which installed plugins may run, and works out which ones the hub no longer lists. + private void PushLoads() + { + if (_disposed) + { + return; + } + + _pulled = _installed + .Select(plugin => (plugin.Id, Reason: HubPolicy.PulledReason(_catalog, plugin.Id))) + .Where(entry => entry.Reason is not null) + .Select(entry => new HubPulledPlugin( + entry.Id, + PluginManifestReader.Read(_store.FolderOf(entry.Id)).Manifest?.Name ?? entry.Id, + entry.Reason!)) + .ToArray(); + // Checked while something is installed; with nothing installed there is nothing to keep up to date. + if (_installed.Count > 0) + { + _timer.Start(); + } + else + { + _timer.Stop(); + } + + // Not awaited: it finishes when every plugin has started, and one that hangs must not hold up the hub. + _ = _manager.SetHubPluginsAsync(HubPolicy.Loads(_catalog, _installed, _store.FolderOf)); + Notify(); + } + + // Nothing is raised after Dispose: the window and the manager it would reach are going away. + private void Notify() + { + if (!_disposed) + { + Changed?.Invoke(); + } + } +} From 8129318f18522f75c699f2f92a2ef99bbf1c67b1 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:59:48 -0500 Subject: [PATCH 15/22] fix: refuse site names that aren't plain host names, and keep every stranger's value in the summary as text --- .../Plugins/HubSubmissionTests.cs | 43 +++++++++++++++++-- .../Plugins/PluginManifestReaderTests.cs | 17 ++++++++ .../Plugins/Hub/HubSubmission.cs | 13 +++--- .../Plugins/PluginManifestReader.cs | 8 +++- src/FourFoldAccountManager.HubTool/Program.cs | 8 ++-- 5 files changed, 76 insertions(+), 13 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs index f0ca5ef..eea10f6 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs @@ -274,6 +274,29 @@ public void ACatalogTheAppWouldRefuseIsNotBuilt() Assert.Single(build.Errors); } + [Fact] + public void ACatalogWithTooManyPluginsIsNotBuilt() + { + // Past 2,000 plugins the app's reader silently drops the rest. 2,001 small ones are still under the size limit, + // so only the count rule stops them. Every entry is listed already at the same commit and repository, so none is + // checked or downloaded. + var repository = new Uri("https://github.com/cody/goal-tracker"); + var entries = Enumerable.Range(0, HubLimits.MaximumCatalogPlugins + 1) + .Select(number => new HubEntry($"cody.plugin-{number}", repository, CommitA, "", false)) + .ToArray(); + var listed = entries + .Select(entry => new HubPlugin( + entry.Id, "Plugin", "Plug", "1.0.0", "cody", "", [], false, [], repository, CommitA, "2026-10-01", 1000, + new string('0', 64))) + .ToArray(); + + var build = HubSubmission.BuildCatalog( + entries, [], new HubCatalog(listed, []), _ => throw new InvalidOperationException("checked")); + + Assert.Null(build.Catalog); + Assert.Single(build.Errors); + } + [Fact] public void TheSummaryCannotBeSteeredByTheSubmission() { @@ -283,19 +306,31 @@ public void TheSummaryCannotBeSteeredByTheSubmission() "2026-10-09"); Assert.Null(result.Error); + // A site whose converted name holds "<": a stranger's plugin.json can't get one through the manifest reader, but the + // summary must not depend on that. + var steered = result.Plugin! with { Sites = [new Uri("https://a\uFE64b.example.com")] }; var summary = HubSubmission.Summary( - "# [evil](http://e).json", Entry(), null, result.Plugin, result.Package, null); + "# [evil](http://e).json", Entry(), null, steered, result.Package, null); - Assert.DoesNotMatch(@"(? Site(PluginNetworkPolicy.SiteLabel(site)))); var cards = plugin.Cards.Count == 0 ? "none" : string.Join(", ", plugin.Cards.Select(card => @@ -253,12 +253,12 @@ public static string Summary( if (shown.Except(before).ToArray() is { Length: > 0 } added) { - changes.Add("Sites added: " + string.Join(", ", added) + "."); + changes.Add("Sites added: " + string.Join(", ", added.Select(Site)) + "."); } if (before.Except(shown).ToArray() is { Length: > 0 } removed) { - changes.Add("Sites removed: " + string.Join(", ", removed) + "."); + changes.Add("Sites removed: " + string.Join(", ", removed.Select(Site)) + "."); } if (listed.Repository != plugin.Repository) @@ -290,7 +290,7 @@ public static string Summary( using var archive = new ZipArchive(new MemoryStream(package)); foreach (var file in archive.Entries.Take(MaximumListedFiles)) { - text.AppendLine($"- {Plain(file.FullName)} ({file.Length} bytes)"); + text.AppendLine($"- File: {Plain(file.FullName)} ({file.Length} bytes)"); } if (archive.Entries.Count > MaximumListedFiles) @@ -301,10 +301,13 @@ public static string Summary( return text.ToString(); } + // A site's label is a host name, but it comes from a stranger's plugin.json, so it is text like the rest. + private static string Site(string label) => Plain(label, 300); + // Text from a plugin, an entry or a repository, made safe to put in the summary, which GitHub draws as Markdown: // anything that could start a new line or hide text (control, formatting and separator characters) becomes "?", // every character Markdown could act on gets a backslash, and a long value is cut and ends in "...". - private static string Plain(string value, int maximum = 100) + public static string Plain(string value, int maximum = 100) { var result = new StringBuilder(); foreach (var rune in value.EnumerateRunes()) diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index a99b937..a0282d9 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -240,7 +240,7 @@ internal static bool TryReadSites(JsonElement root, out IReadOnlyList sites uri.Scheme != Uri.UriSchemeHttps || uri.AbsolutePath != "/" || uri.Query.Length > 0 || uri.Fragment.Length > 0 || uri.UserInfo.Length > 0 || uri.HostNameType != UriHostNameType.Dns || PluginNetworkHosts.IsLocalName(uri.IdnHost) || uri.IdnHost.EndsWith('.') || - IsIpLikeHost(uri.IdnHost) || PluginNetworkPolicy.IsPluginHost(uri.IdnHost)) + IsIpLikeHost(uri.IdnHost) || !IsPlainHost(uri.IdnHost) || PluginNetworkPolicy.IsPluginHost(uri.IdnHost)) { return false; } @@ -258,6 +258,12 @@ internal static bool TryReadSites(JsonElement root, out IReadOnlyList sites return true; } + // What a real host name is once converted: letters, digits, dots and dashes (a name with an umlaut becomes an xn-- + // name). Uri's conversion also turns look-alike characters into punctuation (U+FE64 becomes "<", U+FF5C becomes + // "|"), and a site named like that would rearrange the review summary and every other place a site is shown. + private static bool IsPlainHost(string host) => + host.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '.' or '-'); + private static bool IsIpLikeHost(string host) { var lastLabel = host.Split('.').LastOrDefault() ?? string.Empty; diff --git a/src/FourFoldAccountManager.HubTool/Program.cs b/src/FourFoldAccountManager.HubTool/Program.cs index be2e6e0..b8c2dbc 100644 --- a/src/FourFoldAccountManager.HubTool/Program.cs +++ b/src/FourFoldAccountManager.HubTool/Program.cs @@ -16,8 +16,8 @@ var wellFormed = args.Length % 2 == 1; for (var index = 1; wellFormed && index + 1 < args.Length; index += 2) { - wellFormed = knownOptions.Contains(args[index]); - options[args[index]] = args[index + 1]; + // An option given twice is as much a mistake as a mistyped one. + wellFormed = knownOptions.Contains(args[index]) && options.TryAdd(args[index], args[index + 1]); } if (args.Length == 0 || args[0] is not ("check" or "publish") || !wellFormed || !options.ContainsKey("--hub") || @@ -126,7 +126,9 @@ async Task RunAsync() : HubSubmission.BuildCatalog(entries, removed!, current, entry => CheckAsync(entry).GetAwaiter().GetResult()); foreach (var problem in build.Errors) { - Console.Error.WriteLine(problem); + // A problem can carry a stranger's file name, so it is printed as plain text: a line break in it must not start a + // line of its own, where the runner would read it as a workflow command. + Console.Error.WriteLine(HubSubmission.Plain(problem, 500)); } if (build.Catalog is null) From cfc5a29ac081b0798fe2cdc3a5f82187f0e3e3ee Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 17:06:23 -0500 Subject: [PATCH 16/22] fix: show any-website access before install, keep the hub page quick, and keep the keyboard's place --- .../Views/PluginSidebar.xaml.cs | 113 +++++++++++++++--- 1 file changed, 98 insertions(+), 15 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs b/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs index b7aa088..fbbfff2 100644 --- a/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs @@ -22,6 +22,9 @@ public partial class PluginSidebar : UserControl private const string IconFont = "Segoe Fluent Icons, Segoe MDL2 Assets"; // A private drag format, so only a strip icon can be dropped on the strip. private const string DragFormat = "FourFold.PluginId"; + // The hub page builds every row it shows each time it refreshes, so it shows only this many matches. Installed + // plugins sort first, so they are always among them. A virtualising list is the upgrade if the hub outgrows this. + private const int HubRowLimit = 50; private IReadOnlyList _plugins = []; private PanelSettings _settings = PanelSettings.Default; private bool _showingList; @@ -321,7 +324,6 @@ private UIElement BuildPluginList() var uninstall = new Button { Content = "Uninstall", - Height = 26, Padding = new Thickness(8, 0, 8, 0), Margin = new Thickness(6, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center, @@ -333,8 +335,21 @@ private UIElement BuildPluginList() var row = new Grid(); row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - row.Children.Add(CreateNameBlock( - name, null, "Removed from the hub. " + pulled.Reason, detailBrush: "Brush.Danger")); + // The hub's stock reasons already say it; only a maintainer's own reason needs the lead-in. + var block = CreateNameBlock( + name, + null, + pulled.Reason is HubPolicy.RemovedReason or HubPolicy.UnlistedReason + ? pulled.Reason + : "Removed from the hub. " + pulled.Reason, + detailBrush: "Brush.Danger"); + // A failed removal shows why, on its own line under the reason. + if (_hub.Errors.TryGetValue(pulled.Id, out var removalError)) + { + block.Children.Add(HubNote(removalError, "Brush.Danger")); + } + + row.Children.Add(block); Grid.SetColumn(uninstall, 1); row.Children.Add(uninstall); var border = new Border @@ -431,7 +446,7 @@ private UIElement HubPage() hint.SetResourceReference(TextBlock.ForegroundProperty, "Brush.TextMuted"); _hubSearch.TextChanged += (_, _) => { - hint.Visibility = _hubSearch.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed; + hint.Visibility = string.IsNullOrWhiteSpace(_hubSearch.Text) ? Visibility.Visible : Visibility.Collapsed; RebuildHubRows(); }; var searchArea = new Grid { Margin = new Thickness(0, 0, 0, 8) }; @@ -457,6 +472,8 @@ private UIElement HubPage() return _hubPage; } + // Rebuilding drops the button that has the keyboard focus, so the focus is put back afterwards. Focus that was + // somewhere else (the search box while typing) is left alone. private void RebuildHubRows() { if (_hubRows is null || _hubSearch is null) @@ -464,15 +481,67 @@ private void RebuildHubRows() return; } - _hubRows.Children.Clear(); + string? focusedName = null; + string? focusedRowId = null; + if (_hubRows.IsKeyboardFocusWithin && Keyboard.FocusedElement is DependencyObject focused) + { + focusedName = AutomationProperties.GetName(focused); + focusedRowId = _hubRows.Children.OfType().FirstOrDefault(row => row.IsKeyboardFocusWithin)?.Tag as string; + } + + FillHubRows(); + if (focusedName is not null) + { + RestoreHubFocus(focusedName, focusedRowId); + } + } + + // Focus goes to the button with the same name in the same row, else that row's Details button, else (the row is + // gone) the search box. A Details button keeps its name when it reads "Less", so it is found again. + private void RestoreHubFocus(string name, string? rowId) + { + FrameworkElement? scope = _hubRows; + if (rowId is not null) + { + scope = _hubRows!.Children.OfType().FirstOrDefault(row => row.Tag as string == rowId); + } + + var buttons = scope is null ? [] : HubButtons(scope).Where(button => button.IsEnabled).ToList(); + UIElement? target = buttons.FirstOrDefault(button => AutomationProperties.GetName(button) == name) ?? + (rowId is null ? null : buttons.FirstOrDefault()); + (target ?? _hubSearch)?.Focus(); + } + + // Every button below the element, in order. A row's first button is its Details button. + private static IEnumerable