From 11eb882f828497358c18a30440209e7e681ae643 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:02:42 -0500 Subject: [PATCH 01/49] feat: read and validate community plugin manifests --- .../Plugins/PluginManifestReaderTests.cs | 83 ++++++ .../Plugins/PluginApiException.cs | 8 + .../Plugins/PluginManifest.cs | 26 ++ .../Plugins/PluginManifestReader.cs | 237 ++++++++++++++++++ .../Plugins/PluginPaths.cs | 35 +++ 5 files changed, 389 insertions(+) create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginApiException.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginManifest.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs new file mode 100644 index 0000000..8339510 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -0,0 +1,83 @@ +using FourFoldAccountManager.Core.Overlay; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginManifestReaderTests : IDisposable +{ + private readonly string _folder = Path.Combine(Path.GetTempPath(), $"fourfold-plugin-{Guid.NewGuid():N}"); + + public PluginManifestReaderTests() + { + Directory.CreateDirectory(_folder); + File.WriteAllText(Path.Combine(_folder, "index.html"), ""); + } + + public void Dispose() => Directory.Delete(_folder, recursive: true); + + private PluginManifestResult Read(string json) + { + File.WriteAllText(Path.Combine(_folder, "plugin.json"), json); + return PluginManifestReader.Read(_folder); + } + + private static string Manifest(string overrides = "") => $$""" + { + "id": "cody.goal-tracker", "name": "Goal tracker", "shortLabel": "Goals", "version": "1.0.0", + "author": "Cody", "apiVersion": 1, "panel": "index.html", + "sites": ["https://wiki.example.com"], + "cards": [{ "id": "goal", "name": "Goal", "scope": "account" }] + {{overrides}} + } + """; + + [Fact] + public void AValidManifestLoadsWithItsSitesAndCards() + { + var result = Read(Manifest()); + + Assert.Null(result.Error); + var manifest = Assert.IsType(result.Manifest); + Assert.Equal("cody.goal-tracker", manifest.Id); + Assert.Equal([new Uri("https://wiki.example.com")], manifest.Sites); + Assert.False(manifest.AnySite); + Assert.Equal([new PluginCardManifest("goal", "Goal", OverlayAddOnScope.Account)], manifest.Cards); + Assert.Equal(_folder, manifest.Folder); + } + + [Theory] + [InlineData("\"id\": \"goaltracker\"")] + [InlineData("\"id\": \"Cody.Goal\"")] + [InlineData("\"id\": \"cody..goal\"")] + [InlineData("\"id\": \"timer\"")] + [InlineData("\"apiVersion\": 2")] + [InlineData("\"panel\": \"../outside.html\"")] + [InlineData("\"panel\": \"missing.html\"")] + [InlineData("\"panel\": \"plugin.json\"")] + [InlineData("\"shortLabel\": \"Far too long\"")] + [InlineData("\"version\": \"1.0\"")] + [InlineData("\"sites\": [\"http://wiki.example.com\"]")] + [InlineData("\"sites\": [\"https://wiki.example.com/path\"]")] + [InlineData("\"sites\": [\"https://192.168.1.10\"]")] + [InlineData("\"sites\": [\"https://localhost\"]")] + [InlineData("\"sites\": [\"https://app.localhost\"]")] + [InlineData("\"cards\": [{ \"id\": \"Goal\", \"name\": \"Goal\", \"scope\": \"account\" }]")] + [InlineData("\"cards\": [{ \"id\": \"goal\", \"name\": \"Goal\", \"scope\": \"panel\" }]")] + [InlineData("\"cards\": [{ \"id\": \"a\", \"name\": \"A\", \"scope\": \"global\" }, { \"id\": \"a\", \"name\": \"B\", \"scope\": \"global\" }]")] + public void AManifestThatBreaksARuleIsRejectedWithAReason(string overridingField) + { + // A later duplicate key wins in System.Text.Json, so appending the field overrides the valid value. + var result = Read(Manifest("," + overridingField)); + + Assert.Null(result.Manifest); + Assert.False(string.IsNullOrWhiteSpace(result.Error)); + } + + [Fact] + public void AMissingOrBrokenManifestIsRejectedWithAReason() + { + Assert.Equal("plugin.json is missing.", PluginManifestReader.Read(_folder).Error); + Assert.Equal("plugin.json isn't valid JSON.", Read("{ not json").Error); + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginApiException.cs b/src/FourFoldAccountManager.Core/Plugins/PluginApiException.cs new file mode 100644 index 0000000..f5692e0 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginApiException.cs @@ -0,0 +1,8 @@ +namespace FourFoldAccountManager.Core.Plugins; + +// A plugin API call that was refused. Code is one of: invalid-argument, not-declared, site-not-allowed, +// limit-exceeded, unavailable. The message is shown to the plugin's author. +public sealed class PluginApiException(string code, string message) : Exception(message) +{ + public string Code { get; } = code; +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifest.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifest.cs new file mode 100644 index 0000000..68cf887 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifest.cs @@ -0,0 +1,26 @@ +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins; + +public sealed record PluginCardManifest(string Id, string Name, OverlayAddOnScope Scope); + +// A validated plugin.json. Sites are origins (scheme, host and port only). +public sealed record PluginManifest( + string Id, + string Name, + string ShortLabel, + string Version, + string Author, + string Description, + int ApiVersion, + string Panel, + string? Icon, + IReadOnlyList Sites, + bool AnySite, + IReadOnlyList Cards) +{ + // The plugin's folder on disk. + public string Folder { get; init; } = string.Empty; +} + +public sealed record PluginManifestResult(PluginManifest? Manifest, string? Error); diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs new file mode 100644 index 0000000..314cbaa --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -0,0 +1,237 @@ +using System.Text.Json; +using System.Text.RegularExpressions; +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins; + +public static partial class PluginManifestReader +{ + public const int SupportedApiVersion = 1; + + // author.plugin-name: lowercase letters, digits and dashes in dot-separated parts, with at least one dot. + public const string IdPattern = @"[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+"; + + public const string CardIdPattern = "[a-z0-9]+(-[a-z0-9]+)*"; + + private const int MaximumIconBytes = 64 * 1024; + + [GeneratedRegex("^" + IdPattern + "$")] + private static partial Regex IdRegex(); + + [GeneratedRegex("^" + CardIdPattern + "$")] + private static partial Regex CardIdRegex(); + + [GeneratedRegex(@"^\d+\.\d+\.\d+$")] + private static partial Regex VersionRegex(); + + // Reads and validates /plugin.json. Every rejection carries a reason an author can act on. + public static PluginManifestResult Read(string folder) + { + var path = Path.Combine(folder, "plugin.json"); + if (!File.Exists(path)) + { + return Reject("plugin.json is missing."); + } + + JsonDocument document; + try + { + document = JsonDocument.Parse(File.ReadAllBytes(path)); + } + catch (Exception exception) when (exception is JsonException or IOException or UnauthorizedAccessException) + { + return Reject("plugin.json isn't valid JSON."); + } + + using (document) + { + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return Reject("plugin.json isn't valid JSON."); + } + + 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 (!InRange(Text(root, "name"), 1, 40, out var name)) + { + return Reject("The name must be 1 to 40 characters."); + } + + if (!InRange(Text(root, "shortLabel"), 1, 8, out var shortLabel)) + { + return Reject("The shortLabel must be 1 to 8 characters."); + } + + var version = Text(root, "version"); + if (version is null || !VersionRegex().IsMatch(version)) + { + return Reject("The version must look like 1.0.0."); + } + + if (!InRange(Text(root, "author"), 1, 40, out var author)) + { + return Reject("The author must be 1 to 40 characters."); + } + + var description = Text(root, "description") ?? string.Empty; + if (description.Length > 200) + { + return Reject("The description must be at most 200 characters."); + } + + if (!root.TryGetProperty("apiVersion", out var apiElement) || !apiElement.TryGetInt32(out var apiVersion) || + apiVersion < 1) + { + return Reject("The apiVersion must be a whole number."); + } + + if (apiVersion > SupportedApiVersion) + { + return Reject("Update FourFold to use this plugin."); + } + + var panel = Text(root, "panel"); + if (panel is null || !panel.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || + !PluginPaths.TryResolveInside(folder, panel, out var panelPath) || !File.Exists(panelPath)) + { + return Reject("The panel must be an .html file inside the plugin folder."); + } + + var icon = Text(root, "icon"); + if (icon is not null && + (!icon.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || + !PluginPaths.TryResolveInside(folder, icon, out var iconPath) || !File.Exists(iconPath) || + new FileInfo(iconPath).Length > MaximumIconBytes)) + { + return Reject("The icon must be a .png inside the plugin folder, at most 64 KB."); + } + + if (!TryReadSites(root, out var sites, out var siteError)) + { + return Reject(siteError); + } + + var anySite = root.TryGetProperty("anySite", out var anySiteElement) && + anySiteElement.ValueKind == JsonValueKind.True; + if (!TryReadCards(root, out var cards, out var cardError)) + { + return Reject(cardError); + } + + return new PluginManifestResult( + new PluginManifest(id, name, shortLabel, version, author, description, apiVersion, panel, icon, + sites, anySite, cards) { Folder = folder }, + null); + } + } + + private static PluginManifestResult Reject(string reason) => new(null, reason); + + private 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) + { + result = value ?? string.Empty; + return result.Length >= minimum && result.Length <= maximum; + } + + private 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 localhost."; + if (!root.TryGetProperty("sites", out var element) || element.ValueKind == JsonValueKind.Null) + { + return true; + } + + if (element.ValueKind != JsonValueKind.Array) + { + return false; + } + + var result = new List(); + foreach (var item in element.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.String || + !Uri.TryCreate(item.GetString(), UriKind.Absolute, out var uri) || + 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)) + { + return false; + } + + result.Add(new Uri(uri.GetLeftPart(UriPartial.Authority))); + } + + if (result.Count > 10) + { + error = "A plugin can declare at most 10 sites."; + return false; + } + + sites = Array.AsReadOnly(result.Distinct().ToArray()); + return true; + } + + private static bool TryReadCards(JsonElement root, out IReadOnlyList cards, out string error) + { + cards = []; + error = "Each card needs an id (lowercase letters, digits, dashes), a name (1 to 24 characters) and a scope of account or global."; + if (!root.TryGetProperty("cards", out var element) || element.ValueKind == JsonValueKind.Null) + { + return true; + } + + if (element.ValueKind != JsonValueKind.Array) + { + return false; + } + + var result = new List(); + foreach (var item in element.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.Object) + { + return false; + } + + var id = Text(item, "id"); + var scope = Text(item, "scope"); + if (id is null || id.Length > 32 || !CardIdRegex().IsMatch(id) || + !InRange(Text(item, "name"), 1, 24, out var name) || + scope is not ("account" or "global") || result.Any(card => card.Id == id)) + { + return false; + } + + result.Add(new PluginCardManifest(id, name, + scope == "account" ? OverlayAddOnScope.Account : OverlayAddOnScope.Global)); + } + + if (result.Count > 6) + { + error = "A plugin can declare at most 6 cards."; + return false; + } + + cards = Array.AsReadOnly(result.ToArray()); + return true; + } +} + +// Host-name checks shared by the manifest reader and the network policy. +public static class PluginNetworkHosts +{ + public static bool IsLocalName(string host) => + host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || + host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase); +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs b/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs new file mode 100644 index 0000000..f9e9d63 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs @@ -0,0 +1,35 @@ +namespace FourFoldAccountManager.Core.Plugins; + +public static class PluginPaths +{ + // Resolves relativePath inside folder. False when the path is rooted, empty, or escapes the folder, so a plugin + // can never name a file outside its own folder. + public static bool TryResolveInside(string folder, string relativePath, out string fullPath) + { + fullPath = string.Empty; + if (string.IsNullOrWhiteSpace(relativePath) || relativePath.Contains('\0') || Path.IsPathRooted(relativePath)) + { + return false; + } + + var root = Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + + Path.DirectorySeparatorChar; + string candidate; + try + { + candidate = Path.GetFullPath(Path.Combine(root, relativePath)); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + + if (!candidate.StartsWith(root, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + fullPath = candidate; + return true; + } +} From 834acd101db7fd5a643a0745c205fc1af6441873 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:08:12 -0500 Subject: [PATCH 02/49] fix: reject trailing-dot hosts and wrong-typed manifest values, and test path escapes for real --- .../Plugins/PluginManifestReaderTests.cs | 49 ++++- .../Plugins/PluginManifestReader.cs | 193 ++++++++++-------- 2 files changed, 152 insertions(+), 90 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs index 8339510..fd6c489 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -7,14 +7,36 @@ namespace FourFoldAccountManager.Core.Tests.Plugins; public sealed class PluginManifestReaderTests : IDisposable { private readonly string _folder = Path.Combine(Path.GetTempPath(), $"fourfold-plugin-{Guid.NewGuid():N}"); + private readonly string _outsideFile; + private readonly string _evilFolder; public PluginManifestReaderTests() { Directory.CreateDirectory(_folder); File.WriteAllText(Path.Combine(_folder, "index.html"), ""); + + var parentFolder = Path.GetDirectoryName(_folder)!; + var pluginFolderName = Path.GetFileName(_folder); + _outsideFile = Path.Combine(parentFolder, $"outside-{Guid.NewGuid():N}.html"); + _evilFolder = Path.Combine(parentFolder, $"{pluginFolderName}-evil"); + + File.WriteAllText(_outsideFile, ""); + Directory.CreateDirectory(_evilFolder); + File.WriteAllText(Path.Combine(_evilFolder, "index.html"), ""); } - public void Dispose() => Directory.Delete(_folder, recursive: true); + public void Dispose() + { + Directory.Delete(_folder, recursive: true); + if (File.Exists(_outsideFile)) + { + File.Delete(_outsideFile); + } + if (Directory.Exists(_evilFolder)) + { + Directory.Delete(_evilFolder, recursive: true); + } + } private PluginManifestResult Read(string json) { @@ -52,7 +74,7 @@ public void AValidManifestLoadsWithItsSitesAndCards() [InlineData("\"id\": \"cody..goal\"")] [InlineData("\"id\": \"timer\"")] [InlineData("\"apiVersion\": 2")] - [InlineData("\"panel\": \"../outside.html\"")] + [InlineData("\"apiVersion\": \"1\"")] [InlineData("\"panel\": \"missing.html\"")] [InlineData("\"panel\": \"plugin.json\"")] [InlineData("\"shortLabel\": \"Far too long\"")] @@ -62,6 +84,9 @@ public void AValidManifestLoadsWithItsSitesAndCards() [InlineData("\"sites\": [\"https://192.168.1.10\"]")] [InlineData("\"sites\": [\"https://localhost\"]")] [InlineData("\"sites\": [\"https://app.localhost\"]")] + [InlineData("\"sites\": [\"https://localhost.\"]")] + [InlineData("\"sites\": [\"https://127.0.0.1.\"]")] + [InlineData("\"sites\": [\"https://app.localhost.\"]")] [InlineData("\"cards\": [{ \"id\": \"Goal\", \"name\": \"Goal\", \"scope\": \"account\" }]")] [InlineData("\"cards\": [{ \"id\": \"goal\", \"name\": \"Goal\", \"scope\": \"panel\" }]")] [InlineData("\"cards\": [{ \"id\": \"a\", \"name\": \"A\", \"scope\": \"global\" }, { \"id\": \"a\", \"name\": \"B\", \"scope\": \"global\" }]")] @@ -80,4 +105,24 @@ public void AMissingOrBrokenManifestIsRejectedWithAReason() Assert.Equal("plugin.json is missing.", PluginManifestReader.Read(_folder).Error); Assert.Equal("plugin.json isn't valid JSON.", Read("{ not json").Error); } + + [Fact] + public void AManifestReferencingAnOutsideFileIsRejected() + { + var relativePath = Path.Combine("..", Path.GetFileName(_outsideFile)); + var result = Read(Manifest($", \"panel\": \"{relativePath.Replace("\\", "/")}\"")); + + Assert.Null(result.Manifest); + Assert.False(string.IsNullOrWhiteSpace(result.Error)); + } + + [Fact] + public void AManifestReferencingASiblingFolderIsRejected() + { + var folderName = Path.GetFileName(_evilFolder); + var result = Read(Manifest($", \"panel\": \"../{folderName}/index.html\"")); + + Assert.Null(result.Manifest); + Assert.False(string.IsNullOrWhiteSpace(result.Error)); + } } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index 314cbaa..8358d4d 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -21,7 +21,7 @@ public static partial class PluginManifestReader [GeneratedRegex("^" + CardIdPattern + "$")] private static partial Regex CardIdRegex(); - [GeneratedRegex(@"^\d+\.\d+\.\d+$")] + [GeneratedRegex(@"^[0-9]+\.[0-9]+\.[0-9]+$")] private static partial Regex VersionRegex(); // Reads and validates /plugin.json. Every rejection carries a reason an author can act on. @@ -36,97 +36,104 @@ public static PluginManifestResult Read(string folder) JsonDocument document; try { - document = JsonDocument.Parse(File.ReadAllBytes(path)); + document = JsonDocument.Parse(File.ReadAllText(path)); } catch (Exception exception) when (exception is JsonException or IOException or UnauthorizedAccessException) { return Reject("plugin.json isn't valid JSON."); } - using (document) + try { - var root = document.RootElement; - if (root.ValueKind != JsonValueKind.Object) - { - return Reject("plugin.json isn't valid JSON."); - } - - 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 (!InRange(Text(root, "name"), 1, 40, out var name)) - { - return Reject("The name must be 1 to 40 characters."); - } - - if (!InRange(Text(root, "shortLabel"), 1, 8, out var shortLabel)) - { - return Reject("The shortLabel must be 1 to 8 characters."); - } - - var version = Text(root, "version"); - if (version is null || !VersionRegex().IsMatch(version)) - { - return Reject("The version must look like 1.0.0."); - } - - if (!InRange(Text(root, "author"), 1, 40, out var author)) - { - return Reject("The author must be 1 to 40 characters."); - } - - var description = Text(root, "description") ?? string.Empty; - if (description.Length > 200) - { - return Reject("The description must be at most 200 characters."); - } - - if (!root.TryGetProperty("apiVersion", out var apiElement) || !apiElement.TryGetInt32(out var apiVersion) || - apiVersion < 1) - { - return Reject("The apiVersion must be a whole number."); + using (document) + { + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return Reject("plugin.json isn't valid JSON."); + } + + 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 (!InRange(Text(root, "name"), 1, 40, out var name)) + { + return Reject("The name must be 1 to 40 characters."); + } + + if (!InRange(Text(root, "shortLabel"), 1, 8, out var shortLabel)) + { + return Reject("The shortLabel must be 1 to 8 characters."); + } + + var version = Text(root, "version"); + if (version is null || !VersionRegex().IsMatch(version)) + { + return Reject("The version must look like 1.0.0."); + } + + if (!InRange(Text(root, "author"), 1, 40, out var author)) + { + return Reject("The author must be 1 to 40 characters."); + } + + var description = Text(root, "description") ?? string.Empty; + if (description.Length > 200) + { + return Reject("The description must be at most 200 characters."); + } + + if (!root.TryGetProperty("apiVersion", out var apiElement) || apiElement.ValueKind != JsonValueKind.Number || + !apiElement.TryGetInt32(out var apiVersion) || apiVersion < 1) + { + return Reject("The apiVersion must be a whole number."); + } + + if (apiVersion > SupportedApiVersion) + { + return Reject("Update FourFold to use this plugin."); + } + + var panel = Text(root, "panel"); + if (panel is null || !panel.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || + !PluginPaths.TryResolveInside(folder, panel, out var panelPath) || !File.Exists(panelPath)) + { + return Reject("The panel must be an .html file inside the plugin folder."); + } + + var icon = Text(root, "icon"); + if (icon is not null && + (!icon.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || + !PluginPaths.TryResolveInside(folder, icon, out var iconPath) || !File.Exists(iconPath) || + new FileInfo(iconPath).Length > MaximumIconBytes)) + { + return Reject("The icon must be a .png inside the plugin folder, at most 64 KB."); + } + + if (!TryReadSites(root, out var sites, out var siteError)) + { + return Reject(siteError); + } + + var anySite = root.TryGetProperty("anySite", out var anySiteElement) && + anySiteElement.ValueKind == JsonValueKind.True; + if (!TryReadCards(root, out var cards, out var cardError)) + { + return Reject(cardError); + } + + return new PluginManifestResult( + new PluginManifest(id, name, shortLabel, version, author, description, apiVersion, panel, icon, + sites, anySite, cards) { Folder = folder }, + null); } - - if (apiVersion > SupportedApiVersion) - { - return Reject("Update FourFold to use this plugin."); - } - - var panel = Text(root, "panel"); - if (panel is null || !panel.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || - !PluginPaths.TryResolveInside(folder, panel, out var panelPath) || !File.Exists(panelPath)) - { - return Reject("The panel must be an .html file inside the plugin folder."); - } - - var icon = Text(root, "icon"); - if (icon is not null && - (!icon.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || - !PluginPaths.TryResolveInside(folder, icon, out var iconPath) || !File.Exists(iconPath) || - new FileInfo(iconPath).Length > MaximumIconBytes)) - { - return Reject("The icon must be a .png inside the plugin folder, at most 64 KB."); - } - - if (!TryReadSites(root, out var sites, out var siteError)) - { - return Reject(siteError); - } - - var anySite = root.TryGetProperty("anySite", out var anySiteElement) && - anySiteElement.ValueKind == JsonValueKind.True; - if (!TryReadCards(root, out var cards, out var cardError)) - { - return Reject(cardError); - } - - return new PluginManifestResult( - new PluginManifest(id, name, shortLabel, version, author, description, apiVersion, panel, icon, - sites, anySite, cards) { Folder = folder }, - null); + } + catch (InvalidOperationException) + { + return Reject("plugin.json isn't valid JSON."); } } @@ -164,7 +171,8 @@ private static bool TryReadSites(JsonElement root, out IReadOnlyList sites, !Uri.TryCreate(item.GetString(), UriKind.Absolute, out var uri) || 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)) + PluginNetworkHosts.IsLocalName(uri.IdnHost) || uri.IdnHost.EndsWith('.') || + IsIpLikeHost(uri.IdnHost)) { return false; } @@ -182,6 +190,12 @@ private static bool TryReadSites(JsonElement root, out IReadOnlyList sites, return true; } + private static bool IsIpLikeHost(string host) + { + var lastLabel = host.Split('.').LastOrDefault() ?? string.Empty; + return lastLabel.Length > 0 && lastLabel.All(c => c >= '0' && c <= '9'); + } + private static bool TryReadCards(JsonElement root, out IReadOnlyList cards, out string error) { cards = []; @@ -231,7 +245,10 @@ scope is not ("account" or "global") || result.Any(card => card.Id == id)) // Host-name checks shared by the manifest reader and the network policy. public static class PluginNetworkHosts { - public static bool IsLocalName(string host) => - host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || - host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase); + public static bool IsLocalName(string host) + { + var trimmed = host.TrimEnd('.'); + return trimmed.Equals("localhost", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase); + } } From 890999f979e55834ca6824a2797b9a324abc0692 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:12:22 -0500 Subject: [PATCH 03/49] feat: add the plugin sandbox rules for sites, the local network and file serving --- .../Plugins/PluginFileServerTests.cs | 47 ++++++++ .../Plugins/PluginNetworkPolicyTests.cs | 89 +++++++++++++++ .../Plugins/PluginFileServer.cs | 57 ++++++++++ .../Plugins/PluginNetworkPolicy.cs | 102 ++++++++++++++++++ .../Plugins/PluginTrust.cs | 13 +++ 5 files changed, 308 insertions(+) create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs new file mode 100644 index 0000000..327bb29 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs @@ -0,0 +1,47 @@ +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginFileServerTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"fourfold-serve-{Guid.NewGuid():N}"); + private readonly PluginManifest _manifest; + + public PluginFileServerTests() + { + var folder = Path.Combine(_root, "plugin"); + Directory.CreateDirectory(Path.Combine(folder, "js")); + File.WriteAllText(Path.Combine(folder, "index.html"), ""); + File.WriteAllText(Path.Combine(folder, "js", "app.js"), ""); + File.WriteAllText(Path.Combine(folder, "run.exe"), ""); + File.WriteAllText(Path.Combine(_root, "secret.txt"), "outside the plugin"); + _manifest = new PluginManifest("cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, + "index.html", null, [], false, []) { Folder = folder }; + } + + public void Dispose() => Directory.Delete(_root, recursive: true); + + [Theory] + [InlineData("/", "index.html", "text/html; charset=utf-8")] + [InlineData("/index.html", "index.html", "text/html; charset=utf-8")] + [InlineData("/js/app.js", "app.js", "text/javascript; charset=utf-8")] + public void FilesInsideThePluginFolderAreServedWithAFixedContentType(string urlPath, string fileName, string type) + { + Assert.True(PluginFileServer.TryResolve(_manifest, urlPath, out var filePath, out var contentType)); + Assert.Equal(fileName, Path.GetFileName(filePath)); + Assert.Equal(type, contentType); + } + + [Theory] + [InlineData("/../secret.txt")] + [InlineData("/%2e%2e/secret.txt")] + [InlineData("/js/../../secret.txt")] + [InlineData("/..%5csecret.txt")] + [InlineData("/C:/Windows/win.ini")] + [InlineData("/run.exe")] + [InlineData("/missing.html")] + [InlineData("/plugin.json")] + public void PathsOutsideTheFolderUnknownTypesAndMissingFilesAreRefused(string urlPath) => + Assert.False(PluginFileServer.TryResolve(_manifest, urlPath, out _, out _)); +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs new file mode 100644 index 0000000..bb827e5 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs @@ -0,0 +1,89 @@ +using System.Net; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginNetworkPolicyTests +{ + private static PluginManifest Manifest(bool anySite = false) => new( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, + [new Uri("https://wiki.example.com"), new Uri("https://api.example.com:8443")], anySite, []); + + [Theory] + [InlineData("https://cody.goal-tracker.plugin.fourfold/app.js", true)] + [InlineData("https://wiki.example.com/page?x=1", true)] + [InlineData("https://WIKI.example.com/page", true)] + [InlineData("https://api.example.com:8443/v1", true)] + [InlineData("https://api.example.com/v1", false)] + [InlineData("https://other.example.com/", false)] + [InlineData("https://evil-wiki.example.com.attacker.net/", false)] + [InlineData("http://wiki.example.com/page", false)] + [InlineData("https://other.plugin.fourfold/app.js", false)] + [InlineData("file:///C:/Windows/win.ini", false)] + public void ADefaultPluginReachesOnlyItsOwnFilesAndDeclaredSites(string url, bool allowed) => + Assert.Equal(allowed, PluginNetworkPolicy.IsAllowed(new Uri(url), Manifest(), PluginTrust.Developer)); + + [Theory] + [InlineData("https://localhost/")] + [InlineData("https://app.localhost/")] + [InlineData("https://127.0.0.1/")] + [InlineData("https://10.1.2.3/")] + [InlineData("https://172.16.0.9/")] + [InlineData("https://192.168.1.1/")] + [InlineData("https://169.254.10.10/")] + [InlineData("https://[::1]/")] + [InlineData("https://[fd00::1]/")] + [InlineData("https://[fe80::1]/")] + [InlineData("https://[::ffff:192.168.1.1]/")] + [InlineData("https://localhost./")] + [InlineData("https://127.0.0.1./")] + [InlineData("https://192.168.1.1./")] + public void TheLocalNetworkIsNeverReachableEvenWithAnySite(string url) => + Assert.False(PluginNetworkPolicy.IsAllowed(new Uri(url), Manifest(anySite: true), PluginTrust.Verified)); + + [Fact] + public void AnySiteNeedsTrustAndNeverAllowsOutsideScriptsOrPlainHttp() + { + var any = new Uri("https://anything.example.org/data.json"); + + Assert.True(PluginNetworkPolicy.IsAllowed(any, Manifest(anySite: true), PluginTrust.Verified)); + Assert.True(PluginNetworkPolicy.IsAllowed(any, Manifest(anySite: true), PluginTrust.Developer)); + Assert.False(PluginNetworkPolicy.IsAllowed(any, Manifest(anySite: true), PluginTrust.Standard)); + Assert.False(PluginNetworkPolicy.IsAllowed(any, Manifest(anySite: true), PluginTrust.Verified, isScript: true)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://wiki.example.com/lib.js"), Manifest(), PluginTrust.Developer, isScript: true)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("http://anything.example.org/"), Manifest(anySite: true), PluginTrust.Verified)); + } + + [Fact] + public void TheContentSecurityPolicyNamesOnlyDeclaredSitesAndNeverAllowsInlineScriptOrEval() + { + var policy = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(), PluginTrust.Developer); + + Assert.Contains("default-src 'none'", policy); + Assert.Contains("script-src 'self';", policy); + Assert.DoesNotContain("unsafe-eval", policy); + Assert.DoesNotContain("script-src 'self' 'unsafe-inline'", policy); + Assert.Contains( + "connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443", + policy); + Assert.Contains("frame-src 'none'", policy); + + var anySite = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(anySite: true), PluginTrust.Verified); + Assert.Contains("connect-src 'self' https: wss:", anySite); + Assert.Contains("script-src 'self';", anySite); + + var untrusted = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(anySite: true), PluginTrust.Standard); + Assert.DoesNotContain("https: wss:", untrusted); + } + + [Theory] + [InlineData("8.8.8.8", false)] + [InlineData("172.32.0.1", false)] + [InlineData("172.31.255.255", true)] + [InlineData("0.0.0.0", true)] + public void LocalAddressRangesAreRecognised(string address, bool local) => + Assert.Equal(local, PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse(address))); +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs b/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs new file mode 100644 index 0000000..fb15b30 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs @@ -0,0 +1,57 @@ +namespace FourFoldAccountManager.Core.Plugins; + +// Maps a request path on a plugin's origin to a file in its folder. Only known static file types are served, and +// never plugin.json or anything outside the folder. +public static class PluginFileServer +{ + private static readonly Dictionary ContentTypes = new(StringComparer.OrdinalIgnoreCase) + { + [".html"] = "text/html; charset=utf-8", + [".js"] = "text/javascript; charset=utf-8", + [".mjs"] = "text/javascript; charset=utf-8", + [".css"] = "text/css; charset=utf-8", + [".json"] = "application/json; charset=utf-8", + [".txt"] = "text/plain; charset=utf-8", + [".png"] = "image/png", + [".jpg"] = "image/jpeg", + [".jpeg"] = "image/jpeg", + [".gif"] = "image/gif", + [".svg"] = "image/svg+xml", + [".webp"] = "image/webp", + [".woff2"] = "font/woff2" + }; + + public static bool TryResolve(PluginManifest manifest, string urlPath, out string filePath, out string contentType) + { + filePath = string.Empty; + contentType = string.Empty; + string relative; + try + { + relative = Uri.UnescapeDataString(urlPath).TrimStart('/'); + } + catch (UriFormatException) + { + return false; + } + + if (relative.Length == 0) + { + relative = manifest.Panel; + } + + // A backslash is a path separator on Windows, so "..\" would climb just like "../". + if (relative.Contains('\\') || relative.Contains(':') || + !PluginPaths.TryResolveInside(manifest.Folder, relative, out var resolved) || + !ContentTypes.TryGetValue(Path.GetExtension(resolved), out var type) || + Path.GetFileName(resolved).Equals("plugin.json", StringComparison.OrdinalIgnoreCase) || + !File.Exists(resolved)) + { + return false; + } + + filePath = resolved; + contentType = type; + return true; + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs new file mode 100644 index 0000000..ddcee01 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs @@ -0,0 +1,102 @@ +using System.Net; +using System.Net.Sockets; + +namespace FourFoldAccountManager.Core.Plugins; + +// What a community plugin may load or contact. The same rules back the Content-Security-Policy header, the request +// handler's second check, and the FourFold-run fetch. +public static class PluginNetworkPolicy +{ + public static string OriginHost(string pluginId) => $"{pluginId}.plugin.fourfold"; + + public static Uri Origin(string pluginId) => new($"https://{OriginHost(pluginId)}/"); + + public static bool IsOwnOrigin(Uri uri, string pluginId) => + uri.IsAbsoluteUri && uri.Scheme == Uri.UriSchemeHttps && uri.IsDefaultPort && + uri.Host.Equals(OriginHost(pluginId), StringComparison.OrdinalIgnoreCase); + + public static bool AllowsAnySite(PluginManifest manifest, PluginTrust trust) => + manifest.AnySite && trust is PluginTrust.Developer or PluginTrust.Verified; + + // Loopback, private, link-local and unspecified addresses: a plugin must never reach the user's own network. + public static bool IsLocalAddress(IPAddress address) + { + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) + { + return true; + } + + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + return address.IsIPv6LinkLocal || address.IsIPv6UniqueLocal || address.IsIPv6SiteLocal; + } + + var bytes = address.GetAddressBytes(); + return bytes[0] switch + { + 0 or 10 or 127 => true, + 172 => bytes[1] is >= 16 and <= 31, + 192 => bytes[1] == 168, + 169 => bytes[1] == 254, + _ => false + }; + } + + public static bool IsLocalHost(string host) + { + var normalized = host.Trim('[', ']').TrimEnd('.'); + return PluginNetworkHosts.IsLocalName(normalized) || + (IPAddress.TryParse(normalized, out var address) && IsLocalAddress(address)); + } + + // isScript is true for script and worker requests, which may only ever come from the plugin's own files. + public static bool IsAllowed(Uri uri, PluginManifest manifest, PluginTrust trust, bool isScript = false) + { + if (!uri.IsAbsoluteUri) + { + return false; + } + + if (IsOwnOrigin(uri, manifest.Id)) + { + return true; + } + + if (isScript || uri.Scheme != Uri.UriSchemeHttps || uri.UserInfo.Length > 0 || IsLocalHost(uri.IdnHost)) + { + return false; + } + + return AllowsAnySite(manifest, trust) || + manifest.Sites.Any(site => + site.Port == uri.Port && site.IdnHost.Equals(uri.IdnHost.TrimEnd('.'), StringComparison.OrdinalIgnoreCase)); + } + + public static string BuildContentSecurityPolicy(PluginManifest manifest, PluginTrust trust) + { + string images; + string connections; + if (AllowsAnySite(manifest, trust)) + { + images = "https:"; + connections = "https: wss:"; + } + else + { + var origins = manifest.Sites.Select(site => site.GetLeftPart(UriPartial.Authority)).ToArray(); + images = string.Join(' ', origins); + connections = string.Join(' ', origins.Concat(origins.Select(origin => "wss" + origin["https".Length..]))); + } + + return "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; " + + $"img-src 'self' data:{Prefix(images)}; connect-src 'self'{Prefix(connections)}; " + + "frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"; + + static string Prefix(string value) => value.Length == 0 ? string.Empty : " " + value; + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs b/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs new file mode 100644 index 0000000..f877690 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs @@ -0,0 +1,13 @@ +namespace FourFoldAccountManager.Core.Plugins; + +public enum PluginTrust +{ + // 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. + Verified +} From 4ca9cf8adf69652c67ff2540562391bb9c239a13 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:28:01 -0500 Subject: [PATCH 04/49] fix: give each plugin its own origin domain, close the plugin namespace and harden the local-network check --- .../Plugins/PluginFileServerTests.cs | 5 + .../Plugins/PluginManifestReaderTests.cs | 4 + .../Plugins/PluginNetworkPolicyTests.cs | 66 ++++++++++--- .../Plugins/PluginFileServer.cs | 5 + .../Plugins/PluginManifestReader.cs | 6 +- .../Plugins/PluginNetworkPolicy.cs | 96 ++++++++++++++----- .../Plugins/PluginPaths.cs | 8 +- 7 files changed, 145 insertions(+), 45 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs index 327bb29..fb38fba 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs @@ -15,6 +15,7 @@ public PluginFileServerTests() File.WriteAllText(Path.Combine(folder, "index.html"), ""); File.WriteAllText(Path.Combine(folder, "js", "app.js"), ""); File.WriteAllText(Path.Combine(folder, "run.exe"), ""); + File.WriteAllText(Path.Combine(folder, "plugin.json"), "{}"); File.WriteAllText(Path.Combine(_root, "secret.txt"), "outside the plugin"); _manifest = new PluginManifest("cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, [], false, []) { Folder = folder }; @@ -42,6 +43,10 @@ public void FilesInsideThePluginFolderAreServedWithAFixedContentType(string urlP [InlineData("/run.exe")] [InlineData("/missing.html")] [InlineData("/plugin.json")] + [InlineData("/PLUGIN.JSON")] + [InlineData("/js/../plugin.json")] + [InlineData("/index.html:x")] + [InlineData("/index.html::$DATA")] public void PathsOutsideTheFolderUnknownTypesAndMissingFilesAreRefused(string urlPath) => Assert.False(PluginFileServer.TryResolve(_manifest, urlPath, out _, out _)); } diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs index fd6c489..b87d403 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -14,6 +14,8 @@ public PluginManifestReaderTests() { Directory.CreateDirectory(_folder); File.WriteAllText(Path.Combine(_folder, "index.html"), ""); + Directory.CreateDirectory(Path.Combine(_folder, "sub")); + File.WriteAllText(Path.Combine(_folder, "sub", "index.html"), ""); var parentFolder = Path.GetDirectoryName(_folder)!; var pluginFolderName = Path.GetFileName(_folder); @@ -77,6 +79,7 @@ public void AValidManifestLoadsWithItsSitesAndCards() [InlineData("\"apiVersion\": \"1\"")] [InlineData("\"panel\": \"missing.html\"")] [InlineData("\"panel\": \"plugin.json\"")] + [InlineData("\"panel\": \"sub\\\\index.html\"")] [InlineData("\"shortLabel\": \"Far too long\"")] [InlineData("\"version\": \"1.0\"")] [InlineData("\"sites\": [\"http://wiki.example.com\"]")] @@ -87,6 +90,7 @@ public void AValidManifestLoadsWithItsSitesAndCards() [InlineData("\"sites\": [\"https://localhost.\"]")] [InlineData("\"sites\": [\"https://127.0.0.1.\"]")] [InlineData("\"sites\": [\"https://app.localhost.\"]")] + [InlineData("\"sites\": [\"https://x.fourfoldplugin\"]")] [InlineData("\"cards\": [{ \"id\": \"Goal\", \"name\": \"Goal\", \"scope\": \"account\" }]")] [InlineData("\"cards\": [{ \"id\": \"goal\", \"name\": \"Goal\", \"scope\": \"panel\" }]")] [InlineData("\"cards\": [{ \"id\": \"a\", \"name\": \"A\", \"scope\": \"global\" }, { \"id\": \"a\", \"name\": \"B\", \"scope\": \"global\" }]")] diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs index bb827e5..3782498 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs @@ -11,7 +11,7 @@ public sealed class PluginNetworkPolicyTests [new Uri("https://wiki.example.com"), new Uri("https://api.example.com:8443")], anySite, []); [Theory] - [InlineData("https://cody.goal-tracker.plugin.fourfold/app.js", true)] + [InlineData("https://cody--goal-tracker.fourfoldplugin/app.js", true)] [InlineData("https://wiki.example.com/page?x=1", true)] [InlineData("https://WIKI.example.com/page", true)] [InlineData("https://api.example.com:8443/v1", true)] @@ -19,7 +19,7 @@ public sealed class PluginNetworkPolicyTests [InlineData("https://other.example.com/", false)] [InlineData("https://evil-wiki.example.com.attacker.net/", false)] [InlineData("http://wiki.example.com/page", false)] - [InlineData("https://other.plugin.fourfold/app.js", false)] + [InlineData("https://other--plugin.fourfoldplugin/app.js", false)] [InlineData("file:///C:/Windows/win.ini", false)] public void ADefaultPluginReachesOnlyItsOwnFilesAndDeclaredSites(string url, bool allowed) => Assert.Equal(allowed, PluginNetworkPolicy.IsAllowed(new Uri(url), Manifest(), PluginTrust.Developer)); @@ -39,9 +39,34 @@ public void ADefaultPluginReachesOnlyItsOwnFilesAndDeclaredSites(string url, boo [InlineData("https://localhost./")] [InlineData("https://127.0.0.1./")] [InlineData("https://192.168.1.1./")] + [InlineData("https://100.64.1.1/")] + [InlineData("https://[::127.0.0.1]/")] + [InlineData("https://[64:ff9b::7f00:1]/")] + [InlineData("https://[2002:7f00:1::]/")] public void TheLocalNetworkIsNeverReachableEvenWithAnySite(string url) => Assert.False(PluginNetworkPolicy.IsAllowed(new Uri(url), Manifest(anySite: true), PluginTrust.Verified)); + [Fact] + public void ThePluginNamespaceIsNeverAnOrdinarySite() + { + var manifestWithPluginHost = new PluginManifest( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, + [new Uri("https://wiki.example.com"), new Uri("https://other--plugin.fourfoldplugin")], true, []); + + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://other--plugin.fourfoldplugin/app.js"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://fourfoldplugin/"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://x.y.fourfoldplugin/"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://cody--goal-tracker.fourfoldplugin./"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://cody--goal-tracker.fourfoldplugin:8443/"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.True(PluginNetworkPolicy.IsAllowed( + new Uri("https://cody--goal-tracker.fourfoldplugin/app.js"), manifestWithPluginHost, PluginTrust.Verified)); + } + [Fact] public void AnySiteNeedsTrustAndNeverAllowsOutsideScriptsOrPlainHttp() { @@ -61,22 +86,26 @@ public void AnySiteNeedsTrustAndNeverAllowsOutsideScriptsOrPlainHttp() public void TheContentSecurityPolicyNamesOnlyDeclaredSitesAndNeverAllowsInlineScriptOrEval() { var policy = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(), PluginTrust.Developer); - - Assert.Contains("default-src 'none'", policy); - Assert.Contains("script-src 'self';", policy); - Assert.DoesNotContain("unsafe-eval", policy); - Assert.DoesNotContain("script-src 'self' 'unsafe-inline'", policy); - Assert.Contains( - "connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443", + Assert.Equal( + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://wiki.example.com https://api.example.com:8443; connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'", policy); - Assert.Contains("frame-src 'none'", policy); var anySite = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(anySite: true), PluginTrust.Verified); - Assert.Contains("connect-src 'self' https: wss:", anySite); - Assert.Contains("script-src 'self';", anySite); + Assert.Equal( + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https:; connect-src 'self' https: wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'", + anySite); var untrusted = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(anySite: true), PluginTrust.Standard); - Assert.DoesNotContain("https: wss:", untrusted); + Assert.Equal( + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://wiki.example.com https://api.example.com:8443; connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'", + untrusted); + + var noSites = new PluginManifest("cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, + "index.html", null, [], false, []); + var nositespolicy = PluginNetworkPolicy.BuildContentSecurityPolicy(noSites, PluginTrust.Developer); + Assert.Equal( + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'", + nositespolicy); } [Theory] @@ -84,6 +113,17 @@ public void TheContentSecurityPolicyNamesOnlyDeclaredSitesAndNeverAllowsInlineSc [InlineData("172.32.0.1", false)] [InlineData("172.31.255.255", true)] [InlineData("0.0.0.0", true)] + [InlineData("100.63.255.255", false)] + [InlineData("100.64.0.0", true)] + [InlineData("100.127.255.255", true)] + [InlineData("100.128.0.0", false)] public void LocalAddressRangesAreRecognised(string address, bool local) => Assert.Equal(local, PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse(address))); + + [Fact] + public void Ipv6EmbeddedAddressesAreLocal() + { + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("::1"))); + Assert.False(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("2001:4860:4860::8888"))); + } } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs b/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs index fb15b30..f823c57 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs @@ -25,6 +25,11 @@ public static bool TryResolve(PluginManifest manifest, string urlPath, out strin { filePath = string.Empty; contentType = string.Empty; + if (urlPath is null) + { + return false; + } + string relative; try { diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index 8358d4d..7e403fd 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -98,7 +98,7 @@ public static PluginManifestResult Read(string folder) } var panel = Text(root, "panel"); - if (panel is null || !panel.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || + if (panel is null || panel.Contains('\\') || !panel.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || !PluginPaths.TryResolveInside(folder, panel, out var panelPath) || !File.Exists(panelPath)) { return Reject("The panel must be an .html file inside the plugin folder."); @@ -106,7 +106,7 @@ public static PluginManifestResult Read(string folder) var icon = Text(root, "icon"); if (icon is not null && - (!icon.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || + (icon.Contains('\\') || !icon.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || !PluginPaths.TryResolveInside(folder, icon, out var iconPath) || !File.Exists(iconPath) || new FileInfo(iconPath).Length > MaximumIconBytes)) { @@ -172,7 +172,7 @@ private 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)) + IsIpLikeHost(uri.IdnHost) || PluginNetworkPolicy.IsPluginHost(uri.IdnHost)) { return false; } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs index ddcee01..635307c 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs @@ -7,7 +7,11 @@ namespace FourFoldAccountManager.Core.Plugins; // handler's second check, and the FourFold-run fetch. public static class PluginNetworkPolicy { - public static string OriginHost(string pluginId) => $"{pluginId}.plugin.fourfold"; + // Every plugin page lives under this made-up top-level name, one domain per plugin. + public const string OriginSuffix = "fourfoldplugin"; + + // "--" can't appear in a plugin id, so replacing the dots keeps every id's host unique. + public static string OriginHost(string pluginId) => $"{pluginId.Replace(".", "--")}.{OriginSuffix}"; public static Uri Origin(string pluginId) => new($"https://{OriginHost(pluginId)}/"); @@ -15,36 +19,60 @@ public static bool IsOwnOrigin(Uri uri, string pluginId) => uri.IsAbsoluteUri && uri.Scheme == Uri.UriSchemeHttps && uri.IsDefaultPort && uri.Host.Equals(OriginHost(pluginId), StringComparison.OrdinalIgnoreCase); + // True for any host in the plugin namespace, whichever plugin it belongs to. + public static bool IsPluginHost(string host) + { + var name = host.TrimEnd('.'); + return name.Equals(OriginSuffix, StringComparison.OrdinalIgnoreCase) || + name.EndsWith("." + OriginSuffix, StringComparison.OrdinalIgnoreCase); + } + public static bool AllowsAnySite(PluginManifest manifest, PluginTrust trust) => - manifest.AnySite && trust is PluginTrust.Developer or PluginTrust.Verified; + manifest.AnySite && trust is (PluginTrust.Developer or PluginTrust.Verified); - // Loopback, private, link-local and unspecified addresses: a plugin must never reach the user's own network. + // Loopback, private, link-local, carrier-grade NAT and unspecified addresses, in any spelling: a plugin must never + // reach the user's own network. public static bool IsLocalAddress(IPAddress address) { - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) - { - return true; - } - if (address.AddressFamily == AddressFamily.InterNetworkV6) { - return address.IsIPv6LinkLocal || address.IsIPv6UniqueLocal || address.IsIPv6SiteLocal; + // Rebuilding from the bytes drops any scope id, so "::1%1" is still loopback. + var bytes = address.GetAddressBytes(); + address = new IPAddress(bytes); + if (address.IsIPv4MappedToIPv6) + { + return IsLocalAddress(address.MapToIPv4()); + } + + if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.IPv6Any) || address.IsIPv6LinkLocal || + address.IsIPv6UniqueLocal || address.IsIPv6SiteLocal) + { + return true; + } + + // An IPv6 address that embeds an IPv4 address reaches that IPv4 host: IPv4-compatible (::a.b.c.d), + // SIIT (::ffff:0:a.b.c.d), NAT64 (64:ff9b::a.b.c.d) and 6to4 (2002:AABB:CCDD::). + byte[]? embedded = + AllZero(bytes, 0, 12) ? bytes[12..16] + : AllZero(bytes, 0, 8) && bytes[8] == 0xff && bytes[9] == 0xff && bytes[10] == 0 && bytes[11] == 0 ? bytes[12..16] + : bytes[0] == 0x00 && bytes[1] == 0x64 && bytes[2] == 0xff && bytes[3] == 0x9b && AllZero(bytes, 4, 8) ? bytes[12..16] + : bytes[0] == 0x20 && bytes[1] == 0x02 ? bytes[2..6] + : null; + return embedded is not null && IsLocalAddress(new IPAddress(embedded)); } - var bytes = address.GetAddressBytes(); - return bytes[0] switch + var octets = address.GetAddressBytes(); + return octets[0] switch { 0 or 10 or 127 => true, - 172 => bytes[1] is >= 16 and <= 31, - 192 => bytes[1] == 168, - 169 => bytes[1] == 254, + 100 => octets[1] is >= 64 and <= 127, + 169 => octets[1] == 254, + 172 => octets[1] is >= 16 and <= 31, + 192 => octets[1] == 168, _ => false }; + + static bool AllZero(byte[] value, int start, int count) => value.AsSpan(start, count).IndexOfAnyExcept((byte)0) < 0; } public static bool IsLocalHost(string host) @@ -67,6 +95,11 @@ public static bool IsAllowed(Uri uri, PluginManifest manifest, PluginTrust trust return true; } + if (IsPluginHost(uri.IdnHost)) + { + return false; + } + if (isScript || uri.Scheme != Uri.UriSchemeHttps || uri.UserInfo.Length > 0 || IsLocalHost(uri.IdnHost)) { return false; @@ -79,22 +112,33 @@ public static bool IsAllowed(Uri uri, PluginManifest manifest, PluginTrust trust public static string BuildContentSecurityPolicy(PluginManifest manifest, PluginTrust trust) { + var allowsAnySite = manifest.AnySite && trust is (PluginTrust.Developer or PluginTrust.Verified); + string images; - string connections; - if (AllowsAnySite(manifest, trust)) + string connectHttps; + string connectWss; + + if (allowsAnySite) { images = "https:"; - connections = "https: wss:"; + connectHttps = "https:"; + var wssSites = string.Join(' ', manifest.Sites.Select(site => + site.IsDefaultPort ? $"wss://{site.IdnHost}" : $"wss://{site.IdnHost}:{site.Port}")); + connectWss = wssSites; } else { - var origins = manifest.Sites.Select(site => site.GetLeftPart(UriPartial.Authority)).ToArray(); - images = string.Join(' ', origins); - connections = string.Join(' ', origins.Concat(origins.Select(origin => "wss" + origin["https".Length..]))); + var originParts = manifest.Sites.Select(site => + site.IsDefaultPort ? $"https://{site.IdnHost}" : $"https://{site.IdnHost}:{site.Port}").ToArray(); + images = string.Join(' ', originParts); + connectHttps = string.Join(' ', originParts); + connectWss = string.Join(' ', manifest.Sites.Select(site => + site.IsDefaultPort ? $"wss://{site.IdnHost}" : $"wss://{site.IdnHost}:{site.Port}")); } + var connect = Prefix(connectHttps) + Prefix(connectWss); return "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; " + - $"img-src 'self' data:{Prefix(images)}; connect-src 'self'{Prefix(connections)}; " + + $"img-src 'self' data:{Prefix(images)}; connect-src 'self'{connect}; " + "frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"; static string Prefix(string value) => value.Length == 0 ? string.Empty : " " + value; diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs b/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs index f9e9d63..7b0410e 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs @@ -7,16 +7,18 @@ public static class PluginPaths public static bool TryResolveInside(string folder, string relativePath, out string fullPath) { fullPath = string.Empty; - if (string.IsNullOrWhiteSpace(relativePath) || relativePath.Contains('\0') || Path.IsPathRooted(relativePath)) + if (string.IsNullOrWhiteSpace(folder) || string.IsNullOrWhiteSpace(relativePath) || + relativePath.Contains('\0') || Path.IsPathRooted(relativePath)) { return false; } - var root = Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + - Path.DirectorySeparatorChar; + string root; string candidate; try { + root = Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + + Path.DirectorySeparatorChar; candidate = Path.GetFullPath(Path.Combine(root, relativePath)); } catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) From 2567112926f6dcba1589bd1ae7b9031ef7db444c Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:33:41 -0500 Subject: [PATCH 05/49] test: cover scoped and embedded IPv6 addresses, and keep plugin ids to hosts a browser accepts --- .../Plugins/PluginFileServerTests.cs | 1 + .../Plugins/PluginManifestReaderTests.cs | 2 ++ .../Plugins/PluginNetworkPolicyTests.cs | 22 ++++++++++++++++--- .../Plugins/PluginManifestReader.cs | 6 +++++ .../Plugins/PluginNetworkPolicy.cs | 12 ++++------ 5 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs index fb38fba..c81e9b6 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginFileServerTests.cs @@ -46,6 +46,7 @@ public void FilesInsideThePluginFolderAreServedWithAFixedContentType(string urlP [InlineData("/PLUGIN.JSON")] [InlineData("/js/../plugin.json")] [InlineData("/index.html:x")] + [InlineData("/index.html:x.js")] [InlineData("/index.html::$DATA")] public void PathsOutsideTheFolderUnknownTypesAndMissingFilesAreRefused(string urlPath) => Assert.False(PluginFileServer.TryResolve(_manifest, urlPath, out _, out _)); diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs index b87d403..bfb85b0 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -75,6 +75,8 @@ public void AValidManifestLoadsWithItsSitesAndCards() [InlineData("\"id\": \"Cody.Goal\"")] [InlineData("\"id\": \"cody..goal\"")] [InlineData("\"id\": \"timer\"")] + [InlineData("\"id\": \"xn.foo\"")] + [InlineData("\"id\": \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"")] [InlineData("\"apiVersion\": 2")] [InlineData("\"apiVersion\": \"1\"")] [InlineData("\"panel\": \"missing.html\"")] diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs index 3782498..1db74db 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs @@ -121,9 +121,25 @@ public void LocalAddressRangesAreRecognised(string address, bool local) => Assert.Equal(local, PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse(address))); [Fact] - public void Ipv6EmbeddedAddressesAreLocal() + public void AnIpv6ScopeIdDoesNotHideALocalAddress() { - Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("::1"))); - Assert.False(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("2001:4860:4860::8888"))); + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("::1%1"))); + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("fe80::1%5"))); + } + + [Fact] + public void AnIpv6AddressEmbeddingAPublicIpv4IsNotLocal() + { + Assert.False(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("64:ff9b::808:808"))); + Assert.False(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("2002:808:808::"))); + Assert.False(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("::ffff:0:8.8.8.8"))); + } + + [Fact] + public void AnIpv6AddressEmbeddingALocalIpv4IsLocal() + { + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("64:ff9b::c0a8:1"))); + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("2002:a00:1::"))); + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("::ffff:0:127.0.0.1"))); } } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index 7e403fd..cb0c58e 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -59,6 +59,12 @@ public static PluginManifestResult Read(string folder) return Reject("The id must look like author.plugin-name (lowercase letters, digits, dots and dashes)."); } + var label = id.Replace(".", "--"); + if (label.Length > 63 || label.StartsWith("xn--", StringComparison.OrdinalIgnoreCase)) + { + return Reject("The id must look like author.plugin-name (lowercase letters, digits, dots and dashes)."); + } + if (!InRange(Text(root, "name"), 1, 40, out var name)) { return Reject("The name must be 1 to 40 characters."); diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs index 635307c..4b7ee3d 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs @@ -112,19 +112,17 @@ public static bool IsAllowed(Uri uri, PluginManifest manifest, PluginTrust trust public static string BuildContentSecurityPolicy(PluginManifest manifest, PluginTrust trust) { - var allowsAnySite = manifest.AnySite && trust is (PluginTrust.Developer or PluginTrust.Verified); + var allowsAnySite = AllowsAnySite(manifest, trust); + var wssSites = string.Join(' ', manifest.Sites.Select(site => + site.IsDefaultPort ? $"wss://{site.IdnHost}" : $"wss://{site.IdnHost}:{site.Port}")); string images; string connectHttps; - string connectWss; if (allowsAnySite) { images = "https:"; connectHttps = "https:"; - var wssSites = string.Join(' ', manifest.Sites.Select(site => - site.IsDefaultPort ? $"wss://{site.IdnHost}" : $"wss://{site.IdnHost}:{site.Port}")); - connectWss = wssSites; } else { @@ -132,11 +130,9 @@ public static string BuildContentSecurityPolicy(PluginManifest manifest, PluginT site.IsDefaultPort ? $"https://{site.IdnHost}" : $"https://{site.IdnHost}:{site.Port}").ToArray(); images = string.Join(' ', originParts); connectHttps = string.Join(' ', originParts); - connectWss = string.Join(' ', manifest.Sites.Select(site => - site.IsDefaultPort ? $"wss://{site.IdnHost}" : $"wss://{site.IdnHost}:{site.Port}")); } - var connect = Prefix(connectHttps) + Prefix(connectWss); + var connect = Prefix(connectHttps) + Prefix(wssSites); return "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; " + $"img-src 'self' data:{Prefix(images)}; connect-src 'self'{connect}; " + "frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"; From 3feb586eccba1b914c385e3518628b9cb220f51c Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:36:37 -0500 Subject: [PATCH 06/49] feat: add private key-value storage for community plugins --- .../Plugins/PluginStorageTests.cs | 83 ++++++++++++++ .../Plugins/PluginStorage.cs | 103 ++++++++++++++++++ 2 files changed, 186 insertions(+) create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs new file mode 100644 index 0000000..e3a0bee --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs @@ -0,0 +1,83 @@ +using System.Text.Json; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginStorageTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"fourfold-storage-{Guid.NewGuid():N}"); + + private string FilePath => Path.Combine(_root, "cody.goal-tracker.json"); + + public void Dispose() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + } + + private static JsonElement Json(string json) => JsonDocument.Parse(json).RootElement.Clone(); + + [Fact] + public async Task ValuesSurviveANewInstanceReadingTheSameFile() + { + await new PluginStorage(FilePath).SetAsync("goals", Json("""{"level":50}""")); + + var loaded = await new PluginStorage(FilePath).GetAsync("goals"); + + Assert.Equal(50, loaded!.Value.GetProperty("level").GetInt32()); + Assert.Null(await new PluginStorage(FilePath).GetAsync("missing")); + } + + [Fact] + public async Task AWriteOverTheSizeCapIsRejectedAndKeepsExistingData() + { + var storage = new PluginStorage(FilePath); + await storage.SetAsync("kept", Json("\"safe\"")); + var tooBig = Json("\"" + new string('x', PluginStorage.MaximumBytes) + "\""); + + var error = await Assert.ThrowsAsync(() => storage.SetAsync("big", tooBig)); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal("safe", (await new PluginStorage(FilePath).GetAsync("kept"))!.Value.GetString()); + Assert.Null(await new PluginStorage(FilePath).GetAsync("big")); + } + + [Theory] + [InlineData("")] + [InlineData("this-key-is-longer-than-the-sixty-four-characters-a-plugin-key-may-be")] + public async Task ABadKeyIsRejected(string key) + { + var error = await Assert.ThrowsAsync( + () => new PluginStorage(FilePath).SetAsync(key, Json("1"))); + + Assert.Equal("invalid-argument", error.Code); + } + + [Fact] + public async Task AnUnreadableStoreLoadsAsEmptyAndCanBeWrittenAgain() + { + Directory.CreateDirectory(_root); + await File.WriteAllTextAsync(FilePath, "{ not json"); + var storage = new PluginStorage(FilePath); + + Assert.Null(await storage.GetAsync("goals")); + await storage.SetAsync("goals", Json("1")); + Assert.Equal(1, (await new PluginStorage(FilePath).GetAsync("goals"))!.Value.GetInt32()); + } + + [Fact] + public async Task RemoveDeletesOnlyThatKey() + { + var storage = new PluginStorage(FilePath); + await storage.SetAsync("a", Json("1")); + await storage.SetAsync("b", Json("2")); + + await storage.RemoveAsync("a"); + + Assert.Null(await new PluginStorage(FilePath).GetAsync("a")); + Assert.Equal(2, (await new PluginStorage(FilePath).GetAsync("b"))!.Value.GetInt32()); + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs b/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs new file mode 100644 index 0000000..eae88b0 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs @@ -0,0 +1,103 @@ +using System.Text.Json; +using FourFoldAccountManager.Core.Data; + +namespace FourFoldAccountManager.Core.Plugins; + +// One plugin's private key-value store: a small JSON file, saved atomically. A file that can't be read loads as +// empty, so a damaged store never stops the plugin or the app. +public sealed class PluginStorage(string filePath) +{ + public const int MaximumBytes = 256 * 1024; + + public const int MaximumKeyLength = 64; + + private readonly SemaphoreSlim _gate = new(1, 1); + private Dictionary? _values; + + public async Task GetAsync(string key) + { + ValidateKey(key); + await _gate.WaitAsync(); + try + { + return (await LoadAsync()).TryGetValue(key, out var value) ? value : null; + } + finally + { + _gate.Release(); + } + } + + public async Task SetAsync(string key, JsonElement value) + { + ValidateKey(key); + await _gate.WaitAsync(); + try + { + var values = await LoadAsync(); + var next = new Dictionary(values, StringComparer.Ordinal) { [key] = value.Clone() }; + if (JsonSerializer.SerializeToUtf8Bytes(next).Length > MaximumBytes) + { + throw new PluginApiException("limit-exceeded", "Plugin storage is limited to 256 KB."); + } + + await AtomicJsonFile.WriteAsync(filePath, next, CancellationToken.None); + _values = next; + } + finally + { + _gate.Release(); + } + } + + public async Task RemoveAsync(string key) + { + ValidateKey(key); + await _gate.WaitAsync(); + try + { + var values = await LoadAsync(); + if (!values.ContainsKey(key)) + { + return; + } + + var next = new Dictionary(values, StringComparer.Ordinal); + next.Remove(key); + await AtomicJsonFile.WriteAsync(filePath, next, CancellationToken.None); + _values = next; + } + finally + { + _gate.Release(); + } + } + + private static void ValidateKey(string key) + { + if (string.IsNullOrEmpty(key) || key.Length > MaximumKeyLength) + { + throw new PluginApiException("invalid-argument", "A storage key must be 1 to 64 characters."); + } + } + + private async Task> LoadAsync() + { + if (_values is not null) + { + return _values; + } + + try + { + await using var stream = File.OpenRead(filePath); + _values = await JsonSerializer.DeserializeAsync>(stream) ?? []; + } + catch (Exception exception) when (exception is IOException or JsonException or UnauthorizedAccessException) + { + _values = []; + } + + return _values; + } +} From 9296d0b354b05e10aedd1b59cd599c5f7161245a Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:40:42 -0500 Subject: [PATCH 07/49] fix: cap plugin storage by the bytes written, and never treat a locked store as empty --- .../Plugins/PluginStorageTests.cs | 42 ++++++++++++++++++- .../Plugins/PluginStorage.cs | 16 ++++++- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs index e3a0bee..55ef709 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs @@ -36,13 +36,17 @@ public async Task AWriteOverTheSizeCapIsRejectedAndKeepsExistingData() { var storage = new PluginStorage(FilePath); await storage.SetAsync("kept", Json("\"safe\"")); - var tooBig = Json("\"" + new string('x', PluginStorage.MaximumBytes) + "\""); - var error = await Assert.ThrowsAsync(() => storage.SetAsync("big", tooBig)); + // Create a nested value with many numbers to make indentation matter and exceed the cap + var largeArray = Json("[" + string.Join(",", Enumerable.Range(1, 70000)) + "]"); + var error = await Assert.ThrowsAsync(() => storage.SetAsync("big", largeArray)); Assert.Equal("limit-exceeded", error.Code); Assert.Equal("safe", (await new PluginStorage(FilePath).GetAsync("kept"))!.Value.GetString()); Assert.Null(await new PluginStorage(FilePath).GetAsync("big")); + + // Verify the file size is actually within the cap + Assert.True(new FileInfo(FilePath).Length <= PluginStorage.MaximumBytes); } [Theory] @@ -80,4 +84,38 @@ public async Task RemoveDeletesOnlyThatKey() Assert.Null(await new PluginStorage(FilePath).GetAsync("a")); Assert.Equal(2, (await new PluginStorage(FilePath).GetAsync("b"))!.Value.GetInt32()); } + + [Fact] + public async Task ALockedStoreIsNotTreatedAsEmptyAndKeepsItsData() + { + // Write key "a" with one instance + var storage1 = new PluginStorage(FilePath); + await storage1.SetAsync("a", Json("1")); + + // Lock the file to simulate a transient read failure + FileStream? lockStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None); + try + { + // With a NEW PluginStorage instance, GetAsync should throw "unavailable" + var storage2 = new PluginStorage(FilePath); + var error = await Assert.ThrowsAsync(() => storage2.GetAsync("a")); + Assert.Equal("unavailable", error.Code); + + // Dispose the lock + lockStream.Dispose(); + lockStream = null; + + // With that same instance, SetAsync should now succeed + await storage2.SetAsync("b", Json("2")); + + // A fresh instance should read both "a" and "b" + var storage3 = new PluginStorage(FilePath); + Assert.Equal(1, (await storage3.GetAsync("a"))!.Value.GetInt32()); + Assert.Equal(2, (await storage3.GetAsync("b"))!.Value.GetInt32()); + } + finally + { + lockStream?.Dispose(); + } + } } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs b/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs index eae88b0..927bcda 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs @@ -36,7 +36,7 @@ public async Task SetAsync(string key, JsonElement value) { var values = await LoadAsync(); var next = new Dictionary(values, StringComparer.Ordinal) { [key] = value.Clone() }; - if (JsonSerializer.SerializeToUtf8Bytes(next).Length > MaximumBytes) + if (JsonSerializer.SerializeToUtf8Bytes(next, AtomicJsonFile.Options).Length > MaximumBytes) { throw new PluginApiException("limit-exceeded", "Plugin storage is limited to 256 KB."); } @@ -93,10 +93,22 @@ private async Task> LoadAsync() await using var stream = File.OpenRead(filePath); _values = await JsonSerializer.DeserializeAsync>(stream) ?? []; } - catch (Exception exception) when (exception is IOException or JsonException or UnauthorizedAccessException) + catch (FileNotFoundException) { _values = []; } + catch (DirectoryNotFoundException) + { + _values = []; + } + catch (JsonException) + { + _values = []; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + throw new PluginApiException("unavailable", "Plugin storage couldn't be read right now."); + } return _values; } From 19118bba1638d93601b5dc25e2db33ac40472be3 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:43:38 -0500 Subject: [PATCH 08/49] test: prove the plugin storage cap bounds the bytes on disk --- .../Plugins/PluginStorageTests.cs | 46 +++++++++++++++++-- .../Plugins/PluginStorage.cs | 4 +- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs index 55ef709..c22c64f 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs @@ -1,3 +1,4 @@ +using System.Text; using System.Text.Json; using FourFoldAccountManager.Core.Plugins; using Xunit; @@ -36,17 +37,54 @@ public async Task AWriteOverTheSizeCapIsRejectedAndKeepsExistingData() { var storage = new PluginStorage(FilePath); await storage.SetAsync("kept", Json("\"safe\"")); + var tooBig = Json("\"" + new string('x', PluginStorage.MaximumBytes) + "\""); - // Create a nested value with many numbers to make indentation matter and exceed the cap - var largeArray = Json("[" + string.Join(",", Enumerable.Range(1, 70000)) + "]"); - var error = await Assert.ThrowsAsync(() => storage.SetAsync("big", largeArray)); + var error = await Assert.ThrowsAsync(() => storage.SetAsync("big", tooBig)); Assert.Equal("limit-exceeded", error.Code); Assert.Equal("safe", (await new PluginStorage(FilePath).GetAsync("kept"))!.Value.GetString()); Assert.Null(await new PluginStorage(FilePath).GetAsync("big")); + } + + [Fact] + public async Task AValueThatOnlyFitsWhenCompactIsRejected() + { + // A JSON array of 40,000 ones is ~80 KB compact (under cap) but ~320 KB indented (over cap). + // This test proves the size check measures indented JSON, not compact. + var json = "[" + string.Join(",", Enumerable.Repeat("1", 40000)) + "]"; + var compactBytes = Encoding.UTF8.GetByteCount(json); + Assert.True(compactBytes < PluginStorage.MaximumBytes, + $"Compact size {compactBytes} must be under {PluginStorage.MaximumBytes} to test the boundary"); + + var storage = new PluginStorage(FilePath); + await storage.SetAsync("kept", Json("\"safe\"")); + var largeArray = Json(json); + + var error = await Assert.ThrowsAsync(() => storage.SetAsync("list", largeArray)); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal("safe", (await new PluginStorage(FilePath).GetAsync("kept"))!.Value.GetString()); + Assert.Null(await new PluginStorage(FilePath).GetAsync("list")); + } - // Verify the file size is actually within the cap + [Fact] + public async Task AnAllowedWriteStaysWithinTheCapOnDisk() + { + // A JSON array of 20,000 ones is ~160 KB indented (under cap). + var json = "[" + string.Join(",", Enumerable.Repeat("1", 20000)) + "]"; + var storage = new PluginStorage(FilePath); + + var largeArray = Json(json); + await storage.SetAsync("list", largeArray); + + // Verify the file size is within the cap Assert.True(new FileInfo(FilePath).Length <= PluginStorage.MaximumBytes); + + // Verify the data persists and reads back correctly + var loaded = await new PluginStorage(FilePath).GetAsync("list"); + Assert.NotNull(loaded); + var array = loaded.Value.EnumerateArray().ToList(); + Assert.Equal(20000, array.Count); } [Theory] diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs b/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs index 927bcda..4d2a035 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs @@ -3,8 +3,8 @@ namespace FourFoldAccountManager.Core.Plugins; -// One plugin's private key-value store: a small JSON file, saved atomically. A file that can't be read loads as -// empty, so a damaged store never stops the plugin or the app. +// One plugin's private key-value store: a small JSON file, saved atomically. A missing or corrupt file loads as +// empty; a file that is locked or unreadable at the moment rejects the call and is never overwritten. public sealed class PluginStorage(string filePath) { public const int MaximumBytes = 256 * 1024; From ea9b125343e143af6049435406fa73de07673dfa Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:46:35 -0500 Subject: [PATCH 09/49] feat: add the FourFold-run fetch for community plugins --- .../Plugins/PluginHttpFetcherTests.cs | 185 +++++++++++++ .../Plugins/PluginHttpFetcher.cs | 253 ++++++++++++++++++ 2 files changed, 438 insertions(+) create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs new file mode 100644 index 0000000..752d9b4 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs @@ -0,0 +1,185 @@ +using System.Net; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginHttpFetcherTests +{ + private static readonly PluginManifest Manifest = new( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, + [new Uri("https://wiki.example.com")], false, []); + + private static PluginHttpRequest Get(string url) => new(url, "GET", null, null); + + [Fact] + public async Task AnUndeclaredSiteIsRefusedWithoutSendingAnything() + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://attacker.example.net/steal"))); + + Assert.Equal("site-not-allowed", error.Code); + Assert.Empty(handler.Requests); + } + + [Fact] + public async Task ARedirectToAnUndeclaredSiteIsRefusedAndOneToADeclaredSiteIsFollowed() + { + var handler = new FakeHandler(request => request.RequestUri!.AbsolutePath switch + { + "/out" => Redirect("https://attacker.example.net/"), + "/in" => Redirect("/page"), + _ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("page text") } + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/out"))); + var followed = await fetcher.FetchAsync(Get("https://wiki.example.com/in")); + + Assert.Equal("site-not-allowed", error.Code); + Assert.DoesNotContain(handler.Requests, uri => uri.Host == "attacker.example.net"); + Assert.Equal((200, "page text"), (followed.Status, followed.Text)); + } + + [Fact] + public async Task MoreThanFiveRedirectsAreRefused() + { + var handler = new FakeHandler(_ => Redirect("/again")); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/loop"))); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal(6, handler.Requests.Count); + } + + [Fact] + public async Task ForbiddenHeadersAreDroppedAndOthersAreSent() + { + HttpRequestMessage? sent = null; + var handler = new FakeHandler(request => + { + sent = request; + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/api", "GET", + new Dictionary + { + ["Cookie"] = "session=1", + ["Host"] = "attacker.example.net", + ["Sec-Fetch-Site"] = "same-origin", + ["Proxy-Authorization"] = "Basic x", + ["X-Api-Key"] = "abc" + }, null)); + + Assert.NotNull(sent); + Assert.False(sent.Headers.Contains("Cookie")); + Assert.False(sent.Headers.Contains("Sec-Fetch-Site")); + Assert.False(sent.Headers.Contains("Proxy-Authorization")); + Assert.Null(sent.Headers.Host); + Assert.Equal("abc", sent.Headers.GetValues("X-Api-Key").Single()); + } + + [Fact] + public async Task AResponseOverTwoMegabytesIsRefused() + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new ByteArrayContent(new byte[PluginHttpFetcher.MaximumResponseBytes + 1]) + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/big"))); + + Assert.Equal("limit-exceeded", error.Code); + } + + [Fact] + public async Task TheSixtyFirstRequestInAMinuteIsRefusedAndAllowedAgainLater() + { + var clock = new FakeClock(); + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler, clock); + for (var count = 0; count < 60; count++) + { + await fetcher.FetchAsync(Get("https://wiki.example.com/")); + } + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + clock.Advance(TimeSpan.FromSeconds(61)); + await fetcher.FetchAsync(Get("https://wiki.example.com/")); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal(61, handler.Requests.Count); + } + + [Fact] + public async Task OnlyGetAndPostAreAccepted() + { + using var fetcher = new PluginHttpFetcher( + Manifest, PluginTrust.Developer, new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK))); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "DELETE", null, null))); + + Assert.Equal("invalid-argument", error.Code); + } + + [Theory] + [InlineData("192.168.1.5")] + [InlineData("127.0.0.1")] + [InlineData("8.8.8.8,10.0.0.7")] + public async Task AHostThatResolvesToTheLocalNetworkIsRefused(string addresses) + { + var resolved = addresses.Split(',').Select(IPAddress.Parse).ToArray(); + + var error = await Assert.ThrowsAsync(() => + PluginHttpFetcher.ResolvePublicAddressesAsync( + "wiki.example.com", (_, _) => Task.FromResult(resolved), CancellationToken.None)); + + Assert.Equal("site-not-allowed", error.Code); + } + + [Fact] + public async Task AHostThatResolvesToPublicAddressesReturnsThemAll() + { + var expected = new[] { IPAddress.Parse("8.8.8.8"), IPAddress.Parse("1.1.1.1") }; + var result = await PluginHttpFetcher.ResolvePublicAddressesAsync( + "wiki.example.com", (_, _) => Task.FromResult(expected), CancellationToken.None); + + Assert.Equal(expected, result); + } + + private static HttpResponseMessage Redirect(string location) => + new(HttpStatusCode.Found) { Headers = { Location = new Uri(location, UriKind.RelativeOrAbsolute) } }; + + private sealed class FakeHandler(Func respond) : HttpMessageHandler + { + public List Requests { get; } = []; + + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request.RequestUri!); + return Task.FromResult(respond(request)); + } + } + + private sealed class FakeClock : TimeProvider + { + private DateTimeOffset _now = new(2026, 10, 3, 12, 0, 0, TimeSpan.Zero); + + public override DateTimeOffset GetUtcNow() => _now; + + public void Advance(TimeSpan by) => _now += by; + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs new file mode 100644 index 0000000..eaa4f46 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs @@ -0,0 +1,253 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; + +namespace FourFoldAccountManager.Core.Plugins; + +public sealed record PluginHttpRequest( + string Url, + string? Method, + IReadOnlyDictionary? Headers, + string? Body); + +public sealed record PluginHttpResponse(int Status, IReadOnlyDictionary Headers, string Text); + +// Makes a web request on a plugin's behalf, because most sites refuse cross-origin requests from a page. Every URL +// (and every redirect) passes the same site rules as the plugin's page, no cookies or credentials are ever attached, +// and the connection only goes to an address checked to be outside the local network. +public sealed class PluginHttpFetcher : IDisposable +{ + public const int MaximumResponseBytes = 2 * 1024 * 1024; + + public const int MaximumRedirects = 5; + + public const int MaximumRequestsPerMinute = 60; + + public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(15); + + private static readonly string[] ForbiddenHeaders = + ["Cookie", "Host", "Content-Length", "Transfer-Encoding", "Connection"]; + + private readonly PluginManifest _manifest; + private readonly PluginTrust _trust; + private readonly HttpClient _http; + private readonly TimeProvider _clock; + private readonly Queue _recent = new(); + + public PluginHttpFetcher( + PluginManifest manifest, PluginTrust trust, HttpMessageHandler? handler = null, TimeProvider? clock = null) + { + _manifest = manifest; + _trust = trust; + _clock = clock ?? TimeProvider.System; + _http = new HttpClient(handler ?? CreateHandler()) { Timeout = Timeout.InfiniteTimeSpan }; + } + + public async Task FetchAsync( + PluginHttpRequest request, CancellationToken cancellationToken = default) + { + var method = (request.Method ?? "GET").ToUpperInvariant() switch + { + "GET" => HttpMethod.Get, + "POST" => HttpMethod.Post, + _ => throw new PluginApiException("invalid-argument", "Only GET and POST requests are supported.") + }; + if (!Uri.TryCreate(request.Url, UriKind.Absolute, out var uri)) + { + throw new PluginApiException("invalid-argument", "The URL isn't valid."); + } + + EnsureAllowed(uri); + TakeRateSlot(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(RequestTimeout); + var body = request.Body; + try + { + for (var redirects = 0; ; redirects++) + { + using var message = new HttpRequestMessage(method, uri); + if (method == HttpMethod.Post) + { + message.Content = new StringContent(body ?? string.Empty, Encoding.UTF8); + } + + ApplyHeaders(message, request.Headers); + using var response = await _http.SendAsync( + message, HttpCompletionOption.ResponseHeadersRead, timeout.Token); + if ((int)response.StatusCode is 301 or 302 or 303 or 307 or 308 && + response.Headers.Location is { } location) + { + if (redirects >= MaximumRedirects) + { + throw new PluginApiException("limit-exceeded", "The request was redirected too many times."); + } + + uri = location.IsAbsoluteUri ? location : new Uri(uri, location); + EnsureAllowed(uri); + if ((int)response.StatusCode == 303 || + (method == HttpMethod.Post && (int)response.StatusCode is 301 or 302)) + { + method = HttpMethod.Get; + body = null; + } + + continue; + } + + return new PluginHttpResponse( + (int)response.StatusCode, FlattenHeaders(response), await ReadTextAsync(response, timeout.Token)); + } + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new PluginApiException("unavailable", "The request took longer than 15 seconds."); + } + catch (HttpRequestException exception) when (exception.InnerException is PluginApiException refused) + { + throw new PluginApiException(refused.Code, refused.Message); + } + catch (HttpRequestException) + { + throw new PluginApiException("unavailable", "The request failed."); + } + } + + // Refuses a host when any address it resolves to is on the local network, and returns all addresses outside + // the local network, so the addresses that were checked are the addresses that are used. + public static async Task ResolvePublicAddressesAsync( + string host, + Func> resolve, + CancellationToken cancellationToken) + { + var addresses = await resolve(host, cancellationToken); + if (addresses.Length == 0 || addresses.Any(PluginNetworkPolicy.IsLocalAddress)) + { + throw new PluginApiException("site-not-allowed", "Plugins can't reach the local network."); + } + + return addresses; + } + + public void Dispose() => _http.Dispose(); + + private void EnsureAllowed(Uri uri) + { + if (PluginNetworkPolicy.IsOwnOrigin(uri, _manifest.Id) || + !PluginNetworkPolicy.IsAllowed(uri, _manifest, _trust)) + { + throw new PluginApiException( + "site-not-allowed", $"{uri.Host} isn't one of this plugin's declared sites."); + } + } + + private void TakeRateSlot() + { + lock (_recent) + { + var now = _clock.GetUtcNow(); + while (_recent.Count > 0 && now - _recent.Peek() >= TimeSpan.FromSeconds(60)) + { + _recent.Dequeue(); + } + + if (_recent.Count >= MaximumRequestsPerMinute) + { + throw new PluginApiException("limit-exceeded", "A plugin can make at most 60 requests a minute."); + } + + _recent.Enqueue(now); + } + } + + private static void ApplyHeaders(HttpRequestMessage message, IReadOnlyDictionary? headers) + { + foreach (var (name, value) in headers ?? new Dictionary()) + { + if (ForbiddenHeaders.Contains(name, StringComparer.OrdinalIgnoreCase) || + name.StartsWith("Proxy-", StringComparison.OrdinalIgnoreCase) || + name.StartsWith("Sec-", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + // Content headers (such as Content-Type) belong on the body, not the request. + if (!message.Headers.TryAddWithoutValidation(name, value) && message.Content is not null) + { + message.Content.Headers.Remove(name); + message.Content.Headers.TryAddWithoutValidation(name, value); + } + } + } + + private static Dictionary FlattenHeaders(HttpResponseMessage response) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (name, values) in response.Headers.Concat(response.Content.Headers)) + { + if (!name.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)) + { + result[name] = string.Join(", ", values); + } + } + + return result; + } + + private static async Task ReadTextAsync(HttpResponseMessage response, CancellationToken cancellationToken) + { + if (response.Content.Headers.ContentLength > MaximumResponseBytes) + { + throw new PluginApiException("limit-exceeded", "The response is larger than 2 MB."); + } + + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using var buffer = new MemoryStream(); + var chunk = new byte[16 * 1024]; + int read; + while ((read = await stream.ReadAsync(chunk, cancellationToken)) > 0) + { + if (buffer.Length + read > MaximumResponseBytes) + { + throw new PluginApiException("limit-exceeded", "The response is larger than 2 MB."); + } + + buffer.Write(chunk, 0, read); + } + + return Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length); + } + + // No cookies, no redirects the fetcher hasn't checked, no system proxy (the address check must see the real + // host), and a connection only to addresses outside the local network. + private static SocketsHttpHandler CreateHandler() => new() + { + AllowAutoRedirect = false, + UseCookies = false, + UseProxy = false, + AutomaticDecompression = DecompressionMethods.All, + ConnectCallback = async (context, cancellationToken) => + { + var addresses = await ResolvePublicAddressesAsync( + context.DnsEndPoint.Host, Dns.GetHostAddressesAsync, cancellationToken); + + Exception? lastException = null; + foreach (var address in addresses) + { + var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + await socket.ConnectAsync(new IPEndPoint(address, context.DnsEndPoint.Port), cancellationToken); + return new NetworkStream(socket, ownsSocket: true); + } + catch (Exception ex) + { + lastException = ex; + socket.Dispose(); + } + } + + throw lastException ?? new SocketException(); + } + }; +} From c43b26831a02a4ada54aba752dc32555102725f7 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:02:02 -0500 Subject: [PATCH 10/49] fix: refuse header injection in plugin fetches and report every failure as a plugin error --- .../Plugins/PluginHttpFetcherTests.cs | 209 +++++++++++++++++- .../Plugins/PluginHttpFetcher.cs | 54 ++++- 2 files changed, 254 insertions(+), 9 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs index 752d9b4..c9f52ee 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs @@ -10,6 +10,10 @@ public sealed class PluginHttpFetcherTests "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, [new Uri("https://wiki.example.com")], false, []); + private static readonly PluginManifest MultiSiteManifest = new( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, + [new Uri("https://wiki.example.com"), new Uri("https://cdn.example.net")], false, []); + private static PluginHttpRequest Get(string url) => new(url, "GET", null, null); [Fact] @@ -73,18 +77,27 @@ await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/api", " new Dictionary { ["Cookie"] = "session=1", + ["cookie"] = "lowercase=1", ["Host"] = "attacker.example.net", ["Sec-Fetch-Site"] = "same-origin", + ["SEC-Fetch-Mode"] = "cors", ["Proxy-Authorization"] = "Basic x", - ["X-Api-Key"] = "abc" + ["proxy-connection"] = "keep-alive", + ["Connection"] = "close", + ["X-Keep"] = "yes" }, null)); Assert.NotNull(sent); Assert.False(sent.Headers.Contains("Cookie")); + Assert.False(sent.Headers.Contains("cookie")); Assert.False(sent.Headers.Contains("Sec-Fetch-Site")); + Assert.False(sent.Headers.Contains("SEC-Fetch-Mode")); Assert.False(sent.Headers.Contains("Proxy-Authorization")); + Assert.False(sent.Headers.Contains("proxy-connection")); + Assert.False(sent.Headers.Contains("Connection")); Assert.Null(sent.Headers.Host); - Assert.Equal("abc", sent.Headers.GetValues("X-Api-Key").Single()); + Assert.Null(sent.Content); + Assert.Equal("yes", sent.Headers.GetValues("X-Keep").Single()); } [Fact] @@ -102,6 +115,21 @@ public async Task AResponseOverTwoMegabytesIsRefused() Assert.Equal("limit-exceeded", error.Code); } + [Fact] + public async Task AStreamedResponseOverTwoMegabytesIsRefused() + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new UnknownLengthContent(new byte[PluginHttpFetcher.MaximumResponseBytes + 1]) + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/big"))); + + Assert.Equal("limit-exceeded", error.Code); + } + [Fact] public async Task TheSixtyFirstRequestInAMinuteIsRefusedAndAllowedAgainLater() { @@ -159,6 +187,145 @@ public async Task AHostThatResolvesToPublicAddressesReturnsThemAll() Assert.Equal(expected, result); } + [Theory] + [InlineData("v\r\nCookie: x")] + [InlineData("v\nHost: evil")] + [InlineData("v\rX: y")] + [InlineData("café")] + public async Task AHeaderValueWithALineBreakIsRefusedAndNothingIsSent(string invalidValue) + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "GET", + new Dictionary { ["X-Test"] = invalidValue }, null))); + + Assert.Equal("invalid-argument", error.Code); + Assert.Empty(handler.Requests); + } + + [Theory] + [InlineData("bad name")] + [InlineData("X:Y")] + [InlineData("")] + [InlineData("Cookie ")] + public async Task AnInvalidHeaderNameIsRefused(string invalidName) + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "POST", + new Dictionary { [invalidName] = "value" }, "body"))); + + Assert.Equal("invalid-argument", error.Code); + Assert.Empty(handler.Requests); + } + + [Fact] + public async Task ARequestThatTakesTooLongIsRefused() + { + var handler = new HangingHandler(); + using var fetcher = new PluginHttpFetcher( + Manifest, PluginTrust.Developer, handler, timeout: TimeSpan.FromMilliseconds(100)); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + + Assert.Equal("unavailable", error.Code); + } + + [Fact] + public async Task AMalformedRedirectIsRefusedCleanly() + { + var handler = new FakeHandler(_ => + { + var response = new HttpResponseMessage(HttpStatusCode.Found); + response.Headers.TryAddWithoutValidation("Location", "//host:99999/"); + return response; + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + + Assert.Equal("unavailable", error.Code); + } + + [Fact] + public async Task ABrokenBodyIsRefusedCleanly() + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new ThrowingContent() + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + + Assert.Equal("unavailable", error.Code); + } + + [Fact] + public async Task PluginHeadersAreNotForwardedToAnotherHost() + { + var capturedHeaders = new List<(Uri, bool hasAuth)>(); + var handler = new FakeHandler(request => + { + var hasAuth = request.Headers.Contains("Authorization"); + capturedHeaders.Add((request.RequestUri!, hasAuth)); + + if (request.RequestUri!.Host == "wiki.example.com") + { + return Redirect("https://cdn.example.net/x"); + } + + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + }); + using var fetcher = new PluginHttpFetcher(MultiSiteManifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "GET", + new Dictionary { ["Authorization"] = "Bearer t" }, null)); + + Assert.Equal(2, capturedHeaders.Count); + Assert.True(capturedHeaders[0].hasAuth, "First request should have Authorization"); + Assert.False(capturedHeaders[1].hasAuth, "Second request to different host should not have Authorization"); + } + + [Fact] + public async Task RedirectHopsCountTowardsTheRateLimit() + { + var clock = new FakeClock(); + var requestCount = 0; + var handler = new FakeHandler(_ => + { + requestCount++; + // Each fetch can have up to 5 redirects (6 total requests), so 10 fetches = 60 requests + var withinFetch = requestCount % 6; + if (withinFetch != 0) + { + return Redirect("/again"); + } + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler, clock); + + // Make 10 successful fetches (each with 6 requests = 60 total) + for (var i = 0; i < 10; i++) + { + await fetcher.FetchAsync(Get("https://wiki.example.com/start")); + } + + // The 11th fetch should hit the rate limit + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/start"))); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal(60, requestCount); + } + private static HttpResponseMessage Redirect(string location) => new(HttpStatusCode.Found) { Headers = { Location = new Uri(location, UriKind.RelativeOrAbsolute) } }; @@ -174,6 +341,44 @@ protected override Task SendAsync( } } + private sealed class HangingHandler : HttpMessageHandler + { + protected override async Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + { + await Task.Delay(Timeout.Infinite, cancellationToken); + return new HttpResponseMessage(HttpStatusCode.OK); + } + } + + private sealed class UnknownLengthContent(byte[] data) : HttpContent + { + protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context) + { + await stream.WriteAsync(data); + } + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + } + + private sealed class ThrowingContent : HttpContent + { + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) + { + throw new IOException("broken"); + } + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + } + private sealed class FakeClock : TimeProvider { private DateTimeOffset _now = new(2026, 10, 3, 12, 0, 0, TimeSpan.Zero); diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs index eaa4f46..aa79807 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs @@ -25,6 +25,8 @@ public sealed class PluginHttpFetcher : IDisposable public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(15); + private const string HeaderSeparators = "()<>@,;:\\\"/[]?={}"; + private static readonly string[] ForbiddenHeaders = ["Cookie", "Host", "Content-Length", "Transfer-Encoding", "Connection"]; @@ -32,14 +34,17 @@ public sealed class PluginHttpFetcher : IDisposable private readonly PluginTrust _trust; private readonly HttpClient _http; private readonly TimeProvider _clock; + private readonly TimeSpan _timeout; private readonly Queue _recent = new(); public PluginHttpFetcher( - PluginManifest manifest, PluginTrust trust, HttpMessageHandler? handler = null, TimeProvider? clock = null) + PluginManifest manifest, PluginTrust trust, HttpMessageHandler? handler = null, TimeProvider? clock = null, + TimeSpan? timeout = null) { _manifest = manifest; _trust = trust; _clock = clock ?? TimeProvider.System; + _timeout = timeout ?? RequestTimeout; _http = new HttpClient(handler ?? CreateHandler()) { Timeout = Timeout.InfiniteTimeSpan }; } @@ -57,11 +62,13 @@ public async Task FetchAsync( throw new PluginApiException("invalid-argument", "The URL isn't valid."); } + ValidateHeaders(request.Headers); EnsureAllowed(uri); TakeRateSlot(); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - timeout.CancelAfter(RequestTimeout); + timeout.CancelAfter(_timeout); var body = request.Body; + var originalHost = uri.IdnHost; try { for (var redirects = 0; ; redirects++) @@ -72,7 +79,11 @@ public async Task FetchAsync( message.Content = new StringContent(body ?? string.Empty, Encoding.UTF8); } - ApplyHeaders(message, request.Headers); + // Don't forward plugin headers to a different host after redirects. + var headersToSend = uri.IdnHost.Equals(originalHost, StringComparison.OrdinalIgnoreCase) + ? request.Headers + : null; + ApplyHeaders(message, headersToSend); using var response = await _http.SendAsync( message, HttpCompletionOption.ResponseHeadersRead, timeout.Token); if ((int)response.StatusCode is 301 or 302 or 303 or 307 or 308 && @@ -83,8 +94,14 @@ public async Task FetchAsync( throw new PluginApiException("limit-exceeded", "The request was redirected too many times."); } - uri = location.IsAbsoluteUri ? location : new Uri(uri, location); + if (!Uri.TryCreate(uri, location, out var next)) + { + throw new PluginApiException("unavailable", "The site sent a redirect that isn't valid."); + } + + uri = next; EnsureAllowed(uri); + TakeRateSlot(); if ((int)response.StatusCode == 303 || (method == HttpMethod.Post && (int)response.StatusCode is 301 or 302)) { @@ -95,8 +112,10 @@ public async Task FetchAsync( continue; } + var text = await ReadTextAsync(response, timeout.Token); + text = text.TrimStart(''); return new PluginHttpResponse( - (int)response.StatusCode, FlattenHeaders(response), await ReadTextAsync(response, timeout.Token)); + (int)response.StatusCode, FlattenHeaders(response), text); } } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) @@ -111,6 +130,27 @@ public async Task FetchAsync( { throw new PluginApiException("unavailable", "The request failed."); } + catch (Exception exception) when (exception is not PluginApiException and not OperationCanceledException) + { + throw new PluginApiException("unavailable", "The request failed."); + } + } + + // A header name must be an HTTP token, and a value printable ASCII or a tab: no line breaks, control characters + // or non-ASCII, any of which could smuggle extra headers or a second request onto the connection. + private static void ValidateHeaders(IReadOnlyDictionary? headers) + { + foreach (var (name, value) in headers ?? new Dictionary()) + { + var validName = name.Length > 0 && + name.All(character => character is > ' ' and < '\x7f' && !HeaderSeparators.Contains(character)); + var validValue = value is not null && + value.All(character => character == '\t' || character is >= ' ' and <= '~'); + if (!validName || !validValue) + { + throw new PluginApiException("invalid-argument", "A request header's name or value isn't valid."); + } + } } // Refuses a host when any address it resolves to is on the local network, and returns all addresses outside @@ -240,9 +280,9 @@ private static async Task ReadTextAsync(HttpResponseMessage response, Ca await socket.ConnectAsync(new IPEndPoint(address, context.DnsEndPoint.Port), cancellationToken); return new NetworkStream(socket, ownsSocket: true); } - catch (Exception ex) + catch (Exception exception) when (exception is not OperationCanceledException) { - lastException = ex; + lastException = exception; socket.Dispose(); } } From a7665fbb01aefe7ea64ff9b360138462c6c22c6d Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:19:40 -0500 Subject: [PATCH 11/49] fix: never resend plugin headers after a redirect leaves the host, and make the fetch tests bite --- .../Plugins/PluginHttpFetcherTests.cs | 92 ++++++++++++++++++- .../Plugins/PluginHttpFetcher.cs | 22 +++-- 2 files changed, 106 insertions(+), 8 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs index c9f52ee..d8970e2 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs @@ -326,6 +326,96 @@ public async Task RedirectHopsCountTowardsTheRateLimit() Assert.Equal(60, requestCount); } + [Fact] + public async Task PluginHeadersAreNotSentAgainAfterReturningToTheOriginalHost() + { + var capturedHeaders = new List<(Uri, bool hasAuth)>(); + var handler = new FakeHandler(request => + { + var hasAuth = request.Headers.Contains("Authorization"); + capturedHeaders.Add((request.RequestUri!, hasAuth)); + + if (request.RequestUri!.Host == "wiki.example.com" && request.RequestUri.AbsolutePath == "/start") + { + return Redirect("https://cdn.example.net/x"); + } + + if (request.RequestUri!.Host == "cdn.example.net") + { + return Redirect("https://wiki.example.com/back"); + } + + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + }); + using var fetcher = new PluginHttpFetcher(MultiSiteManifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/start", "GET", + new Dictionary { ["Authorization"] = "Bearer t" }, null)); + + Assert.Equal(3, capturedHeaders.Count); + Assert.True(capturedHeaders[0].hasAuth, "First request (wiki) should have Authorization"); + Assert.False(capturedHeaders[1].hasAuth, "Second request (cdn) should not have Authorization"); + Assert.False(capturedHeaders[2].hasAuth, "Third request (back to wiki) should not have Authorization"); + } + + [Fact] + public async Task FramingHeadersFromThePluginAreIgnoredOnAPost() + { + HttpRequestMessage? sent = null; + long? contentLength = null; + var handler = new FakeHandler(request => + { + sent = request; + contentLength = sent.Content?.Headers.ContentLength; + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "POST", + new Dictionary + { + ["Content-Length"] = "999", + ["Transfer-Encoding"] = "chunked", + ["Connection"] = "close", + ["X-Keep"] = "1" + }, "hello")); + + Assert.NotNull(sent); + Assert.Equal(5, contentLength); + Assert.True(sent.Headers.TransferEncodingChunked != true); + Assert.False(sent.Headers.Contains("Transfer-Encoding")); + Assert.False(sent.Headers.Contains("Connection")); + Assert.Equal("1", sent.Headers.GetValues("X-Keep").Single()); + } + + [Fact] + public async Task AnInvalidRequestDoesNotUseTheRateLimit() + { + var clock = new FakeClock(); + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler, clock); + + // Make 60 invalid requests (invalid header values) — none should consume rate slots + for (var i = 0; i < 60; i++) + { + await Assert.ThrowsAsync( + () => fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "GET", + new Dictionary { ["X-Test"] = "v\r\nCookie: x" }, null))); + } + + // Now make 60 valid requests — all should succeed + for (var i = 0; i < 60; i++) + { + await fetcher.FetchAsync(Get("https://wiki.example.com/")); + } + + // The 61st valid request should hit the rate limit + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + + Assert.Equal("limit-exceeded", error.Code); + } + private static HttpResponseMessage Redirect(string location) => new(HttpStatusCode.Found) { Headers = { Location = new Uri(location, UriKind.RelativeOrAbsolute) } }; @@ -369,7 +459,7 @@ private sealed class ThrowingContent : HttpContent { protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) { - throw new IOException("broken"); + throw new InvalidDataException("broken"); } protected override bool TryComputeLength(out long length) diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs index aa79807..e261f54 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs @@ -69,6 +69,7 @@ public async Task FetchAsync( timeout.CancelAfter(_timeout); var body = request.Body; var originalHost = uri.IdnHost; + var forwardHeaders = true; try { for (var redirects = 0; ; redirects++) @@ -79,11 +80,13 @@ public async Task FetchAsync( message.Content = new StringContent(body ?? string.Empty, Encoding.UTF8); } - // Don't forward plugin headers to a different host after redirects. - var headersToSend = uri.IdnHost.Equals(originalHost, StringComparison.OrdinalIgnoreCase) - ? request.Headers - : null; - ApplyHeaders(message, headersToSend); + // Don't forward plugin headers to a different host; once headers are dropped, keep them dropped. + if (!uri.IdnHost.Equals(originalHost, StringComparison.OrdinalIgnoreCase)) + { + forwardHeaders = false; + } + + ApplyHeaders(message, forwardHeaders ? request.Headers : null); using var response = await _http.SendAsync( message, HttpCompletionOption.ResponseHeadersRead, timeout.Token); if ((int)response.StatusCode is 301 or 302 or 303 or 307 or 308 && @@ -120,7 +123,7 @@ public async Task FetchAsync( } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { - throw new PluginApiException("unavailable", "The request took longer than 15 seconds."); + throw new PluginApiException("unavailable", "The request took too long."); } catch (HttpRequestException exception) when (exception.InnerException is PluginApiException refused) { @@ -280,7 +283,12 @@ private static async Task ReadTextAsync(HttpResponseMessage response, Ca await socket.ConnectAsync(new IPEndPoint(address, context.DnsEndPoint.Port), cancellationToken); return new NetworkStream(socket, ownsSocket: true); } - catch (Exception exception) when (exception is not OperationCanceledException) + catch (OperationCanceledException) + { + socket.Dispose(); + throw; + } + catch (Exception exception) { lastException = exception; socket.Dispose(); From 949ee0b4766e65bb1113b2e8b61596a30fdf224f Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:23:53 -0500 Subject: [PATCH 12/49] fix: keep plugin headers off another port of the same host, and write the BOM as an escape --- .../Plugins/PluginHttpFetcherTests.cs | 23 +++++++++++++++++++ .../Plugins/PluginHttpFetcher.cs | 8 ++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs index d8970e2..4d8cd0a 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs @@ -358,6 +358,29 @@ await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/start", Assert.False(capturedHeaders[2].hasAuth, "Third request (back to wiki) should not have Authorization"); } + [Fact] + public async Task PluginHeadersAreNotSentToAnotherPortOnTheSameHost() + { + var manifest = MultiSiteManifest with + { + Sites = [new Uri("https://wiki.example.com"), new Uri("https://wiki.example.com:8443")] + }; + var sawAuth = new List(); + var handler = new FakeHandler(request => + { + sawAuth.Add(request.Headers.Contains("Authorization")); + return request.RequestUri!.Port == 443 + ? Redirect("https://wiki.example.com:8443/x") + : new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + }); + using var fetcher = new PluginHttpFetcher(manifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/start", "GET", + new Dictionary { ["Authorization"] = "Bearer t" }, null)); + + Assert.Equal([true, false], sawAuth); + } + [Fact] public async Task FramingHeadersFromThePluginAreIgnoredOnAPost() { diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs index e261f54..09f27b9 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs @@ -69,6 +69,7 @@ public async Task FetchAsync( timeout.CancelAfter(_timeout); var body = request.Body; var originalHost = uri.IdnHost; + var originalPort = uri.Port; var forwardHeaders = true; try { @@ -80,8 +81,9 @@ public async Task FetchAsync( message.Content = new StringContent(body ?? string.Empty, Encoding.UTF8); } - // Don't forward plugin headers to a different host; once headers are dropped, keep them dropped. - if (!uri.IdnHost.Equals(originalHost, StringComparison.OrdinalIgnoreCase)) + // Don't forward plugin headers to a different host or port; once headers are dropped, keep them dropped. + if (uri.Port != originalPort || + !uri.IdnHost.Equals(originalHost, StringComparison.OrdinalIgnoreCase)) { forwardHeaders = false; } @@ -116,7 +118,7 @@ public async Task FetchAsync( } var text = await ReadTextAsync(response, timeout.Token); - text = text.TrimStart(''); + text = text.TrimStart('\uFEFF'); return new PluginHttpResponse( (int)response.StatusCode, FlattenHeaders(response), text); } From d5d8d7fe91f755576929aaaaad05c42b570c3927 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:28:44 -0500 Subject: [PATCH 13/49] feat: save plugin cards and developer mode, and keep a missing plugin's place in the strip --- .../Data/SettingsStorePluginCardTests.cs | 76 +++++++++++++++++++ .../Data/LocalDataPaths.cs | 12 +++ .../Models/OverlayAddOnKind.cs | 4 +- .../Models/OverlayCardPlacement.cs | 8 +- .../Models/PanelSettings.cs | 3 + .../Overlay/OverlayAddOnCatalog.cs | 5 ++ .../Overlay/OverlayCardPolicy.cs | 24 ++++-- .../Plugins/PluginCardId.cs | 18 +++++ .../Plugins/PluginDescriptor.cs | 19 ++++- .../Plugins/PluginLayoutPolicy.cs | 28 +++++-- .../Plugins/PluginManifestReader.cs | 4 +- 11 files changed, 178 insertions(+), 23 deletions(-) create mode 100644 src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginCardTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginCardTests.cs b/src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginCardTests.cs new file mode 100644 index 0000000..448b5e1 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginCardTests.cs @@ -0,0 +1,76 @@ +using System.Text.Json.Nodes; +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Models; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Data; + +public sealed class SettingsStorePluginCardTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"fourfold-settings-{Guid.NewGuid():N}"); + private readonly SettingsStore _store; + + public SettingsStorePluginCardTests() + { + Directory.CreateDirectory(_root); + _store = new SettingsStore(new LocalDataPaths(_root)); + } + + private string SettingsPath => Path.Combine(_root, "settings.json"); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + [Fact] + public async Task PluginCardsAndDeveloperModeRoundTripThroughSaveAndLoad() + { + var accountId = Guid.NewGuid(); + var cards = new[] + { + new OverlayCardPlacement(OverlayAddOnKind.Plugin, accountId, true, new OverlayBounds(0.1, 0.2, 0.3, 0.1)) + { + PluginCard = "cody.goal-tracker/goal" + }, + new OverlayCardPlacement(OverlayAddOnKind.Plugin, null, false, null) + { + PluginCard = "cody.goal-tracker/summary" + } + }; + + await _store.SaveAsync(PanelSettings.Default with { PluginDeveloperMode = true, OverlayCards = cards }); + var loaded = await _store.LoadAsync(); + + Assert.True(loaded.PluginDeveloperMode); + Assert.Equal(cards, loaded.OverlayCards); + } + + [Fact] + public async Task MalformedPluginCardsAreDroppedWithoutLosingOtherSettings() + { + var accountId = Guid.NewGuid(); + await _store.SaveAsync(PanelSettings.Default with { ShowOverlaysInTheatreMode = false }); + var json = JsonNode.Parse(await File.ReadAllTextAsync(SettingsPath))!.AsObject(); + json["overlayCards"] = new JsonArray + { + new JsonObject { ["kind"] = 4, ["accountId"] = null, ["enabled"] = true }, + new JsonObject { ["kind"] = 4, ["accountId"] = null, ["enabled"] = true, ["pluginCard"] = "" }, + new JsonObject { ["kind"] = 4, ["accountId"] = null, ["enabled"] = true, ["pluginCard"] = "Not Valid" }, + new JsonObject { ["kind"] = 4, ["accountId"] = null, ["enabled"] = true, ["pluginCard"] = 7 }, + new JsonObject + { + ["kind"] = 0, ["accountId"] = accountId.ToString(), ["enabled"] = true, + ["pluginCard"] = "cody.goal-tracker/goal" + }, + new JsonObject + { + ["kind"] = 4, ["accountId"] = null, ["enabled"] = true, ["pluginCard"] = "cody.goal-tracker/summary" + } + }; + await File.WriteAllTextAsync(SettingsPath, json.ToJsonString()); + + var loaded = await _store.LoadAsync(); + + Assert.False(loaded.ShowOverlaysInTheatreMode); + var kept = Assert.Single(loaded.OverlayCards); + Assert.Equal("cody.goal-tracker/summary", kept.PluginCard); + } +} diff --git a/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs b/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs index 9f09d94..dde8b50 100644 --- a/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs +++ b/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs @@ -16,6 +16,9 @@ public LocalDataPaths(string? root = null) XpTrackerFilePath = Path.Combine(DataRoot, "xp-tracker.json"); LeaderboardStateFilePath = Path.Combine(DataRoot, "leaderboard-state.json"); WebViewUserDataRoot = Path.Combine(DataRoot, "WebView2"); + DevPluginsRoot = Path.Combine(DataRoot, "dev-plugins"); + PluginDataRoot = Path.Combine(DataRoot, "plugin-data"); + PluginWebViewUserDataRoot = Path.Combine(DataRoot, "PluginWebView2"); } public string DataRoot { get; } @@ -29,4 +32,13 @@ public LocalDataPaths(string? root = null) public string LeaderboardStateFilePath { get; } public string WebViewUserDataRoot { get; } + + // Plugin authors' work-in-progress plugins, loaded while developer mode is on. + public string DevPluginsRoot { get; } + + // One JSON file of private storage per community plugin. + public string PluginDataRoot { get; } + + // The plugin browser's own data folder, separate from the game profiles in WebViewUserDataRoot. + public string PluginWebViewUserDataRoot { get; } } diff --git a/src/FourFoldAccountManager.Core/Models/OverlayAddOnKind.cs b/src/FourFoldAccountManager.Core/Models/OverlayAddOnKind.cs index 2dc2541..944b023 100644 --- a/src/FourFoldAccountManager.Core/Models/OverlayAddOnKind.cs +++ b/src/FourFoldAccountManager.Core/Models/OverlayAddOnKind.cs @@ -6,5 +6,7 @@ public enum OverlayAddOnKind Xp = 0, Timer = 1, Stats = 2, - XpCalc = 3 + XpCalc = 3, + // A community plugin's card; OverlayCardPlacement.PluginCard says which. + Plugin = 4 } diff --git a/src/FourFoldAccountManager.Core/Models/OverlayCardPlacement.cs b/src/FourFoldAccountManager.Core/Models/OverlayCardPlacement.cs index 24499c6..0589d21 100644 --- a/src/FourFoldAccountManager.Core/Models/OverlayCardPlacement.cs +++ b/src/FourFoldAccountManager.Core/Models/OverlayCardPlacement.cs @@ -2,7 +2,7 @@ namespace FourFoldAccountManager.Core.Models; -public readonly record struct OverlayCardKey(OverlayAddOnKind Kind, Guid? AccountId); +public readonly record struct OverlayCardKey(OverlayAddOnKind Kind, Guid? AccountId, string? PluginCard = null); public sealed record OverlayCardPlacement( OverlayAddOnKind Kind, @@ -11,7 +11,11 @@ public sealed record OverlayCardPlacement( OverlayBounds? Bounds) { [JsonIgnore] - public OverlayCardKey Key => new(Kind, AccountId); + public OverlayCardKey Key => new(Kind, AccountId, PluginCard); + + // "/" when Kind is Plugin; null for FourFold's own cards. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? PluginCard { get; init; } // Shown as its own floating window instead of over the game. Only meaningful while Enabled. public bool IsFloating { get; init; } diff --git a/src/FourFoldAccountManager.Core/Models/PanelSettings.cs b/src/FourFoldAccountManager.Core/Models/PanelSettings.cs index 4ddec56..2047b69 100644 --- a/src/FourFoldAccountManager.Core/Models/PanelSettings.cs +++ b/src/FourFoldAccountManager.Core/Models/PanelSettings.cs @@ -30,6 +30,9 @@ public PanelSettings(PanelLayout layout, IReadOnlyList slotAccountIds) // Whether the whole plugin strip and its panel show in the main window; the toolbar button toggles it. public bool PluginStripVisible { get; init; } = true; + // Loads community plugins from the dev plugins folder, for plugin authors. + public bool PluginDeveloperMode { get; init; } + // Plugin ids in strip order. Empty means the built-in order. Unknown ids are kept for plugins that may return. [JsonConverter(typeof(LenientListJsonConverter))] public IReadOnlyList PluginOrder { get; init; } = Array.Empty(); diff --git a/src/FourFoldAccountManager.Core/Overlay/OverlayAddOnCatalog.cs b/src/FourFoldAccountManager.Core/Overlay/OverlayAddOnCatalog.cs index 2649414..cb8706c 100644 --- a/src/FourFoldAccountManager.Core/Overlay/OverlayAddOnCatalog.cs +++ b/src/FourFoldAccountManager.Core/Overlay/OverlayAddOnCatalog.cs @@ -37,6 +37,11 @@ public static bool TryGet(OverlayAddOnKind kind, [NotNullWhen(true)] out Overlay public static int IndexOf(OverlayAddOnKind kind) { + if (kind == OverlayAddOnKind.Plugin) + { + return All.Count; + } + for (var index = 0; index < All.Count; index++) { if (All[index].Kind == kind) diff --git a/src/FourFoldAccountManager.Core/Overlay/OverlayCardPolicy.cs b/src/FourFoldAccountManager.Core/Overlay/OverlayCardPolicy.cs index 0d0d78c..1eac9b2 100644 --- a/src/FourFoldAccountManager.Core/Overlay/OverlayCardPolicy.cs +++ b/src/FourFoldAccountManager.Core/Overlay/OverlayCardPolicy.cs @@ -1,4 +1,5 @@ using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Plugins; namespace FourFoldAccountManager.Core.Overlay; @@ -9,10 +10,17 @@ public static class OverlayCardPolicy public const double CascadeStep = 16; public static bool IsValidKey(OverlayCardKey key) => - OverlayAddOnCatalog.TryGet(key.Kind, out var definition) && - (definition.Scope == OverlayAddOnScope.Account - ? key.AccountId is { } accountId && accountId != Guid.Empty - : key.AccountId is null); + key.Kind == OverlayAddOnKind.Plugin + // A plugin card's scope is only known while its plugin is loaded, so either scope is valid here. + ? PluginCardId.IsValid(key.PluginCard) && key.AccountId != Guid.Empty + : key.PluginCard is null && + OverlayAddOnCatalog.TryGet(key.Kind, out var definition) && + (definition.Scope == OverlayAddOnScope.Account + ? key.AccountId is { } accountId && accountId != Guid.Empty + : key.AccountId is null); + + private static OverlayCardPlacement NewPlacement(OverlayCardKey key, bool enabled) => + new(key.Kind, key.AccountId, enabled, null) { PluginCard = key.PluginCard }; // Settings files may be old or hand-edited; normalize instead of rejecting them. public static IReadOnlyList Normalize( @@ -66,7 +74,7 @@ public static IReadOnlyList RemoveAccount( // Showing a card over the game stops it floating, so a card is only ever in one place. public static PanelSettings WithEnabled(PanelSettings settings, OverlayCardKey key, bool enabled) => Upsert(settings, key, existing => - (existing ?? new OverlayCardPlacement(key.Kind, key.AccountId, false, null)) with + (existing ?? NewPlacement(key, false)) with { Enabled = enabled, IsFloating = false @@ -75,7 +83,7 @@ public static PanelSettings WithEnabled(PanelSettings settings, OverlayCardKey k // Ticking a card in the floating checklist floats it and takes it off the game; unticking switches it off. public static PanelSettings WithFloating(PanelSettings settings, OverlayCardKey key, bool show) => Upsert(settings, key, existing => - (existing ?? new OverlayCardPlacement(key.Kind, key.AccountId, false, null)) with + (existing ?? NewPlacement(key, false)) with { Enabled = show, IsFloating = show @@ -90,7 +98,7 @@ public static PanelSettings WithFloatingBounds(PanelSettings settings, OverlayCa } return Upsert(settings, key, existing => - (existing ?? new OverlayCardPlacement(key.Kind, key.AccountId, true, null) { IsFloating = true }) with + (existing ?? NewPlacement(key, true) with { IsFloating = true }) with { FloatingBounds = bounds }); @@ -115,7 +123,7 @@ public static PanelSettings WithBounds(PanelSettings settings, OverlayCardKey ke } return Upsert(settings, key, existing => - (existing ?? new OverlayCardPlacement(key.Kind, key.AccountId, true, null)) with { Bounds = bounds }); + (existing ?? NewPlacement(key, true)) with { Bounds = bounds }); } private static PanelSettings Upsert( diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs b/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs new file mode 100644 index 0000000..3ab21c8 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs @@ -0,0 +1,18 @@ +using System.Text.RegularExpressions; + +namespace FourFoldAccountManager.Core.Plugins; + +// A community plugin's card is identified by "/", for example "cody.goal-tracker/goal". +public static partial class PluginCardId +{ + [GeneratedRegex("^(?" + PluginManifestReader.IdPattern + ")/(?" + + PluginManifestReader.CardIdPattern + @")\z")] + private static partial Regex Pattern(); + + public static string Create(string pluginId, string cardId) => $"{pluginId}/{cardId}"; + + public static bool IsValid(string? value) => value is { Length: <= 97 } && Pattern().IsMatch(value); + + public static string? PluginId(string? value) => + value is not null && Pattern().Match(value) is { Success: true } match ? match.Groups["plugin"].Value : null; +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs b/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs index bdd58bd..bb4e3d4 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs @@ -1,13 +1,28 @@ using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Overlay; namespace FourFoldAccountManager.Core.Plugins; +public sealed record PluginCardDescriptor(string Id, string Name, OverlayAddOnScope Scope); + // Everything the strip, the plugin list and the "off" rules need to know about a plugin, with no UI. -// A community plugin's manifest will load into this same shape. public sealed record PluginDescriptor( string Id, string Name, string ShortLabel, string Icon, IReadOnlyList OverlayCards, - IReadOnlyList Shortcuts); + IReadOnlyList Shortcuts) +{ + // The cards a community plugin declared. FourFold's own plugins use OverlayCards instead. + public IReadOnlyList Cards { get; init; } = []; + + // A community plugin's icon image; when null the strip shows the Icon glyph. + public string? IconPath { get; init; } + + // 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. + public string? Detail { get; init; } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs index 36c4998..03feb61 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs @@ -32,6 +32,9 @@ public static bool IsCardSuppressed(PanelSettings settings, OverlayAddOnKind kin public static bool IsShortcutSuppressed(PanelSettings settings, GlobalShortcutAction action) => BuiltInPlugins.All.Any(plugin => plugin.Shortcuts.Contains(action) && !IsEnabled(settings, plugin.Id)); + public static bool IsPluginCardSuppressed(PanelSettings settings, string pluginCard) => + PluginCardId.PluginId(pluginCard) is not { } pluginId || !IsEnabled(settings, pluginId); + // The saved open plugin when it is known and switched on; otherwise null. public static PluginDescriptor? OpenPlugin(PanelSettings settings, IReadOnlyList known) => known.FirstOrDefault(plugin => plugin.Id == settings.OpenPlugin && IsEnabled(settings, plugin.Id)); @@ -53,26 +56,35 @@ public static PanelSettings WithEnabled(PanelSettings settings, string id, bool return !enabled && settings.OpenPlugin == id ? next with { PluginsSidebarExpanded = false } : next; } - // Moves a plugin to index among the strip's icons (switched-on plugins, in order). Switched-off plugins keep their - // places, and unknown saved ids stay at the end. + // Moves a plugin to index among the strip's icons (known, switched-on plugins, in order). Every other saved id + // keeps its slot: switched-off plugins, and plugins that aren't loaded right now. public static PanelSettings WithMoved( PanelSettings settings, IReadOnlyList known, string id, int index) { - var full = Ordered(settings, known).Select(plugin => plugin.Id).ToList(); - var strip = full.Where(other => IsEnabled(settings, other)).ToList(); + var knownIds = known.Select(plugin => plugin.Id).ToHashSet(StringComparer.Ordinal); + var full = settings.PluginOrder + .Concat(known.Select(plugin => plugin.Id) + .Where(knownId => !settings.PluginOrder.Contains(knownId, StringComparer.Ordinal))) + .ToList(); + bool OnStrip(string other) => knownIds.Contains(other) && IsEnabled(settings, other); + + var strip = full.Where(OnStrip).ToList(); if (!strip.Remove(id)) { return settings; } strip.Insert(Math.Clamp(index, 0, strip.Count), id); + var order = new List(full.Count); var nextStripId = 0; - var reordered = full.Select(other => IsEnabled(settings, other) ? strip[nextStripId++] : other); - var unknown = settings.PluginOrder.Where(saved => known.All(plugin => plugin.Id != saved)); - var order = reordered.Concat(unknown).ToArray(); + foreach (var other in full) + { + order.Add(OnStrip(other) ? strip[nextStripId++] : other); + } + return order.SequenceEqual(settings.PluginOrder) ? settings - : settings with { PluginOrder = Array.AsReadOnly(order) }; + : settings with { PluginOrder = Array.AsReadOnly(order.ToArray()) }; } public static PanelSettings WithOpened(PanelSettings settings, string id) => diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index cb0c58e..adacbdf 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -15,10 +15,10 @@ public static partial class PluginManifestReader private const int MaximumIconBytes = 64 * 1024; - [GeneratedRegex("^" + IdPattern + "$")] + [GeneratedRegex("^" + IdPattern + @"\z")] private static partial Regex IdRegex(); - [GeneratedRegex("^" + CardIdPattern + "$")] + [GeneratedRegex("^" + CardIdPattern + @"\z")] private static partial Regex CardIdRegex(); [GeneratedRegex(@"^[0-9]+\.[0-9]+\.[0-9]+$")] From de7b03f44d5458be544f8017d41779f41f095911 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:32:13 -0500 Subject: [PATCH 14/49] test: prove two cards from one plugin survive a settings load --- .../Overlay/OverlayCardPolicyTests.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/FourFoldAccountManager.Core.Tests/Overlay/OverlayCardPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Overlay/OverlayCardPolicyTests.cs index 7f2182e..ab48be6 100644 --- a/src/FourFoldAccountManager.Core.Tests/Overlay/OverlayCardPolicyTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Overlay/OverlayCardPolicyTests.cs @@ -131,4 +131,17 @@ public void MovingACardBetweenTheGameAndFloatingKeepsOnePlaceAndBothPositions() Assert.Equal(floatingSpot, returnedCard.FloatingBounds); Assert.True(OverlayCardPolicy.Get(returned, timerKey)!.Enabled); } + + [Fact] + public void TwoCardsFromOnePluginAreKeptApartThroughALoad() + { + var one = new OverlayCardKey(OverlayAddOnKind.Plugin, null, "cody.goal-tracker/one"); + var two = new OverlayCardKey(OverlayAddOnKind.Plugin, null, "cody.goal-tracker/two"); + + var settings = OverlayCardPolicy.WithEnabled(PanelSettings.Default, one, true); + settings = OverlayCardPolicy.WithBounds(settings, two, Second); + var loaded = OverlayCardPolicy.Normalize(settings.OverlayCards, null); + + Assert.Equal(["cody.goal-tracker/one", "cody.goal-tracker/two"], loaded.Select(card => card.PluginCard)); + } } From 0b127da143b522ada35e2b4aa04210f01b58796b Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:38:22 -0500 Subject: [PATCH 15/49] feat: host community plugins as sandboxed web pages with a message API --- .../Plugins/PluginApiTests.cs | 179 +++++++++ .../Plugins/Web/PluginApi.cs | 239 ++++++++++++ .../Plugins/Web/PluginBrowser.cs | 33 ++ .../Plugins/Web/PluginCardStore.cs | 32 ++ .../Plugins/Web/PluginHostData.cs | 54 +++ .../Plugins/Web/PluginSdk.cs | 109 ++++++ .../Plugins/Web/WebPlugin.cs | 347 ++++++++++++++++++ 7 files changed, 993 insertions(+) create mode 100644 src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs create mode 100644 src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs create mode 100644 src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs create mode 100644 src/FourFoldAccountManager.Desktop/Plugins/Web/PluginCardStore.cs create mode 100644 src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs create mode 100644 src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs create mode 100644 src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs new file mode 100644 index 0000000..9d757e1 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs @@ -0,0 +1,179 @@ +using System.IO; +using System.Text.Json; +using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Overlay; +using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Desktop.Plugins.Web; +using Xunit; + +namespace FourFoldAccountManager.Desktop.Tests.Plugins; + +public sealed class PluginApiTests : IDisposable +{ + private const string PluginId = "cody.goal-tracker"; + + private static readonly Guid KnownAccount = Guid.Parse("6b1d7c3e-2f4a-4c58-9e0b-1a2b3c4d5e6f"); + + private readonly string _folder = Path.Combine(Path.GetTempPath(), "fourfold-plugin-api-" + Guid.NewGuid().ToString("N")); + private readonly FakeHost _host = new(); + private readonly ManualTimeProvider _clock = new(); + private readonly PluginCardStore _cards = new(); + 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, + [ + 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); + } + + public void Dispose() + { + _http.Dispose(); + if (Directory.Exists(_folder)) + { + Directory.Delete(_folder, recursive: true); + } + } + + [Fact] + public async Task OpenExternalOnlyOpensPublicHttpsLinks() + { + _host.PanelShowing = true; + + foreach (var url in new[] + { + "file:///C:/Windows/System32/calc.exe", "javascript:alert(1)", "http://example.com/", + "https://localhost/", "https://192.168.1.1/", "https://user@example.com/", "ms-settings:", + "not a url" + }) + { + Assert.Equal("invalid-argument", ErrorCode(await Call("openExternal", new { url }))); + } + + Assert.Empty(_host.Opened); + + var opened = await Call("openExternal", new { url = "https://example.com/page" }); + + Assert.Null(ErrorCode(opened)); + Assert.Equal(new Uri("https://example.com/page"), Assert.Single(_host.Opened)); + } + + [Fact] + public async Task OpenExternalNeedsTheShowingPanelAndIsRateLimited() + { + var link = new { url = "https://example.com/" }; + + Assert.Equal("unavailable", ErrorCode(await Call("openExternal", link))); + Assert.Empty(_host.Opened); + + _host.PanelShowing = true; + Assert.Null(ErrorCode(await Call("openExternal", link))); + Assert.Single(_host.Opened); + + Assert.Equal("limit-exceeded", ErrorCode(await Call("openExternal", link))); + Assert.Single(_host.Opened); + + _clock.Advance(TimeSpan.FromSeconds(2)); + Assert.Null(ErrorCode(await Call("openExternal", link))); + Assert.Equal(2, _host.Opened.Count); + } + + [Fact] + public async Task ACardCanOnlyBeSetForADeclaredCardAndAKnownAccount() + { + Assert.Equal( + "not-declared", ErrorCode(await Call("cards.set", new { cardId = "other", accountId = KnownAccount }))); + Assert.Equal( + "invalid-argument", ErrorCode(await Call("cards.set", new { cardId = "goal", accountId = Guid.NewGuid() }))); + + var key = new OverlayCardKey(OverlayAddOnKind.Plugin, KnownAccount, "cody.goal-tracker/goal"); + Assert.Null(_cards.Get(key)); + + var reply = await Call("cards.set", new + { + cardId = "goal", + accountId = KnownAccount, + summary = "3 of 5", + rows = new[] { new { label = "Done", value = "3", progress = 0.6 } } + }); + + Assert.Null(ErrorCode(reply)); + var content = Assert.IsType(_cards.Get(key)); + Assert.Equal("3 of 5", content.Summary); + var row = Assert.Single(content.Rows); + Assert.Equal(("Done", "3", 0.6), (row.Label, row.Value, row.Progress)); + } + + [Fact] + public async Task HostileMessagesNeverThrow() + { + var messages = new[] + { + "not json", + "[]", + "{}", + """{"id":"x"}""", + """{"id":1}""", + """{"id":1,"method":5}""", + """{"id":1,"method":"xp.get","params":[]}""", + """{"id":1,"method":"cards.set","params":{"cardId":"goal","rows":"x"}}""", + """{"id":1,"method":"cards.set","params":{"cardId":"summary","rows":[5,null,{"progress":"x"}]}}""", + "{\"id\":1,\"method\":\"storage.set\",\"params\":{\"key\":\"k\",\"value\":\"" + + new string('x', PluginApi.MaximumMessageLength) + "\"}}" + }; + + foreach (var message in messages) + { + var reply = await _api.HandleAsync(message); + + if (reply is null) + { + continue; + } + + using var document = JsonDocument.Parse(reply); + Assert.True( + document.RootElement.TryGetProperty("result", out _) || document.RootElement.TryGetProperty("error", out _), + $"The reply to {message[..Math.Min(message.Length, 60)]} had neither a result nor an error."); + } + } + + private async Task Call(string method, object parameters) + { + var reply = await _api.HandleAsync(JsonSerializer.Serialize(new { id = 1, method, @params = parameters })); + Assert.NotNull(reply); + return JsonDocument.Parse(reply).RootElement; + } + + private static string? ErrorCode(JsonElement reply) => + reply.TryGetProperty("error", out var error) ? error.GetProperty("code").GetString() : null; + + private sealed class FakeHost : IPluginHostData + { + public IReadOnlyList Accounts { get; set; } = []; + + public bool PanelShowing { get; set; } + + public List Opened { get; } = []; + + public IReadOnlyList GetAccounts() => Accounts; + + public PluginXpInfo? GetXp(Guid accountId) => null; + + public PluginStatsInfo? GetStats(Guid accountId) => null; + + public PluginTimerInfo GetTimer() => new("stopped", 0, []); + + public bool IsPanelShowing(string pluginId) => PanelShowing; + + public void OpenInBrowser(Uri uri) => Opened.Add(uri); + } +} diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs new file mode 100644 index 0000000..8200993 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs @@ -0,0 +1,239 @@ +using System.Text.Json; +using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Overlay; +using FourFoldAccountManager.Core.Plugins; + +namespace FourFoldAccountManager.Desktop.Plugins.Web; + +// Answers one plugin's API messages. Every request is checked against that plugin's manifest; a bad or hostile +// message gets an error reply (or none) and never throws into the app. +internal sealed class PluginApi( + PluginManifest manifest, + IPluginHostData host, + PluginStorage storage, + PluginHttpFetcher http, + PluginCardStore cards, + TimeProvider clock) +{ + public const int MaximumMessageLength = 512 * 1024; + + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + private static readonly JsonElement EmptyObject = JsonDocument.Parse("{}").RootElement.Clone(); + private long? _lastOpened; + + // Returns the reply JSON, or null when the message can't be answered (too large, not JSON, or no id). + public async Task HandleAsync(string messageJson) + { + JsonElement id = default; + try + { + if (messageJson.Length > MaximumMessageLength) + { + return null; + } + + using var document = JsonDocument.Parse(messageJson); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("id", out var idElement) || + idElement.ValueKind != JsonValueKind.Number) + { + return null; + } + + id = idElement.Clone(); + var method = root.TryGetProperty("method", out var methodElement) && + methodElement.ValueKind == JsonValueKind.String + ? methodElement.GetString() + : null; + // A message without params gets an empty object, so every later property lookup is safe. + var parameters = root.TryGetProperty("params", out var paramsElement) && + paramsElement.ValueKind == JsonValueKind.Object + ? paramsElement + : EmptyObject; + var result = await DispatchAsync(method, parameters); + return JsonSerializer.Serialize(new { id, result }, Json); + } + catch (PluginApiException exception) + { + return Error(id, exception.Code, exception.Message); + } + catch (JsonException) + { + return Error(id, "invalid-argument", "The request wasn't valid."); + } + catch (Exception) + { + return Error(id, "unavailable", "FourFold couldn't complete the request."); + } + } + + private static string? Error(JsonElement id, string code, string message) => + id.ValueKind == JsonValueKind.Undefined + ? null + : JsonSerializer.Serialize(new { id, error = new { code, message } }, Json); + + private async Task DispatchAsync(string? method, JsonElement parameters) + { + switch (method) + { + case "accounts.list": + return host.GetAccounts(); + case "xp.get": + return host.GetXp(AccountId(parameters)) ?? throw UnknownAccount(); + case "stats.get": + { + var accountId = AccountId(parameters); + return host.GetAccounts().Any(account => account.Id == accountId) + ? host.GetStats(accountId) + : throw UnknownAccount(); + } + case "timer.get": + return host.GetTimer(); + case "storage.get": + return await storage.GetAsync(Text(parameters, "key")); + case "storage.set": + if (!parameters.TryGetProperty("value", out var value)) + { + throw new PluginApiException("invalid-argument", "storage.set needs a value."); + } + + await storage.SetAsync(Text(parameters, "key"), value); + return null; + case "storage.remove": + await storage.RemoveAsync(Text(parameters, "key")); + return null; + case "cards.set": + cards.Set(CardKey(parameters), CardContent(parameters)); + return null; + case "cards.clear": + cards.Clear(CardKey(parameters)); + return null; + case "http.fetch": + return await http.FetchAsync(new PluginHttpRequest( + Text(parameters, "url"), OptionalText(parameters, "method"), Headers(parameters), + OptionalText(parameters, "body"))); + case "openExternal": + OpenExternal(Text(parameters, "url")); + return null; + default: + throw new PluginApiException("invalid-argument", $"Unknown method '{method}'."); + } + } + + private static PluginApiException UnknownAccount() => new("invalid-argument", "That account id isn't known."); + + private static string Text(JsonElement parameters, string name) => + OptionalText(parameters, name) ?? throw new PluginApiException("invalid-argument", $"'{name}' must be text."); + + private static string? OptionalText(JsonElement parameters, string name) => + parameters.ValueKind == JsonValueKind.Object && parameters.TryGetProperty(name, out var element) && + element.ValueKind == JsonValueKind.String + ? element.GetString() + : null; + + private static Guid AccountId(JsonElement parameters) => + Guid.TryParse(OptionalText(parameters, "accountId"), out var accountId) ? accountId : throw UnknownAccount(); + + private static Dictionary? Headers(JsonElement parameters) + { + if (parameters.ValueKind != JsonValueKind.Object || !parameters.TryGetProperty("headers", out var element) || + element.ValueKind != JsonValueKind.Object) + { + return null; + } + + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var header in element.EnumerateObject().Where(header => header.Value.ValueKind == JsonValueKind.String)) + { + result[header.Name] = header.Value.GetString()!; + } + + return result; + } + + private OverlayCardKey CardKey(JsonElement parameters) + { + var cardId = Text(parameters, "cardId"); + var card = manifest.Cards.FirstOrDefault(candidate => candidate.Id == cardId) ?? + throw new PluginApiException("not-declared", $"The card '{cardId}' isn't declared in plugin.json."); + Guid? accountId = null; + if (card.Scope == OverlayAddOnScope.Account) + { + var id = AccountId(parameters); + if (host.GetAccounts().All(account => account.Id != id)) + { + throw UnknownAccount(); + } + + accountId = id; + } + else if (parameters.TryGetProperty("accountId", out var element) && element.ValueKind != JsonValueKind.Null) + { + throw new PluginApiException("invalid-argument", "A global card takes a null accountId."); + } + + return new OverlayCardKey(OverlayAddOnKind.Plugin, accountId, PluginCardId.Create(manifest.Id, cardId)); + } + + private static PluginCardContent CardContent(JsonElement parameters) + { + var summary = OptionalText(parameters, "summary") ?? string.Empty; + var rows = new List(); + if (parameters.TryGetProperty("rows", out var rowsElement) && rowsElement.ValueKind == JsonValueKind.Array) + { + foreach (var row in rowsElement.EnumerateArray()) + { + double? progress = null; + if (row.ValueKind == JsonValueKind.Object && row.TryGetProperty("progress", out var progressElement) && + progressElement.ValueKind != JsonValueKind.Null) + { + var number = progressElement.ValueKind == JsonValueKind.Number + ? progressElement.GetDouble() + : double.NaN; + if (number is not (>= 0 and <= 1)) + { + throw new PluginApiException("invalid-argument", "A row's progress must be from 0 to 1."); + } + + progress = number; + } + + rows.Add(new PluginCardRow( + OptionalText(row, "label") ?? string.Empty, OptionalText(row, "value") ?? string.Empty, progress)); + } + } + + if (summary.Length > 40 || rows.Count > 8 || rows.Any(row => row.Label.Length > 40 || row.Value.Length > 40)) + { + throw new PluginApiException( + "limit-exceeded", "A card takes a summary of up to 40 characters and up to 8 rows of up to 40 characters."); + } + + return new PluginCardContent(summary, rows); + } + + 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)) + { + throw new PluginApiException("invalid-argument", "Only https links can be opened."); + } + + if (!host.IsPanelShowing(manifest.Id)) + { + throw new PluginApiException("unavailable", "A link can only be opened while the plugin's panel is showing."); + } + + // The monotonic timestamp, not the wall clock: setting the system time can't skip the wait. + var now = clock.GetTimestamp(); + if (_lastOpened is { } last && clock.GetElapsedTime(last, now) < TimeSpan.FromSeconds(2)) + { + throw new PluginApiException("limit-exceeded", "A plugin can open one link every 2 seconds."); + } + + _lastOpened = now; + host.OpenInBrowser(uri); + } +} diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs new file mode 100644 index 0000000..33b7447 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs @@ -0,0 +1,33 @@ +using System.IO; +using FourFoldAccountManager.Core.Data; +using Microsoft.Web.WebView2.Core; + +namespace FourFoldAccountManager.Desktop.Plugins.Web; + +// The one WebView2 environment every community plugin runs in. Its data folder is separate from the games', so a +// plugin can never see a game's cookies, storage or pages. +public sealed class PluginBrowser(LocalDataPaths paths) +{ + private Task? _environment; + + public async Task GetEnvironmentAsync() + { + Directory.CreateDirectory(paths.PluginWebViewUserDataRoot); + var environment = _environment ??= CoreWebView2Environment.CreateAsync( + browserExecutableFolder: null, userDataFolder: paths.PluginWebViewUserDataRoot); + try + { + return await environment; + } + catch + { + // Let a later start try again instead of caching the failure. + if (environment.IsFaulted || environment.IsCanceled) + { + _environment = null; + } + + throw; + } + } +} diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginCardStore.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginCardStore.cs new file mode 100644 index 0000000..f387dbd --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginCardStore.cs @@ -0,0 +1,32 @@ +using FourFoldAccountManager.Core.Models; + +namespace FourFoldAccountManager.Desktop.Plugins.Web; + +public sealed record PluginCardRow(string Label, string Value, double? Progress); + +public sealed record PluginCardContent(string Summary, IReadOnlyList Rows); + +// The contents community plugins have set for their cards. Contents stay after a plugin stops, so its cards keep +// showing their last data (drawn stale) until it runs again. +public sealed class PluginCardStore +{ + private readonly Dictionary _cards = []; + + public event Action? Changed; + + public PluginCardContent? Get(OverlayCardKey key) => _cards.GetValueOrDefault(key); + + public void Set(OverlayCardKey key, PluginCardContent content) + { + _cards[key] = content; + Changed?.Invoke(); + } + + public void Clear(OverlayCardKey key) + { + if (_cards.Remove(key)) + { + Changed?.Invoke(); + } + } +} diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs new file mode 100644 index 0000000..4f651f0 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs @@ -0,0 +1,54 @@ +namespace FourFoldAccountManager.Desktop.Plugins.Web; + +public sealed record PluginAccountInfo(Guid Id, string Label, string? InGameName, bool IsOpen); + +public sealed record PluginClassInfo(string ClassName, int Level, long CurrentXp, long NextLevelXp); + +public sealed record PluginXpInfo( + string? ClassName, + int? Level, + long? CurrentXp, + long? NextLevelXp, + long? XpUntilNextLevel, + double? HoursUntilNextLevel, + double? XpPerHour, + long SessionXp, + IReadOnlyList Classes, + DateTimeOffset? UpdatedAt, + bool IsStale); + +public sealed record PluginStatsInfo( + string ClassName, + int Level, + long? Hp, + long? Sp, + long? Attack, + long? Magic, + long? Skill, + long? Speed, + long? Luck, + long? Defense, + long? Resistance); + +public sealed record PluginLapInfo(int Number, long LapMs, long TotalMs); + +public sealed record PluginTimerInfo(string State, long ElapsedMs, IReadOnlyList Laps); + +// What the app shows to community plugins. Nothing here can reach a saved login, a game session or a file. +public interface IPluginHostData +{ + IReadOnlyList GetAccounts(); + + // Null when the account id isn't one of the user's accounts. + PluginXpInfo? GetXp(Guid accountId); + + // Null before the account's first profile read. + PluginStatsInfo? GetStats(Guid accountId); + + PluginTimerInfo GetTimer(); + + // True while this plugin's panel is the one showing in the strip. + bool IsPanelShowing(string pluginId); + + void OpenInBrowser(Uri uri); +} diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs new file mode 100644 index 0000000..1e4f4cb --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs @@ -0,0 +1,109 @@ +using System.Text.Json; +using FourFoldAccountManager.Core.Plugins; + +namespace FourFoldAccountManager.Desktop.Plugins.Web; + +// The window.fourfold library, injected into every plugin document before its own scripts run. +internal static class PluginSdk +{ + private const string Script = """ + (() => { + const info = __FOURFOLD_INFO__; + const pending = new Map(); + const listeners = new Map(); + let nextId = 1; + const call = (method, params) => new Promise((resolve, reject) => { + const id = nextId++; + pending.set(id, { resolve, reject }); + window.chrome.webview.postMessage({ id, method, params: params ?? {} }); + }); + window.chrome.webview.addEventListener('message', event => { + const message = event.data; + if (!message) return; + if (message.id !== undefined) { + const waiting = pending.get(message.id); + if (!waiting) return; + pending.delete(message.id); + if (message.error) { + waiting.reject(Object.assign(new Error(message.error.message), { code: message.error.code })); + } else { + waiting.resolve(message.result); + } + return; + } + if (message.event) { + for (const callback of listeners.get(message.event) ?? []) { + try { callback(message.data); } catch (error) { console.error(error); } + } + } + }); + const on = (name, callback) => { + const callbacks = listeners.get(name) ?? new Set(); + listeners.set(name, callbacks); + callbacks.add(callback); + return () => callbacks.delete(callback); + }; + const applyTheme = () => { + for (const [name, value] of Object.entries(info.cssVariables)) { + document.documentElement.style.setProperty(name, value); + } + }; + if (document.documentElement) applyTheme(); + else document.addEventListener('DOMContentLoaded', applyTheme); + window.fourfold = Object.freeze({ + plugin: Object.freeze(info.plugin), + theme: Object.freeze(info.theme), + accounts: Object.freeze({ + list: () => call('accounts.list'), + onChanged: callback => on('accounts.changed', callback) + }), + xp: Object.freeze({ + get: accountId => call('xp.get', { accountId }), + onUpdated: callback => on('xp.updated', callback) + }), + stats: Object.freeze({ get: accountId => call('stats.get', { accountId }) }), + timer: Object.freeze({ + get: () => call('timer.get'), + onChanged: callback => on('timer.changed', callback) + }), + http: Object.freeze({ fetch: (url, options) => call('http.fetch', { url, ...(options ?? {}) }) }), + openExternal: url => navigator.userActivation && !navigator.userActivation.isActive + ? Promise.reject(Object.assign(new Error('openExternal needs a click.'), { code: 'unavailable' })) + : call('openExternal', { url }), + storage: Object.freeze({ + get: key => call('storage.get', { key }), + set: (key, value) => call('storage.set', { key, value }), + remove: key => call('storage.remove', { key }) + }), + cards: Object.freeze({ + set: (cardId, accountId, content) => call('cards.set', { cardId, accountId, ...(content ?? {}) }), + clear: (cardId, accountId) => call('cards.clear', { cardId, accountId }) + }) + }); + })(); + """; + + // The app's palette, matching Theme.xaml. + private static readonly (string Name, string Css, string Color)[] Palette = + [ + ("background", "--ff-background", "#101419"), + ("surface", "--ff-surface", "#171D24"), + ("surfaceRaised", "--ff-surface-raised", "#1D252F"), + ("border", "--ff-border", "#29333E"), + ("text", "--ff-text", "#F2F0E9"), + ("textMuted", "--ff-text-muted", "#98A4B1"), + ("accent", "--ff-accent", "#E7C16B"), + ("danger", "--ff-danger", "#E57777") + ]; + + public static string Build(PluginManifest manifest) + { + var info = JsonSerializer.Serialize(new + { + plugin = new { id = manifest.Id, version = manifest.Version, apiVersion = manifest.ApiVersion }, + theme = Palette.ToDictionary(entry => entry.Name, entry => entry.Color), + cssVariables = Palette.ToDictionary(entry => entry.Css, entry => entry.Color) + }); + return Script.Replace("__FOURFOLD_INFO__", info); + } +} diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs new file mode 100644 index 0000000..f16415a --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs @@ -0,0 +1,347 @@ +using System.IO; +using System.Runtime.InteropServices; +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; + +namespace FourFoldAccountManager.Desktop.Plugins.Web; + +// A community plugin: a sandboxed page in the shared plugin browser. The page keeps running while its panel isn't +// showing (its web view waits in a small invisible parking host), so its cards stay up to date. +public sealed class WebPlugin : IFourFoldPlugin, IDisposable +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + private readonly PluginTrust _trust; + private readonly PluginBrowser _browser; + private readonly Panel _parkingHost; + private readonly PluginHttpFetcher _http; + private readonly PluginApi _api; + private readonly string _contentSecurityPolicy; + private readonly Border _root; + private readonly Grid _viewHost = new(); + private readonly StackPanel _stoppedNotice; + private WebView2CompositionControl? _view; + + // Stop moves the generation on. A start that finds it changed after an await was stopped meanwhile, so it tears + // down the view it was building instead of bringing the plugin up. _startingGeneration is the generation whose + // start is in flight, so a second start for the same generation does nothing. + private int _generation; + private int _startingGeneration = -1; + + public WebPlugin( + PluginManifest manifest, + PluginTrust trust, + PluginBrowser browser, + Panel parkingHost, + IPluginHostData host, + PluginCardStore cards, + LocalDataPaths paths) + { + 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); + _contentSecurityPolicy = PluginNetworkPolicy.BuildContentSecurityPolicy(manifest, trust); + Descriptor = new PluginDescriptor(manifest.Id, manifest.Name, manifest.ShortLabel, "", [], []) + { + 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}")) + }; + + var reload = new Button { Content = "Reload", Height = 30, Padding = new Thickness(12, 0, 12, 0) }; + reload.SetResourceReference(FrameworkElement.StyleProperty, "AppButtonStyle"); + reload.Click += async (_, _) => await RestartAsync(); + _stoppedNotice = new StackPanel + { + VerticalAlignment = VerticalAlignment.Center, + HorizontalAlignment = HorizontalAlignment.Center, + Visibility = Visibility.Collapsed, + Children = + { + new TextBlock { Text = "This plugin stopped.", Margin = new Thickness(0, 0, 0, 10) }, + reload + } + }; + _viewHost.Children.Add(_stoppedNotice); + _root = new Border { BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(9), Child = _viewHost }; + _root.SetResourceReference(Border.BackgroundProperty, "Brush.Surface"); + _root.SetResourceReference(Border.BorderBrushProperty, "Brush.Border"); + // The view lives in the panel while the panel is in a window, and in the parking host the rest of the time. + _root.Loaded += (_, _) => MoveView(_viewHost); + _root.Unloaded += (_, _) => MoveView(_parkingHost); + } + + public PluginManifest Manifest { get; } + + public PluginDescriptor Descriptor { get; } + + public FrameworkElement Panel => _root; + + public FrameworkElement? SettingsPage => null; + + public bool IsRunning => _view is not null; + + public void Opened() + { + } + + public async Task StartAsync() + { + if (_view is not null || _startingGeneration == _generation) + { + return; + } + + var generation = _startingGeneration = _generation; + WebView2CompositionControl? view = null; + var started = false; + try + { + var environment = await _browser.GetEnvironmentAsync(); + if (generation != _generation) + { + return; + } + + view = new WebView2CompositionControl(); + (_root.IsLoaded ? _viewHost : _parkingHost).Children.Add(view); + await view.EnsureCoreWebView2Async(environment); + if (generation != _generation) + { + return; + } + + var core = view.CoreWebView2; + var developer = _trust == PluginTrust.Developer; + core.Settings.AreDevToolsEnabled = developer; + core.Settings.AreDefaultContextMenusEnabled = developer; + core.Settings.AreBrowserAcceleratorKeysEnabled = developer; + core.Settings.AreHostObjectsAllowed = false; + core.Settings.IsPasswordAutosaveEnabled = false; + core.Settings.IsGeneralAutofillEnabled = false; + core.Settings.IsStatusBarEnabled = false; + // No alert, confirm or prompt: a plugin can't pose as FourFold. + core.Settings.AreDefaultScriptDialogsEnabled = false; + core.AddWebResourceRequestedFilter( + "*", CoreWebView2WebResourceContext.All, CoreWebView2WebResourceRequestSourceKinds.All); + core.WebResourceRequested += (_, args) => OnWebResourceRequested(environment, args); + core.NavigationStarting += (_, args) => args.Cancel = !IsOwnOrigin(args.Uri); + core.FrameNavigationStarting += (_, args) => args.Cancel = true; + core.NewWindowRequested += (_, args) => args.Handled = true; + core.DownloadStarting += (_, args) => args.Cancel = true; + core.PermissionRequested += (_, args) => args.State = CoreWebView2PermissionState.Deny; + core.BasicAuthenticationRequested += (_, args) => args.Cancel = true; + core.ClientCertificateRequested += (_, args) => + { + args.Cancel = true; + args.Handled = true; + }; + core.LaunchingExternalUriScheme += (_, args) => args.Cancel = true; + core.WebMessageReceived += OnWebMessageReceived; + core.ProcessFailed += (_, _) => ShowStopped(); + await core.AddScriptToExecuteOnDocumentCreatedAsync(PluginSdk.Build(Manifest)); + if (generation != _generation) + { + return; + } + + _view = view; + // The panel may have been shown or hidden while the view was starting. + MoveView(_root.IsLoaded ? _viewHost : _parkingHost); + _stoppedNotice.Visibility = Visibility.Collapsed; + core.Navigate(new Uri(PluginNetworkPolicy.Origin(Manifest.Id), Manifest.Panel.Replace('\\', '/')).AbsoluteUri); + started = true; + } + catch when (generation != _generation) + { + // Stopped while it was starting, so the failure no longer matters. + } + finally + { + if (_startingGeneration == generation) + { + _startingGeneration = -1; + } + + if (!started) + { + if (ReferenceEquals(_view, view)) + { + _view = null; + } + + Discard(view); + } + } + } + + public void Stop() + { + _generation++; + var view = _view; + _view = null; + Discard(view); + } + + public void PostEvent(string name, object? data) + { + try + { + _view?.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(new { @event = name, data }, Json)); + } + catch (Exception exception) when (exception is InvalidOperationException or ObjectDisposedException or COMException) + { + // The page went away between the check and the post. + } + } + + public void Dispose() + { + Stop(); + _http.Dispose(); + } + + private async Task RestartAsync() + { + Stop(); + try + { + await StartAsync(); + } + catch + { + ShowStopped(); + } + } + + private void ShowStopped() + { + Stop(); + _stoppedNotice.Visibility = Visibility.Visible; + } + + private static void Discard(WebView2CompositionControl? view) + { + if (view is null) + { + return; + } + + (view.Parent as Panel)?.Children.Remove(view); + view.Dispose(); + } + + private bool IsOwnOrigin(string value) => + Uri.TryCreate(value, UriKind.Absolute, out var uri) && PluginNetworkPolicy.IsOwnOrigin(uri, Manifest.Id); + + private void MoveView(Panel target) + { + if (_view is not { } view || ReferenceEquals(view.Parent, target)) + { + return; + } + + (view.Parent as Panel)?.Children.Remove(view); + target.Children.Add(view); + } + + // Serves the plugin's own files, with the content security policy on every response, and refuses any outside + // request the policy wouldn't allow. Anything unexpected is refused too, never let through. + private void OnWebResourceRequested(CoreWebView2Environment environment, CoreWebView2WebResourceRequestedEventArgs args) + { + try + { + if (!Uri.TryCreate(args.Request.Uri, UriKind.Absolute, out var uri)) + { + args.Response = Respond(environment, null, 403, "Blocked"); + return; + } + + // data: and blob: URLs never leave the page; the content security policy decides where they may be used. + if (uri.Scheme is "data" or "blob") + { + return; + } + + if (PluginNetworkPolicy.IsOwnOrigin(uri, Manifest.Id)) + { + args.Response = ServeFile(environment, args.Request.Method, uri); + return; + } + + var isScript = args.ResourceContext == CoreWebView2WebResourceContext.Script; + if (!PluginNetworkPolicy.IsAllowed(uri, Manifest, _trust, isScript)) + { + args.Response = Respond(environment, null, 403, "Blocked"); + } + } + catch (Exception) + { + args.Response = Respond(environment, null, 403, "Blocked"); + } + } + + private CoreWebView2WebResourceResponse ServeFile(CoreWebView2Environment environment, string method, Uri uri) + { + if (method == "GET" && PluginFileServer.TryResolve(Manifest, uri.AbsolutePath, out var path, out var type)) + { + try + { + return Respond(environment, new MemoryStream(File.ReadAllBytes(path)), 200, "OK", type); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Fall through to a 404: the file went away or is locked by an editor mid-save. + } + } + + return Respond(environment, null, 404, "Not Found"); + } + + // Every response FourFold creates carries the same policy headers, so none can be left without them. + private CoreWebView2WebResourceResponse Respond( + CoreWebView2Environment environment, Stream? content, int status, string reason, string? contentType = null) => + environment.CreateWebResourceResponse( + content, status, reason, + (contentType is null ? string.Empty : $"Content-Type: {contentType}\r\n") + + $"Content-Security-Policy: {_contentSecurityPolicy}\r\nX-Content-Type-Options: nosniff\r\n" + + "Cache-Control: no-store"); + + private async void OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs args) + { + try + { + if (!IsOwnOrigin(args.Source)) + { + return; + } + + var view = _view; + var reply = await _api.HandleAsync(args.WebMessageAsJson); + // A reply for a page that was stopped or reloaded while the call ran is dropped. + if (reply is not null && view is not null && ReferenceEquals(view, _view)) + { + view.CoreWebView2.PostWebMessageAsJson(reply); + } + } + catch (Exception) + { + // A plugin's message must never take the app down. + } + } +} From 600c11e7e9956a5eabc8886e8874ee54860b4016 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:12:48 -0500 Subject: [PATCH 16/49] fix: close the worker escape, bound plugin floods, and add the missing plugin view locks --- .../Plugins/PluginManifestReaderTests.cs | 2 + .../Plugins/PluginNetworkPolicyTests.cs | 8 +- .../Plugins/PluginManifestReader.cs | 10 ++ .../Plugins/PluginNetworkPolicy.cs | 2 +- .../Plugins/PluginApiTests.cs | 72 +++++++++++- .../Plugins/Web/PluginApi.cs | 65 ++++++++++- .../Plugins/Web/PluginSdk.cs | 13 ++- .../Plugins/Web/WebPlugin.cs | 105 ++++++++++++++++-- 8 files changed, 256 insertions(+), 21 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs index bfb85b0..69499c3 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -76,6 +76,8 @@ public void AValidManifestLoadsWithItsSitesAndCards() [InlineData("\"id\": \"cody..goal\"")] [InlineData("\"id\": \"timer\"")] [InlineData("\"id\": \"xn.foo\"")] + [InlineData("\"id\": \"nul.tools\"")] + [InlineData("\"id\": \"com1.tools\"")] [InlineData("\"id\": \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"")] [InlineData("\"apiVersion\": 2")] [InlineData("\"apiVersion\": \"1\"")] diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs index 1db74db..67d8a40 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs @@ -87,24 +87,24 @@ public void TheContentSecurityPolicyNamesOnlyDeclaredSitesAndNeverAllowsInlineSc { var policy = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(), PluginTrust.Developer); Assert.Equal( - "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://wiki.example.com https://api.example.com:8443; connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'", + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://wiki.example.com https://api.example.com:8443; connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'", policy); var anySite = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(anySite: true), PluginTrust.Verified); Assert.Equal( - "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https:; connect-src 'self' https: wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'", + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https:; connect-src 'self' https: wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'", anySite); var untrusted = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(anySite: true), PluginTrust.Standard); Assert.Equal( - "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://wiki.example.com https://api.example.com:8443; connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'", + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://wiki.example.com https://api.example.com:8443; connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'", untrusted); var noSites = new PluginManifest("cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, [], false, []); var nositespolicy = PluginNetworkPolicy.BuildContentSecurityPolicy(noSites, PluginTrust.Developer); Assert.Equal( - "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'", + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'", nositespolicy); } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index adacbdf..c9d013b 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -24,6 +24,11 @@ public static partial class PluginManifestReader [GeneratedRegex(@"^[0-9]+\.[0-9]+\.[0-9]+$")] 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 + // file "nul.tools.json" that silently swallows every write. + [GeneratedRegex("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$")] + private static partial Regex DeviceNameRegex(); + // Reads and validates /plugin.json. Every rejection carries a reason an author can act on. public static PluginManifestResult Read(string folder) { @@ -59,6 +64,11 @@ public static PluginManifestResult Read(string folder) return Reject("The id must look like author.plugin-name (lowercase letters, digits, dots and dashes)."); } + if (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)) { diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs index 4b7ee3d..8c53e73 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs @@ -135,7 +135,7 @@ public static string BuildContentSecurityPolicy(PluginManifest manifest, PluginT var connect = Prefix(connectHttps) + Prefix(wssSites); return "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; " + $"img-src 'self' data:{Prefix(images)}; connect-src 'self'{connect}; " + - "frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"; + "frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'"; static string Prefix(string value) => value.Length == 0 ? string.Empty : " " + value; } diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs index 9d757e1..2635dd4 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.IO; using System.Text.Json; using FourFoldAccountManager.Core.Models; @@ -125,9 +126,7 @@ public async Task HostileMessagesNeverThrow() """{"id":1,"method":5}""", """{"id":1,"method":"xp.get","params":[]}""", """{"id":1,"method":"cards.set","params":{"cardId":"goal","rows":"x"}}""", - """{"id":1,"method":"cards.set","params":{"cardId":"summary","rows":[5,null,{"progress":"x"}]}}""", - "{\"id\":1,\"method\":\"storage.set\",\"params\":{\"key\":\"k\",\"value\":\"" + - new string('x', PluginApi.MaximumMessageLength) + "\"}}" + """{"id":1,"method":"cards.set","params":{"cardId":"summary","rows":[5,null,{"progress":"x"}]}}""" }; foreach (var message in messages) @@ -144,6 +143,53 @@ public async Task HostileMessagesNeverThrow() document.RootElement.TryGetProperty("result", out _) || document.RootElement.TryGetProperty("error", out _), $"The reply to {message[..Math.Min(message.Length, 60)]} had neither a result nor an error."); } + + var tooLong = "{\"id\":1,\"method\":\"storage.set\",\"params\":{\"key\":\"k\",\"value\":\"" + + new string('x', PluginApi.MaximumMessageLength) + "\"}}"; + Assert.Null(await _api.HandleAsync(tooLong)); + } + + [Fact] + public void CallsBeyondTheInFlightLimitAreRefusedNotQueued() + { + // Resumed work waits in a queue until the test runs it, so the calls stay in flight the way a slow disk keeps + // them (the app resumes them on the UI thread one at a time). + var context = new QueuedContext(); + var previous = SynchronizationContext.Current; + SynchronizationContext.SetSynchronizationContext(context); + try + { + var calls = Enumerable.Range(1, 100) + .Select(id => _api.HandleAsync(JsonSerializer.Serialize( + new { id, method = "storage.set", @params = new { key = "k" + id, value = "v" } }))) + .ToList(); + context.RunUntil(Task.WhenAll(calls)); + + var codes = calls.Select(call => ErrorCode(JsonDocument.Parse(call.Result!).RootElement)).ToList(); + Assert.Contains("limit-exceeded", codes); + Assert.True(codes.Count(code => code is null) <= PluginApi.MaximumCallsInFlight); + } + finally + { + SynchronizationContext.SetSynchronizationContext(previous); + } + } + + [Fact] + public async Task StorageWritesAreRateLimited() + { + for (var write = 0; write < PluginApi.MaximumStorageWritesPerMinute; write++) + { + var reply = write % 2 == 0 + ? await Call("storage.set", new { key = "k", value = write }) + : await Call("storage.remove", new { key = "k" }); + Assert.Null(ErrorCode(reply)); + } + + Assert.Equal("limit-exceeded", ErrorCode(await Call("storage.set", new { key = "k", value = 0 }))); + + _clock.Advance(TimeSpan.FromSeconds(60)); + Assert.Null(ErrorCode(await Call("storage.set", new { key = "k", value = 1 }))); } private async Task Call(string method, object parameters) @@ -156,6 +202,26 @@ private async Task Call(string method, object parameters) private static string? ErrorCode(JsonElement reply) => reply.TryGetProperty("error", out var error) ? error.GetProperty("code").GetString() : null; + private sealed class QueuedContext : SynchronizationContext + { + private readonly BlockingCollection<(SendOrPostCallback Callback, object? State)> _queue = []; + + public override void Post(SendOrPostCallback callback, object? state) => _queue.Add((callback, state)); + + public void RunUntil(Task task) + { + var deadline = DateTime.UtcNow.AddSeconds(30); + while (!task.IsCompleted) + { + Assert.True(DateTime.UtcNow < deadline, "The calls never finished."); + if (_queue.TryTake(out var item, 50)) + { + item.Callback(item.State); + } + } + } + } + private sealed class FakeHost : IPluginHostData { public IReadOnlyList Accounts { get; set; } = []; diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs index 8200993..707e746 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs @@ -17,14 +17,24 @@ internal sealed class PluginApi( { public const int MaximumMessageLength = 512 * 1024; + // Calls still waiting on a reply (storage, a web request). Without a cap a plugin could queue thousands of + // half-megabyte writes and grow the app's memory without bound. + public const int MaximumCallsInFlight = 32; + + // Each write rewrites the plugin's whole storage file, so writes are limited, not just their size. + public const int MaximumStorageWritesPerMinute = 120; + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); private static readonly JsonElement EmptyObject = JsonDocument.Parse("{}").RootElement.Clone(); + private readonly Queue _storageWrites = new(); + private int _callsInFlight; private long? _lastOpened; // Returns the reply JSON, or null when the message can't be answered (too large, not JSON, or no id). public async Task HandleAsync(string messageJson) { JsonElement id = default; + var counted = false; try { if (messageJson.Length > MaximumMessageLength) @@ -41,6 +51,12 @@ internal sealed class PluginApi( } id = idElement.Clone(); + counted = true; + if (Interlocked.Increment(ref _callsInFlight) > MaximumCallsInFlight) + { + return Error(id, "limit-exceeded", "Too many requests at once."); + } + var method = root.TryGetProperty("method", out var methodElement) && methodElement.ValueKind == JsonValueKind.String ? methodElement.GetString() @@ -65,6 +81,13 @@ internal sealed class PluginApi( { return Error(id, "unavailable", "FourFold couldn't complete the request."); } + finally + { + if (counted) + { + Interlocked.Decrement(ref _callsInFlight); + } + } } private static string? Error(JsonElement id, string code, string message) => @@ -97,10 +120,14 @@ internal sealed class PluginApi( throw new PluginApiException("invalid-argument", "storage.set needs a value."); } - await storage.SetAsync(Text(parameters, "key"), value); + var setKey = Text(parameters, "key"); + TakeStorageWriteSlot(); + await storage.SetAsync(setKey, value); return null; case "storage.remove": - await storage.RemoveAsync(Text(parameters, "key")); + var removeKey = Text(parameters, "key"); + TakeStorageWriteSlot(); + await storage.RemoveAsync(removeKey); return null; case "cards.set": cards.Set(CardKey(parameters), CardContent(parameters)); @@ -120,6 +147,27 @@ internal sealed class PluginApi( } } + // A rolling minute on the same monotonic clock as openExternal. A refused call isn't recorded, so it doesn't count. + private void TakeStorageWriteSlot() + { + lock (_storageWrites) + { + var now = clock.GetTimestamp(); + while (_storageWrites.Count > 0 && + clock.GetElapsedTime(_storageWrites.Peek(), now) >= TimeSpan.FromSeconds(60)) + { + _storageWrites.Dequeue(); + } + + if (_storageWrites.Count >= MaximumStorageWritesPerMinute) + { + throw new PluginApiException("limit-exceeded", "A plugin can write to its storage 120 times a minute."); + } + + _storageWrites.Enqueue(now); + } + } + private static PluginApiException UnknownAccount() => new("invalid-argument", "That account id isn't known."); private static string Text(JsonElement parameters, string name) => @@ -183,8 +231,13 @@ private static PluginCardContent CardContent(JsonElement parameters) { foreach (var row in rowsElement.EnumerateArray()) { + if (row.ValueKind != JsonValueKind.Object) + { + throw new PluginApiException("invalid-argument", "Every row must be an object."); + } + double? progress = null; - if (row.ValueKind == JsonValueKind.Object && row.TryGetProperty("progress", out var progressElement) && + if (row.TryGetProperty("progress", out var progressElement) && progressElement.ValueKind != JsonValueKind.Null) { var number = progressElement.ValueKind == JsonValueKind.Number @@ -209,6 +262,12 @@ private static PluginCardContent CardContent(JsonElement parameters) "limit-exceeded", "A card takes a summary of up to 40 characters and up to 8 rows of up to 40 characters."); } + // A line break or other control character would let a card's text pose as a different row or hide its end. + if (summary.Any(char.IsControl) || rows.Any(row => row.Label.Any(char.IsControl) || row.Value.Any(char.IsControl))) + { + throw new PluginApiException("invalid-argument", "A card's text can't contain control characters."); + } + return new PluginCardContent(summary, rows); } diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs index 1e4f4cb..d166db1 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs @@ -48,8 +48,17 @@ internal static class PluginSdk document.documentElement.style.setProperty(name, value); } }; - if (document.documentElement) applyTheme(); - else document.addEventListener('DOMContentLoaded', applyTheme); + if (document.documentElement) { + applyTheme(); + } else { + // The page's doesn't exist yet when this runs; theme it the moment it does, before the first paint. + const observer = new MutationObserver(() => { + if (!document.documentElement) return; + observer.disconnect(); + applyTheme(); + }); + observer.observe(document, { childList: true }); + } window.fourfold = Object.freeze({ plugin: Object.freeze(info.plugin), theme: Object.freeze(info.theme), diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs index f16415a..5be9bc0 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs @@ -1,5 +1,4 @@ using System.IO; -using System.Runtime.InteropServices; using System.Text.Json; using System.Windows; using System.Windows.Controls; @@ -14,6 +13,15 @@ namespace FourFoldAccountManager.Desktop.Plugins.Web; // showing (its web view waits in a small invisible parking host), so its cards stay up to date. public sealed class WebPlugin : IFourFoldPlugin, IDisposable { + // A page can post messages or ask for files in a tight loop, faster than the UI thread can answer, which freezes + // the whole app (and again on every launch). More than this many events, or this much message text, within one + // second stops the plugin; its Reload button starts it fresh. + private const int MaximumEventsPerSecond = 2_000; + private const int MaximumMessageCharactersPerSecond = 8 * 1024 * 1024; + + // Serving a file reads it whole on the UI thread, so a larger one is treated as missing. + private const long MaximumFileBytes = 8 * 1024 * 1024; + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); private readonly PluginTrust _trust; @@ -33,6 +41,11 @@ public sealed class WebPlugin : IFourFoldPlugin, IDisposable private int _generation; private int _startingGeneration = -1; + // The current one-second window of the flood limits. + private long _windowStart; + private int _windowEvents; + private long _windowCharacters; + public WebPlugin( PluginManifest manifest, PluginTrust trust, @@ -118,7 +131,8 @@ public async Task StartAsync() return; } - view = new WebView2CompositionControl(); + // The panel's colour, so there is no white flash before the page's own background loads. + view = new WebView2CompositionControl { DefaultBackgroundColor = System.Drawing.Color.FromArgb(0x17, 0x1D, 0x24) }; (_root.IsLoaded ? _viewHost : _parkingHost).Children.Add(view); await view.EnsureCoreWebView2Async(environment); if (generation != _generation) @@ -130,7 +144,6 @@ public async Task StartAsync() var developer = _trust == PluginTrust.Developer; core.Settings.AreDevToolsEnabled = developer; core.Settings.AreDefaultContextMenusEnabled = developer; - core.Settings.AreBrowserAcceleratorKeysEnabled = developer; core.Settings.AreHostObjectsAllowed = false; core.Settings.IsPasswordAutosaveEnabled = false; core.Settings.IsGeneralAutofillEnabled = false; @@ -152,8 +165,27 @@ public async Task StartAsync() args.Handled = true; }; core.LaunchingExternalUriScheme += (_, args) => args.Cancel = true; + core.ScreenCaptureStarting += (_, args) => args.Cancel = true; + // Script dialogs are off, and an unanswered "leave this page?" prompt would make F5 do nothing, so a + // page can't use one to stop the user reloading it. The browser's own keys (F5 included) stay on. + core.ScriptDialogOpening += (_, args) => + { + if (args.Kind == CoreWebView2ScriptDialogKind.Beforeunload) + { + args.Accept(); + } + }; core.WebMessageReceived += OnWebMessageReceived; - core.ProcessFailed += (_, _) => ShowStopped(); + // The GPU and utility processes recover on their own and are shared with other plugins' pages. + core.ProcessFailed += (_, args) => + { + if (args.ProcessFailedKind is CoreWebView2ProcessFailedKind.BrowserProcessExited + or CoreWebView2ProcessFailedKind.RenderProcessExited + or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive) + { + ShowStopped(); + } + }; await core.AddScriptToExecuteOnDocumentCreatedAsync(PluginSdk.Build(Manifest)); if (generation != _generation) { @@ -161,6 +193,7 @@ public async Task StartAsync() } _view = view; + ResetFloodWindow(); // The panel may have been shown or hidden while the view was starting. MoveView(_root.IsLoaded ? _viewHost : _parkingHost); _stoppedNotice.Visibility = Visibility.Collapsed; @@ -204,9 +237,10 @@ public void PostEvent(string name, object? data) { _view?.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(new { @event = name, data }, Json)); } - catch (Exception exception) when (exception is InvalidOperationException or ObjectDisposedException or COMException) + catch (Exception) { - // The page went away between the check and the post. + // The page went away between the check and the post, or the data can't be written as JSON (a NaN, say). + // An event that can't be sent must never take the app down. } } @@ -246,6 +280,27 @@ private static void Discard(WebView2CompositionControl? view) view.Dispose(); } + // Counts one page event (a request, or a message of the given length) and says whether the page has now gone past + // a flood limit within the current second. + private bool IsFlooding(int messageCharacters = 0) + { + if (Environment.TickCount64 - _windowStart >= 1000) + { + ResetFloodWindow(); + } + + _windowEvents++; + _windowCharacters += messageCharacters; + return _windowEvents > MaximumEventsPerSecond || _windowCharacters > MaximumMessageCharactersPerSecond; + } + + private void ResetFloodWindow() + { + _windowStart = Environment.TickCount64; + _windowEvents = 0; + _windowCharacters = 0; + } + private bool IsOwnOrigin(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && PluginNetworkPolicy.IsOwnOrigin(uri, Manifest.Id); @@ -266,6 +321,23 @@ private void OnWebResourceRequested(CoreWebView2Environment environment, CoreWeb { try { + // Plugins get no workers. A service worker would answer the page's requests itself, out of reach of this + // handler, and worker requests are raised on every web view in the shared environment, so every plugin's + // handler refuses them. This comes before the flood count so another page's traffic never counts here. + if (args.RequestedSourceKind != CoreWebView2WebResourceRequestSourceKinds.Document || + args.Request.Headers.Contains("Service-Worker")) + { + args.Response = Respond(environment, null, 403, "Blocked"); + return; + } + + if (IsFlooding()) + { + args.Response = Respond(environment, null, 403, "Blocked"); + ShowStopped(); + return; + } + if (!Uri.TryCreate(args.Request.Uri, UriKind.Absolute, out var uri)) { args.Response = Respond(environment, null, 403, "Blocked"); @@ -302,7 +374,11 @@ private CoreWebView2WebResourceResponse ServeFile(CoreWebView2Environment enviro { try { - return Respond(environment, new MemoryStream(File.ReadAllBytes(path)), 200, "OK", type); + // A file over the limit falls through to the 404, the same as a missing one. + if (new FileInfo(path).Length <= MaximumFileBytes) + { + return Respond(environment, new MemoryStream(File.ReadAllBytes(path)), 200, "OK", type); + } } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { @@ -326,13 +402,26 @@ private async void OnWebMessageReceived(object? sender, CoreWebView2WebMessageRe { try { + // A late event from a view that was stopped must neither act nor be answered into a newer view. + if (!ReferenceEquals(sender, _view?.CoreWebView2)) + { + return; + } + + var message = args.WebMessageAsJson; + if (IsFlooding(message.Length)) + { + ShowStopped(); + return; + } + if (!IsOwnOrigin(args.Source)) { return; } var view = _view; - var reply = await _api.HandleAsync(args.WebMessageAsJson); + var reply = await _api.HandleAsync(message); // A reply for a page that was stopped or reloaded while the call ran is dropped. if (reply is not null && view is not null && ReferenceEquals(view, _view)) { From 26d29da7c650414a25b74a8aa34a23b768a2209c Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:17:59 -0500 Subject: [PATCH 17/49] fix: keep WebRTC out of plugin pages as far as the browser allows --- .../Plugins/Web/PluginSdk.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs index d166db1..9ed0023 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs @@ -8,6 +8,14 @@ internal static class PluginSdk { private const string Script = """ (() => { + // Best effort: the content security policy's webrtc 'block' is the intended lock, but this browser doesn't + // enforce it yet, and the hub review (part 3) rejects plugins that use WebRTC. + for (const name of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'RTCDataChannel', 'RTCSessionDescription', 'RTCIceCandidate']) { + try { + delete window[name]; + Object.defineProperty(window, name, { value: undefined, configurable: false, writable: false }); + } catch {} + } const info = __FOURFOLD_INFO__; const pending = new Map(); const listeners = new Map(); From d93f0e99f10de8f81cfe509c8883ae0b9a9ba734 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:35:17 -0500 Subject: [PATCH 18/49] fix: count every page request toward the flood stop, and budget the bytes a plugin is served --- .../Plugins/Web/PluginCardStore.cs | 7 ++++ .../Plugins/Web/WebPlugin.cs | 37 +++++++++++++++---- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginCardStore.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginCardStore.cs index f387dbd..d441eee 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginCardStore.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginCardStore.cs @@ -18,6 +18,13 @@ public sealed class PluginCardStore public void Set(OverlayCardKey key, PluginCardContent content) { + // Setting the same content again (a plugin repainting on a timer) isn't a change. + if (_cards.TryGetValue(key, out var current) && current.Summary == content.Summary && + current.Rows.SequenceEqual(content.Rows)) + { + return; + } + _cards[key] = content; Changed?.Invoke(); } diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs index 5be9bc0..987d0b2 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs @@ -19,8 +19,10 @@ public sealed class WebPlugin : IFourFoldPlugin, IDisposable private const int MaximumEventsPerSecond = 2_000; private const int MaximumMessageCharactersPerSecond = 8 * 1024 * 1024; - // Serving a file reads it whole on the UI thread, so a larger one is treated as missing. + // Serving a file reads it whole on the UI thread, so a larger one is treated as missing, and a page that asks for + // more than this much of its own files within one second is stopped like any other flood. private const long MaximumFileBytes = 8 * 1024 * 1024; + private const long MaximumServedBytesPerSecond = 32 * 1024 * 1024; private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); @@ -45,6 +47,7 @@ public sealed class WebPlugin : IFourFoldPlugin, IDisposable private long _windowStart; private int _windowEvents; private long _windowCharacters; + private long _windowServedBytes; public WebPlugin( PluginManifest manifest, @@ -152,7 +155,7 @@ public async Task StartAsync() core.Settings.AreDefaultScriptDialogsEnabled = false; core.AddWebResourceRequestedFilter( "*", CoreWebView2WebResourceContext.All, CoreWebView2WebResourceRequestSourceKinds.All); - core.WebResourceRequested += (_, args) => OnWebResourceRequested(environment, args); + core.WebResourceRequested += (sender, args) => OnWebResourceRequested(sender, environment, args); core.NavigationStarting += (_, args) => args.Cancel = !IsOwnOrigin(args.Uri); core.FrameNavigationStarting += (_, args) => args.Cancel = true; core.NewWindowRequested += (_, args) => args.Handled = true; @@ -177,9 +180,10 @@ public async Task StartAsync() }; core.WebMessageReceived += OnWebMessageReceived; // The GPU and utility processes recover on their own and are shared with other plugins' pages. - core.ProcessFailed += (_, args) => + core.ProcessFailed += (sender, args) => { - if (args.ProcessFailedKind is CoreWebView2ProcessFailedKind.BrowserProcessExited + if (ReferenceEquals(sender, _view?.CoreWebView2) && + args.ProcessFailedKind is CoreWebView2ProcessFailedKind.BrowserProcessExited or CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive) { @@ -299,6 +303,7 @@ private void ResetFloodWindow() _windowStart = Environment.TickCount64; _windowEvents = 0; _windowCharacters = 0; + _windowServedBytes = 0; } private bool IsOwnOrigin(string value) => @@ -317,15 +322,17 @@ private void MoveView(Panel target) // Serves the plugin's own files, with the content security policy on every response, and refuses any outside // request the policy wouldn't allow. Anything unexpected is refused too, never let through. - private void OnWebResourceRequested(CoreWebView2Environment environment, CoreWebView2WebResourceRequestedEventArgs args) + private void OnWebResourceRequested( + object? sender, CoreWebView2Environment environment, CoreWebView2WebResourceRequestedEventArgs args) { try { // Plugins get no workers. A service worker would answer the page's requests itself, out of reach of this // handler, and worker requests are raised on every web view in the shared environment, so every plugin's - // handler refuses them. This comes before the flood count so another page's traffic never counts here. + // handler refuses them. This comes before the flood count so another page's traffic never counts here; + // so does a late request from a view that was stopped. if (args.RequestedSourceKind != CoreWebView2WebResourceRequestSourceKinds.Document || - args.Request.Headers.Contains("Service-Worker")) + !ReferenceEquals(sender, _view?.CoreWebView2)) { args.Response = Respond(environment, null, 403, "Blocked"); return; @@ -338,6 +345,13 @@ private void OnWebResourceRequested(CoreWebView2Environment environment, CoreWeb return; } + // The page can put this header on its own requests, so it is refused after the flood count, not before. + if (args.Request.Headers.Contains("Service-Worker")) + { + args.Response = Respond(environment, null, 403, "Blocked"); + return; + } + if (!Uri.TryCreate(args.Request.Uri, UriKind.Absolute, out var uri)) { args.Response = Respond(environment, null, 403, "Blocked"); @@ -353,6 +367,11 @@ private void OnWebResourceRequested(CoreWebView2Environment environment, CoreWeb if (PluginNetworkPolicy.IsOwnOrigin(uri, Manifest.Id)) { args.Response = ServeFile(environment, args.Request.Method, uri); + if (_windowServedBytes > MaximumServedBytesPerSecond) + { + ShowStopped(); + } + return; } @@ -375,8 +394,10 @@ private CoreWebView2WebResourceResponse ServeFile(CoreWebView2Environment enviro try { // A file over the limit falls through to the 404, the same as a missing one. - if (new FileInfo(path).Length <= MaximumFileBytes) + var length = new FileInfo(path).Length; + if (length <= MaximumFileBytes) { + _windowServedBytes += length; return Respond(environment, new MemoryStream(File.ReadAllBytes(path)), 200, "OK", type); } } From 0a1d0b505413b317dfe4831e8fcf44efba36b3db Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:42:04 -0500 Subject: [PATCH 19/49] feat: load community plugins from the dev folder in developer mode --- .../MainWindow.CommunityPlugins.cs | 166 +++++++++++ .../MainWindow.xaml | 3 + .../MainWindow.xaml.cs | 11 +- .../Plugins/Web/CommunityPluginManager.cs | 279 ++++++++++++++++++ .../Services/TimerCoordinator.cs | 6 + .../Views/PluginSidebar.xaml.cs | 166 ++++++++++- 6 files changed, 626 insertions(+), 5 deletions(-) create mode 100644 src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs create mode 100644 src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs new file mode 100644 index 0000000..37cfd47 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs @@ -0,0 +1,166 @@ +using System.Diagnostics; +using System.IO; +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Timing; +using FourFoldAccountManager.Desktop.Plugins; +using FourFoldAccountManager.Desktop.Plugins.Web; + +namespace FourFoldAccountManager.Desktop; + +// Community plugins: loading, the data they may read, and the events they are sent. +public partial class MainWindow : IPluginHostData +{ + private readonly PluginCardStore _pluginCards = new(); + private readonly Dictionary _postedXpUpdates = []; + private CommunityPluginManager _communityPlugins = null!; + private string _postedAccounts = string.Empty; + + // Built-in plugins first, then community plugins: the one list the strip, the plugin list and the layout policy use. + private IReadOnlyList AllPlugins => [.. _plugins.All, .. _communityPlugins.Plugins]; + + private IReadOnlyList AllPluginDescriptors => + AllPlugins.Select(plugin => plugin.Descriptor).ToArray(); + + private void InitializeCommunityPlugins(LocalDataPaths paths) + { + _communityPlugins = new CommunityPluginManager(paths, this, PluginParkingHost, _pluginCards); + _communityPlugins.Changed += () => + { + RefreshPluginSidebar(); + RefreshTrackerRows(); + }; + _timer.StateChanged += () => _communityPlugins.PostEvent("timer.changed", null); + PluginSidebar.DeveloperModeChangeRequested += on => + _ = ApplyPluginChangeAsync( + settings => settings.PluginDeveloperMode == on ? settings : settings with { PluginDeveloperMode = on }, + refreshEffects: true); + PluginSidebar.PanelOpenRequested += () => + _ = ApplyPluginChangeAsync( + settings => settings.PluginsSidebarExpanded ? settings : settings with { PluginsSidebarExpanded = true }, + refreshEffects: false); + PluginSidebar.OpenDevFolderRequested += () => + { + try + { + Directory.CreateDirectory(paths.DevPluginsRoot); + Process.Start(new ProcessStartInfo(paths.DevPluginsRoot) { UseShellExecute = true }); + } + catch (Exception) + { + GlobalStatusText.Text = "The dev plugins folder couldn't be opened."; + } + }; + } + + private void RefreshPluginSidebar() + { + PluginSidebar.SetPlugins(AllPlugins); + PluginSidebar.SetCommunityState(_communityPlugins.Rejected, _communityPlugins.StartupError); + } + + // Tells running plugins what changed since the last refresh: the account list, and each account's XP read. + private void NotifyPluginsOfDataChanges() + { + var accounts = string.Join('|', _accounts.Select( + account => $"{account.Id}:{account.Label}:{_openAccountIds.Contains(account.Id)}")); + if (accounts != _postedAccounts) + { + _postedAccounts = accounts; + _communityPlugins.PostEvent("accounts.changed", null); + } + + foreach (var state in _xpTracker.GetStates()) + { + if (!_postedXpUpdates.TryGetValue(state.AccountId, out var posted) || posted != state.LastUpdated) + { + _postedXpUpdates[state.AccountId] = state.LastUpdated; + _communityPlugins.PostEvent("xp.updated", new { accountId = state.AccountId }); + } + } + } + + // A NaN or infinite number can't be written as JSON, so it goes to plugins as null. + private static double? Finite(double? value) => value is { } number && double.IsFinite(number) ? number : null; + + IReadOnlyList IPluginHostData.GetAccounts() => + _accounts.Select(account => new PluginAccountInfo( + account.Id, + account.Label, + // The public name from the profile page or the saved ranking name; never the saved login. + _xpTracker.GetLatestSnapshot(account.Id)?.Username ?? account.RankingUsername, + _openAccountIds.Contains(account.Id))).ToArray(); + + PluginXpInfo? IPluginHostData.GetXp(Guid accountId) + { + if (_accounts.All(account => account.Id != accountId)) + { + return null; + } + + var state = _xpTracker.GetStates().FirstOrDefault(candidate => candidate.AccountId == accountId); + var snapshot = _xpTracker.GetLatestSnapshot(accountId); + var active = snapshot?.ActiveClassName is { } className && snapshot.Classes.TryGetValue(className, out var found) + ? found + : null; + return new PluginXpInfo( + state?.ActiveClass ?? snapshot?.ActiveClassName, + active?.Level, + active?.CurrentXp, + active?.NextLevelXp, + state?.XpUntilNextLevel, + Finite(state?.HoursUntilNextLevel), + Finite(state?.RatePerHour), + state?.SessionGain ?? 0, + snapshot?.Classes + .Select(entry => new PluginClassInfo( + entry.Key, entry.Value.Level, entry.Value.CurrentXp, entry.Value.NextLevelXp)) + .ToArray() ?? [], + state?.LastUpdated, + state?.IsStale ?? true); + } + + PluginStatsInfo? IPluginHostData.GetStats(Guid accountId) + { + var snapshot = _xpTracker.GetLatestSnapshot(accountId); + return snapshot?.ActiveClassName is { } className && snapshot.Classes.TryGetValue(className, out var active) + ? new PluginStatsInfo(className, active.Level, active.Hp, active.Sp, active.Attack, active.Magic, + active.Skill, active.Speed, active.Luck, active.Defense, active.Resistance) + : null; + } + + PluginTimerInfo IPluginHostData.GetTimer() + { + var snapshot = _timer.Snapshot(); + return new PluginTimerInfo( + snapshot.State switch + { + SpeedrunTimerState.Running => "running", + SpeedrunTimerState.Finished => "finished", + _ => "ready" + }, + (long)snapshot.Total.TotalMilliseconds, + snapshot.Laps.Select(lap => new PluginLapInfo( + lap.Number, (long)lap.LapTime.TotalMilliseconds, (long)lap.SplitTotal.TotalMilliseconds)).ToArray()); + } + + bool IPluginHostData.IsPanelShowing(string pluginId) => PluginSidebar.IsShowing(pluginId); + + // The shell gets AbsoluteUri, never ToString(), which un-escapes %22 into a quote and could add an argument. + void IPluginHostData.OpenInBrowser(Uri uri) + { + if (uri.Scheme != Uri.UriSchemeHttps) + { + return; + } + + try + { + Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true }); + } + catch (Exception) + { + GlobalStatusText.Text = "The link couldn't be opened."; + } + } +} diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml b/src/FourFoldAccountManager.Desktop/MainWindow.xaml index 11ab3ab..e547d92 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml @@ -226,6 +226,9 @@ + + + + + + + + diff --git a/samples/sandbox-check/plugin.json b/samples/sandbox-check/plugin.json new file mode 100644 index 0000000..fb49081 --- /dev/null +++ b/samples/sandbox-check/plugin.json @@ -0,0 +1,11 @@ +{ + "id": "fourfold.sandbox-check", + "name": "Sandbox check", + "shortLabel": "Sandbox", + "version": "1.0.0", + "author": "FourFold", + "description": "Tries everything a plugin must not be able to do, and reports PASS or FAIL.", + "apiVersion": 1, + "panel": "index.html", + "sites": ["https://example.com"] +} From 07985ef6b038d9e5554e3d35bb8733cc741e1282 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:36:41 -0500 Subject: [PATCH 24/49] fix: keep plugin cards from disturbing the overlay panel, and tighten plugin names, hosts and message limits --- PLUGIN_AUTHORS.md | 16 +++++----- .../Plugins/PluginManifestReaderTests.cs | 7 +++++ .../Plugins/PluginManifestReader.cs | 24 ++++++++++++--- .../Plugins/PluginApiTests.cs | 3 +- .../MainWindow.CommunityPlugins.cs | 13 ++++++++- .../MainWindow.xaml.cs | 26 ++++++++++++++--- .../Plugins/Web/CommunityPluginManager.cs | 12 +++++++- .../Plugins/Web/PluginSdk.cs | 8 ++++- .../Plugins/Web/WebPlugin.cs | 29 +++++++++++++++---- .../Resources/OverlayCardTemplates.xaml | 1 + .../Views/FullscreenOverlayTray.xaml | 2 +- .../Views/FullscreenOverlayTray.xaml.cs | 27 ++++++++++++++--- .../Views/OverlayCardLayer.cs | 7 ++++- 13 files changed, 144 insertions(+), 31 deletions(-) diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md index e6ab9c4..68018dd 100644 --- a/PLUGIN_AUTHORS.md +++ b/PLUGIN_AUTHORS.md @@ -52,11 +52,11 @@ Dev plugins are not reviewed, and FourFold honors their `plugin.json` as written } ``` -A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, and the plugin list shows the reason. Text values are trimmed. Fields not listed here are ignored. The file can be at most 64 KB, and it is never served to your page. +A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, and the plugin list shows the reason. Text values are trimmed. The `name`, `shortLabel`, `author` and `description` fields, and a card's `name`, can't contain control characters (a line break or a bell character, say), because FourFold shows them. Fields not listed here are ignored. The file can be at most 64 KB, and it is never served to your page. | Field | Required | Rule | |---|---|---| -| `id` | yes | `author.plugin-name`. Lowercase letters and digits, with single dashes allowed between them, in parts joined by dots. At least one dot, at most 64 characters. The first part can't be a Windows device name (`con`, `prn`, `aux`, `nul`, `com0` to `com9`, `lpt0` to `lpt9`). With each dot written as `--`, the id can be at most 63 characters. Two plugins can't share an id. | +| `id` | yes | `author.plugin-name`. Lowercase letters and digits, with single dashes allowed between them, in parts joined by dots. At least one dot, at most 64 characters. The first part can't be a Windows device name (`con`, `prn`, `aux`, `nul`, `com0` to `com9`, `lpt0` to `lpt9`), and an id can't begin with the label `xn` (`xn.tools` is rejected). With each dot written as `--`, the id can be at most 63 characters. Two plugins can't share an id. | | `name` | yes | 1 to 40 characters. | | `shortLabel` | yes | 1 to 8 characters, shown on the strip. | | `version` | yes | `MAJOR.MINOR.PATCH`, digits only, such as `1.0.0`. | @@ -65,7 +65,7 @@ A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, | `apiVersion` | yes | A whole number. FourFold supports `1`. A higher number is rejected with "Update FourFold to use this plugin." | | `panel` | yes | Path to an existing `.html` file inside the plugin folder. Forward slashes only. | | `icon` | no | Path to a `.png` inside the plugin folder, at most 64 KB. Forward slashes only. Without one, the strip shows a default icon. | -| `sites` | no | At most 10 websites the plugin may contact. Each is an origin: `https://host` or `https://host:port`, with no path, query or `user@`. The host must be a DNS name: no IP address, no `localhost` or `.localhost` name, no trailing dot. A subdomain is its own site, so `https://example.com` doesn't cover `https://www.example.com`. | +| `sites` | no | At most 10 websites the plugin may contact. Each is an origin: `https://host` or `https://host:port`, with no path, query or `user@`. The host must be a DNS name: no IP address, no trailing dot, and no name that only works on the local network. `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names are refused, and so is a single-label name such as `router`. A subdomain is its own site, so `https://example.com` doesn't cover `https://www.example.com`. | | `anySite` | no | `true` lets the plugin contact any `https` site. Default `false`. FourFold honors it for plugins in the dev folder. | | `cards` | no | At most 6 overlay cards. See [Cards](#cards). | @@ -189,7 +189,7 @@ button.addEventListener('click', () => { `fourfold.openExternal(url)` opens an `https` link in the user's default browser. -- The URL must be `https`, with no `user@`, and not `localhost`, a `.localhost` name or a local network address (`invalid-argument`). +- The URL must be `https`, with no `user@`, and not `localhost`, a `.localhost`, `.local`, `.internal`, `.lan` or `.home.arpa` name, a single-label name such as `router`, or a local network address (`invalid-argument`). - It works only while the plugin's panel is showing, and only in response to a click (`unavailable`). - At most one link every 2 seconds (`limit-exceeded`). @@ -258,7 +258,7 @@ body { background: var(--ff-surface); color: var(--ff-text); } | What | Limit | |---|---| -| One message from your page to FourFold | 512 KB. A larger message gets no reply, so its promise never settles. | +| One message from your page to FourFold | 512 KB. A larger one isn't sent: the call is rejected with `limit-exceeded`. | | Calls waiting for an answer at once | 32. More are rejected with `limit-exceeded`. | | `http.fetch` | 60 requests a minute, 5 redirects, 15 seconds, 2 MB response. | | Storage | 256 KB in all, 120 writes a minute, keys up to 64 characters. | @@ -310,7 +310,7 @@ What that means for you: ### The local network -No page request and no `http.fetch` can reach the user's own network. That covers `localhost`, `.localhost` names, and addresses in `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`, `100.64.0.0/10`, `::1`, `fc00::/7` and `fe80::/10`, in any spelling. Page requests are checked by host name or address. `http.fetch` also checks every address a host name resolves to. +No page request and no `http.fetch` can reach the user's own network. That covers `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names, single-label names such as `router`, and addresses in `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`, `100.64.0.0/10`, `::1`, `fc00::/7` and `fe80::/10`, in any spelling. Page requests are checked by host name or address. `http.fetch` also checks every address a host name resolves to. ### The browser around your page @@ -325,7 +325,7 @@ No page request and no `http.fetch` can reach the user's own network. That cover FourFold stops a plugin that: - sends more than 2,000 requests or messages in one second (every request the page makes counts, including for its own files); -- sends more than 8 MB of messages in one second; +- sends more than 8 MB of messages in one second, counting FourFold's replies too (a loop of `storage.get` calls on a big value can reach it); - loads more than 32 MB of its own files in one second; - crashes, or stops responding. @@ -362,6 +362,8 @@ Text with control characters (line breaks, for example) fails with `invalid-argu - The card shows the account's label (for an `account` card), the card's `name` as its title, then your rows: label on the left, value on the right, and a thin bar under each row that has `progress`. - A card with no rows shows "No data yet". - The `summary` is not drawn on the card. The Overlays panel shows it beside the card's switch. Before your first `set`, the Overlays panel shows "No data yet" there. +- The Overlays panel and the floating checklist list a card as "Card name (plugin short label)", for example "Goal (Goals)", so users can tell your card from another plugin's, and from FourFold's own. The card itself shows only the name. +- A value too long for its row, and a summary too long for the Overlays panel, are trimmed with an ellipsis. - FourFold redraws cards at most four times a second. Setting the same content again changes nothing. **How users switch cards on:** a declared card is offered wherever FourFold's own cards are. The Overlays panel has one switch per open account for an `account` card and one switch for a `global` card. The card can then be dragged and resized over the game, or shown in its own floating window when Floating cards mode is on. It starts at 220 by 120 and can shrink to 150 by 44. diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs index 4e877c8..79ad0db 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -95,6 +95,13 @@ public void AValidManifestLoadsWithItsSitesAndCards() [InlineData("\"sites\": [\"https://127.0.0.1.\"]")] [InlineData("\"sites\": [\"https://app.localhost.\"]")] [InlineData("\"sites\": [\"https://x.fourfoldplugin\"]")] + [InlineData("\"sites\": [\"https://printer.local\"]")] + [InlineData("\"sites\": [\"https://nas.lan\"]")] + [InlineData("\"sites\": [\"https://router\"]")] + // The JSON escape \u0007 (a bell character) is what the file holds, so it is the reader's control-character rule + // that rejects these, not the JSON parser. + [InlineData("\"name\": \"Goal\\u0007tracker\"")] + [InlineData("\"cards\": [{ \"id\": \"goal\", \"name\": \"Go\\u0007al\", \"scope\": \"account\" }]")] // A zero-width joiner in a host makes Uri.IdnHost throw rather than return a name. [InlineData("\"sites\": [\"https://a\u200Db.example\"]")] [InlineData("\"cards\": [{ \"id\": \"Goal\", \"name\": \"Goal\", \"scope\": \"account\" }]")] diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index 8db7ac0..e4a765b 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -123,6 +123,11 @@ private static PluginManifestResult ReadManifest(string folder) return Reject("The description must be at most 200 characters."); } + if (HasControlCharacter(name, shortLabel, author, description)) + { + return Reject("The name, shortLabel, author and description can't contain control characters."); + } + if (!root.TryGetProperty("apiVersion", out var apiElement) || apiElement.ValueKind != JsonValueKind.Number || !apiElement.TryGetInt32(out var apiVersion) || apiVersion < 1) { @@ -187,10 +192,14 @@ private static bool InRange(string? value, int minimum, int maximum, out string return result.Length >= minimum && result.Length <= maximum; } + // The text a manifest supplies is drawn in the app (the plugin list, the Overlays panel), so a line break or a bell + // character in it is never wanted. + private static bool HasControlCharacter(params string[] values) => values.Any(value => value.Any(char.IsControl)); + private 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 localhost."; + error = "Each site must look like https://example.com, with no path, and can't be an IP address or a local network name."; if (!root.TryGetProperty("sites", out var element) || element.ValueKind == JsonValueKind.Null) { return true; @@ -236,7 +245,7 @@ private static bool IsIpLikeHost(string host) private static bool TryReadCards(JsonElement root, out IReadOnlyList cards, out string error) { cards = []; - error = "Each card needs an id (lowercase letters, digits, dashes), a name (1 to 24 characters) and a scope of account or global."; + error = "Each card needs an id (lowercase letters, digits, dashes), a name (1 to 24 characters, no control characters) and a scope of account or global."; if (!root.TryGetProperty("cards", out var element) || element.ValueKind == JsonValueKind.Null) { return true; @@ -258,7 +267,7 @@ private static bool TryReadCards(JsonElement root, out IReadOnlyList 32 || !CardIdRegex().IsMatch(id) || - !InRange(Text(item, "name"), 1, 24, out var name) || + !InRange(Text(item, "name"), 1, 24, out var name) || HasControlCharacter(name) || scope is not ("account" or "global") || result.Any(card => card.Id == id)) { return false; @@ -282,10 +291,17 @@ scope is not ("account" or "global") || result.Any(card => card.Id == id)) // Host-name checks shared by the manifest reader and the network policy. public static class PluginNetworkHosts { + // Names that only mean something on the user's own network: localhost, mDNS (.local), common intranet endings, and + // a single-label name such as "router". An IPv6 literal has colons and no dots, so it isn't a single-label name. public static bool IsLocalName(string host) { var trimmed = host.TrimEnd('.'); return trimmed.Equals("localhost", StringComparison.OrdinalIgnoreCase) || - trimmed.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase); + trimmed.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".local", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".internal", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".lan", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".home.arpa", StringComparison.OrdinalIgnoreCase) || + (trimmed.Length > 0 && !trimmed.Contains('.') && !trimmed.Contains(':')); } } diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs index 2635dd4..7a9db5b 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs @@ -52,7 +52,8 @@ public async Task OpenExternalOnlyOpensPublicHttpsLinks() foreach (var url in new[] { "file:///C:/Windows/System32/calc.exe", "javascript:alert(1)", "http://example.com/", - "https://localhost/", "https://192.168.1.1/", "https://user@example.com/", "ms-settings:", + "https://localhost/", "https://192.168.1.1/", "https://printer.local/", + "https://user@example.com/", "ms-settings:", "not a url" }) { diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs index eec3b17..7f4668a 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using System.IO; +using System.Windows.Input; using FourFoldAccountManager.Core.Data; using FourFoldAccountManager.Core.Models; using FourFoldAccountManager.Core.Overlay; @@ -81,6 +82,13 @@ private void QueuePluginCardRefresh() }; _pluginCardRefreshTimer.Tick += (_, _) => { + // A click that straddles a rebuild of the switches is lost, so wait for the button to come up; the + // timer keeps running and tries again 250 ms later. + if (Mouse.LeftButton == MouseButtonState.Pressed || Mouse.RightButton == MouseButtonState.Pressed) + { + return; + } + _pluginCardRefreshTimer.Stop(); RefreshTrackerRows(); }; @@ -115,8 +123,11 @@ private void AddPluginCards( IsStale: !plugin.IsRunning, content?.Rows.Select(row => new PluginCardRowData(row.Label, row.Value, row.Progress)).ToArray() ?? [], content?.Summary ?? "No data yet"); + // The short label says whose card it is: two plugins can both declare "Goals", and a card named "Timer" + // must not pass for FourFold's own in the Overlays panel and the floating checklist. AddOverlayCard( - new OverlayAddOnDefinition(OverlayAddOnKind.Plugin, scope, card.Name, 220, 120, 150, 44), + new OverlayAddOnDefinition( + OverlayAddOnKind.Plugin, scope, $"{card.Name} ({plugin.Descriptor.ShortLabel})", 220, 120, 150, 44), key, accountLabel, data, showOverGame, switches, build); } } diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs index 697efce..e90e3cc 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs @@ -1595,7 +1595,7 @@ private void RefreshTrackerRows() var states = _xpTracker.GetStates().ToDictionary(state => state.AccountId); var accountRows = new List(); var editing = OverlaysShown && _overlayEditing; - _xpTrackerRows.Clear(); + var trackerRows = new List(); // Every card over the game sits on the one window-wide layer, so it can go anywhere in the window. var build = new OverlayCardBuild(); @@ -1626,7 +1626,7 @@ private void RefreshTrackerRows() if (states.TryGetValue(trackedAccountId, out var state)) { trackerRow = XpTrackerRow.FromState(slot.SlotIndex + 1, label, state); - _xpTrackerRows.Add(trackerRow); + trackerRows.Add(trackerRow); } if (account is not null) @@ -1649,12 +1649,30 @@ private void RefreshTrackerRows() } } - GlobalOverlayLayer.SetCards(build.GameCards, editing); + // Rows that show what the XP tracker already shows are left alone, so a refresh doesn't rebuild them under the + // mouse (a plugin's card can cause four a second). + if (!_xpTrackerRows.SequenceEqual(trackerRows)) + { + _xpTrackerRows.Clear(); + foreach (var row in trackerRows) + { + _xpTrackerRows.Add(row); + } + } + + // Plugin cards go after every built-in card, so a plugin never moves where a built-in card that was never + // dragged first appears (its cascade spot, or its new floating window's). + var gameCards = build.GameCards + .OrderBy(card => card.Key.Kind == OverlayAddOnKind.Plugin) + .Select((card, index) => card with { CascadeIndex = index }) + .ToList(); + var floatingCards = build.FloatingCards.OrderBy(card => card.Key.Kind == OverlayAddOnKind.Plugin).ToList(); + GlobalOverlayLayer.SetCards(gameCards, editing); _floatingChecklist = build.Checklist; // Floating windows exist only in Floating cards mode, and never during shutdown, when they are closed. _floatingCards.Update( _panelSettings.SecondMonitorMode == SecondMonitorMode.FloatingCards && !_shutdownStarted - ? build.FloatingCards + ? floatingCards : [], _arrangingFloatingCards); FullscreenOverlayTray.SetRows(globalSwitches, accountRows); diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs index 34ee0b2..a6cc09f 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs @@ -166,7 +166,17 @@ changedFolders is not null && continue; } - kept.Add(new WebPlugin(manifest, PluginTrust.Developer, _browser, _parkingHost, _host, _cards, _paths)); + var webPlugin = new WebPlugin(manifest, PluginTrust.Developer, _browser, _parkingHost, _host, _cards, _paths); + // 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(); diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs index 9ed0023..9c06ed6 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs @@ -22,8 +22,14 @@ internal static class PluginSdk let nextId = 1; const call = (method, params) => new Promise((resolve, reject) => { const id = nextId++; + const message = { id, method, params: params ?? {} }; + // FourFold drops a message this long without a reply, which would leave the promise waiting for ever. + if (JSON.stringify(message).length > 512 * 1024) { + reject(Object.assign(new Error('The message is too large.'), { code: 'limit-exceeded' })); + return; + } pending.set(id, { resolve, reject }); - window.chrome.webview.postMessage({ id, method, params: params ?? {} }); + window.chrome.webview.postMessage(message); }); window.chrome.webview.addEventListener('message', event => { const message = event.data; diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs index 65c7680..f8acccf 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs @@ -14,8 +14,9 @@ namespace FourFoldAccountManager.Desktop.Plugins.Web; public sealed class WebPlugin : IFourFoldPlugin, IDisposable { // A page can post messages or ask for files in a tight loop, faster than the UI thread can answer, which freezes - // the whole app (and again on every launch). More than this many events, or this much message text, within one - // second stops the plugin; its Reload button starts it fresh. + // the whole app (and again on every launch). More than this many events, or this much message and reply text, + // within one second stops the plugin; its Reload button starts it fresh. Replies count too: a loop of reads that + // each return a big stored value saturates the UI thread well before the event limit. private const int MaximumEventsPerSecond = 2_000; private const int MaximumMessageCharactersPerSecond = 8 * 1024 * 1024; @@ -115,6 +116,10 @@ public WebPlugin( public bool IsRunning => _view is not null; + // Raised when the plugin stops (a flood, a crash, Reload, being switched off) and when it has started. The manager + // forwards it, so the cards' stale dimming follows IsRunning. + public event Action? RunningChanged; + public void Opened() { } @@ -206,6 +211,7 @@ or CoreWebView2ProcessFailedKind.RenderProcessExited _stoppedNotice.Visibility = Visibility.Collapsed; core.Navigate(new Uri(PluginNetworkPolicy.Origin(Manifest.Id), Manifest.Panel.Replace('\\', '/')).AbsoluteUri); started = true; + RunningChanged?.Invoke(); } catch when (generation != _generation) { @@ -242,6 +248,10 @@ public void Stop() var view = _view; _view = null; Discard(view); + if (view is not null) + { + RunningChanged?.Invoke(); + } } public void PostEvent(string name, object? data) @@ -294,16 +304,16 @@ private static void Discard(WebView2CompositionControl? view) view.Dispose(); } - // Counts one page event (a request, or a message of the given length) and says whether the page has now gone past - // a flood limit within the current second. - private bool IsFlooding(int messageCharacters = 0) + // Counts page events (a request or message by default) and message or reply characters, and says whether the page + // has now gone past a flood limit within the current second. + private bool IsFlooding(int messageCharacters = 0, int events = 1) { if (Environment.TickCount64 - _windowStart >= 1000) { ResetFloodWindow(); } - _windowEvents++; + _windowEvents += events; _windowCharacters += messageCharacters; return _windowEvents > MaximumEventsPerSecond || _windowCharacters > MaximumMessageCharactersPerSecond; } @@ -456,6 +466,13 @@ private async void OnWebMessageReceived(object? sender, CoreWebView2WebMessageRe // A reply for a page that was stopped or reloaded while the call ran is dropped. if (reply is not null && view is not null && ReferenceEquals(view, _view)) { + // The reply's text is counted, but it is not a second event. + if (IsFlooding(reply.Length, events: 0)) + { + ShowStopped(); + return; + } + view.CoreWebView2.PostWebMessageAsJson(reply); } } diff --git a/src/FourFoldAccountManager.Desktop/Resources/OverlayCardTemplates.xaml b/src/FourFoldAccountManager.Desktop/Resources/OverlayCardTemplates.xaml index baf08f8..096dfb1 100644 --- a/src/FourFoldAccountManager.Desktop/Resources/OverlayCardTemplates.xaml +++ b/src/FourFoldAccountManager.Desktop/Resources/OverlayCardTemplates.xaml @@ -112,6 +112,7 @@ Foreground="{DynamicResource Brush.TextMuted}" /> + VerticalAlignment="Center" TextTrimming="CharacterEllipsis" MaxWidth="120" /> diff --git a/src/FourFoldAccountManager.Desktop/Views/FullscreenOverlayTray.xaml.cs b/src/FourFoldAccountManager.Desktop/Views/FullscreenOverlayTray.xaml.cs index b2e9b77..cc41a1e 100644 --- a/src/FourFoldAccountManager.Desktop/Views/FullscreenOverlayTray.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/Views/FullscreenOverlayTray.xaml.cs @@ -30,6 +30,9 @@ public partial class FullscreenOverlayTray : UserControl private bool _isFullScreen; private bool _isEditing; private bool _ignoreEdgeTabMouseEnterUntilLeave; + private bool _switchClicked; + private OverlayTraySwitch[] _globalSwitches = []; + private OverlayTrayAccountRow[] _accountRows = []; public FullscreenOverlayTray() { @@ -44,14 +47,29 @@ public FullscreenOverlayTray() public event EventHandler? SecondMonitorRequested; - // Rows are rebuilt from saved settings after every toggle, so a failed save shows the persisted state. + // Rows are rebuilt from saved settings after every toggle, so a failed save shows the persisted state. Rows that + // show what the tray already shows are left alone, so a click that lands during a refresh isn't lost to a rebuild; + // after a click on a switch the next rows are always applied, since the box may no longer match them. public void SetRows(IReadOnlyList globalSwitches, IReadOnlyList accountRows) { ArgumentNullException.ThrowIfNull(globalSwitches); ArgumentNullException.ThrowIfNull(accountRows); - GlobalSwitchesControl.ItemsSource = globalSwitches.ToArray(); - GlobalSection.Visibility = globalSwitches.Count > 0 ? Visibility.Visible : Visibility.Collapsed; - AccountRowsControl.ItemsSource = accountRows.ToArray(); + var globals = globalSwitches.ToArray(); + var accounts = accountRows.ToArray(); + if (!_switchClicked && globals.SequenceEqual(_globalSwitches) && accounts.Length == _accountRows.Length && + accounts.Zip(_accountRows, (next, shown) => + next.AccountId == shown.AccountId && next.AccountLabel == shown.AccountLabel && + next.Switches.SequenceEqual(shown.Switches)).All(same => same)) + { + return; + } + + _switchClicked = false; + _globalSwitches = globals; + _accountRows = accounts; + GlobalSwitchesControl.ItemsSource = globals; + GlobalSection.Visibility = globals.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + AccountRowsControl.ItemsSource = accounts; } public void SetFullscreen(bool isFullScreen) @@ -102,6 +120,7 @@ private void Switch_Click(object sender, RoutedEventArgs args) { if (sender is CheckBox { DataContext: OverlayTraySwitch item } checkBox) { + _switchClicked = true; RequestToggle(item.Key, checkBox.IsChecked == true); } } diff --git a/src/FourFoldAccountManager.Desktop/Views/OverlayCardLayer.cs b/src/FourFoldAccountManager.Desktop/Views/OverlayCardLayer.cs index eaf6418..a0b620a 100644 --- a/src/FourFoldAccountManager.Desktop/Views/OverlayCardLayer.cs +++ b/src/FourFoldAccountManager.Desktop/Views/OverlayCardLayer.cs @@ -63,7 +63,12 @@ public void SetCards(IReadOnlyList cards, bool editing) entry!.Model = model; entry.Frame.CardData = model.Data; entry.Frame.IsEditing = editing; - Panel.SetZIndex(entry.Frame, OverlayAddOnCatalog.IndexOf(model.Key.Kind)); + // A refresh in the middle of a drag must not drop the dragged card behind its neighbours. + if (Panel.GetZIndex(entry.Frame) != DraggingZIndex) + { + Panel.SetZIndex(entry.Frame, OverlayAddOnCatalog.IndexOf(model.Key.Kind)); + } + if (boundsChanged) { ApplyBounds(entry); From 9aa1e288affb9326bf74ecca456ee9b17bdcab29 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:53:03 -0500 Subject: [PATCH 25/49] docs: correct the plugin guide and samples against the code, and send a default User-Agent --- PLUGIN_AUTHORS.md | 51 +++++++++++-------- samples/goal-tracker/app.js | 16 +++++- samples/sandbox-check/check.js | 12 +++-- samples/sandbox-check/index.html | 1 + .../Plugins/PluginHttpFetcherTests.cs | 19 +++++++ .../Plugins/PluginHttpFetcher.cs | 9 ++++ .../MainWindow.CommunityPlugins.cs | 3 +- .../Plugins/Web/PluginApi.cs | 3 +- .../Plugins/Web/WebPlugin.cs | 33 ++++++++---- .../Views/FullscreenOverlayTray.xaml | 2 +- 10 files changed, 109 insertions(+), 40 deletions(-) diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md index 68018dd..2e3dafb 100644 --- a/PLUGIN_AUTHORS.md +++ b/PLUGIN_AUTHORS.md @@ -13,21 +13,27 @@ The page runs in its own sandboxed browser. It talks to FourFold only through `w - a small private store; - overlay cards, drawn by FourFold. -The page keeps running while its panel is closed, so its cards stay up to date. It stops when the user switches the plugin off or closes FourFold. +The page keeps running while its panel is closed, so its cards stay up to date. It stops when the user switches the plugin off or closes FourFold. It runs whenever the plugin is switched on: when FourFold starts, on **Reload**, and on every file save in the dev folder. Keep start-up work light. + +The panel is narrow: about 250 px wide in the main window, and as wide as the window allows in the pop-out tools window. Design a single narrow column. ## Quick start 1. Open the plugin list (the wrench in the plugin strip). 2. Switch on **Developer mode**, at the bottom of the list. 3. Press **Open dev plugins folder**. It is `%LOCALAPPDATA%\FourFoldAccountManager\dev-plugins`. -4. Copy the `samples/goal-tracker` folder into it, so that `plugin.json` sits at `dev-plugins\goal-tracker\plugin.json`. +4. Copy the `samples/goal-tracker` folder into it, so that `plugin.json` sits at `dev-plugins\goal-tracker\plugin.json`. The [`samples`](samples) folder is in the GitHub repository, not in the release download. 5. The plugin appears in the strip and the plugin list with a **DEV** badge. +When you build on a copy of a sample, change its `id` and `author` in `plugin.json` first. + +The other sample, `samples/sandbox-check`, contacts example.com each time it runs. See [Check your own plugin](#check-your-own-plugin). + Every folder directly inside `dev-plugins` is one plugin. - **Saving a file** in a plugin's folder reloads the plugin within about a second. A changed `plugin.json` is read again, including its cards and sites. - **A rejected `plugin.json`** still gets a row in the plugin list, with the folder name and the reason. Fix the file and it loads. -- **Right-click, Inspect** opens the browser developer tools. This works for plugins in the dev folder only. Blocked requests and rejected calls show up in the console. +- **Right-click, Inspect** opens the browser developer tools. This works for plugins in the dev folder only. Blocked requests show up in the console, and so does a rejected call that your code doesn't catch. - **F5** reloads the plugin's page. - **Developer mode off** stops every dev plugin and removes it from the strip. Order and on/off state are kept. @@ -64,18 +70,18 @@ A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, | `description` | no | At most 200 characters. | | `apiVersion` | yes | A whole number. FourFold supports `1`. A higher number is rejected with "Update FourFold to use this plugin." | | `panel` | yes | Path to an existing `.html` file inside the plugin folder. Forward slashes only. | -| `icon` | no | Path to a `.png` inside the plugin folder, at most 64 KB. Forward slashes only. Without one, the strip shows a default icon. | +| `icon` | no | Path to a `.png` inside the plugin folder, at most 64 KB. Forward slashes only. Without one, the strip shows just the `shortLabel`. | | `sites` | no | At most 10 websites the plugin may contact. Each is an origin: `https://host` or `https://host:port`, with no path, query or `user@`. The host must be a DNS name: no IP address, no trailing dot, and no name that only works on the local network. `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names are refused, and so is a single-label name such as `router`. A subdomain is its own site, so `https://example.com` doesn't cover `https://www.example.com`. | | `anySite` | no | `true` lets the plugin contact any `https` site. Default `false`. FourFold honors it for plugins in the dev folder. | | `cards` | no | At most 6 overlay cards. See [Cards](#cards). | Each entry in `cards`: -| Field | Rule | -|---|---| -| `id` | Lowercase letters and digits, with single dashes allowed between them. 1 to 32 characters. Unique in the plugin. | -| `name` | 1 to 24 characters. It is the card's title. | -| `scope` | `account` (one card per open account) or `global` (one card). | +| Field | Required | Rule | +|---|---|---| +| `id` | yes | Lowercase letters and digits, with single dashes allowed between them. 1 to 32 characters. Unique in the plugin. | +| `name` | yes | 1 to 24 characters. It is the card's title. | +| `scope` | yes | `account` (one card per open account) or `global` (one card). | ## The API @@ -85,6 +91,7 @@ Each entry in `cards`: - An `on...` call takes a callback and returns a function that stops the callback. - A call that is refused rejects with an `Error`. Its `code` property is one of the [error codes](#error-codes) and its `message` says which rule was broken. - A rejected call never stops your plugin. +- Events can arrive in bursts (`xp.onUpdated` fires once per account), so a handler can start while the last run is still waiting for answers. Run redraws one after another, as the `queue` in `samples/goal-tracker/app.js` does. ### Accounts @@ -129,9 +136,9 @@ fourfold.xp.onUpdated(({ accountId }) => console.log('new XP data for', accountI | `sessionXp` | number | XP gained this session. `0` when unknown. | | `classes` | array | `{ className, level, currentXp, nextLevelXp }` for every class. May be empty. | | `updatedAt` | string or null | Time of the last successful read, as an ISO 8601 date. | -| `isStale` | boolean | `true` when the last read failed, or there is no data. | +| `isStale` | boolean | `true` when there is no XP data yet, when the last read failed, and for a closed account. | -FourFold reads an account's XP only while that account is open. For a closed account the number and text fields are `null`, `classes` is empty and `isStale` is `true`. An id that isn't one of the user's accounts is rejected with `invalid-argument`. +FourFold reads an account's XP only while that account is open, and only if FourFold's own XP tracker can read it. If the XP tracker plugin shows no data for an account, neither will yours. For a closed account the number and text fields are `null`, `classes` is empty and `isStale` is `true`. An id that isn't one of the user's accounts is rejected with `invalid-argument`. `fourfold.xp.onUpdated(callback)` calls `callback({ accountId })` when that account's XP data changes, about once a minute for each open account. @@ -142,7 +149,7 @@ const stats = await fourfold.stats.get(account.id); if (stats) console.log(stats.className, stats.level, stats.hp, stats.attack); ``` -`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance }` for the account's active class, or `null` before the account's first read. `hp` to `resistance` are numbers, or `null` when unknown. An unknown account id is rejected with `invalid-argument`. +`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. An unknown account id is rejected with `invalid-argument`. ### Timer @@ -172,11 +179,11 @@ console.log(response.status, response.text.length); - **Where:** a site in your `sites`, or any `https` site if the plugin has `anySite`. The host name must match exactly. Plain `http` never works. A site on the local network never works, and FourFold also checks the addresses the host name resolves to. - **Method:** `GET` (default) or `POST`. -- **`body`:** a string. It is sent as UTF-8 with a `text/plain` content type unless you set `Content-Type` in `headers`. -- **`headers`:** an object of strings. A name must be a valid header name, and a value must be printable ASCII, or the call fails with `invalid-argument`. `Cookie`, `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Proxy-*` and `Sec-*` are dropped. +- **`body`:** must be a string, so `JSON.stringify` an object yourself. A body that isn't a string is sent empty, and `body` is ignored for `GET`. It is sent as UTF-8 with a `text/plain` content type unless you set `Content-Type` in `headers`. +- **`headers`:** an object of strings. A name must be a valid header name, and a value must be printable ASCII, or the call fails with `invalid-argument`. `Cookie`, `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Proxy-*` and `Sec-*` are dropped. FourFold sends `User-Agent: FourFold-Plugin/1` unless you set your own. - **No shared state:** no cookies are kept or sent, and no FourFold credentials are attached. - **Redirects:** followed up to 5 times. Each one must go to an allowed site. Your headers are not sent again once a redirect leaves the original host or port. `301` and `302` on a `POST`, and `303`, turn the request into a `GET`. -- **Response:** `status` is the HTTP status. A `404` or `500` still resolves, so check `status`. `headers` is an object of the response headers (`Set-Cookie` is left out). `text` is the body read as UTF-8, so it only suits text. +- **Response:** `status` is the HTTP status. A `404` or `500` still resolves, so check `status`. `headers` is an object of the response headers (`Set-Cookie` is left out). Header names come in whatever case the server used, so compare them case-insensitively. `text` is the body read as UTF-8, so it only suits text. - **Limits:** at most 60 requests a minute (each redirect counts), a 15 second timeout, a 2 MB response. ### Opening a link @@ -211,7 +218,7 @@ Each plugin has a private key-value store that is kept between runs. - `set` and `remove` together are limited to 120 a minute (`limit-exceeded`). - The data is saved in `%LOCALAPPDATA%\FourFoldAccountManager\plugin-data\.json`. If that file can't be read at the moment (it is locked, say), the call is rejected with `unavailable`. A missing or damaged file loads as empty. -### Cards +### Card calls ```js await fourfold.cards.set('goal', account.id, { @@ -266,7 +273,7 @@ body { background: var(--ff-surface); color: var(--ff-text); } | Card text | Summary up to 40 characters, up to 8 rows, label and value up to 40 characters each. | | Card redraws | At most four a second. | | One served file | 8 MB. | -| Flood stop | See [The sandbox](#the-sandbox). | +| Flood stop | More than 2,000 requests or messages, more than 8 MB of messages, or more than 64 MB of replies, in a second. See [When a plugin is stopped](#when-a-plugin-is-stopped). | ## The sandbox @@ -297,7 +304,7 @@ Every response carries a content security policy. For a plugin that declares `ht default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://example.com; connect-src 'self' https://example.com wss://example.com; frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none' ``` -With `anySite`, `img-src` and `connect-src` accept `https:` in place of the declared sites. WebSockets still need a declared site. +With `anySite`, `img-src` and `connect-src` accept `https:` in place of the declared sites. WebSockets still need a declared site. The developer tools console may warn about an unknown `webrtc` directive in this policy. It is harmless. What that means for you: @@ -310,11 +317,11 @@ What that means for you: ### The local network -No page request and no `http.fetch` can reach the user's own network. That covers `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names, single-label names such as `router`, and addresses in `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`, `100.64.0.0/10`, `::1`, `fc00::/7` and `fe80::/10`, in any spelling. Page requests are checked by host name or address. `http.fetch` also checks every address a host name resolves to. +FourFold refuses local names and addresses for page requests and for `http.fetch`. That covers `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names, single-label names such as `router`, and addresses in `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`, `100.64.0.0/10`, `::1`, `fc00::/7` and `fe80::/10`, in any spelling. Only `http.fetch` also checks what a host name resolves to, so declare only hosts you trust. ### The browser around your page -- Leaving your plugin's page is cancelled. New windows are blocked. Downloads are cancelled. +- Navigating to any other site is cancelled. Links between your own pages work. New windows are blocked. Downloads are cancelled. - Every permission request is denied: camera, microphone, location, clipboard read, notifications, screen capture and the rest. - `alert`, `confirm` and `prompt` do nothing. - Password saving and autofill are off. Sign-in prompts and links to other apps (`mailto:`, say) are cancelled. @@ -325,7 +332,7 @@ No page request and no `http.fetch` can reach the user's own network. That cover FourFold stops a plugin that: - sends more than 2,000 requests or messages in one second (every request the page makes counts, including for its own files); -- sends more than 8 MB of messages in one second, counting FourFold's replies too (a loop of `storage.get` calls on a big value can reach it); +- sends more than 8 MB of messages in one second, or is sent more than 64 MB of FourFold's replies in one second (a loop of `storage.get` calls on a big value can reach it); - loads more than 32 MB of its own files in one second; - crashes, or stops responding. @@ -333,7 +340,7 @@ The panel then shows "This plugin stopped." with a **Reload** button. The plugin ### Check your own plugin -`samples/sandbox-check` tries everything above that a plugin must not be able to do, and prints PASS or FAIL for each. It needs an internet connection, because it makes one request to example.com. Its **Flood FourFold** button should stop the plugin. +`samples/sandbox-check` tries the main things above that a plugin must not be able to do, and prints PASS or FAIL for each. It contacts example.com each time it runs, so it needs an internet connection. Its **Flood FourFold** button should stop the plugin. ## Cards diff --git a/samples/goal-tracker/app.js b/samples/goal-tracker/app.js index 86d38ab..560020f 100644 --- a/samples/goal-tracker/app.js +++ b/samples/goal-tracker/app.js @@ -9,10 +9,21 @@ function progressTo(goal, xp) { return Math.min(1, (xp.level + withinLevel) / goal); } -async function render() { +// Events arrive in bursts (xp.onUpdated fires once per account), so redraws run one after another, never overlapping. +let queue = Promise.resolve(); +const render = () => (queue = queue.then(draw).catch(error => console.warn(error.code ?? error.message))); + +async function draw() { + // Leave the list alone while the user is typing a goal. + if (container.contains(document.activeElement) && document.activeElement.tagName === 'INPUT') return; const accounts = await fourfold.accounts.list(); - // Events can start a second render while this one is waiting, so the page is swapped once, at the end. const panels = []; + if (accounts.length === 0) { + const none = document.createElement('p'); + none.className = 'muted'; + none.textContent = 'No accounts yet. Add one in FourFold.'; + panels.push(none); + } for (const account of accounts) { const xp = await fourfold.xp.get(account.id); const goal = goals[account.id] ?? null; @@ -33,6 +44,7 @@ async function render() { if (Number.isFinite(value) && value > 0) goals[account.id] = value; else delete goals[account.id]; await fourfold.storage.set('goals', goals); + input.blur(); await render(); }); const bar = document.createElement('div'); diff --git a/samples/sandbox-check/check.js b/samples/sandbox-check/check.js index 3e89475..c9f53c1 100644 --- a/samples/sandbox-check/check.js +++ b/samples/sandbox-check/check.js @@ -38,6 +38,7 @@ async function run() { frame.src = 'https://example.com/'; frame.hidden = true; document.body.append(frame); + const popup = window.open('https://example.com/'); let workerMade = false; try { new Worker('check.js'); workerMade = true; } catch { /* blocked */ } let serviceWorkerRegistered = false; @@ -46,7 +47,7 @@ async function run() { serviceWorkerRegistered = true; } catch { /* blocked */ } await settle(); - report('A script from another site is blocked, even a declared one', violated('script-src') > 0); + report('A script from another site is blocked, even a declared one', violated('script-src-elem') > 0); report('Page fetch and WebSocket to an undeclared site are blocked', violated('connect-src') >= 2); report('Frames are blocked', violated('frame-src') > 0); report('Web Workers are blocked', !workerMade || violated('worker-src') > 0); @@ -54,7 +55,7 @@ async function run() { report('WebRTC is removed', typeof RTCPeerConnection === 'undefined'); report('alert() does nothing', alert('This should not appear') === undefined); - report('New windows are blocked', window.open('https://example.com/') === null); + report('New windows are blocked', popup === null || popup.closed); await rejects('FourFold-run fetch to an undeclared site is refused', () => fourfold.http.fetch('https://example.org/'), 'site-not-allowed'); @@ -72,7 +73,7 @@ async function run() { await rejects('An undeclared card is refused', () => fourfold.cards.set('nope', null, { rows: [] }), 'not-declared'); - await rejects('openExternal without a click is refused', () => fourfold.openExternal('https://example.com/')); + await rejects('openExternal is refused while the checks run', () => fourfold.openExternal('https://example.com/')); await fourfold.storage.set('probe', { at: Date.now() }); report('Storage round-trips', (await fourfold.storage.get('probe')) !== null); @@ -88,6 +89,9 @@ async function run() { document.getElementById('open').addEventListener('click', () => fourfold.openExternal('https://example.com/')); document.getElementById('leave').addEventListener('click', () => { location.href = 'https://example.com/'; }); document.getElementById('flood').addEventListener('click', () => { - for (let i = 0; i < 20000; i++) window.chrome.webview.postMessage({ id: -1 - i, method: 'timer.get' }); + // Large messages first, so the budget for message text trips whatever the machine's speed. + const pad = 'x'.repeat(500000); + for (let i = 0; i < 20; i++) window.chrome.webview.postMessage({ id: -1 - i, method: 'timer.get', pad }); + for (let i = 0; i < 20000; i++) window.chrome.webview.postMessage({ id: -100 - i, method: 'timer.get' }); }); run().catch(error => report('The check itself ran', false, error.message)); diff --git a/samples/sandbox-check/index.html b/samples/sandbox-check/index.html index 9b2dd34..ed62fd8 100644 --- a/samples/sandbox-check/index.html +++ b/samples/sandbox-check/index.html @@ -7,6 +7,7 @@

Sandbox check

Every line should say PASS.

+

Don't click or type in this panel until the list is complete.

    diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs index 4d8cd0a..ce10151 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs @@ -100,6 +100,25 @@ await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/api", " Assert.Equal("yes", sent.Headers.GetValues("X-Keep").Single()); } + [Fact] + public async Task ARequestCarriesTheFourFoldUserAgentUnlessThePluginSetsItsOwn() + { + var sent = new List(); + var handler = new FakeHandler(request => + { + sent.Add(request); + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(Get("https://wiki.example.com/api")); + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/api", "GET", + new Dictionary { ["user-agent"] = "mine/2" }, null)); + + Assert.Equal("FourFold-Plugin/1", sent[0].Headers.GetValues("User-Agent").Single()); + Assert.Equal("mine/2", sent[1].Headers.GetValues("User-Agent").Single()); + } + [Fact] public async Task AResponseOverTwoMegabytesIsRefused() { diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs index 09f27b9..2f9650a 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs @@ -27,6 +27,10 @@ public sealed class PluginHttpFetcher : IDisposable private const string HeaderSeparators = "()<>@,;:\\\"/[]?={}"; + // Many public APIs refuse a request that has no User-Agent. This is a FourFold default, not a plugin header, so it + // goes on every hop (a redirect to another host drops the plugin's headers, not this), and a plugin's own wins. + private const string DefaultUserAgent = "FourFold-Plugin/1"; + private static readonly string[] ForbiddenHeaders = ["Cookie", "Host", "Content-Length", "Transfer-Encoding", "Connection"]; @@ -223,6 +227,11 @@ private static void ApplyHeaders(HttpRequestMessage message, IReadOnlyDictionary message.Content.Headers.TryAddWithoutValidation(name, value); } } + + if (!message.Headers.Contains("User-Agent")) + { + message.Headers.TryAddWithoutValidation("User-Agent", DefaultUserAgent); + } } private static Dictionary FlattenHeaders(HttpResponseMessage response) diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs index 7f4668a..99f15a3 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs @@ -198,7 +198,8 @@ IReadOnlyList IPluginHostData.GetAccounts() => entry.Key, entry.Value.Level, entry.Value.CurrentXp, entry.Value.NextLevelXp)) .ToArray() ?? [], state?.LastUpdated, - state?.IsStale ?? true); + // No XP data yet reads as stale, for an open account as for a closed one. + state is null || state.IsStale || state.LastUpdated is null); } PluginStatsInfo? IPluginHostData.GetStats(Guid accountId) diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs index 707e746..c8c8fc3 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs @@ -147,7 +147,8 @@ internal sealed class PluginApi( } } - // A rolling minute on the same monotonic clock as openExternal. A refused call isn't recorded, so it doesn't count. + // A rolling minute on the same monotonic clock as openExternal. Only a call refused by this limit isn't recorded; one + // that is refused later, for its size or its key, has already taken a slot. private void TakeStorageWriteSlot() { lock (_storageWrites) diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs index f8acccf..23859fb 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs @@ -14,11 +14,13 @@ namespace FourFoldAccountManager.Desktop.Plugins.Web; public sealed class WebPlugin : IFourFoldPlugin, IDisposable { // A page can post messages or ask for files in a tight loop, faster than the UI thread can answer, which freezes - // the whole app (and again on every launch). More than this many events, or this much message and reply text, - // within one second stops the plugin; its Reload button starts it fresh. Replies count too: a loop of reads that - // each return a big stored value saturates the UI thread well before the event limit. + // the whole app (and again on every launch). More than this many events, or this much message text, within one + // second stops the plugin; its Reload button starts it fresh. Replies have a budget of their own, because one web + // request's reply can be several MB once JSON-escaped (non-ASCII text grows up to six-fold), but a loop of reads that + // each return a big stored value still saturates the UI thread well before the event limit. private const int MaximumEventsPerSecond = 2_000; private const int MaximumMessageCharactersPerSecond = 8 * 1024 * 1024; + private const int MaximumReplyCharactersPerSecond = 64 * 1024 * 1024; // Serving a file reads it whole on the UI thread, so a larger one is treated as missing, and a page that asks for // more than this much of its own files within one second is stopped like any other flood. @@ -51,6 +53,7 @@ public sealed class WebPlugin : IFourFoldPlugin, IDisposable private long _windowStart; private int _windowEvents; private long _windowCharacters; + private long _windowReplyCharacters; private long _windowServedBytes; public WebPlugin( @@ -304,25 +307,38 @@ private static void Discard(WebView2CompositionControl? view) view.Dispose(); } - // Counts page events (a request or message by default) and message or reply characters, and says whether the page - // has now gone past a flood limit within the current second. - private bool IsFlooding(int messageCharacters = 0, int events = 1) + // Counts one page event (a request, or a message of the given length) and says whether the page has now gone past + // a flood limit within the current second. + private bool IsFlooding(int messageCharacters = 0) { if (Environment.TickCount64 - _windowStart >= 1000) { ResetFloodWindow(); } - _windowEvents += events; + _windowEvents++; _windowCharacters += messageCharacters; return _windowEvents > MaximumEventsPerSecond || _windowCharacters > MaximumMessageCharactersPerSecond; } + // Counts the text of one reply against the reply budget of the current second. A reply is not a page event. + private bool IsReplyFlooding(int replyCharacters) + { + if (Environment.TickCount64 - _windowStart >= 1000) + { + ResetFloodWindow(); + } + + _windowReplyCharacters += replyCharacters; + return _windowReplyCharacters > MaximumReplyCharactersPerSecond; + } + private void ResetFloodWindow() { _windowStart = Environment.TickCount64; _windowEvents = 0; _windowCharacters = 0; + _windowReplyCharacters = 0; _windowServedBytes = 0; } @@ -466,8 +482,7 @@ private async void OnWebMessageReceived(object? sender, CoreWebView2WebMessageRe // A reply for a page that was stopped or reloaded while the call ran is dropped. if (reply is not null && view is not null && ReferenceEquals(view, _view)) { - // The reply's text is counted, but it is not a second event. - if (IsFlooding(reply.Length, events: 0)) + if (IsReplyFlooding(reply.Length)) { ShowStopped(); return; diff --git a/src/FourFoldAccountManager.Desktop/Views/FullscreenOverlayTray.xaml b/src/FourFoldAccountManager.Desktop/Views/FullscreenOverlayTray.xaml index e4b1a4f..bec700b 100644 --- a/src/FourFoldAccountManager.Desktop/Views/FullscreenOverlayTray.xaml +++ b/src/FourFoldAccountManager.Desktop/Views/FullscreenOverlayTray.xaml @@ -14,7 +14,7 @@ Click="Switch_Click" VerticalAlignment="Center" FontSize="11" Foreground="{DynamicResource Brush.TextPrimary}" AutomationProperties.Name="{Binding AccessibleName}"> - + Date: Sat, 3 Oct 2026 05:47:41 -0500 Subject: [PATCH 26/49] fix: stop a plugin page closing FourFold, and cap its icon and browser storage --- PLUGIN_AUTHORS.md | 13 ++-- samples/sandbox-check/check.js | 17 +++-- .../Plugins/PluginLayoutPolicyTests.cs | 27 +++++++ .../Plugins/PluginManifestReaderTests.cs | 50 +++++++++++++ .../Plugins/PluginCardId.cs | 6 +- .../Plugins/PluginHttpFetcher.cs | 4 -- .../Plugins/PluginLayoutPolicy.cs | 3 - .../Plugins/PluginManifestReader.cs | 29 +++++--- .../Plugins/PluginText.cs | 18 +++++ .../Plugins/PluginApiTests.cs | 10 +++ .../MainWindow.xaml | 2 +- .../MainWindow.xaml.cs | 3 +- .../Plugins/Web/CommunityPluginManager.cs | 28 ++++---- .../Plugins/Web/PluginApi.cs | 9 ++- .../Plugins/Web/PluginSdk.cs | 4 ++ .../Plugins/Web/WebPlugin.cs | 70 +++++++++++++++---- .../Views/PluginSidebar.xaml.cs | 1 - 17 files changed, 231 insertions(+), 63 deletions(-) create mode 100644 src/FourFoldAccountManager.Core.Tests/Plugins/PluginLayoutPolicyTests.cs create mode 100644 src/FourFoldAccountManager.Core/Plugins/PluginText.cs diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md index 2e3dafb..0d11879 100644 --- a/PLUGIN_AUTHORS.md +++ b/PLUGIN_AUTHORS.md @@ -58,7 +58,7 @@ Dev plugins are not reviewed, and FourFold honors their `plugin.json` as written } ``` -A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, and the plugin list shows the reason. Text values are trimmed. The `name`, `shortLabel`, `author` and `description` fields, and a card's `name`, can't contain control characters (a line break or a bell character, say), because FourFold shows them. Fields not listed here are ignored. The file can be at most 64 KB, and it is never served to your page. +A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, and the plugin list shows the reason. Text values are trimmed. The `name`, `shortLabel`, `author` and `description` fields, and a card's `name`, can't contain control characters (a line break or a bell character, say) or invisible formatting characters (a right-to-left override, say), because FourFold shows them. Fields not listed here are ignored. The file can be at most 64 KB, and it is never served to your page. | Field | Required | Rule | |---|---|---| @@ -70,7 +70,7 @@ A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, | `description` | no | At most 200 characters. | | `apiVersion` | yes | A whole number. FourFold supports `1`. A higher number is rejected with "Update FourFold to use this plugin." | | `panel` | yes | Path to an existing `.html` file inside the plugin folder. Forward slashes only. | -| `icon` | no | Path to a `.png` inside the plugin folder, at most 64 KB. Forward slashes only. Without one, the strip shows just the `shortLabel`. | +| `icon` | no | Path to a PNG inside the plugin folder, at most 256 by 256 pixels and 64 KB. Forward slashes only. Without one, the strip shows a default icon. | | `sites` | no | At most 10 websites the plugin may contact. Each is an origin: `https://host` or `https://host:port`, with no path, query or `user@`. The host must be a DNS name: no IP address, no trailing dot, and no name that only works on the local network. `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names are refused, and so is a single-label name such as `router`. A subdomain is its own site, so `https://example.com` doesn't cover `https://www.example.com`. | | `anySite` | no | `true` lets the plugin contact any `https` site. Default `false`. FourFold honors it for plugins in the dev folder. | | `cards` | no | At most 6 overlay cards. See [Cards](#cards). | @@ -218,6 +218,8 @@ Each plugin has a private key-value store that is kept between runs. - `set` and `remove` together are limited to 120 a minute (`limit-exceeded`). - The data is saved in `%LOCALAPPDATA%\FourFoldAccountManager\plugin-data\.json`. If that file can't be read at the moment (it is locked, say), the call is rejected with `unavailable`. A missing or damaged file loads as empty. +The page's own browser storage (IndexedDB, the Cache API, `localStorage`) is capped at about 5 MB per plugin, and a write past the cap fails with a `QuotaExceededError`. Keep settings in `fourfold.storage`: it is the supported place for them. + ### Card calls ```js @@ -269,6 +271,7 @@ body { background: var(--ff-surface); color: var(--ff-text); } | Calls waiting for an answer at once | 32. More are rejected with `limit-exceeded`. | | `http.fetch` | 60 requests a minute, 5 redirects, 15 seconds, 2 MB response. | | Storage | 256 KB in all, 120 writes a minute, keys up to 64 characters. | +| Browser storage | About 5 MB per plugin in IndexedDB, the Cache API and `localStorage`. | | `openExternal` | One link every 2 seconds. | | Card text | Summary up to 40 characters, up to 8 rows, label and value up to 40 characters each. | | Card redraws | At most four a second. | @@ -323,7 +326,7 @@ FourFold refuses local names and addresses for page requests and for `http.fetch - Navigating to any other site is cancelled. Links between your own pages work. New windows are blocked. Downloads are cancelled. - Every permission request is denied: camera, microphone, location, clipboard read, notifications, screen capture and the rest. -- `alert`, `confirm` and `prompt` do nothing. +- `alert`, `confirm` and `prompt` do nothing, and so do `window.close()` and `window.print()`. - Password saving and autofill are off. Sign-in prompts and links to other apps (`mailto:`, say) are cancelled. - The page has no access to FourFold's objects, to a game's cookies or pages, or to any other plugin. @@ -360,7 +363,7 @@ A card is a small box FourFold draws over the game, or in a floating window. You | `summary` | Optional text, at most 40 characters. | | `rows` | At most 8 rows. Each is `{ label, value, progress }`. `label` and `value` are strings of at most 40 characters (anything that isn't a string is drawn empty, so convert numbers with `String()`). `progress` is optional: `null`, or a number from 0 to 1. | -Text with control characters (line breaks, for example) fails with `invalid-argument`. A text too long, or too many rows, fails with `limit-exceeded`. +Text with control characters (line breaks, for example) or invisible formatting characters (a right-to-left override, say) fails with `invalid-argument`. A text too long, or too many rows, fails with `limit-exceeded`. **Clear** it with `fourfold.cards.clear(cardId, accountId)`. @@ -386,7 +389,7 @@ If the user switches the plugin off in the plugin list, its cards are hidden eve - Draw custom cards. Cards are FourFold's data cards. - Add a settings page behind the cog. Keep settings in your own panel. - Run while FourFold is closed or the plugin is switched off. (A plugin's page does keep running while its panel is hidden.) -- Rely on printing or file pickers. They open the system's own dialogs. +- Print (`window.print()` does nothing), or rely on file pickers, which open the system's own dialog. ## Getting on the hub diff --git a/samples/sandbox-check/check.js b/samples/sandbox-check/check.js index c9f53c1..f3042b7 100644 --- a/samples/sandbox-check/check.js +++ b/samples/sandbox-check/check.js @@ -1,9 +1,11 @@ // Each check tries something a plugin must not be able to do. PASS means FourFold stopped it. const results = document.getElementById('results'); const violations = []; -document.addEventListener('securitypolicyviolation', event => violations.push(event.effectiveDirective)); +document.addEventListener('securitypolicyviolation', event => + violations.push({ directive: event.effectiveDirective, blocked: event.blockedURI })); const settle = () => new Promise(resolve => setTimeout(resolve, 1000)); -const violated = directive => violations.filter(found => found.startsWith(directive)).length; +const violated = (directive, blocked = '') => + violations.filter(found => found.directive.startsWith(directive) && found.blocked.startsWith(blocked)).length; function report(name, passed, detail = '') { const item = document.createElement('li'); @@ -47,13 +49,20 @@ async function run() { serviceWorkerRegistered = true; } catch { /* blocked */ } await settle(); - report('A script from another site is blocked, even a declared one', violated('script-src-elem') > 0); + report('A script from another site is blocked, even a declared one', + violated('script-src-elem', 'https://example.com') > 0); report('Page fetch and WebSocket to an undeclared site are blocked', violated('connect-src') >= 2); report('Frames are blocked', violated('frame-src') > 0); report('Web Workers are blocked', !workerMade || violated('worker-src') > 0); report('Service workers are blocked', !serviceWorkerRegistered); report('WebRTC is removed', typeof RTCPeerConnection === 'undefined'); - report('alert() does nothing', alert('This should not appear') === undefined); + report('alert() shows nothing (check by eye)', alert('This should not appear') === undefined); + + // If window.close() worked, FourFold would be closing instead of getting here. + let stillRunning = false; + window.close(); + stillRunning = true; + report('window.close() does nothing', stillRunning); report('New windows are blocked', popup === null || popup.closed); diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginLayoutPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginLayoutPolicyTests.cs new file mode 100644 index 0000000..3c31a45 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginLayoutPolicyTests.cs @@ -0,0 +1,27 @@ +using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginLayoutPolicyTests +{ + [Fact] + public void MovingAPluginKeepsTheSlotsOfUnloadedAndSwitchedOffPlugins() + { + // "missing" is saved but not loaded right now, and "off" is loaded but switched off; both must stay where they + // are, or the user's saved order is silently rewritten. + var settings = PanelSettings.Default with + { + PluginOrder = ["a", "missing", "off", "b"], + DisabledPlugins = ["off"] + }; + PluginDescriptor[] known = [Descriptor("a"), Descriptor("off"), Descriptor("b")]; + + var moved = PluginLayoutPolicy.WithMoved(settings, known, "b", 0); + + Assert.Equal(["b", "missing", "off", "a"], moved.PluginOrder); + } + + private static PluginDescriptor Descriptor(string id) => new(id, id, id, "", [], []); +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs index 79ad0db..cf417bf 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -1,3 +1,5 @@ +using System.Buffers.Binary; +using System.Text; using FourFoldAccountManager.Core.Overlay; using FourFoldAccountManager.Core.Plugins; using Xunit; @@ -46,6 +48,24 @@ private PluginManifestResult Read(string json) return PluginManifestReader.Read(_folder); } + private PluginManifestResult ReadWithIcon(byte[] iconBytes) + { + File.WriteAllBytes(Path.Combine(_folder, "icon.png"), iconBytes); + return Read(Manifest(", \"icon\": \"icon.png\"")); + } + + // The first 24 bytes of a PNG: the signature, the IHDR chunk's length and name, then its width and height. + private static byte[] PngHeader(uint width, uint height) + { + var header = new byte[24]; + new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }.CopyTo(header, 0); + BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(8), 13); + "IHDR"u8.CopyTo(header.AsSpan(12)); + BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(16), width); + BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(20), height); + return header; + } + private static string Manifest(string overrides = "") => $$""" { "id": "cody.goal-tracker", "name": "Goal tracker", "shortLabel": "Goals", "version": "1.0.0", @@ -102,6 +122,8 @@ public void AValidManifestLoadsWithItsSitesAndCards() // that rejects these, not the JSON parser. [InlineData("\"name\": \"Goal\\u0007tracker\"")] [InlineData("\"cards\": [{ \"id\": \"goal\", \"name\": \"Go\\u0007al\", \"scope\": \"account\" }]")] + // U+202E is a right-to-left override, which would make FourFold draw the rest of the name backwards. + [InlineData("\"name\": \"Goal\\u202Etracker\"")] // A zero-width joiner in a host makes Uri.IdnHost throw rather than return a name. [InlineData("\"sites\": [\"https://a\u200Db.example\"]")] [InlineData("\"cards\": [{ \"id\": \"Goal\", \"name\": \"Goal\", \"scope\": \"account\" }]")] @@ -132,6 +154,34 @@ public void AnOversizedManifestIsRejectedWithoutBeingRead() Assert.Equal("plugin.json is too large.", result.Error); } + [Fact] + public void AnIconThatDeclaresAHugeImageIsRejectedWithoutBeingDecoded() + { + // A 274-byte PNG declaring 1 by 100000 pixels made the app commit 215 MB the moment it drew the strip. + var result = ReadWithIcon(PngHeader(width: 1, height: 100000)); + + Assert.Null(result.Manifest); + Assert.Contains("icon", result.Error); + } + + [Fact] + public void AnIconThatIsNotAPngIsRejectedWhateverItIsNamed() + { + var result = ReadWithIcon(Encoding.ASCII.GetBytes("This is text, not a PNG image.")); + + Assert.Null(result.Manifest); + Assert.Contains("icon", result.Error); + } + + [Fact] + public void AnIconWithASmallPngHeaderIsAccepted() + { + var result = ReadWithIcon(PngHeader(width: 64, height: 64)); + + Assert.Null(result.Error); + Assert.Equal("icon.png", result.Manifest!.Icon); + } + [Fact] public void AManifestReferencingAnOutsideFileIsRejected() { diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs b/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs index 3ab21c8..5bc66e0 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs @@ -5,14 +5,10 @@ namespace FourFoldAccountManager.Core.Plugins; // A community plugin's card is identified by "/", for example "cody.goal-tracker/goal". public static partial class PluginCardId { - [GeneratedRegex("^(?" + PluginManifestReader.IdPattern + ")/(?" + - PluginManifestReader.CardIdPattern + @")\z")] + [GeneratedRegex("^" + PluginManifestReader.IdPattern + "/" + PluginManifestReader.CardIdPattern + @"\z")] private static partial Regex Pattern(); public static string Create(string pluginId, string cardId) => $"{pluginId}/{cardId}"; public static bool IsValid(string? value) => value is { Length: <= 97 } && Pattern().IsMatch(value); - - public static string? PluginId(string? value) => - value is not null && Pattern().Match(value) is { Success: true } match ? match.Groups["plugin"].Value : null; } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs index 2f9650a..fc6fa95 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs @@ -135,10 +135,6 @@ public async Task FetchAsync( { throw new PluginApiException(refused.Code, refused.Message); } - catch (HttpRequestException) - { - throw new PluginApiException("unavailable", "The request failed."); - } catch (Exception exception) when (exception is not PluginApiException and not OperationCanceledException) { throw new PluginApiException("unavailable", "The request failed."); diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs index 03feb61..6a582b0 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs @@ -32,9 +32,6 @@ public static bool IsCardSuppressed(PanelSettings settings, OverlayAddOnKind kin public static bool IsShortcutSuppressed(PanelSettings settings, GlobalShortcutAction action) => BuiltInPlugins.All.Any(plugin => plugin.Shortcuts.Contains(action) && !IsEnabled(settings, plugin.Id)); - public static bool IsPluginCardSuppressed(PanelSettings settings, string pluginCard) => - PluginCardId.PluginId(pluginCard) is not { } pluginId || !IsEnabled(settings, pluginId); - // The saved open plugin when it is known and switched on; otherwise null. public static PluginDescriptor? OpenPlugin(PanelSettings settings, IReadOnlyList known) => known.FirstOrDefault(plugin => plugin.Id == settings.OpenPlugin && IsEnabled(settings, plugin.Id)); diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index e4a765b..7f0d4b2 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -1,3 +1,4 @@ +using System.Buffers.Binary; using System.Text.Json; using System.Text.RegularExpressions; using FourFoldAccountManager.Core.Overlay; @@ -123,9 +124,9 @@ private static PluginManifestResult ReadManifest(string folder) return Reject("The description must be at most 200 characters."); } - if (HasControlCharacter(name, shortLabel, author, description)) + if (new[] { name, shortLabel, author, description }.Any(PluginText.HasUnsafeCharacter)) { - return Reject("The name, shortLabel, author and description can't contain control characters."); + return Reject("The name, shortLabel, author and description can't contain control characters or invisible formatting characters."); } if (!root.TryGetProperty("apiVersion", out var apiElement) || apiElement.ValueKind != JsonValueKind.Number || @@ -150,9 +151,9 @@ private static PluginManifestResult ReadManifest(string folder) if (icon is not null && (icon.Contains('\\') || !icon.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || !PluginPaths.TryResolveInside(folder, icon, out var iconPath) || !File.Exists(iconPath) || - new FileInfo(iconPath).Length > MaximumIconBytes)) + new FileInfo(iconPath).Length > MaximumIconBytes || !IsSmallPng(iconPath))) { - return Reject("The icon must be a .png inside the plugin folder, at most 64 KB."); + return Reject("The icon must be a PNG inside the plugin folder, at most 256 by 256 pixels and 64 KB."); } if (!TryReadSites(root, out var sites, out var siteError)) @@ -192,9 +193,19 @@ private static bool InRange(string? value, int minimum, int maximum, out string return result.Length >= minimum && result.Length <= maximum; } - // The text a manifest supplies is drawn in the app (the plugin list, the Overlays panel), so a line break or a bell - // character in it is never wanted. - private static bool HasControlCharacter(params string[] values) => values.Any(value => value.Any(char.IsControl)); + // The app decodes the icon on every render of the strip, and a tiny file can declare an enormous image (a 274-byte + // PNG declaring 1 by 100000 pixels made it commit 215 MB), so the header is checked first, not the file's content. + // A PNG's first 24 bytes are the signature, then the IHDR chunk's length and name, then its width and height. + private static bool IsSmallPng(string path) + { + Span header = stackalloc byte[24]; + using var stream = File.OpenRead(path); + return stream.ReadAtLeast(header, header.Length, throwOnEndOfStream: false) == header.Length && + header[..8].SequenceEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }) && + header[12..16].SequenceEqual("IHDR"u8) && + BinaryPrimitives.ReadUInt32BigEndian(header[16..]) is >= 1 and <= 256 && + BinaryPrimitives.ReadUInt32BigEndian(header[20..]) is >= 1 and <= 256; + } private static bool TryReadSites(JsonElement root, out IReadOnlyList sites, out string error) { @@ -245,7 +256,7 @@ private static bool IsIpLikeHost(string host) private static bool TryReadCards(JsonElement root, out IReadOnlyList cards, out string error) { cards = []; - error = "Each card needs an id (lowercase letters, digits, dashes), a name (1 to 24 characters, no control characters) and a scope of account or global."; + error = "Each card needs an id (lowercase letters, digits, dashes), a name (1 to 24 characters, no control or invisible formatting characters) and a scope of account or global."; if (!root.TryGetProperty("cards", out var element) || element.ValueKind == JsonValueKind.Null) { return true; @@ -267,7 +278,7 @@ private static bool TryReadCards(JsonElement root, out IReadOnlyList 32 || !CardIdRegex().IsMatch(id) || - !InRange(Text(item, "name"), 1, 24, out var name) || HasControlCharacter(name) || + !InRange(Text(item, "name"), 1, 24, out var name) || PluginText.HasUnsafeCharacter(name) || scope is not ("account" or "global") || result.Any(card => card.Id == id)) { return false; diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginText.cs b/src/FourFoldAccountManager.Core/Plugins/PluginText.cs new file mode 100644 index 0000000..06736be --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginText.cs @@ -0,0 +1,18 @@ +using System.Globalization; +using System.Text; + +namespace FourFoldAccountManager.Core.Plugins; + +public static class PluginText +{ + // Text a plugin supplies is drawn by FourFold, so it can't carry anything that rearranges or hides the text around + // it: control characters (a line break, a bell), direction overrides, zero-width spaces and the line and paragraph + // separators. U+200D, the zero-width joiner, is allowed because emoji use it. + public static bool HasUnsafeCharacter(string text) => + text.EnumerateRunes().Any(rune => Rune.IsControl(rune) || Rune.GetUnicodeCategory(rune) switch + { + UnicodeCategory.Format => rune.Value != 0x200D, + UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator => true, + _ => false + }); +} diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs index 7a9db5b..703a24d 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs @@ -96,6 +96,16 @@ public async Task ACardCanOnlyBeSetForADeclaredCardAndAKnownAccount() Assert.Equal( "invalid-argument", ErrorCode(await Call("cards.set", new { cardId = "goal", accountId = Guid.NewGuid() }))); + // A right-to-left override (U+202E) in a label would reverse the text drawn after it. + Assert.Equal( + "invalid-argument", + ErrorCode(await Call("cards.set", new + { + cardId = "goal", + accountId = KnownAccount, + rows = new[] { new { label = "Done\u202E", value = "3" } } + }))); + var key = new OverlayCardKey(OverlayAddOnKind.Plugin, KnownAccount, "cody.goal-tracker/goal"); Assert.Null(_cards.Get(key)); diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml b/src/FourFoldAccountManager.Desktop/MainWindow.xaml index e547d92..56016cc 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml @@ -228,7 +228,7 @@ HorizontalAlignment="Left" VerticalAlignment="Top" /> + KeyboardNavigation.TabNavigation="None" HorizontalAlignment="Left" VerticalAlignment="Top" />