diff --git a/FourFoldAccountManager.sln b/FourFoldAccountManager.sln index ed69279..fca42bf 100644 --- a/FourFoldAccountManager.sln +++ b/FourFoldAccountManager.sln @@ -17,6 +17,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FourFoldAccountManager.Lead EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FourFoldAccountManager.Desktop.Tests", "src\FourFoldAccountManager.Desktop.Tests\FourFoldAccountManager.Desktop.Tests.csproj", "{B1001A02-C503-4CC9-9BF3-473EE45297D0}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FourFoldAccountManager.HubTool", "src\FourFoldAccountManager.HubTool\FourFoldAccountManager.HubTool.csproj", "{4C1F820F-039F-4288-9458-F78626241946}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -99,6 +101,18 @@ Global {B1001A02-C503-4CC9-9BF3-473EE45297D0}.Release|x64.Build.0 = Release|Any CPU {B1001A02-C503-4CC9-9BF3-473EE45297D0}.Release|x86.ActiveCfg = Release|Any CPU {B1001A02-C503-4CC9-9BF3-473EE45297D0}.Release|x86.Build.0 = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|x64.ActiveCfg = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|x64.Build.0 = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|x86.ActiveCfg = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Debug|x86.Build.0 = Debug|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|Any CPU.Build.0 = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|x64.ActiveCfg = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|x64.Build.0 = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|x86.ActiveCfg = Release|Any CPU + {4C1F820F-039F-4288-9458-F78626241946}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -110,5 +124,6 @@ Global {8DC5AD11-A59F-445F-84AC-D10C5F7A9C17} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {B3971592-86AD-488E-85E2-8C9F87A41670} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {B1001A02-C503-4CC9-9BF3-473EE45297D0} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {4C1F820F-039F-4288-9458-F78626241946} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} EndGlobalSection EndGlobal diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md index 6852ed2..01df8c6 100644 --- a/PLUGIN_AUTHORS.md +++ b/PLUGIN_AUTHORS.md @@ -15,10 +15,12 @@ The page runs in its own sandboxed browser. It talks to FourFold only through `w 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. +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. FourFold draws a 24-pixel bar at the top of the panel, above your page. It shows the plugin's name, its author and a COMMUNITY tag (DEV for a plugin in the dev folder), and a long name or author is shortened with an ellipsis. Your page gets the rest of the panel. ## Quick start +Users get plugins from the plugin hub: they open the plugin list (the wrench in the plugin strip) and choose **Plugin hub**. The dev folder is for authors, to try a plugin before it is submitted. To submit one, see [Getting on the hub](#getting-on-the-hub). + 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`. @@ -37,7 +39,7 @@ Every folder directly inside `dev-plugins` is one plugin. - **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. -Dev plugins are not reviewed, and FourFold honors their `plugin.json` as written. Right now the dev folder is the only place a community plugin can run. +Dev plugins are not reviewed, and FourFold honors their `plugin.json` as written. While developer mode is on, a dev plugin runs instead of an installed hub plugin with the same id. ## plugin.json @@ -71,8 +73,8 @@ 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` file 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. | +| `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`. An international host name is fine: FourFold converts it to its `xn--` form, and that form is what it shows users. After the conversion the host can contain only letters, digits, dots and dashes, so a name with an underscore or any other punctuation is refused. | +| `anySite` | no | `true` lets the plugin contact any `https` site. Default `false`. FourFold honors it for plugins in the dev folder. A plugin from the plugin hub gets it only when the maintainers also approve it there. See [Getting on the hub](#getting-on-the-hub). | | `cards` | no | At most 6 overlay cards. See [Cards](#cards). | Each entry in `cards`: @@ -177,7 +179,7 @@ console.log(response.status, response.text.length); `fourfold.http.fetch(url, { method, headers, body })` returns `{ status, headers, text }`. FourFold makes the request, not your page, so it isn't subject to CORS. Only `url` is required. -- **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. +- **Where:** a site in your `sites`, or any `https` site if the plugin has `anySite` and FourFold honors it. 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`:** 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. @@ -194,10 +196,11 @@ button.addEventListener('click', () => { }); ``` -`fourfold.openExternal(url)` opens an `https` link in the user's default browser. +`fourfold.openExternal(url)` opens an `https` link in the user's default browser. The example works because the `plugin.json` above declares `https://wiki.example.com`. -- 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`). +- A URL that isn't a valid `https` link fails with `invalid-argument`. That covers other schemes, a `user@` part, `localhost`, a `.localhost`, `.local`, `.internal`, `.lan` or `.home.arpa` name, a single-label name such as `router`, a local network address, and a host name that can't be converted to a real host name. +- The link must be on one of the plugin's `sites`, with the same host and port, or on any public host if the plugin has `anySite` and FourFold honors it. The path and query can be anything. A link to any other site fails with `site-not-allowed`. +- It works only while the plugin's panel is showing, and only right after the user clicks or presses a key in your page. Otherwise it fails with `unavailable`. - At most one link every 2 seconds (`limit-exceeded`). ### Storage @@ -259,9 +262,9 @@ body { background: var(--ff-surface); color: var(--ff-text); } |---|---| | `invalid-argument` | A parameter is missing or wrong: an unknown account id, a missing or bad key, URL, header or method, control characters or a `progress` outside 0 to 1 in a card, a method FourFold doesn't have. | | `not-declared` | `cards.set` or `cards.clear` for a card id that isn't in `plugin.json`. | -| `site-not-allowed` | `http.fetch` to a site that isn't allowed: not in `sites`, not `https`, or on the local network. This includes a redirect to such a site. | +| `site-not-allowed` | `http.fetch` to a site that isn't allowed: not in `sites`, not `https`, or on the local network. This includes a redirect to such a site. `openExternal` to an `https` site the plugin isn't allowed to contact also gets this code. | | `limit-exceeded` | A size, rate or count limit. See the table below. | -| `unavailable` | FourFold couldn't do it right now: storage can't be read, a web request failed or took longer than 15 seconds, `openExternal` with no click or no panel showing, or an unexpected failure. | +| `unavailable` | FourFold couldn't do it right now: storage can't be read, a web request failed or took longer than 15 seconds, `openExternal` with no recent click or key press, or no panel showing, or an unexpected failure. | ### Limits @@ -307,7 +310,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. The developer tools console may warn about an unknown `webrtc` directive in this policy. It is harmless. +When FourFold honors `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: @@ -393,4 +396,67 @@ If the user switches the plugin off in the plugin list, its cards are hidden eve ## Getting on the hub -Publishing to the plugin hub, and review by FourFold's maintainers, is coming. +FourFold installs plugins only from its plugin hub, and its maintainers review every plugin before it is listed. +The hub is a GitHub repository: +[FourFoldAccountManager-plugin-hub](https://github.com/CodySimonds65/FourFoldAccountManager-plugin-hub). + +1. Put your plugin in a public GitHub repository, at the root or in a folder. +2. Test the exact commit you want listed, with developer mode on. The hub's check (step 4) runs on Linux, where + names are case-sensitive. `panel`, `icon` and `path` must match the real file and folder names letter for + letter, even though Windows lets a mismatch work in the dev folder. +3. Open a pull request on the hub that adds your entry file, `plugins/.json`: + + ```json + { + "repository": "https://github.com/you/your-plugin", + "commit": "0123456789abcdef0123456789abcdef01234567" + } + ``` + + `repository` must be exactly `https://github.com/owner/repo`, with no trailing slash, no `/tree/...` and no `.git` + at the end. `commit` is the full 40-character commit in lowercase. Add `"path"` when the plugin is in a folder. + `path` is written with forward slashes, uses only letters, digits, `.`, `_` and `-`, has no trailing slash, no `.` + or `..` parts, and at most 200 characters. The pull request changes only that one file. +4. A check validates your `plugin.json` with the same rules FourFold uses, builds the package (the zip that users + install), and scans the files in your repository at that commit for secrets. If the check fails, its summary page + says why. Fix it in your plugin's repository (then put the new commit in your entry file), or in the entry file + itself. Then a maintainer reads the code. When they merge, the plugin is on the hub. + +The check downloads your whole repository at that commit, not only the plugin's folder. It must be public, under +50 MB as a download, at most 200 MB once unpacked, and hold at most 20,000 files. No path in your repository can +have more than 63 parts, counting the folders from the repository root and the file's name. + +To update, raise `version` in `plugin.json` and open a pull request that changes `commit` in your entry file. Users +get the new version automatically once it is merged: FourFold checks the hub when it starts and every 6 hours. + +A `version` is three numbers joined by dots, such as `1.4.0`, and each number can be at most 2147483647. The check +refuses a version it can't compare, and an update must raise it, comparing number by number (`1.10.0` is higher than +`1.9.0`). + +What goes into the package: `plugin.json` and every file of a type FourFold serves (see +[Where your page runs](#where-your-page-runs)) in the plugin's folder (the repository root, or `path`). At most 500 +files and 5 MB in all. Every such file goes in, whether or not your page loads it, so keep tests and screenshots +outside the plugin's folder (put the plugin in a folder and set `path`), or in a folder whose name starts with a +dot. Everything else is left out, such as `README.md` and `LICENSE`, and so is any file or folder whose +name starts with a dot. Your panel page, and everything it loads, must be in the package, so none of them can start +with a dot. The files that go in must also unpack on Windows: + +- A file or folder name can't contain `< > " | ? *` or a control character, and can't end in a dot or a space. A + file with a `\` or a `:` in its path is left out. +- A file or folder can't be named like a Windows device: `con`, `prn`, `aux`, `nul`, `com0` to `com9` or `lpt0` to + `lpt9`, in any case, alone or before a dot. `aux.js` is refused, and `auxiliary.js` is fine. +- Two files can't differ only by capital letters. + +A user can uninstall a plugin: FourFold asks first, and uninstalling deletes the plugin's saved data. If the +maintainers remove a plugin from the hub, FourFold stops it for everyone who has it and shows them why. Its saved +data is kept until they uninstall it. + +**Never put a secret key in a plugin.** Everything in a plugin is public and runs on users' machines. A plugin that +needs a secret key can't be listed. + +A plugin gets access to any website only when it asks for it in `plugin.json` **and** a maintainer approves it on the +hub. Ask in your pull request and say why. Users see "Can contact any website" next to a plugin that has it in the hub +before they install it. For every other plugin, the hub's **Details** list the sites it declares. + +The hub's [README](https://github.com/CodySimonds65/FourFoldAccountManager-plugin-hub#readme) has the rest of the +submission rules: what a pull request may change, the secret scan and any-website access. diff --git a/README.md b/README.md index ad507fb..7c6ab01 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ A Windows client for running several FourFold accounts side by side, each in its - **Layouts**: run up to five games in a grid, or give each account its own tab. - **Theatre mode and full screen**: hide everything but the games. - **Plugins**: XP tracker, stats, XP calculator and a speedrun timer in a RuneLite-style strip. Click an icon to open its panel, drag icons to reorder them, and use the wrench to switch plugins off or change the Timer's keys. The button at the right of the toolbar hides or shows the strip. -- **Community plugins (in development)**: plugin authors can build sandboxed web plugins and test them from a local dev folder. See [PLUGIN_AUTHORS.md](PLUGIN_AUTHORS.md). +- **Community plugins**: open the plugin list (the wrench) and choose **Plugin hub** to search and install plugins made by the community. Every plugin is reviewed before it is listed, runs in a sandbox, and updates itself. To make one, see [PLUGIN_AUTHORS.md](PLUGIN_AUTHORS.md). - **Overlays**: drag XP/hr, stats, XP calc and timer cards anywhere over the game. - **Second monitor**: pop the tools panel into its own window, or float individual cards on any screen. - **Shared XP leaderboard**: daily, weekly and monthly XP gains across opted-in players. diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs new file mode 100644 index 0000000..4839890 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubCatalogJsonTests.cs @@ -0,0 +1,173 @@ +using System.Text.Json.Nodes; +using FourFoldAccountManager.Core.Overlay; +using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubCatalogJsonTests +{ + private const string Commit = "0123456789abcdef0123456789abcdef01234567"; + private static readonly string Hash = new('a', 64); + + private static HubPlugin Plugin(string id = "cody.goal-tracker") => new( + id, "Goal tracker", "Goals", "1.2.0", "cody", "Tracks a level goal.", + [new Uri("https://example.com")], false, [new HubCard("Goal", OverlayAddOnScope.Account)], + new Uri("https://github.com/cody/goal-tracker"), Commit, "2026-10-09", 18234, Hash); + + [Fact] + public void AWrittenCatalogReadsBackTheSame() + { + var written = HubCatalogJson.Write(new HubCatalog([Plugin()], [new HubRemoval("x.y", "Broken.")])); + + var read = HubCatalogJson.Parse(written)!; + + var plugin = Assert.Single(read.Plugins); + var expected = Plugin(); + Assert.Equal(expected.Id, plugin.Id); + Assert.Equal(expected.Name, plugin.Name); + Assert.Equal(expected.ShortLabel, plugin.ShortLabel); + Assert.Equal(expected.Version, plugin.Version); + Assert.Equal(expected.Author, plugin.Author); + Assert.Equal(expected.Description, plugin.Description); + Assert.Equal(expected.Sites, plugin.Sites); + Assert.Equal(expected.AnySite, plugin.AnySite); + Assert.Equal(expected.Cards, plugin.Cards); + Assert.Equal(expected.Repository, plugin.Repository); + Assert.Equal(expected.Commit, plugin.Commit); + Assert.Equal(expected.Reviewed, plugin.Reviewed); + Assert.Equal(expected.Size, plugin.Size); + Assert.Equal(expected.Sha256, plugin.Sha256); + Assert.Equal([new HubRemoval("x.y", "Broken.")], read.Removed); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("not json")] + [InlineData("[]")] + [InlineData("{}")] + [InlineData("{\"version\":2,\"plugins\":[]}")] + [InlineData("{\"version\":\"1\"}")] + [InlineData("{\"version\":1,\"plugins\":\"x\"}")] + [InlineData("{\"version\":1,\"removed\":{}}")] + [InlineData("{\"version\":1,\"removed\":\"x\",\"plugins\":[]}")] + public void ACatalogThatCannotBeUsedReadsAsNothing(string? json) => Assert.Null(HubCatalogJson.Parse(json)); + + [Fact] + public void AMissingOrNullListReadsAsEmpty() + { + var read = HubCatalogJson.Parse("{\"version\":1,\"plugins\":null}")!; + + Assert.Empty(read.Plugins); + Assert.Empty(read.Removed); + } + + [Fact] + public void ARawLoneSurrogateReadsAsNothingNotAnException() => + Assert.Null(HubCatalogJson.Parse("{\"version\":1,\"pad\":\"\ud800\"}")); + + [Fact] + public void AnEscapedLoneSurrogateCostsOnlyItsOwnItem() + { + var read = HubCatalogJson.Parse( + "{\"version\":1,\"plugins\":[]," + + "\"removed\":[{\"id\":\"pulled.plugin\",\"reason\":\"\\ud800\"}," + + "{\"id\":\"\\ud800\",\"reason\":\"x\"}," + + "{\"id\":\"other.plugin\",\"reason\":\"Gone.\"}]}")!; + + Assert.Equal([new HubRemoval("pulled.plugin", string.Empty), new HubRemoval("other.plugin", "Gone.")], read.Removed); + } + + [Fact] + public void ACatalogThatStartsWithAByteOrderMarkStillReads() => + Assert.Single(HubCatalogJson.Parse("\uFEFF" + HubCatalogJson.Write(new HubCatalog([Plugin()], [])))!.Plugins); + + [Fact] + public void ASecondEntryWithTheSameIdIsDropped() + { + var catalog = JsonNode.Parse(HubCatalogJson.Write(new HubCatalog([Plugin()], [])))!; + var second = catalog["plugins"]![0]!.DeepClone(); + second["commit"] = new string('b', 40); + catalog["plugins"]!.AsArray().Add(second); + + var read = HubCatalogJson.Parse(catalog.ToJsonString())!; + + Assert.Equal(Commit, Assert.Single(read.Plugins).Commit); + } + + [Fact] + public void AnAddressIsNeverBuiltFromAnUncheckedIdCommitOrRepository() + { + var repository = new Uri("https://github.com/cody/goal-tracker"); + + Assert.Throws(() => HubAddresses.PackageName("../evil", Commit)); + Assert.Throws(() => HubAddresses.Package("cody.goal-tracker", "main")); + Assert.Throws(() => HubAddresses.RepositoryArchive(repository, "main")); + Assert.Throws( + () => HubAddresses.RepositoryArchive(new Uri("https://evil.example/cody/goal-tracker"), Commit)); + Assert.Throws( + () => HubAddresses.RepositoryArchive(new Uri("https://github.com/cody/goal-tracker/tree/main"), Commit)); + Assert.EndsWith($"/cody.goal-tracker-{Commit}.zip", HubAddresses.Package("cody.goal-tracker", Commit).AbsoluteUri); + Assert.Equal( + $"https://codeload.github.com/cody/goal-tracker/zip/{Commit}", + HubAddresses.RepositoryArchive(repository, Commit).AbsoluteUri); + } + + [Fact] + public void AVersionWithATrailingNewlineIsNotAVersion() => + Assert.False(PluginManifestReader.IsVersion("1.2.0\n")); + + [Fact] + public void AnOversizedCatalogReadsAsNothing() => + Assert.Null(HubCatalogJson.Parse( + "{\"version\":1,\"pad\":\"" + new string('x', HubLimits.MaximumCatalogBytes) + "\"}")); + + [Theory] + [InlineData("id", "\"../evil\"")] + [InlineData("id", "\"nul.tools\"")] + [InlineData("id", "7")] + [InlineData("commit", "\"abc\"")] + [InlineData("commit", "\"0123456789ABCDEF0123456789ABCDEF01234567\"")] + [InlineData("commit", "\"../../0123456789abcdef0123456789abcdef0123\"")] + [InlineData("sha256", "\"zz\"")] + [InlineData("size", "0")] + [InlineData("size", "99999999")] + [InlineData("size", "\"1\"")] + [InlineData("repository", "\"https://evil.example/cody/goal-tracker\"")] + [InlineData("repository", "\"https://github.com/cody/goal-tracker/tree/main\"")] + [InlineData("name", "\"Goal\\u202Etracker\"")] + [InlineData("name", "\"\"")] + [InlineData("version", "\"1.2\"")] + [InlineData("sites", "[\"http://example.com\"]")] + [InlineData("sites", "[\"https://localhost\"]")] + [InlineData("sites", "[\"https://a\\u200Db.example\"]")] + [InlineData("cards", "[{\"name\":\"Goal\",\"scope\":\"everywhere\"}]")] + public void ABadEntryIsSkippedAndTheOthersLoad(string property, string value) + { + var catalog = JsonNode.Parse(HubCatalogJson.Write(new HubCatalog([Plugin("good.plugin")], [])))!; + var bad = JsonNode.Parse(HubCatalogJson.Write(new HubCatalog([Plugin("bad.plugin")], [])))!["plugins"]![0]! + .DeepClone(); + bad[property] = JsonNode.Parse(value); + catalog["plugins"]!.AsArray().Insert(0, bad); + + var read = HubCatalogJson.Parse(catalog.ToJsonString()); + + Assert.Equal("good.plugin", Assert.Single(read!.Plugins).Id); + } + + [Fact] + public void APulledPluginIsNeverAlsoListedAndAPullSurvivesABadReason() + { + var catalog = JsonNode.Parse( + HubCatalogJson.Write(new HubCatalog([Plugin("pulled.plugin"), Plugin("kept.plugin")], [])))!; + catalog["removed"] = JsonNode.Parse( + "[{\"id\":\"pulled.plugin\",\"reason\":\"Bad\\u202Ereason\"},{\"id\":\"../x\",\"reason\":\"ignored\"}]"); + + var read = HubCatalogJson.Parse(catalog.ToJsonString())!; + + Assert.Equal("kept.plugin", Assert.Single(read.Plugins).Id); + Assert.Equal([new HubRemoval("pulled.plugin", string.Empty)], read.Removed); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs new file mode 100644 index 0000000..c4c5c5a --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubHttpTests.cs @@ -0,0 +1,76 @@ +using System.Net; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubHttpTests +{ + // No Content-Length, so only counting the bytes as they arrive can stop an oversized download. + private sealed class UnknownLengthContent(byte[] body) : HttpContent + { + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => + stream.WriteAsync(body).AsTask(); + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + } + + private sealed class FixedHandler(byte[] body) : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new UnknownLengthContent(body), + RequestMessage = request + }); + } + + [Fact] + public async Task ADownloadLargerThanTheLimitIsRefused() + { + using var atLimit = new HttpClient(new FixedHandler(new byte[100])); + using var overLimit = new HttpClient(new FixedHandler(new byte[101])); + var uri = new Uri("https://example.com/file"); + + Assert.Equal(100, (await HubHttp.DownloadAsync(atLimit, uri, 100, CancellationToken.None))!.Length); + Assert.Null(await HubHttp.DownloadAsync(overLimit, uri, 100, CancellationToken.None)); + } + + // What a handler that decompresses throws on a corrupt body. + private sealed class CorruptContent : HttpContent + { + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => + throw new InvalidDataException("The archive entry was compressed using an unsupported compression method."); + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + } + + private sealed class CorruptHandler : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new CorruptContent(), + RequestMessage = request + }); + } + + [Fact] + public async Task ACorruptBodyIsRefusedNotThrown() + { + using var http = new HttpClient(new CorruptHandler()); + + Assert.Null(await HubHttp.DownloadAsync( + http, new Uri("https://example.com/file"), 100, CancellationToken.None)); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs new file mode 100644 index 0000000..33c3e99 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubPolicyTests.cs @@ -0,0 +1,119 @@ +using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubPolicyTests +{ + private const string CommitA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string CommitB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + + private static HubPlugin Listed(string id, string commit, bool anySite = false) => new( + id, "Name", "Short", "1.0.0", "author", "", [], anySite, [], + new Uri("https://github.com/author/repo"), commit, "2026-10-09", 100, new string('a', 64)); + + [Fact] + public void APulledOrUnlistedPluginNeverLoads() + { + var catalog = new HubCatalog( + [Listed("kept.plugin", CommitA)], + [new HubRemoval("pulled.plugin", "Sent data away."), new HubRemoval("quiet.plugin", "")]); + HubInstalled[] installed = + [ + new("kept.plugin", CommitA), new("pulled.plugin", CommitA), new("quiet.plugin", CommitA), + new("gone.plugin", CommitA) + ]; + + var loads = HubPolicy.Loads(catalog, installed, id => id); + + Assert.Equal("kept.plugin", Assert.Single(loads).Id); + Assert.Null(HubPolicy.PulledReason(catalog, "kept.plugin")); + Assert.Equal("Sent data away.", HubPolicy.PulledReason(catalog, "pulled.plugin")); + Assert.Equal(HubPolicy.RemovedReason, HubPolicy.PulledReason(catalog, "quiet.plugin")); + Assert.Equal(HubPolicy.UnlistedReason, HubPolicy.PulledReason(catalog, "gone.plugin")); + + // A pull wins even when a hand-built catalog also lists the plugin. + var both = new HubCatalog( + [Listed("both.plugin", CommitA, anySite: true)], [new HubRemoval("both.plugin", "Pulled after listing.")]); + Assert.Equal("Pulled after listing.", HubPolicy.PulledReason(both, "both.plugin")); + Assert.Empty(HubPolicy.Loads(both, [new HubInstalled("both.plugin", CommitA)], id => id)); + } + + [Fact] + public void AnyWebsiteNeedsTheCatalogsClearanceForTheInstalledCommit() + { + var catalog = new HubCatalog( + [ + Listed("cleared.plugin", CommitA, anySite: true), Listed("plain.plugin", CommitA), + Listed("updating.plugin", CommitB, anySite: true) + ], + []); + HubInstalled[] installed = + [new("cleared.plugin", CommitA), new("plain.plugin", CommitA), new("updating.plugin", CommitA)]; + + // The update that was cleared isn't installed yet, so the old code doesn't get the clearance early. + Assert.Equal( + [PluginTrust.Verified, PluginTrust.Standard, PluginTrust.Standard], + HubPolicy.Loads(catalog, installed, id => id).Select(load => load.Trust)); + Assert.Equal("updating.plugin", Assert.Single(HubPolicy.Updates(catalog, installed)).Id); + + // No catalog at all (a first start offline): everything installed still runs, with its declared sites only. + var offline = HubPolicy.Loads(null, installed, id => id); + Assert.Equal(3, offline.Count); + Assert.All(offline, load => Assert.Equal(PluginTrust.Standard, load.Trust)); + Assert.Empty(HubPolicy.Updates(null, installed)); + } + + [Fact] + public void ADevPluginReplacesTheHubPluginOfTheSameId() + { + HubLoad[] loads = + [ + new("cody.goal-tracker", "a", CommitA, PluginTrust.Standard), + new("other.plugin", "b", CommitA, PluginTrust.Standard) + ]; + + Assert.Equal( + "other.plugin", + Assert.Single(HubPolicy.Visible(loads, new HashSet { "cody.goal-tracker" })).Id); + Assert.Equal(2, HubPolicy.Visible(loads, new HashSet()).Count); + } + + [Fact] + public void UninstallingRemovesThePluginsCardsAndIdsFromSettings() + { + var accountId = Guid.NewGuid(); + var settings = PanelSettings.Default with + { + PluginOrder = ["xp-tracker", "cody.goal-tracker", "other.plugin"], + DisabledPlugins = ["cody.goal-tracker"], + OpenPlugin = "cody.goal-tracker", + OverlayCards = + [ + new OverlayCardPlacement(OverlayAddOnKind.Plugin, accountId, true, null) + { + PluginCard = "cody.goal-tracker/goal" + }, + // Another plugin whose id merely starts the same way keeps its card. + new OverlayCardPlacement(OverlayAddOnKind.Plugin, null, true, null) + { + PluginCard = "cody.goal-tracker-two/goal" + }, + new OverlayCardPlacement(OverlayAddOnKind.Xp, accountId, true, null) + ] + }; + + var next = HubPolicy.WithUninstalled(settings, "cody.goal-tracker"); + + Assert.Equal(["xp-tracker", "other.plugin"], next.PluginOrder); + Assert.Empty(next.DisabledPlugins); + Assert.Null(next.OpenPlugin); + Assert.False(next.PluginsSidebarExpanded); + Assert.Equal( + [null, "cody.goal-tracker-two/goal"], + next.OverlayCards.Select(card => card.PluginCard).OrderBy(card => card)); + Assert.Same(next, HubPolicy.WithUninstalled(next, "cody.goal-tracker")); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs new file mode 100644 index 0000000..ba54e2b --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubStoreTests.cs @@ -0,0 +1,351 @@ +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubStoreTests : IDisposable +{ + private const string CommitA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string CommitB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "fourfold-hub-" + Guid.NewGuid().ToString("N")); + private readonly LocalDataPaths _paths; + private readonly HubStore _store; + + public HubStoreTests() + { + Directory.CreateDirectory(_root); + _paths = new LocalDataPaths(Path.Combine(_root, "data")); + _store = new HubStore(_paths); + } + + public void Dispose() => Directory.Delete(_root, recursive: true); + + // A real package for a small plugin, and the catalog record that names it. + private (HubPlugin Plugin, byte[] Package) Build( + string id, string version, string commit, string page = "

v

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

one

"); + await InstallAsync(first, firstPackage); + + // An intact package still has to be the one the catalog records, by hash and by size. + var (second, secondPackage) = Build("cody.goal-tracker", "1.1.0", CommitB, "

two

"); + Assert.NotNull(_store.Stage(second with { Sha256 = new string('0', 64) }, secondPackage, out _)); + Assert.NotNull(_store.Stage(second with { Size = second.Size + 1 }, secondPackage, out _)); + + // A download that was tampered with never gets as far as a folder. + secondPackage[^1] ^= 0xFF; + Assert.NotNull(_store.Stage(second, secondPackage, out _)); + + // A swap that fails halfway puts the old version back. + await Assert.ThrowsAnyAsync( + () => _store.CommitAsync(second, Path.Combine(_root, "missing"), CancellationToken.None)); + + Assert.Equal("

one

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

one

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

two

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

one

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

one

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

two

"); + Assert.Null(_store.Stage(second, secondPackage, out var staging)); + + // A file of the installed version held open, so its folder can't be set aside and the swap never starts. + var held = Path.Combine(_store.FolderOf("cody.goal-tracker"), "index.html"); + using (new FileStream(held, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + await Assert.ThrowsAnyAsync( + () => _store.CommitAsync(second, staging, CancellationToken.None)); + } + + Assert.Equal("

one

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

one

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

one

", File.ReadAllText(Path.Combine(_store.FolderOf("cody.goal-tracker"), "index.html"))); + Assert.Empty(DotFolders()); + } + + [Fact] + public async Task TheSavedCatalogIsReadBack() + { + var plugin = new HubPlugin( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "cody", "", [], false, [], + new Uri("https://github.com/cody/goal-tracker"), CommitA, "2026-10-09", 100, new string('a', 64)); + var catalog = new HubCatalog([plugin], [new HubRemoval("pulled.plugin", "Sent data away.")]); + Assert.Null(_store.LoadCatalog()); + + await _store.SaveCatalogAsync(HubCatalogJson.Write(catalog), CancellationToken.None); + + var loaded = _store.LoadCatalog(); + Assert.NotNull(loaded); + var listed = Assert.Single(loaded.Plugins); + Assert.Equal((plugin.Id, plugin.Commit, plugin.Sha256), (listed.Id, listed.Commit, listed.Sha256)); + Assert.Equal(new HubRemoval("pulled.plugin", "Sent data away."), Assert.Single(loaded.Removed)); + } + + [Fact] + public void WhatTheToolPublishesTheAppInstalls() + { + // If the tool, the catalog's reader and the app ever disagree about a plugin, either nothing installs or an + // installed plugin reads as unlisted. This one has two sites (one an international name with a port), a card + // and any-website clearance, which is everything the catalog carries. + var folder = Path.Combine(_root, "repository"); + Directory.CreateDirectory(folder); + File.WriteAllText( + Path.Combine(folder, "plugin.json"), + """{"id":"cody.goal-tracker","name":"Goal tracker","shortLabel":"Goals","version":"1.0.0","author":"cody","apiVersion":1,"panel":"index.html","anySite":true,"sites":["https://example.com","https://bücher.example:8443"],"cards":[{"id":"goals","name":"Goals","scope":"account"}]}"""); + File.WriteAllText(Path.Combine(folder, "index.html"), "

v

"); + var entry = new HubEntry( + "cody.goal-tracker", new Uri("https://github.com/cody/goal-tracker"), CommitA, "", true); + + var build = HubSubmission.BuildCatalog( + [entry], [], null, item => HubSubmission.Check(item, folder, null, "2026-10-09")); + Assert.Empty(build.Errors); + var (_, package) = Assert.Single(build.Packages); + var published = HubCatalogJson.Parse(HubCatalogJson.Write(build.Catalog!)); + + var listed = Assert.Single(published!.Plugins); + Assert.Equal(2, listed.Sites.Count); + Assert.Contains(listed.Sites, site => site.IdnHost == "xn--bcher-kva.example" && site.Port == 8443); + Assert.True(listed.AnySite); + Assert.Single(listed.Cards); + Assert.Null(_store.Stage(listed, package, out _)); + } + + [Fact] + public async Task AnIdThatIsNotAPluginIdNeverReachesTheDisk() + { + var (plugin, package) = Build("cody.goal-tracker", "1.0.0", CommitA); + await InstallAsync(plugin, package); + var victim = Path.Combine(_paths.DataRoot, "victim"); + Directory.CreateDirectory(victim); + File.WriteAllText(Path.Combine(victim, "keep.txt"), "x"); + + Assert.Throws(() => _store.FolderOf("../victim")); + Assert.Throws(() => _store.FolderOf("..\\victim")); + Assert.Throws(() => _store.IsIntact("../victim")); + await Assert.ThrowsAsync( + () => _store.UninstallAsync("../victim", CancellationToken.None)); + + Assert.True(File.Exists(Path.Combine(victim, "keep.txt"))); + Assert.Equal([new HubInstalled("cody.goal-tracker", CommitA)], _store.LoadInstalled()); + Assert.True(_store.IsIntact("cody.goal-tracker")); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs new file mode 100644 index 0000000..00cd572 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/HubSubmissionTests.cs @@ -0,0 +1,361 @@ +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class HubSubmissionTests : IDisposable +{ + private const string CommitA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string CommitB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + private const string GoodEntry = + "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\"}"; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "fourfold-submit-" + Guid.NewGuid().ToString("N")); + + public HubSubmissionTests() => Directory.CreateDirectory(_root); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + private string Repository( + string id, string version, bool anySite = false, string folder = "", string name = "Goal tracker", + string panel = "index.html", string? extraFile = null) + { + var root = Path.Combine(_root, "repo-" + Guid.NewGuid().ToString("N")); + var plugin = Path.Combine(root, folder); + Directory.CreateDirectory(plugin); + File.WriteAllText( + Path.Combine(plugin, "plugin.json"), + $$"""{"id":"{{id}}","name":"{{name}}","shortLabel":"Goals","version":"{{version}}","author":"cody","apiVersion":1,"panel":"{{panel}}","anySite":{{(anySite ? "true" : "false")}}}"""); + File.WriteAllText(Path.Combine(plugin, panel), "

hello

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

extra

"); + } + + return root; + } + + private static HubEntry Entry(string commit = CommitA, string path = "", bool anySite = false) => + new("cody.goal-tracker", new Uri("https://github.com/cody/goal-tracker"), commit, path, anySite); + + [Theory] + [InlineData("Not An Id.json", GoodEntry)] + [InlineData("cody.goal-tracker.txt", GoodEntry)] + [InlineData("cody.goal-tracker.json", "not json")] + [InlineData("cody.goal-tracker.json", "[]")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://gitlab.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker.git\",\"commit\":\"" + CommitA + "\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"main\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"aaaaaaa\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":\"../other\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":\"/abs\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"anySite\":\"yes\"}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":5}")] + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":null}")] + // The same property twice reads as its last value, while a reviewer of the raw file sees the first. + [InlineData("cody.goal-tracker.json", "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"anySite\":false,\"anySite\":true}")] + // A lone surrogate escape: JSON the reader can't hand back as text, which once crashed the tool. + [InlineData("cody.goal-tracker.json", "{\"repository\":\"\\ud800\",\"commit\":\"" + CommitA + "\"}")] + public void AnEntryThatBreaksARuleIsRejected(string fileName, string json) + { + var (entry, error) = HubEntryReader.Read(fileName, json); + + Assert.Null(entry); + Assert.False(string.IsNullOrEmpty(error)); + } + + [Fact] + public void AGoodEntryIsRead() + { + var (entry, error) = HubEntryReader.Read( + "cody.goal-tracker.json", + "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + + "\",\"path\":\"samples/goal-tracker\",\"anySite\":true}"); + + Assert.Null(error); + Assert.Equal(Entry(path: "samples/goal-tracker", anySite: true), entry); + } + + [Fact] + public void ASubmissionMustMatchItsEntry() + { + // The plugin.json names another plugin than the file is named for. + Assert.NotNull(HubSubmission.Check(Entry(), Repository("other.plugin", "1.0.0"), null, "2026-10-09").Error); + // The entry clears any website, but the plugin never asked for it. + Assert.NotNull( + HubSubmission.Check(Entry(anySite: true), Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09").Error); + // The folder the entry names isn't in the repository. + Assert.NotNull( + HubSubmission.Check(Entry(path: "plugin"), Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09").Error); + + var good = HubSubmission.Check( + Entry(path: "plugin", anySite: true), Repository("cody.goal-tracker", "1.0.0", anySite: true, folder: "plugin"), + null, "2026-10-09"); + + Assert.Null(good.Error); + Assert.True(good.Plugin!.AnySite); + Assert.Equal("2026-10-09", good.Plugin.Reviewed); + Assert.True(PluginPackage.Matches(good.Package!, good.Plugin.Size, good.Plugin.Sha256)); + } + + [Fact] + public void AnUpdateMustRaiseTheVersion() + { + var listed = HubSubmission.Check(Entry(), Repository("cody.goal-tracker", "1.2.0"), null, "2026-10-01").Plugin!; + var current = new HubCatalog([listed], []); + + Assert.NotNull( + HubSubmission.Check(Entry(CommitB), Repository("cody.goal-tracker", "1.2.0"), current, "2026-10-09").Error); + Assert.NotNull( + HubSubmission.Check(Entry(CommitB), Repository("cody.goal-tracker", "1.1.9"), current, "2026-10-09").Error); + Assert.Null( + HubSubmission.Check(Entry(CommitB), Repository("cody.goal-tracker", "1.10.0"), current, "2026-10-09").Error); + } + + [Fact] + public void AnUnchangedEntryKeepsItsRecordWithoutBeingFetchedAgain() + { + var listed = HubSubmission.Check(Entry(), Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-01").Plugin!; + + // The author's repository may be gone by now; an unchanged entry must not need it. + var build = HubSubmission.BuildCatalog( + [Entry()], [], new HubCatalog([listed], []), _ => throw new InvalidOperationException("fetched again")); + + Assert.Empty(build.Errors); + Assert.Empty(build.Packages); + Assert.Same(listed, Assert.Single(build.Catalog!.Plugins)); + } + + [Fact] + public void APluginCannotBeBothListedAndRemoved() + { + var build = HubSubmission.BuildCatalog( + [Entry()], [new HubRemoval("cody.goal-tracker", "Pulled.")], null, + entry => HubSubmission.Check(entry, Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09")); + + Assert.Null(build.Catalog); + Assert.Single(build.Errors); + } + + [Fact] + public void AnEntryPathPastTwoHundredCharactersIsRejected() + { + var (entry, error) = HubEntryReader.Read( + "cody.goal-tracker.json", + "{\"repository\":\"https://github.com/cody/goal-tracker\",\"commit\":\"" + CommitA + "\",\"path\":\"" + + new string('a', 201) + "\"}"); + + Assert.Null(entry); + Assert.False(string.IsNullOrEmpty(error)); + } + + [Theory] + [InlineData("not json")] + [InlineData("{}")] + [InlineData("[{\"id\":\"cody.goal-tracker\"}]")] + [InlineData("[{\"id\":\"cody.goal-tracker\",\"reason\":\"a\"},{\"id\":\"cody.goal-tracker\",\"reason\":\"b\"}]")] + [InlineData("[{\"id\":\"cody.goal-tracker\",\"reason\":\"a\",\"reason\":\"b\"}]")] + [InlineData("[{\"id\":\"cody.goal-tracker\",\"reason\":\"\\ud800\"}]")] + [InlineData("[{\"id\":\"\\ud800\",\"reason\":\"a\"}]")] + public void ARemovedListThatBreaksARuleIsRejected(string json) + { + var (removed, error) = HubEntryReader.ReadRemoved(json); + + Assert.Null(removed); + Assert.False(string.IsNullOrEmpty(error)); + } + + [Fact] + public void AGoodRemovedListIsRead() + { + var (removed, error) = HubEntryReader.ReadRemoved("[{\"id\":\"cody.goal-tracker\",\"reason\":\"Pulled.\"}]"); + + Assert.Null(error); + Assert.Equal(new HubRemoval("cody.goal-tracker", "Pulled."), Assert.Single(removed!)); + } + + [Fact] + public void AnEntryClearsAnyWebsiteOnlyWhenItSaysSo() + { + // The plugin's plugin.json asks for any website, but the maintainers' entry doesn't clear it. + var plugin = HubSubmission.Check( + Entry(anySite: false), Repository("cody.goal-tracker", "1.0.0", anySite: true), null, "2026-10-09").Plugin!; + + Assert.False(plugin.AnySite); + } + + [Fact] + public void AVersionTooLargeToCompareIsRefused() + { + Assert.NotNull( + HubSubmission.Check(Entry(), Repository("cody.goal-tracker", "99999999999.0.0"), null, "2026-10-09").Error); + } + + [Fact] + public void APluginThatWouldNotInstallFromItsPackageIsRefused() + { + // The package leaves dot-files out, so this plugin would have no panel once a user installed it. + var result = HubSubmission.Check( + Entry(), Repository("cody.goal-tracker", "1.0.0", panel: ".index.html"), null, "2026-10-09"); + + Assert.NotNull(result.Error); + Assert.Null(result.Package); + } + + [Fact] + public void ARevokedClearanceIsCheckedAgainNotReused() + { + var cleared = HubSubmission.Check( + Entry(anySite: true), Repository("cody.goal-tracker", "1.0.0", anySite: true), null, "2026-10-01").Plugin!; + var current = new HubCatalog([cleared], []); + var checkedAgain = false; + + // Same commit, but the entry no longer clears any website: the listed record must not be kept as it is. + var build = HubSubmission.BuildCatalog( + [Entry(anySite: false)], [], current, + entry => + { + checkedAgain = true; + return HubSubmission.Check( + entry, Repository("cody.goal-tracker", "1.0.0", anySite: true), current, "2026-10-09"); + }); + + Assert.True(checkedAgain); + Assert.False(Assert.Single(build.Catalog!.Plugins).AnySite); + } + + [Fact] + public void AChangedRepositoryIsCheckedAgainNotReused() + { + var listed = HubSubmission.Check(Entry(), Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-01").Plugin!; + var moved = Entry() with { Repository = new Uri("https://github.com/someone-else/goal-tracker") }; + var checkedAgain = false; + + var build = HubSubmission.BuildCatalog( + [moved], [], new HubCatalog([listed], []), + entry => + { + checkedAgain = true; + return HubSubmission.Check(entry, Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09"); + }); + + Assert.True(checkedAgain); + Assert.Equal(moved.Repository, Assert.Single(build.Catalog!.Plugins).Repository); + } + + [Fact] + public void NoPackagesAreOfferedWhenThereIsNoCatalog() + { + var other = Entry() with { Id = "cody.other" }; + + var build = HubSubmission.BuildCatalog( + [Entry(), other], [], null, + entry => entry.Id == "cody.other" + ? new HubCheckResult("Refused.", null, null) + : HubSubmission.Check(entry, Repository("cody.goal-tracker", "1.0.0"), null, "2026-10-09")); + + Assert.Null(build.Catalog); + Assert.Empty(build.Packages); + Assert.Single(build.Errors); + } + + [Fact] + public void ACatalogTheAppWouldRefuseIsNotBuilt() + { + // The app reads at most 1 MB of catalog, so a larger one would leave the hub dead for every user. + var removals = Enumerable.Range(0, 6000) + .Select(number => new HubRemoval($"cody.pulled-{number}", new string('x', 200))) + .ToArray(); + + var build = HubSubmission.BuildCatalog([], removals, null, _ => throw new InvalidOperationException("no entries")); + + Assert.Null(build.Catalog); + Assert.Single(build.Errors); + } + + [Fact] + public void ACatalogWithTooManyPluginsIsNotBuilt() + { + // Past 2,000 plugins the app's reader silently drops the rest. 2,001 small ones are still under the size limit, + // so only the count rule stops them. Every entry is listed already at the same commit and repository, so none is + // checked or downloaded. + var repository = new Uri("https://github.com/cody/goal-tracker"); + var entries = Enumerable.Range(0, HubLimits.MaximumCatalogPlugins + 1) + .Select(number => new HubEntry($"cody.plugin-{number}", repository, CommitA, "", false)) + .ToArray(); + var listed = entries + .Select(entry => new HubPlugin( + entry.Id, "Plugin", "Plug", "1.0.0", "cody", "", [], false, [], repository, CommitA, "2026-10-01", 1000, + new string('0', 64))) + .ToArray(); + + var build = HubSubmission.BuildCatalog( + entries, [], new HubCatalog(listed, []), _ => throw new InvalidOperationException("checked")); + + Assert.Null(build.Catalog); + Assert.Single(build.Errors); + } + + [Fact] + public void TheSummaryCannotBeSteeredByTheSubmission() + { + // A name that is a Markdown link, and a file name with a backtick (legal on Windows and Linux). + var result = HubSubmission.Check( + Entry(), Repository("cody.goal-tracker", "1.0.0", name: "[x](http://e)", extraFile: "a`b.html"), null, + "2026-10-09"); + Assert.Null(result.Error); + + // A site whose converted name holds "<": a stranger's plugin.json can't get one through the manifest reader, but the + // summary must not depend on that. + var steered = result.Plugin! with { Sites = [new Uri("https://a\uFE64b.example.com")] }; + var summary = HubSubmission.Summary( + "# [evil](http://e).json", Entry(), null, steered, result.Package, null); + + Assert.DoesNotMatch(@"(? Directory.CreateDirectory(_root); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + private static byte[] Zip(params (string Name, byte[] Content)[] entries) => Zip(null, entries); + + private static byte[] Zip(Action? configure, params (string Name, byte[] Content)[] entries) + { + using var buffer = new MemoryStream(); + using (var archive = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (var (name, content) in entries) + { + var entry = archive.CreateEntry(name); + configure?.Invoke(entry); + using var stream = entry.Open(); + stream.Write(content); + } + } + + return buffer.ToArray(); + } + + [Fact] + public void APackageThatDoesNotMatchTheCatalogIsRefused() + { + var package = Zip(("plugin.json", "{}"u8.ToArray())); + var hash = PluginPackage.Sha256(package); + + Assert.True(PluginPackage.Matches(package, package.Length, hash)); + Assert.False(PluginPackage.Matches(package, package.Length + 1, hash)); + Assert.False(PluginPackage.Matches(package, package.Length, new string('0', 64))); + Assert.False(PluginPackage.Matches([.. package, 0], package.Length, hash)); + } + + [Theory] + [InlineData("../evil.txt")] + [InlineData("a/../../evil.txt")] + [InlineData("/evil.txt")] + [InlineData("C:/evil.txt")] + [InlineData("./evil.txt")] + public void AnEntryThatEscapesTheFolderIsRefused(string name) + { + var target = Path.Combine(_root, "inner", "plugin"); + + Assert.Throws( + () => PluginPackage.Extract(Zip((name, new byte[] { 1 })), target)); + + Assert.Empty(Directory.EnumerateFiles(_root, "evil.txt", SearchOption.AllDirectories)); + } + + [Fact] + public void TooManyFilesOrTooMuchDataIsRefused() + { + var many = Enumerable.Range(0, HubLimits.MaximumPackageFiles + 1) + .Select(index => ($"file{index}.txt", new byte[] { 1 })) + .ToArray(); + Assert.Throws(() => PluginPackage.Extract(Zip(many), Path.Combine(_root, "many"))); + + // Zeros compress to almost nothing, so the package is small and only the unpacked size gives it away. + var large = Zip(("big.txt", new byte[HubLimits.MaximumUnpackedBytes + 1])); + Assert.True(large.Length < 100_000); + Assert.Throws(() => PluginPackage.Extract(large, Path.Combine(_root, "large"))); + + // Each entry is under the limit; only the total is over it. + var two = Zip(("a.txt", new byte[3 * 1024 * 1024]), ("b.txt", new byte[3 * 1024 * 1024])); + Assert.Throws(() => PluginPackage.Extract(two, Path.Combine(_root, "two"))); + } + + [Fact] + public void AnEntryNestedTooDeeplyIsRefused() + { + // Deleting a tree thousands of levels deep overflows the stack, so a deep entry must never be unpacked. + var name = string.Join('/', Enumerable.Repeat("a", 100)) + "/f.txt"; + var target = Path.Combine(_root, "deep"); + + Assert.Throws(() => PluginPackage.Extract(Zip((name, new byte[] { 1 })), target)); + + Assert.Empty(Directory.EnumerateFileSystemEntries(target)); + } + + [Fact] + public void AFileWhereAFolderAlreadyIsIsRefused() + { + using var package = new MemoryStream(Zip(("a/b.txt", new byte[] { 1 }), ("a", new byte[] { 1 }))); + + var exception = Assert.ThrowsAny( + () => SafeArchive.Extract( + package, Path.Combine(_root, "clash"), 500, HubLimits.MaximumUnpackedBytes, stripTopFolder: false)); + + Assert.IsNotType(exception); + } + + [Fact] + public void AFolderThatAlreadyHasFilesIsNotUnpackedInto() + { + var target = Path.Combine(_root, "taken"); + Directory.CreateDirectory(target); + File.WriteAllText(Path.Combine(target, "mine.txt"), "mine"); + + Assert.Throws(() => PluginPackage.Extract(Zip(("plugin.json", "{}"u8.ToArray())), target)); + + Assert.Equal(["mine.txt"], Directory.EnumerateFileSystemEntries(target).Select(path => Path.GetFileName(path))); + } + + [Fact] + public void LinksAndOddNamesAreSkippedOnlyWhenAsked() + { + var package = Zip( + entry => + { + if (entry.FullName == "link.txt") + { + entry.ExternalAttributes = unchecked((int)0xA1FF0000); + } + }, + ("link.txt", "target"u8.ToArray()), + ("a:b.txt", new byte[] { 1 }), + ("logs\\c.log", new byte[] { 1 }), + ("ok.txt", new byte[] { 1 })); + var skipped = Path.Combine(_root, "skipped"); + + using (var stream = new MemoryStream(package)) + { + SafeArchive.Extract( + stream, skipped, 500, HubLimits.MaximumUnpackedBytes, stripTopFolder: false, skipLinksAndOddNames: true); + } + + Assert.Equal(["ok.txt"], Directory.EnumerateFileSystemEntries(skipped).Select(path => Path.GetFileName(path))); + + using var strict = new MemoryStream(package); + Assert.Throws( + () => SafeArchive.Extract( + strict, Path.Combine(_root, "strict"), 500, HubLimits.MaximumUnpackedBytes, stripTopFolder: false)); + } + + [Fact] + public void APackageWithAFileFourFoldDoesNotServeIsRefusedBeforeAnythingIsWritten() + { + var package = Zip(("plugin.json", "{}"u8.ToArray()), ("run.exe", new byte[] { 1 })); + var target = Path.Combine(_root, "exe"); + + Assert.Throws(() => PluginPackage.Extract(package, target)); + + Assert.False(Directory.Exists(target)); + } + + [Fact] + public void FileNamesWindowsCannotUnpackAreFoundWhenBuilding() + { + Assert.Null(PluginPackage.UnpackableReason(["plugin.json", "index.html", "img/a.png", "img/b.png"])); + Assert.NotNull(PluginPackage.UnpackableReason(["a:b.png"])); + Assert.NotNull(PluginPackage.UnpackableReason(["what?.png"])); + Assert.NotNull(PluginPackage.UnpackableReason(["trail.png."])); + Assert.NotNull(PluginPackage.UnpackableReason(["dir /a.png"])); + Assert.NotNull(PluginPackage.UnpackableReason(["A.png", "a.png"])); + Assert.NotNull(PluginPackage.UnpackableReason(["aux.js"])); + Assert.NotNull(PluginPackage.UnpackableReason(["nul"])); + // Only the device names themselves, not names that start with the same letters. + Assert.Null(PluginPackage.UnpackableReason(["console.js", "auxiliary.png", "com10.png"])); + } + + [Fact] + public void ALinkInAnArchiveIsRefused() + { + // A Unix symbolic link: file type 0xA in the mode bits a zip keeps in the high half of this field. + var package = Zip( + entry => entry.ExternalAttributes = unchecked((int)0xA1FF0000), ("link.txt", "target"u8.ToArray())); + + Assert.Throws(() => PluginPackage.Extract(package, Path.Combine(_root, "link"))); + } + + [Fact] + public void BuildLeavesOutFilesFourFoldDoesNotServeAndIsRepeatable() + { + var plugin = Path.Combine(_root, "plugin"); + Directory.CreateDirectory(Path.Combine(plugin, ".github")); + Directory.CreateDirectory(Path.Combine(plugin, "img")); + foreach (var name in new[] + { + "plugin.json", "index.html", "README.md", ".gitignore", "tool.exe", ".github/ci.yml", "img/a.png" + }) + { + File.WriteAllText(Path.Combine(plugin, name), name); + } + + var first = PluginPackage.Build(plugin); + var second = PluginPackage.Build(plugin); + + using var archive = new ZipArchive(new MemoryStream(first)); + Assert.Equal(["img/a.png", "index.html", "plugin.json"], archive.Entries.Select(entry => entry.FullName)); + Assert.Equal(first, second); + } +} diff --git a/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs b/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs index dde8b50..8b244c6 100644 --- a/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs +++ b/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs @@ -19,6 +19,9 @@ public LocalDataPaths(string? root = null) DevPluginsRoot = Path.Combine(DataRoot, "dev-plugins"); PluginDataRoot = Path.Combine(DataRoot, "plugin-data"); PluginWebViewUserDataRoot = Path.Combine(DataRoot, "PluginWebView2"); + HubPluginsRoot = Path.Combine(DataRoot, "plugins"); + HubCatalogFilePath = Path.Combine(DataRoot, "hub", "catalog.json"); + HubInstalledFilePath = Path.Combine(DataRoot, "hub", "installed.json"); } public string DataRoot { get; } @@ -41,4 +44,13 @@ public LocalDataPaths(string? root = null) // The plugin browser's own data folder, separate from the game profiles in WebViewUserDataRoot. public string PluginWebViewUserDataRoot { get; } + + // Plugins installed from the hub, one folder per plugin id. + public string HubPluginsRoot { get; } + + // The last good copy of the hub's catalog, so installed plugins work offline. + public string HubCatalogFilePath { get; } + + // Which hub plugins are installed, and at which reviewed commit. + public string HubInstalledFilePath { get; } } diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs new file mode 100644 index 0000000..e17b8a5 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubAddresses.cs @@ -0,0 +1,27 @@ +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// Where the hub lives. Every address is built here from fixed parts plus an id, a commit and (for an archive) a +// repository, and all three are checked here, the last stop before a request: a bad one throws ArgumentException. +// Nothing is ever taken from the catalog as a URL. +public static class HubAddresses +{ + public const string Repository = "CodySimonds65/FourFoldAccountManager-plugin-hub"; + + private const string ReleaseBase = "https://github.com/" + Repository + "/releases/download/catalog/"; + + public static Uri Catalog { get; } = new(ReleaseBase + "catalog.json"); + + public static string PackageName(string id, string commit) => + PluginManifestReader.IsValidId(id) && HubCatalogJson.IsCommit(commit) + ? $"{id}-{commit}.zip" + : throw new ArgumentException("The id must be a valid plugin id and the commit a full lowercase commit id."); + + public static Uri Package(string id, string commit) => new(ReleaseBase + PackageName(id, commit)); + + // GitHub's zip of a repository at one commit. repository is https://github.com//. + public static Uri RepositoryArchive(Uri repository, string commit) => + HubCatalogJson.TryParseRepository(repository.AbsoluteUri, out _) && HubCatalogJson.IsCommit(commit) + ? new Uri($"https://codeload.github.com{repository.AbsolutePath}/zip/{commit}") + : throw new ArgumentException( + "The repository must be https://github.com// and the commit a full lowercase commit id."); +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalog.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalog.cs new file mode 100644 index 0000000..76aa9fe --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalog.cs @@ -0,0 +1,29 @@ +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +public sealed record HubCard(string Name, OverlayAddOnScope Scope); + +// One listed plugin: what the hub page shows, and the reviewed commit, size and hash of its package. +public sealed record HubPlugin( + string Id, + string Name, + string ShortLabel, + string Version, + string Author, + string Description, + IReadOnlyList Sites, + // Already the combined answer: the maintainers cleared it and the plugin's plugin.json asks for it. + bool AnySite, + IReadOnlyList Cards, + Uri Repository, + string Commit, + // yyyy-MM-dd, or empty when the catalog's value couldn't be read. + string Reviewed, + long Size, + string Sha256); + +// A plugin the maintainers pulled, and why. +public sealed record HubRemoval(string Id, string Reason); + +public sealed record HubCatalog(IReadOnlyList Plugins, IReadOnlyList Removed); diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs new file mode 100644 index 0000000..ee2cfa2 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubCatalogJson.cs @@ -0,0 +1,253 @@ +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// Reads and writes the hub's catalog.json. Reading never throws: the file comes from the network, so an entry that +// breaks a rule is skipped, and a catalog that can't be used at all reads as null. +public static partial class HubCatalogJson +{ + public const int Version = 1; + + [GeneratedRegex(@"^[0-9a-f]{40}\z")] + private static partial Regex CommitRegex(); + + [GeneratedRegex(@"^[0-9a-f]{64}\z")] + private static partial Regex Sha256Regex(); + + [GeneratedRegex(@"^https://github\.com/[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}\z")] + private static partial Regex RepositoryRegex(); + + // A full commit id in lowercase: never a branch, a tag or a short id. + public static bool IsCommit([NotNullWhen(true)] string? value) => value is not null && CommitRegex().IsMatch(value); + + public static bool IsSha256([NotNullWhen(true)] string? value) => value is not null && Sha256Regex().IsMatch(value); + + // Exactly https://github.com//. + public static bool TryParseRepository(string? value, out Uri repository) + { + repository = null!; + if (value is null || !RepositoryRegex().IsMatch(value) || + value.EndsWith("/.", StringComparison.Ordinal) || value.EndsWith("/..", StringComparison.Ordinal) || + value.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + repository = new Uri(value); + return true; + } + + public static HubCatalog? Parse(string? json) + { + if (json is null || json.Length > HubLimits.MaximumCatalogBytes) + { + return null; + } + + try + { + // A byte order mark is no part of the JSON, and some editors add one. + using var document = JsonDocument.Parse(json.TrimStart('\uFEFF')); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("version", out var version) || version.ValueKind != JsonValueKind.Number || + !version.TryGetInt32(out var number) || number != Version || + !TryGetList(root, "removed", out var removedElement) || + !TryGetList(root, "plugins", out var pluginsElement)) + { + return null; + } + + // Sets, not lists: a catalog can hold tens of thousands of ids, and a list scan per id takes seconds. + var removed = new List(); + var removedIds = new HashSet(StringComparer.Ordinal); + if (removedElement.ValueKind == JsonValueKind.Array) + { + foreach (var item in removedElement.EnumerateArray()) + { + if (TryReadRemoval(item) is { } removal && removedIds.Add(removal.Id)) + { + removed.Add(removal); + } + } + } + + var plugins = new List(); + var pluginIds = new HashSet(StringComparer.Ordinal); + if (pluginsElement.ValueKind == JsonValueKind.Array) + { + foreach (var item in pluginsElement.EnumerateArray().Take(HubLimits.MaximumCatalogPlugins)) + { + if (TryReadPlugin(item) is { } plugin && !removedIds.Contains(plugin.Id) && pluginIds.Add(plugin.Id)) + { + plugins.Add(plugin); + } + } + } + + return new HubCatalog(Array.AsReadOnly(plugins.ToArray()), Array.AsReadOnly(removed.ToArray())); + } + catch (Exception exception) when (exception is JsonException or InvalidOperationException or ArgumentException) + { + return null; + } + } + + // A missing or null list reads as an empty one. Any other type makes the catalog unusable: reading it as empty + // would drop the pulls, and the app would replace a good cached copy that still carries them. + private static bool TryGetList(JsonElement root, string name, out JsonElement list) + { + list = default; + return !root.TryGetProperty(name, out list) || list.ValueKind is JsonValueKind.Null or JsonValueKind.Array; + } + + private static HubRemoval? TryReadRemoval(JsonElement item) + { + string id; + try + { + if (item.ValueKind != JsonValueKind.Object || + PluginManifestReader.Text(item, "id") is not { } text || !PluginManifestReader.IsValidId(text)) + { + return null; + } + + id = text; + } + catch (Exception exception) when (exception is InvalidOperationException or ArgumentException) + { + return null; + } + + // A pull must never be lost over its wording: a reason that can't be read or shown is dropped, not the pull. + try + { + var reason = PluginManifestReader.Text(item, "reason") ?? string.Empty; + return new HubRemoval( + id, reason.Length > 200 || PluginText.HasUnsafeCharacter(reason) ? string.Empty : reason); + } + catch (Exception exception) when (exception is InvalidOperationException or ArgumentException) + { + return new HubRemoval(id, string.Empty); + } + } + + public static string Write(HubCatalog catalog) => JsonSerializer.Serialize( + new + { + version = Version, + plugins = catalog.Plugins.Select(plugin => new + { + id = plugin.Id, + name = plugin.Name, + shortLabel = plugin.ShortLabel, + version = plugin.Version, + author = plugin.Author, + description = plugin.Description, + sites = plugin.Sites.Select(site => site.GetLeftPart(UriPartial.Authority)), + anySite = plugin.AnySite, + cards = plugin.Cards.Select(card => new + { + name = card.Name, + scope = card.Scope == OverlayAddOnScope.Account ? "account" : "global" + }), + repository = plugin.Repository.AbsoluteUri, + commit = plugin.Commit, + reviewed = plugin.Reviewed, + size = plugin.Size, + sha256 = plugin.Sha256 + }), + removed = catalog.Removed.Select(removal => new { id = removal.Id, reason = removal.Reason }) + }, + AtomicJsonFile.Options); + + // An entry that breaks a rule is skipped, so an entry this version of the app can't read is skipped too, and an + // installed plugin whose entry is skipped counts as no longer on the hub and is switched off on that machine. A + // rule here may therefore only be loosened once users have the version that accepts the looser entries. + private static HubPlugin? TryReadPlugin(JsonElement item) + { + try + { + if (item.ValueKind != JsonValueKind.Object) + { + return null; + } + + var id = PluginManifestReader.Text(item, "id"); + var version = PluginManifestReader.Text(item, "version"); + var commit = PluginManifestReader.Text(item, "commit"); + var sha256 = PluginManifestReader.Text(item, "sha256"); + var description = PluginManifestReader.Text(item, "description") ?? string.Empty; + if (!PluginManifestReader.IsValidId(id) || !PluginManifestReader.IsVersion(version) || + !PluginManifestReader.InRange(PluginManifestReader.Text(item, "name"), 1, 40, out var name) || + !PluginManifestReader.InRange(PluginManifestReader.Text(item, "shortLabel"), 1, 8, out var shortLabel) || + !PluginManifestReader.InRange(PluginManifestReader.Text(item, "author"), 1, 40, out var author) || + description.Length > 200 || + new[] { name, shortLabel, author, description }.Any(PluginText.HasUnsafeCharacter) || + !PluginManifestReader.TryReadSites(item, out var sites, out _) || + !TryParseRepository(PluginManifestReader.Text(item, "repository"), out var repository) || + !IsCommit(commit) || !IsSha256(sha256) || + !item.TryGetProperty("size", out var sizeElement) || sizeElement.ValueKind != JsonValueKind.Number || + !sizeElement.TryGetInt64(out var size) || size < 1 || size > HubLimits.MaximumPackageBytes || + !TryReadCards(item, out var cards)) + { + return null; + } + + var reviewed = PluginManifestReader.Text(item, "reviewed"); + return new HubPlugin( + id, name, shortLabel, version, author, description, sites, + item.TryGetProperty("anySite", out var anySite) && anySite.ValueKind == JsonValueKind.True, + cards, repository, commit, + DateOnly.TryParseExact(reviewed, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _) + ? reviewed! + : string.Empty, + size, sha256); + } + catch (Exception) + { + // A host name Uri refuses, say. One bad entry never costs the rest of the catalog. + return null; + } + } + + private static bool TryReadCards(JsonElement item, out IReadOnlyList cards) + { + cards = []; + if (!item.TryGetProperty("cards", out var element) || element.ValueKind == JsonValueKind.Null) + { + return true; + } + + if (element.ValueKind != JsonValueKind.Array || element.GetArrayLength() > 6) + { + return false; + } + + var result = new List(); + foreach (var card in element.EnumerateArray()) + { + if (card.ValueKind != JsonValueKind.Object) + { + return false; + } + + var scope = PluginManifestReader.Text(card, "scope"); + if (!PluginManifestReader.InRange(PluginManifestReader.Text(card, "name"), 1, 24, out var name) || + PluginText.HasUnsafeCharacter(name) || scope is not ("account" or "global")) + { + return false; + } + + result.Add(new HubCard(name, scope == "account" ? OverlayAddOnScope.Account : OverlayAddOnScope.Global)); + } + + cards = Array.AsReadOnly(result.ToArray()); + return true; + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubEntry.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubEntry.cs new file mode 100644 index 0000000..aa1546d --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubEntry.cs @@ -0,0 +1,109 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// One file in the hub repository's plugins folder: which repository and commit to list, and whether the maintainers +// cleared the plugin for any website. The plugin's id is the file's name. +public sealed record HubEntry(string Id, Uri Repository, string Commit, string Path, bool AnySite); + +public static partial class HubEntryReader +{ + [GeneratedRegex(@"^[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*\z")] + private static partial Regex PathRegex(); + + // A property written twice would read as its last value while a reviewer of the raw file sees the first, so a + // duplicate makes the file invalid. + private static readonly JsonDocumentOptions Options = new() { AllowDuplicateProperties = false }; + + // fileName is the entry's file name, ".json". Every rejection carries a reason an author can act on. + public static (HubEntry? Entry, string? Error) Read(string fileName, string json) + { + var id = fileName.EndsWith(".json", StringComparison.Ordinal) ? fileName[..^5] : null; + if (!PluginManifestReader.IsValidId(id)) + { + return (null, "The file must be named .json, for example cody.goal-tracker.json."); + } + + try + { + using var document = JsonDocument.Parse(json, Options); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return (null, "The entry must be a JSON object."); + } + + if (!HubCatalogJson.TryParseRepository(PluginManifestReader.Text(root, "repository"), out var repository)) + { + return (null, "\"repository\" must look like https://github.com/owner/repo."); + } + + var commit = PluginManifestReader.Text(root, "commit"); + if (!HubCatalogJson.IsCommit(commit)) + { + return (null, "\"commit\" must be a full 40-character commit in lowercase, not a branch or a tag."); + } + + const string PathError = + "\"path\" must be a folder inside the repository, written with forward slashes (at most 200 characters)."; + var path = PluginManifestReader.Text(root, "path") ?? string.Empty; + if (root.TryGetProperty("path", out var pathElement) && pathElement.ValueKind != JsonValueKind.String) + { + return (null, PathError); + } + + if (path.Length > 0 && + (path.Length > 200 || !PathRegex().IsMatch(path) || path.Split('/').Any(part => part is "." or ".."))) + { + return (null, PathError); + } + + var hasAnySite = root.TryGetProperty("anySite", out var anySite); + if (hasAnySite && anySite.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) + { + return (null, "\"anySite\" must be true or false."); + } + + return (new HubEntry(id, repository, commit, path, hasAnySite && anySite.ValueKind == JsonValueKind.True), null); + } + catch (Exception exception) when (exception is JsonException or InvalidOperationException or ArgumentException) + { + // InvalidOperationException: text with a lone surrogate escape (\ud800) is JSON the reader can't hand back. + return (null, "The entry isn't valid JSON."); + } + } + + public static (IReadOnlyList? Removed, string? Error) ReadRemoved(string json) + { + try + { + using var document = JsonDocument.Parse(json, Options); + if (document.RootElement.ValueKind != JsonValueKind.Array) + { + return (null, "removed.json must be a list."); + } + + var result = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + var isObject = item.ValueKind == JsonValueKind.Object; + var id = isObject ? PluginManifestReader.Text(item, "id") : null; + var reason = isObject ? PluginManifestReader.Text(item, "reason") : null; + if (!PluginManifestReader.IsValidId(id) || reason is null || reason.Length is 0 or > 200 || + PluginText.HasUnsafeCharacter(reason) || result.Any(other => other.Id == id)) + { + return (null, "Each removed.json line needs a plugin \"id\" (once) and a \"reason\" of 1 to 200 characters."); + } + + result.Add(new HubRemoval(id, reason)); + } + + return (result, null); + } + catch (Exception exception) when (exception is JsonException or InvalidOperationException or ArgumentException) + { + return (null, "removed.json isn't valid JSON."); + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs new file mode 100644 index 0000000..a17ea3e --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubHttp.cs @@ -0,0 +1,43 @@ +namespace FourFoldAccountManager.Core.Plugins.Hub; + +public static class HubHttp +{ + // Downloads a file of at most maximumBytes over https. Null when the request fails, ends anywhere but https, or + // the file is larger; a cancelled or corrupt download also gives null. The bytes are counted as they arrive, since + // a response needn't say how long it is. + public static async Task DownloadAsync( + HttpClient http, Uri uri, long maximumBytes, CancellationToken cancellationToken) + { + try + { + using var response = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + if (!response.IsSuccessStatusCode || + response.RequestMessage?.RequestUri?.Scheme != Uri.UriSchemeHttps || + response.Content.Headers.ContentLength > maximumBytes) + { + return null; + } + + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await stream.ReadAsync(chunk, cancellationToken)) > 0) + { + if (buffer.Length + read > maximumBytes) + { + return null; + } + + buffer.Write(chunk, 0, read); + } + + return buffer.ToArray(); + } + catch (Exception exception) when ( + exception is HttpRequestException or IOException or InvalidDataException or OperationCanceledException) + { + return null; + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubLimits.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubLimits.cs new file mode 100644 index 0000000..7a01a1c --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubLimits.cs @@ -0,0 +1,16 @@ +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// The size limits the hub tool enforces when it builds a package and the app enforces again when it installs one. +public static class HubLimits +{ + public const int MaximumCatalogBytes = 1024 * 1024; + + public const int MaximumCatalogPlugins = 2000; + + public const int MaximumPackageFiles = 500; + + public const long MaximumUnpackedBytes = 5 * 1024 * 1024; + + // A package is a zip of at most MaximumUnpackedBytes, so an honest one is never larger than this. + public const long MaximumPackageBytes = 6 * 1024 * 1024; +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs new file mode 100644 index 0000000..f3fc40b --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubPolicy.cs @@ -0,0 +1,110 @@ +using FourFoldAccountManager.Core.Models; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// A plugin installed from the hub, at the commit that was reviewed. +public sealed record HubInstalled(string Id, string Commit); + +// An installed plugin that may run, and with what trust. +public sealed record HubLoad(string Id, string Folder, string Commit, PluginTrust Trust); + +// The decisions about hub plugins that need no files and no network. +public static class HubPolicy +{ + public const string UnlistedReason = "This plugin is no longer on the hub."; + + public const string RemovedReason = "This plugin was removed from the hub."; + + // Why an installed plugin may not run, or null when it may. A removal wins even when the catalog also lists the id, + // and a plugin the catalog doesn't list at all counts as pulled, so a mistake on the hub's side stops a plugin and + // never leaves an unlisted one running. With no catalog yet, nothing is known to be pulled. + public static string? PulledReason(HubCatalog? catalog, string id) + { + if (catalog is null) + { + return null; + } + + var removal = catalog.Removed.FirstOrDefault(removed => removed.Id == id); + if (removal is not null) + { + return removal.Reason.Length > 0 ? removal.Reason : RemovedReason; + } + + return catalog.Plugins.Any(plugin => plugin.Id == id) ? null : UnlistedReason; + } + + // The installed plugins that may run. A plugin gets any-website trust only when the catalog clears the exact + // commit that is installed: with no catalog, or while a cleared update is still to be installed, it gets its + // declared sites only. + public static IReadOnlyList Loads( + HubCatalog? catalog, IReadOnlyList installed, Func folderOf) => + installed + .Where(plugin => PulledReason(catalog, plugin.Id) is null) + .Select(plugin => + { + var listed = catalog?.Plugins.FirstOrDefault(candidate => candidate.Id == plugin.Id); + return new HubLoad( + plugin.Id, folderOf(plugin.Id), plugin.Commit, + listed is { AnySite: true } && listed.Commit == plugin.Commit + ? PluginTrust.Verified + : PluginTrust.Standard); + }) + .ToArray(); + + // While developer mode has a plugin with the same id in the dev folder, that copy runs instead of the hub's. + public static IReadOnlyList Visible(IReadOnlyList loads, IReadOnlySet devIds) => + loads.Where(load => !devIds.Contains(load.Id)).ToArray(); + + // Listed plugins whose reviewed commit differs from the one installed. + public static IReadOnlyList Updates(HubCatalog? catalog, IReadOnlyList installed) => + catalog is null + ? [] + : catalog.Plugins + .Where(plugin => installed.Any(other => other.Id == plugin.Id && other.Commit != plugin.Commit)) + .ToArray(); + + // Forgets an uninstalled plugin in saved settings: its cards, its place in the strip, and its switch. When it was + // the open plugin the panel closes, as when it is switched off. Returns the same instance when there was nothing + // to forget, so callers can skip the save. + public static PanelSettings WithUninstalled(PanelSettings settings, string id) + { + var cardPrefix = id + "/"; + var cards = settings.OverlayCards + .Where(card => card.PluginCard?.StartsWith(cardPrefix, StringComparison.Ordinal) != true) + .ToArray(); + var order = settings.PluginOrder.Where(other => other != id).ToArray(); + var disabled = settings.DisabledPlugins.Where(other => other != id).ToArray(); + if (cards.Length == settings.OverlayCards.Count && order.Length == settings.PluginOrder.Count && + disabled.Length == settings.DisabledPlugins.Count && settings.OpenPlugin != id) + { + return settings; + } + + var wasOpen = settings.OpenPlugin == id; + return settings with + { + OverlayCards = Array.AsReadOnly(cards), + PluginOrder = Array.AsReadOnly(order), + DisabledPlugins = Array.AsReadOnly(disabled), + OpenPlugin = wasOpen ? null : settings.OpenPlugin, + PluginsSidebarExpanded = !wasOpen && settings.PluginsSidebarExpanded + }; + } + + // The hub page's list: installed plugins first, then by name. An empty query matches everything. + public static IReadOnlyList Search( + IReadOnlyList plugins, string? query, IReadOnlySet installed) + { + var text = query?.Trim() ?? string.Empty; + return plugins + .Where(plugin => text.Length == 0 || + plugin.Name.Contains(text, StringComparison.OrdinalIgnoreCase) || + plugin.Author.Contains(text, StringComparison.OrdinalIgnoreCase) || + plugin.Description.Contains(text, StringComparison.OrdinalIgnoreCase)) + .OrderBy(plugin => installed.Contains(plugin.Id) ? 0 : 1) + .ThenBy(plugin => plugin.Name, StringComparer.OrdinalIgnoreCase) + .ThenBy(plugin => plugin.Id, StringComparer.Ordinal) + .ToArray(); + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs new file mode 100644 index 0000000..8d0c295 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubStore.cs @@ -0,0 +1,306 @@ +using System.Text; +using System.Text.Json; +using FourFoldAccountManager.Core.Data; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// What the hub keeps on disk: each installed plugin's folder, the record of what is installed, and the last good +// catalog. Nothing here talks to the network or to a running plugin. +public sealed class HubStore(LocalDataPaths paths) +{ + // Git's null id. A record rebuilt from the folders on disk can't know which commit they hold, so it names this + // one: it passes the commit check, never equals a commit the catalog lists (so it never earns any-website trust), + // and the next hub check sees a different commit and installs the plugin again, cleanly. + public static readonly string UnknownCommit = new('0', 40); + + private const string OldPrefix = ".old-"; + + // Commit and uninstall each read the record, wait, then write it, so two at once would lose one of the writes. + private readonly SemaphoreSlim _gate = new(1, 1); + + // Throws for anything but a plugin id, so no caller can point this (or the recursive delete in UninstallAsync) at + // a folder outside the plugins folder. + public string FolderOf(string id) => PluginManifestReader.IsValidId(id) + ? Path.Combine(paths.HubPluginsRoot, id) + : throw new ArgumentException("That isn't a plugin id.", nameof(id)); + + // False when the folder is missing or broken: a crash mid-install left the record without its files, or a file the + // plugin needs is gone. The next hub check installs it again. + public bool IsIntact(string id) => PluginManifestReader.Read(FolderOf(id)).Manifest is not null; + + // No file means nothing is installed. A record that is not JSON, is empty, or holds an entry of the wrong shape is + // rebuilt from the plugin folders on disk, so a damaged record never makes the next install forget the others; an + // entry whose id or commit isn't valid is left out. A file that exists but can't be opened throws (IOException, or + // UnauthorizedAccessException when access is denied), so a locked record is never mistaken for "nothing installed" + // and then written over. + public IReadOnlyList LoadInstalled() + { + if (!File.Exists(paths.HubInstalledFilePath)) + { + return []; + } + + List? records; + try + { + records = JsonSerializer.Deserialize>( + File.ReadAllText(paths.HubInstalledFilePath), AtomicJsonFile.Options); + } + catch (JsonException) + { + records = null; + } + + return records is null + ? RebuildFromFolders() + : records + .Where(record => record is not null && PluginManifestReader.IsValidId(record.Id) && + HubCatalogJson.IsCommit(record.Commit)) + .Select(record => record!) + .DistinctBy(record => record.Id) + .ToArray(); + } + + public HubCatalog? LoadCatalog() + { + try + { + return File.Exists(paths.HubCatalogFilePath) + ? HubCatalogJson.Parse(File.ReadAllText(paths.HubCatalogFilePath)) + : null; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + } + + // Written through to disk before it takes the final name, so a power cut can't leave a short file there. + public async Task SaveCatalogAsync(string json, CancellationToken cancellationToken) + { + Directory.CreateDirectory(Path.GetDirectoryName(paths.HubCatalogFilePath)!); + var temporary = paths.HubCatalogFilePath + ".tmp"; + await using (var stream = new FileStream( + temporary, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 16 * 1024, + FileOptions.Asynchronous | FileOptions.WriteThrough)) + { + await stream.WriteAsync(Encoding.UTF8.GetBytes(json), cancellationToken); + await stream.FlushAsync(cancellationToken); + stream.Flush(flushToDisk: true); + } + + File.Move(temporary, paths.HubCatalogFilePath, overwrite: true); + } + + // Checks a downloaded package and unpacks it into a staging folder beside the installed plugins. Returns the + // reason it was refused, or null. Nothing that is installed is touched. + public string? Stage(HubPlugin plugin, byte[] package, out string stagingFolder) + { + stagingFolder = Path.Combine(paths.HubPluginsRoot, ".staging-" + Guid.NewGuid().ToString("N")); + if (!PluginPackage.Matches(package, plugin.Size, plugin.Sha256)) + { + return "The download didn't match the hub's record."; + } + + try + { + PluginPackage.Extract(package, stagingFolder); + } + catch (Exception exception) when (exception is InvalidDataException or IOException or UnauthorizedAccessException) + { + TryDeleteFolder(stagingFolder); + return "The package isn't valid."; + } + + // The hash matched, but it must also be the plugin the user asked for, asking for the websites the hub page + // showed: the catalog's sites are what the user saw, and the plugin.json is what the sandbox enforces. + var read = PluginManifestReader.Read(stagingFolder); + var manifest = read.Manifest; + if (manifest is null || manifest.Id != plugin.Id || manifest.Version != plugin.Version || + !manifest.Sites.ToHashSet().SetEquals(plugin.Sites) || (plugin.AnySite && !manifest.AnySite)) + { + TryDeleteFolder(stagingFolder); + return read.Error == PluginManifestReader.NeedsNewerFourFold + ? "This version needs a newer FourFold." + : "The package isn't the plugin the hub listed."; + } + + return null; + } + + // Puts a staged plugin in place and records it. If the swap or the record fails, the version that was installed + // before is back in place when this throws, and the staging folder is gone. + public async Task CommitAsync(HubPlugin plugin, string stagingFolder, CancellationToken cancellationToken) + { + var target = FolderOf(plugin.Id); + await _gate.WaitAsync(cancellationToken); + try + { + // The id is in the name so CleanUp can put the folder back if a crash comes between the two moves. + var previous = Path.Combine(paths.HubPluginsRoot, $"{OldPrefix}{plugin.Id}-{Guid.NewGuid():N}"); + IReadOnlyList records; + bool hadPrevious; + try + { + // Read before anything moves: a record that can't be read stops the install here. + records = LoadInstalled(); + hadPrevious = Directory.Exists(target); + if (hadPrevious) + { + Directory.Move(target, previous); + } + } + catch + { + // Nothing was swapped, so only the staged files need to go. + TryDeleteFolder(stagingFolder); + throw; + } + + try + { + Directory.Move(stagingFolder, target); + try + { + await SaveInstalledAsync( + records.Where(record => record.Id != plugin.Id) + .Append(new HubInstalled(plugin.Id, plugin.Commit)) + .ToArray(), + cancellationToken); + } + catch + { + Directory.Move(target, stagingFolder); + throw; + } + } + catch + { + // If putting the old version back fails, nothing below runs and the staged files stay. + if (hadPrevious) + { + Directory.Move(previous, target); + } + + TryDeleteFolder(stagingFolder); + throw; + } + + TryDeleteFolder(previous); + } + finally + { + _gate.Release(); + } + } + + // The record goes first, so a crash partway leaves files nothing points at, never a record without its files. The + // folder is renamed before it is deleted: a delete that fails partway then leaves a leftover CleanUp finishes at + // the next start, never a half-deleted plugin folder that could be loaded. A folder that can't be renamed stays + // under its own name, unrecorded, and installing the plugin again replaces it. + public async Task UninstallAsync(string id, CancellationToken cancellationToken) + { + var folder = FolderOf(id); + await _gate.WaitAsync(cancellationToken); + try + { + await SaveInstalledAsync(LoadInstalled().Where(record => record.Id != id).ToArray(), cancellationToken); + var saved = Path.Combine(paths.PluginDataRoot, id + ".json"); + if (File.Exists(saved)) + { + File.Delete(saved); + } + + if (Directory.Exists(folder)) + { + var trash = Path.Combine(paths.HubPluginsRoot, ".trash-" + Guid.NewGuid().ToString("N")); + Directory.Move(folder, trash); + TryDeleteFolder(trash); + } + } + finally + { + _gate.Release(); + } + } + + // Clears what a crash or a failed delete left behind. An installed plugin's folder never starts with a dot. A + // folder CommitAsync set aside is put back when the swap never finished and the plugin has no folder; otherwise it + // is deleted with the rest. Never throws: a plugins folder that can't be listed must not stop the hub starting. + public void CleanUp() + { + try + { + if (!Directory.Exists(paths.HubPluginsRoot)) + { + return; + } + + foreach (var folder in Directory.GetDirectories(paths.HubPluginsRoot, ".*")) + { + if (SetAsideId(Path.GetFileName(folder)) is { } id && !Directory.Exists(FolderOf(id))) + { + try + { + Directory.Move(folder, FolderOf(id)); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Kept, never deleted: it may be the only copy. The next start tries again. + } + + continue; + } + + TryDeleteFolder(folder); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // The next start tries again. + } + } + + // The plugin id in ".old--<32 hex digits>", or null for any other name. + private static string? SetAsideId(string name) + { + if (!name.StartsWith(OldPrefix, StringComparison.Ordinal)) + { + return null; + } + + var rest = name[OldPrefix.Length..]; + return rest.Length > 33 && rest[^33] == '-' && Guid.TryParseExact(rest[^32..], "N", out _) && + PluginManifestReader.IsValidId(rest[..^33]) + ? rest[..^33] + : null; + } + + private IReadOnlyList RebuildFromFolders() => + !Directory.Exists(paths.HubPluginsRoot) + ? [] + : Directory.GetDirectories(paths.HubPluginsRoot) + .Select(folder => Path.GetFileName(folder)) + .Where(name => !name.StartsWith('.') && PluginManifestReader.IsValidId(name) && IsIntact(name)) + .Order(StringComparer.Ordinal) + .Select(name => new HubInstalled(name, UnknownCommit)) + .ToArray(); + + private Task SaveInstalledAsync(IReadOnlyList records, CancellationToken cancellationToken) => + AtomicJsonFile.WriteAsync(paths.HubInstalledFilePath, records, cancellationToken); + + private static void TryDeleteFolder(string folder) + { + try + { + if (Directory.Exists(folder)) + { + Directory.Delete(folder, recursive: true); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // CleanUp tries again at the next start. + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs new file mode 100644 index 0000000..7eb8665 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/HubSubmission.cs @@ -0,0 +1,333 @@ +using System.IO.Compression; +using System.Text; +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +public sealed record HubCheckResult(string? Error, HubPlugin? Plugin, byte[]? Package); + +// The catalog a publish run would upload, the packages that are new in it, and what stopped it. +public sealed record HubBuild( + HubCatalog? Catalog, IReadOnlyList<(string Name, byte[] Bytes)> Packages, IReadOnlyList Errors); + +// What the hub repository's workflows check before a plugin is listed. The plugin's code is never run. +public static class HubSubmission +{ + private const int MaximumListedFiles = 100; + + // Every character Markdown could act on in the summary. "$" is here because GitHub draws $...$ as maths, which + // could restyle the text between two values on one line. + private const string MarkdownCharacters = "\\`*_[]<>&|~!()#$"; + + // Checks one entry against its repository, unpacked at the entry's commit in repositoryFolder, and builds its + // package. today is the review date recorded for it (yyyy-MM-dd). + public static HubCheckResult Check(HubEntry entry, string repositoryFolder, HubCatalog? current, string today) + { + var folder = repositoryFolder; + if (entry.Path.Length > 0 && + (!PluginPaths.TryResolveInside(repositoryFolder, entry.Path, out folder) || !Directory.Exists(folder))) + { + return Fail($"The repository has no folder \"{entry.Path}\" at that commit."); + } + + var read = PluginManifestReader.Read(folder); + if (read.Manifest is not { } manifest) + { + return Fail(read.Error ?? "plugin.json couldn't be read."); + } + + if (manifest.Id != entry.Id) + { + return Fail($"The file is named for \"{entry.Id}\", but plugin.json says \"{manifest.Id}\"."); + } + + if (entry.AnySite && !manifest.AnySite) + { + return Fail("\"anySite\" is true in the entry, but the plugin's plugin.json doesn't ask for it."); + } + + // The reader accepts any digits, but a number past 2,147,483,647 can't be compared, so no update to it could + // ever pass the "must raise" rule below. + if (!System.Version.TryParse(manifest.Version, out _)) + { + return Fail("Each number in the version must be at most 2147483647, for example 1.4.0."); + } + + var listed = current?.Plugins.FirstOrDefault(plugin => plugin.Id == entry.Id); + if (listed is not null && listed.Commit != entry.Commit && !IsNewer(manifest.Version, listed.Version)) + { + return Fail( + $"An update must raise the version: the hub lists {listed.Version} and plugin.json says {manifest.Version}."); + } + + byte[] package; + try + { + package = PluginPackage.Build(folder); + } + catch (InvalidDataException exception) + { + return Fail(exception.Message); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return Fail("The plugin's files couldn't be read."); + } + + if (package.LongLength > HubLimits.MaximumPackageBytes) + { + return Fail("The package is too large."); + } + + if (Unpackable(package, manifest) is { } unpackProblem) + { + return Fail(unpackProblem); + } + + return new HubCheckResult( + null, + new HubPlugin( + manifest.Id, manifest.Name, manifest.ShortLabel, manifest.Version, manifest.Author, manifest.Description, + manifest.Sites, entry.AnySite && manifest.AnySite, + manifest.Cards.Select(card => new HubCard(card.Name, card.Scope)).ToArray(), + entry.Repository, entry.Commit, today, package.LongLength, PluginPackage.Sha256(package)), + package); + + static HubCheckResult Fail(string reason) => new(reason, null, null); + } + + // The package is built from the author's folder, but what users get is what the app unpacks from it. Unpacks it the + // way the app does, into a throwaway folder, and returns why it wouldn't install as the same plugin, or null. A + // manifest whose panel is a dot-file, say, passes the folder's own check and then has no panel in the package. + private static string? Unpackable(byte[] package, PluginManifest manifest) + { + var staging = Path.Combine(Path.GetTempPath(), "fourfold-hub-check-" + Guid.NewGuid().ToString("N")); + try + { + PluginPackage.Extract(package, staging); + var unpacked = PluginManifestReader.Read(staging); + if (unpacked.Manifest is not { } installed) + { + return "Once packaged, the plugin can't be installed: " + unpacked.Error; + } + + return installed.Id == manifest.Id && installed.Version == manifest.Version + ? null + : "Once packaged, the plugin isn't the same id and version."; + } + catch (Exception exception) when (exception is InvalidDataException or IOException or UnauthorizedAccessException) + { + return "The package can't be unpacked: " + + (exception is InvalidDataException ? exception.Message : "a file couldn't be written."); + } + finally + { + try + { + if (Directory.Exists(staging)) + { + Directory.Delete(staging, recursive: true); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A leftover folder in the temporary folder costs nothing; it must not hide the result. + } + } + } + + // Builds the catalog for every entry. An entry whose repository, commit and clearance are unchanged keeps its + // record and its published package, so a listed plugin survives its author deleting the repository; only new and + // changed entries go through check. One failure means no catalog, and then no packages either. + public static HubBuild BuildCatalog( + IReadOnlyList entries, + IReadOnlyList removed, + HubCatalog? current, + Func check) + { + var errors = new List(); + var plugins = new List(); + var packages = new List<(string Name, byte[] Bytes)>(); + foreach (var entry in entries.OrderBy(entry => entry.Id, StringComparer.Ordinal)) + { + if (removed.Any(removal => removal.Id == entry.Id)) + { + errors.Add($"{entry.Id}: a plugin can't be both listed and in removed.json."); + continue; + } + + if (current?.Plugins.FirstOrDefault(plugin => plugin.Id == entry.Id) is { } listed && + listed.Commit == entry.Commit && listed.AnySite == entry.AnySite && listed.Repository == entry.Repository) + { + plugins.Add(listed); + continue; + } + + var result = check(entry); + if (result.Error is not null) + { + errors.Add($"{entry.Id}: {result.Error}"); + continue; + } + + plugins.Add(result.Plugin!); + packages.Add((HubAddresses.PackageName(entry.Id, entry.Commit), result.Package!)); + } + + if (errors.Count > 0) + { + return new HubBuild(null, [], errors); + } + + // The app reads at most this much of a catalog and refuses a larger one, which would leave the hub dead for + // every user, so a catalog it would refuse is never built. The app counts characters and the download is capped + // in bytes, so both are checked. + var catalog = new HubCatalog(plugins, removed); + if (plugins.Count > HubLimits.MaximumCatalogPlugins) + { + errors.Add($"The catalog would list {plugins.Count} plugins, and FourFold reads at most {HubLimits.MaximumCatalogPlugins}."); + } + else + { + var json = HubCatalogJson.Write(catalog); + if (json.Length > HubLimits.MaximumCatalogBytes || Encoding.UTF8.GetByteCount(json) > HubLimits.MaximumCatalogBytes) + { + errors.Add($"The catalog would be larger than the {HubLimits.MaximumCatalogBytes} bytes FourFold reads."); + } + } + + return errors.Count == 0 ? new HubBuild(catalog, packages, errors) : new HubBuild(null, [], errors); + } + + // What a reviewer needs to see for one entry, as Markdown for the check's summary page. A maintainer reads this + // before merging, and most of it is a stranger's text: Plain makes each such value harmless, and every line starts + // with text written here, never with a stranger's value. + public static string Summary( + string fileName, HubEntry? entry, string? error, HubPlugin? plugin, byte[]? package, HubCatalog? current) + { + var text = new StringBuilder().AppendLine($"### {Plain(fileName)}").AppendLine(); + if (error is not null || entry is null || plugin is null || package is null) + { + return text.AppendLine($"**Not accepted:** {Plain(error ?? "The entry couldn't be checked.", 500)}").ToString(); + } + + if (plugin.AnySite) + { + text.AppendLine("**WARNING: this entry asks for ANY WEBSITE access. Merging it grants that.**").AppendLine(); + } + + var contact = plugin.AnySite ? "any website (requested by this entry)" + : plugin.Sites.Count == 0 ? "no websites" + : string.Join(", ", plugin.Sites.Select(site => Site(PluginNetworkPolicy.SiteLabel(site)))); + var cards = plugin.Cards.Count == 0 + ? "none" + : string.Join(", ", plugin.Cards.Select(card => + $"{Plain(card.Name)} ({(card.Scope == OverlayAddOnScope.Account ? "per account" : "global")})")); + text.AppendLine("| | |") + .AppendLine("|---|---|") + .AppendLine($"| Name | {Plain(plugin.Name)} ({Plain(plugin.ShortLabel)}) |") + .AppendLine($"| Author | {Plain(plugin.Author)} |") + .AppendLine($"| Version | {plugin.Version} |") + .AppendLine($"| Description | {Plain(plugin.Description, 200)} |") + .AppendLine($"| Can contact | {contact} |") + .AppendLine($"| Cards | {cards} |") + .AppendLine($"| Package | {plugin.Size} bytes |") + .AppendLine(); + + var listed = current?.Plugins.FirstOrDefault(other => other.Id == plugin.Id); + var repository = entry.Repository.AbsoluteUri; + var sameRepository = listed is not null && listed.Repository == entry.Repository; + text.AppendLine(sameRepository + ? $"Update from {listed!.Version}. Review the changes: {repository}/compare/{listed.Commit}...{entry.Commit}" + : $"{(listed is null ? "New plugin" : $"Update from {listed.Version}, from another repository")}. " + + $"Review the code: {repository}/tree/{entry.Commit}{(entry.Path.Length > 0 ? "/" + entry.Path : "")}"); + if (listed is not null) + { + // What an update escalates is what a reviewer must not miss, so it is spelled out, not left to the table. + var shown = plugin.Sites.Select(PluginNetworkPolicy.SiteLabel).ToArray(); + var before = listed.Sites.Select(PluginNetworkPolicy.SiteLabel).ToArray(); + var changes = new List(); + if (plugin.AnySite != listed.AnySite) + { + changes.Add(plugin.AnySite ? "Any-website access gained." : "Any-website access dropped."); + } + + if (shown.Except(before).ToArray() is { Length: > 0 } added) + { + changes.Add("Sites added: " + string.Join(", ", added.Select(Site)) + "."); + } + + if (before.Except(shown).ToArray() is { Length: > 0 } removed) + { + changes.Add("Sites removed: " + string.Join(", ", removed.Select(Site)) + "."); + } + + if (listed.Repository != plugin.Repository) + { + changes.Add($"Repository changed from {listed.Repository.AbsoluteUri} to {repository}."); + } + + if (listed.Author != plugin.Author) + { + changes.Add($"Author changed from {Plain(listed.Author)} to {Plain(plugin.Author)}."); + } + + text.AppendLine(); + if (changes.Count == 0) + { + text.AppendLine("No change to access, sites, repository or author."); + } + else + { + text.AppendLine("Changed:").AppendLine(); + foreach (var change in changes) + { + text.AppendLine("- " + change); + } + } + } + + text.AppendLine().AppendLine("Files in the package:").AppendLine(); + using var archive = new ZipArchive(new MemoryStream(package)); + foreach (var file in archive.Entries.Take(MaximumListedFiles)) + { + text.AppendLine($"- File: {Plain(file.FullName)} ({file.Length} bytes)"); + } + + if (archive.Entries.Count > MaximumListedFiles) + { + text.AppendLine($"- \u2026and {archive.Entries.Count - MaximumListedFiles} more"); + } + + return text.ToString(); + } + + // A site's label is a host name, but it comes from a stranger's plugin.json, so it is text like the rest. + private static string Site(string label) => Plain(label, 300); + + // Text from a plugin, an entry or a repository, made safe to put in the summary, which GitHub draws as Markdown: + // anything that could start a new line or hide text (control, formatting and separator characters) becomes "?", + // every character Markdown could act on gets a backslash, and a long value is cut and ends in "...". + public static string Plain(string value, int maximum = 100) + { + var result = new StringBuilder(); + foreach (var rune in value.EnumerateRunes()) + { + var text = rune.ToString(); + var piece = PluginText.HasUnsafeCharacter(text) ? "?" + : rune.IsBmp && MarkdownCharacters.Contains((char)rune.Value) ? "\\" + text + : text; + if (result.Length + piece.Length > maximum) + { + return result.Append('\u2026').ToString(); + } + + result.Append(piece); + } + + return result.ToString(); + } + + private static bool IsNewer(string version, string than) => + System.Version.TryParse(version, out var left) && System.Version.TryParse(than, out var right) && left > right; +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs new file mode 100644 index 0000000..315032d --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/PluginPackage.cs @@ -0,0 +1,139 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text.RegularExpressions; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// A plugin as the hub ships it: a zip of plugin.json and the files FourFold serves. +public static partial class PluginPackage +{ + private static readonly DateTimeOffset EntryTime = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); + + // Windows treats these names as devices, alone or before a dot (aux.js), in any case. + [GeneratedRegex("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$", RegexOptions.IgnoreCase)] + private static partial Regex DeviceNameRegex(); + + // Builds the package for the plugin in folder. README, LICENSE, dot-files and other file types are left out. The + // same files always give the same bytes. Throws InvalidDataException when the plugin is past the limits, contains + // a link, or has a file name that Windows can't unpack. + public static byte[] Build(string folder) + { + var files = new List<(string Name, string Path)>(); + Collect(folder, string.Empty, files); + files.Sort((left, right) => string.CompareOrdinal(left.Name, right.Name)); + if (UnpackableReason(files.ConvertAll(file => file.Name)) is { } reason) + { + throw new InvalidDataException(reason); + } + + if (files.Count > HubLimits.MaximumPackageFiles) + { + throw new InvalidDataException($"A plugin can have at most {HubLimits.MaximumPackageFiles} files."); + } + + if (files.Sum(file => new FileInfo(file.Path).Length) > HubLimits.MaximumUnpackedBytes) + { + throw new InvalidDataException("A plugin's files can be at most 5 MB together."); + } + + using var buffer = new MemoryStream(); + using (var archive = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (var (name, path) in files) + { + var entry = archive.CreateEntry(name, CompressionLevel.Optimal); + entry.LastWriteTime = EntryTime; + using var output = entry.Open(); + output.Write(File.ReadAllBytes(path)); + } + } + + return buffer.ToArray(); + } + + public static string Sha256(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes)); + + // Whether a downloaded package is the one the catalog names. + public static bool Matches(byte[] package, long size, string sha256) => + package.LongLength == size && string.Equals(Sha256(package), sha256, StringComparison.Ordinal); + + // Why files with these names (paths inside a package, with '/') can't all be unpacked on Windows, or null. The hub + // tool runs on Linux, where Path.GetInvalidFileNameChars lists only '/' and NUL, so the Windows rules are written + // out here; without this a package would build fine and then be refused on a user's machine. + public static string? UnpackableReason(IReadOnlyList names) + { + var seen = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var name in names) + { + foreach (var part in name.Split('/')) + { + if (part.Any(character => char.IsControl(character) || "\\:<>\"|?*".Contains(character)) || + part.EndsWith('.') || part.EndsWith(' ')) + { + return $"{name} can't be unpacked on Windows: a file or folder name can't contain \\ : < > \" | ? * " + + "or a control character, or end with a dot or a space."; + } + + if (DeviceNameRegex().IsMatch(part.Split('.')[0])) + { + return $"{name} can't be unpacked on Windows: a file or folder name can't be con, prn, aux, nul, " + + "com0 to com9 or lpt0 to lpt9, alone or before a dot."; + } + } + + if (!seen.TryAdd(name, name)) + { + return $"{name} and {seen[name]} differ only by capital letters, which Windows can't tell apart."; + } + } + + return null; + } + + // Unpacks a package into targetFolder. Throws InvalidDataException or IOException when it breaks a rule; the + // caller deletes the folder. A package holds only plugin.json and the file types FourFold serves, as Build + // makes it; anything else, such as an .exe, is refused before a byte is written. + public static void Extract(byte[] package, string targetFolder) + { + using var stream = new MemoryStream(package); + using (var archive = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true)) + { + if (archive.Entries.Any(entry => + !entry.FullName.EndsWith('/') && entry.FullName != "plugin.json" && + !PluginFileServer.IsServed(entry.FullName))) + { + throw new InvalidDataException("The package holds a file that FourFold doesn't serve."); + } + } + + SafeArchive.Extract( + stream, targetFolder, HubLimits.MaximumPackageFiles, HubLimits.MaximumUnpackedBytes, stripTopFolder: false); + } + + private static void Collect(string folder, string prefix, List<(string Name, string Path)> files) + { + foreach (var path in Directory.EnumerateFileSystemEntries(folder)) + { + var name = Path.GetFileName(path); + if (name.StartsWith('.')) + { + continue; + } + + var attributes = File.GetAttributes(path); + if (attributes.HasFlag(FileAttributes.ReparsePoint)) + { + throw new InvalidDataException("A plugin can't contain links."); + } + + if (attributes.HasFlag(FileAttributes.Directory)) + { + Collect(path, prefix + name + "/", files); + } + else if (prefix + name == "plugin.json" || PluginFileServer.IsServed(name)) + { + files.Add((prefix + name, path)); + } + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs b/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs new file mode 100644 index 0000000..615a664 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/Hub/SafeArchive.cs @@ -0,0 +1,109 @@ +using System.IO.Compression; + +namespace FourFoldAccountManager.Core.Plugins.Hub; + +// Unpacks a zip that came from the network. Anything that could write outside the target folder, or fill the disk, +// throws InvalidDataException before it is written. The caller deletes the target folder when this throws. +public static class SafeArchive +{ + // Deleting a folder tree is recursive and overflows the stack when the tree is thousands of levels deep, which + // nothing can catch, so no entry may nest deeper than this. + private const int MaximumDepth = 64; + + // stripTopFolder drops each entry's first path part, for GitHub's repository zips, which wrap everything in one + // "-" folder. skipLinksAndOddNames skips links and names with a ':' or '\' instead of refusing the + // archive, for an author's whole repository, where such a file has nothing to do with the plugin. + public static void Extract( + Stream zip, string targetFolder, int maximumFiles, long maximumBytes, bool stripTopFolder, + bool skipLinksAndOddNames = false) + { + // Callers unpack into a fresh folder; one with files in it could hold a link that leads somewhere else. + if (Directory.Exists(targetFolder) && Directory.EnumerateFileSystemEntries(targetFolder).Any()) + { + throw new IOException("The folder to unpack into isn't empty."); + } + + using var archive = new ZipArchive(zip, ZipArchiveMode.Read, leaveOpen: true); + Directory.CreateDirectory(targetFolder); + var files = 0; + long bytes = 0; + var buffer = new byte[81920]; + foreach (var entry in archive.Entries) + { + var name = entry.FullName; + if (name.EndsWith('/')) + { + continue; + } + + var parts = name.Split('/'); + if (parts.Length > MaximumDepth) + { + throw new InvalidDataException("The archive nests folders too deeply."); + } + + if (parts.Any(part => part.Length == 0 || part is "." or "..")) + { + throw new InvalidDataException("The archive contains a path that isn't allowed."); + } + + // A Unix symbolic link is stored as a file whose mode bits say "link". + var isLink = ((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000; + if (isLink || name.Contains('\\') || name.Contains(':')) + { + if (skipLinksAndOddNames) + { + continue; + } + + throw new InvalidDataException( + isLink ? "The archive contains a link." : "The archive contains a path that isn't allowed."); + } + + if (stripTopFolder) + { + if (parts.Length == 1) + { + continue; + } + + parts = parts[1..]; + } + + if (!PluginPaths.TryResolveInside(targetFolder, string.Join('/', parts), out var path)) + { + throw new InvalidDataException("The archive contains a path that isn't allowed."); + } + + if (++files > maximumFiles) + { + throw new InvalidDataException("The archive has too many files."); + } + + try + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using var input = entry.Open(); + using var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write); + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + { + // Counted as it is written: the size an entry declares can lie. + bytes += read; + if (bytes > maximumBytes) + { + throw new InvalidDataException("The archive is too large."); + } + + output.Write(buffer, 0, read); + } + } + catch (UnauthorizedAccessException exception) + { + // A file where a folder is needed, or the reverse; callers expect only InvalidDataException or + // IOException from this method. + throw new IOException("The archive can't be unpacked: access to a path was denied.", exception); + } + } + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs b/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs index bb4e3d4..33c036a 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs @@ -23,6 +23,7 @@ public sealed record PluginDescriptor( // A short tag beside the plugin's name in the plugin list, such as "DEV". public string? Badge { get; init; } - // One line under the plugin's name in the plugin list, such as the sites it can contact. + // Text under the plugin's name in the plugin list. A community plugin gives two lines: its author, then the sites + // it can contact. public string? Detail { get; init; } } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs b/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs index f823c57..76232d7 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs @@ -21,6 +21,9 @@ public static class PluginFileServer [".woff2"] = "font/woff2" }; + // Whether a file of this name is a type FourFold serves; the hub packages only these. + public static bool IsServed(string path) => ContentTypes.ContainsKey(Path.GetExtension(path)); + public static bool TryResolve(PluginManifest manifest, string urlPath, out string filePath, out string contentType) { filePath = string.Empty; diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs index 6a582b0..7df82cb 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs @@ -4,7 +4,8 @@ namespace FourFoldAccountManager.Core.Plugins; public static class PluginLayoutPolicy { - public const int MaximumIds = 64; + // Room for the built-in plugins plus every hub plugin a user is likely to install. + public const int MaximumIds = 256; // Known plugins in saved order; a known plugin missing from the saved order goes last, in the order given. public static IReadOnlyList Ordered(PanelSettings settings, IReadOnlyList known) @@ -92,7 +93,7 @@ public static PanelSettings WithOpened(PanelSettings settings, string id) => public static PanelSettings WithClosed(PanelSettings settings) => settings.PluginsSidebarExpanded ? settings with { PluginsSidebarExpanded = false } : settings; - // Load-time cleanup: blank ids and repeats go (the first wins), and at most 64 ids stay. + // Load-time cleanup: blank ids and repeats go (the first wins), and at most 256 ids stay. public static IReadOnlyList CleanIds(IReadOnlyList? ids) => Array.AsReadOnly((ids ?? Array.Empty()) .Where(id => !string.IsNullOrWhiteSpace(id)) diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index 7f0d4b2..95a278b 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using System.Diagnostics.CodeAnalysis; using System.Text.Json; using System.Text.RegularExpressions; using FourFoldAccountManager.Core.Overlay; @@ -14,6 +15,9 @@ public static partial class PluginManifestReader public const string CardIdPattern = "[a-z0-9]+(-[a-z0-9]+)*"; + // What a plugin that asks for a newer apiVersion is told. The hub's install step matches on it. + public const string NeedsNewerFourFold = "Update FourFold to use this plugin."; + private const int MaximumIconBytes = 64 * 1024; private const int MaximumManifestBytes = 64 * 1024; @@ -24,7 +28,7 @@ public static partial class PluginManifestReader [GeneratedRegex("^" + CardIdPattern + @"\z")] private static partial Regex CardIdRegex(); - [GeneratedRegex(@"^[0-9]+\.[0-9]+\.[0-9]+$")] + [GeneratedRegex(@"^[0-9]+\.[0-9]+\.[0-9]+\z")] private static partial Regex VersionRegex(); // Windows treats these names as devices whatever follows the dot, so a plugin called nul.tools would get a storage @@ -32,6 +36,21 @@ public static partial class PluginManifestReader [GeneratedRegex("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$")] private static partial Regex DeviceNameRegex(); + // True for an id the reader accepts: the pattern, no Windows device name first, and a usable host label. + public static bool IsValidId([NotNullWhen(true)] string? id) + { + if (id is null || id.Length > 64 || !IdRegex().IsMatch(id) || DeviceNameRegex().IsMatch(id[..id.IndexOf('.')])) + { + return false; + } + + var label = id.Replace(".", "--"); + return label.Length <= 63 && !label.StartsWith("xn--", StringComparison.OrdinalIgnoreCase); + } + + public static bool IsVersion([NotNullWhen(true)] string? version) => + version is not null && VersionRegex().IsMatch(version); + // Reads and validates /plugin.json. Every rejection carries a reason an author can act on, and a file the // reader can't make sense of for any other reason (one that vanishes mid-read, a host name Uri refuses) is // rejected too: this never throws. @@ -81,18 +100,13 @@ private static PluginManifestResult ReadManifest(string folder) } var id = Text(root, "id"); - if (id is null || id.Length > 64 || !IdRegex().IsMatch(id)) - { - return Reject("The id must look like author.plugin-name (lowercase letters, digits, dots and dashes)."); - } - - if (DeviceNameRegex().IsMatch(id[..id.IndexOf('.')])) + if (id is not null && id.Length <= 64 && IdRegex().IsMatch(id) && + DeviceNameRegex().IsMatch(id[..id.IndexOf('.')])) { return Reject("The id can't start with a Windows device name such as nul, con or com1."); } - var label = id.Replace(".", "--"); - if (label.Length > 63 || label.StartsWith("xn--", StringComparison.OrdinalIgnoreCase)) + if (!IsValidId(id)) { return Reject("The id must look like author.plugin-name (lowercase letters, digits, dots and dashes)."); } @@ -108,7 +122,7 @@ private static PluginManifestResult ReadManifest(string folder) } var version = Text(root, "version"); - if (version is null || !VersionRegex().IsMatch(version)) + if (!IsVersion(version)) { return Reject("The version must look like 1.0.0."); } @@ -137,7 +151,7 @@ private static PluginManifestResult ReadManifest(string folder) if (apiVersion > SupportedApiVersion) { - return Reject("Update FourFold to use this plugin."); + return Reject(NeedsNewerFourFold); } var panel = Text(root, "panel"); @@ -182,12 +196,12 @@ private static PluginManifestResult ReadManifest(string folder) private static PluginManifestResult Reject(string reason) => new(null, reason); - private static string? Text(JsonElement root, string property) => + internal static string? Text(JsonElement root, string property) => root.TryGetProperty(property, out var element) && element.ValueKind == JsonValueKind.String ? element.GetString()?.Trim() : null; - private static bool InRange(string? value, int minimum, int maximum, out string result) + internal static bool InRange(string? value, int minimum, int maximum, out string result) { result = value ?? string.Empty; return result.Length >= minimum && result.Length <= maximum; @@ -207,7 +221,7 @@ private static bool IsSmallPng(string path) BinaryPrimitives.ReadUInt32BigEndian(header[20..]) is >= 1 and <= 256; } - private static bool TryReadSites(JsonElement root, out IReadOnlyList sites, out string error) + internal static bool TryReadSites(JsonElement root, out IReadOnlyList sites, out string error) { sites = []; error = "Each site must look like https://example.com, with no path, and can't be an IP address or a local network name."; @@ -229,7 +243,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) || PluginNetworkPolicy.IsPluginHost(uri.IdnHost)) + IsIpLikeHost(uri.IdnHost) || !IsPlainHost(uri.IdnHost) || PluginNetworkPolicy.IsPluginHost(uri.IdnHost)) { return false; } @@ -247,6 +261,12 @@ private static bool TryReadSites(JsonElement root, out IReadOnlyList sites, return true; } + // What a real host name is once converted: letters, digits, dots and dashes (a name with an umlaut becomes an xn-- + // name). Uri's conversion also turns look-alike characters into punctuation (U+FE64 becomes "<", U+FF5C becomes + // "|"), and a site named like that would rearrange the review summary and every other place a site is shown. + private static bool IsPlainHost(string host) => + host.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '.' or '-'); + private static bool IsIpLikeHost(string host) { var lastLabel = host.Split('.').LastOrDefault() ?? string.Empty; diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs index 8c53e73..268de4f 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs @@ -27,6 +27,9 @@ public static bool IsPluginHost(string host) name.EndsWith("." + OriginSuffix, StringComparison.OrdinalIgnoreCase); } + // How a site is shown to a user or a reviewer: its real (xn--) host name, with the port when it isn't 443. + public static string SiteLabel(Uri site) => site.IsDefaultPort ? site.IdnHost : $"{site.IdnHost}:{site.Port}"; + public static bool AllowsAnySite(PluginManifest manifest, PluginTrust trust) => manifest.AnySite && trust is (PluginTrust.Developer or PluginTrust.Verified); diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs b/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs index f877690..0544d79 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs @@ -2,12 +2,12 @@ namespace FourFoldAccountManager.Core.Plugins; public enum PluginTrust { - // Declared sites only; anySite in the manifest is ignored. + // A hub plugin without that clearance: declared sites only; anySite in the manifest is ignored. Standard, // Loaded from the dev plugins folder: the manifest is honored as written. Developer, - // Reviewed and signed by FourFold's maintainers (part 3): anySite is honored. + // Listed on the hub and cleared by the maintainers for any website: anySite is honored. Verified } diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs index 703a24d..068e2c0 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs @@ -19,20 +19,24 @@ public sealed class PluginApiTests : IDisposable private readonly FakeHost _host = new(); private readonly ManualTimeProvider _clock = new(); private readonly PluginCardStore _cards = new(); + private readonly PluginManifest _manifest; private readonly PluginHttpFetcher _http; private readonly PluginApi _api; public PluginApiTests() { - var manifest = new PluginManifest( - PluginId, "Goal tracker", "Goals", "1.0.0", "Cody", "Tracks goals.", 1, "index.html", null, [], false, + _manifest = new PluginManifest( + PluginId, "Goal tracker", "Goals", "1.0.0", "Cody", "Tracks goals.", 1, "index.html", null, + [new Uri("https://example.com")], false, [ new PluginCardManifest("goal", "Goal", OverlayAddOnScope.Account), new PluginCardManifest("summary", "Summary", OverlayAddOnScope.Global) ]) { Folder = _folder }; _host.Accounts = [new PluginAccountInfo(KnownAccount, "Main", "Cody", true)]; - _http = new PluginHttpFetcher(manifest, PluginTrust.Standard); - _api = new PluginApi(manifest, _host, new PluginStorage(Path.Combine(_folder, "storage.json")), _http, _cards, _clock); + _http = new PluginHttpFetcher(_manifest, PluginTrust.Standard); + _api = new PluginApi( + _manifest, PluginTrust.Standard, _host, new PluginStorage(Path.Combine(_folder, "storage.json")), _http, + _cards, _clock); } public void Dispose() @@ -45,7 +49,7 @@ public void Dispose() } [Fact] - public async Task OpenExternalOnlyOpensPublicHttpsLinks() + public async Task OpenExternalOnlyOpensPublicHttpsLinksOnDeclaredSites() { _host.PanelShowing = true; @@ -54,12 +58,24 @@ public async Task OpenExternalOnlyOpensPublicHttpsLinks() "file:///C:/Windows/System32/calc.exe", "javascript:alert(1)", "http://example.com/", "https://localhost/", "https://192.168.1.1/", "https://printer.local/", "https://user@example.com/", "ms-settings:", - "not a url" + "not a url", + // An invalid international host name, for which reading the Uri's IdnHost throws. + "https://a\u200Db.example/" }) { Assert.Equal("invalid-argument", ErrorCode(await Call("openExternal", new { url }))); } + // The plugin declares example.com and nothing else. Its own address, and another plugin's, are never sites. + foreach (var url in new[] + { + "https://example.org/", "https://sub.example.com/", "https://example.com:8443/", + "https://cody--goal-tracker.fourfoldplugin/", "https://other--plugin.fourfoldplugin/" + }) + { + Assert.Equal("site-not-allowed", ErrorCode(await Call("openExternal", new { url }))); + } + Assert.Empty(_host.Opened); var opened = await Call("openExternal", new { url = "https://example.com/page" }); @@ -68,6 +84,26 @@ public async Task OpenExternalOnlyOpensPublicHttpsLinks() Assert.Equal(new Uri("https://example.com/page"), Assert.Single(_host.Opened)); } + [Fact] + public async Task OnlyAPluginClearedForAnyWebsiteCanOpenLinksAnywhere() + { + _host.PanelShowing = true; + var asking = _manifest with { AnySite = true }; + var notCleared = new PluginApi( + asking, PluginTrust.Standard, _host, new PluginStorage(Path.Combine(_folder, "a.json")), _http, _cards, _clock); + var cleared = new PluginApi( + asking, PluginTrust.Verified, _host, new PluginStorage(Path.Combine(_folder, "b.json")), _http, _cards, _clock); + var link = new { url = "https://example.org/" }; + + // Asking for any website in plugin.json isn't enough; the hub must have cleared it. + Assert.Equal("site-not-allowed", ErrorCode(await Call(notCleared, "openExternal", link))); + Assert.Empty(_host.Opened); + + Assert.Null(ErrorCode(await Call(cleared, "openExternal", link))); + Assert.Equal(new Uri("https://example.org/"), Assert.Single(_host.Opened)); + Assert.Equal("invalid-argument", ErrorCode(await Call(cleared, "openExternal", new { url = "https://localhost/" }))); + } + [Fact] public async Task OpenExternalNeedsTheShowingPanelAndIsRateLimited() { @@ -203,9 +239,11 @@ public async Task StorageWritesAreRateLimited() Assert.Null(ErrorCode(await Call("storage.set", new { key = "k", value = 1 }))); } - private async Task Call(string method, object parameters) + private Task Call(string method, object parameters) => Call(_api, method, parameters); + + private static async Task Call(PluginApi api, string method, object parameters) { - var reply = await _api.HandleAsync(JsonSerializer.Serialize(new { id = 1, method, @params = parameters })); + var reply = await api.HandleAsync(JsonSerializer.Serialize(new { id = 1, method, @params = parameters })); Assert.NotNull(reply); return JsonDocument.Parse(reply).RootElement; } diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs index 99f15a3..5cb60e0 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs @@ -1,12 +1,15 @@ using System.Diagnostics; using System.IO; +using System.Windows; using System.Windows.Input; using FourFoldAccountManager.Core.Data; using FourFoldAccountManager.Core.Models; using FourFoldAccountManager.Core.Overlay; using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; using FourFoldAccountManager.Core.Timing; using FourFoldAccountManager.Desktop.Plugins; +using FourFoldAccountManager.Desktop.Plugins.Hub; using FourFoldAccountManager.Desktop.Plugins.Web; using FourFoldAccountManager.Desktop.Views; @@ -19,6 +22,7 @@ public partial class MainWindow : IPluginHostData private readonly Dictionary _postedXpUpdates = []; private CommunityPluginManager _communityPlugins = null!; + private PluginHub _pluginHub = null!; private string _postedAccounts = string.Empty; private System.Windows.Threading.DispatcherTimer? _pluginCardRefreshTimer; @@ -36,6 +40,17 @@ private void InitializeCommunityPlugins(LocalDataPaths paths) RefreshPluginSidebar(); RefreshTrackerRows(); }; + _pluginHub = new PluginHub(paths, _communityPlugins); + _pluginHub.Changed += () => PluginSidebar.SetHubState(_pluginHub.ViewState); + // An uninstalled plugin's cards, its place in the strip and its switch go from the saved settings too. + _pluginHub.Uninstalled += id => + _ = ApplyPluginChangeAsync(settings => HubPolicy.WithUninstalled(settings, id), refreshEffects: true); + PluginSidebar.HubOpened += () => _ = _pluginHub.RefreshAsync(userAsked: false); + PluginSidebar.HubRetryRequested += () => _ = _pluginHub.RefreshAsync(userAsked: true); + PluginSidebar.HubInstallRequested += id => _ = _pluginHub.InstallAsync(id); + PluginSidebar.HubUninstallRequested += ConfirmPluginUninstall; + // The catalog reader only lets through https://github.com//, and OpenInBrowser opens https only. + PluginSidebar.HubSourceRequested += uri => ((IPluginHostData)this).OpenInBrowser(uri); _pluginCards.Changed += QueuePluginCardRefresh; _timer.StateChanged += () => _communityPlugins.PostEvent("timer.changed", null); PluginSidebar.DeveloperModeChangeRequested += on => @@ -60,6 +75,28 @@ private void InitializeCommunityPlugins(LocalDataPaths paths) }; } + // Uninstalling deletes the plugin's saved data, so it asks first, and No is the answer Enter gives. The name comes from + // the catalog or the plugin, so it only ever goes into the message as it is. The sidebar can be in the separate + // tools window, so the box belongs to whichever window the user clicked in. + private void ConfirmPluginUninstall(string id) + { + var state = _pluginHub.ViewState; + var name = state.Plugins.FirstOrDefault(plugin => plugin.Id == id)?.Name + ?? state.Pulled.FirstOrDefault(plugin => plugin.Id == id)?.Name + ?? id; + var answer = MessageBox.Show( + Window.GetWindow(PluginSidebar) ?? this, + $"Uninstall {name}? Its saved data on this computer will be deleted.", + "Uninstall plugin", + MessageBoxButton.YesNo, + MessageBoxImage.Warning, + MessageBoxResult.No); + if (answer == MessageBoxResult.Yes) + { + _ = _pluginHub.UninstallAsync(id); + } + } + private void RefreshPluginSidebar() { PluginSidebar.SetPlugins(AllPlugins); diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs index 79c26ce..308e33f 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs @@ -331,6 +331,9 @@ private async void MainWindow_Loaded(object sender, RoutedEventArgs e) SetManagerEnabled(true); // Not awaited: a slow or stuck plugin start must never keep the manager disabled. _ = _communityPlugins.ApplyAsync(_panelSettings); + // After ApplyAsync: the manager starts no hub plugin until it has seen the user's settings, so a plugin + // they switched off is never started first. + _ = _pluginHub.StartAsync(); LayoutPicker.SelectedValue = _panelSettings.Layout; AccountsListBox.SelectedIndex = _accounts.Count > 0 ? 0 : -1; UpdateAccountActions(); @@ -3422,6 +3425,8 @@ private async void MainWindow_Closing(object? sender, System.ComponentModel.Canc // typed just before closing reaches disk instead of being lost. _plugins.XpCalc.View.FlushPendingTargetSave(); _pluginCardRefreshTimer?.Stop(); + // First, so a download that finishes now can't reach the plugins that are being disposed. + _pluginHub.Dispose(); _communityPlugins.Dispose(); try diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Hub/HubViewState.cs b/src/FourFoldAccountManager.Desktop/Plugins/Hub/HubViewState.cs new file mode 100644 index 0000000..103b367 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Hub/HubViewState.cs @@ -0,0 +1,22 @@ +using FourFoldAccountManager.Core.Plugins.Hub; + +namespace FourFoldAccountManager.Desktop.Plugins.Hub; + +// An installed plugin the hub no longer lists, with the reason to show. +public sealed record HubPulledPlugin(string Id, string Name, string Reason); + +// Everything the hub page and the plugin list show about the hub. +public sealed record HubViewState( + bool Loading, + bool Unreachable, + IReadOnlyList Plugins, + IReadOnlySet Installed, + // Plugins being installed, updated or removed right now. + IReadOnlySet Busy, + // The reason a plugin's last install or removal failed, by plugin id. + IReadOnlyDictionary Errors, + IReadOnlyList Pulled) +{ + public static HubViewState Empty { get; } = new( + false, false, [], new HashSet(), new HashSet(), new Dictionary(), []); +} diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Hub/PluginHub.cs b/src/FourFoldAccountManager.Desktop/Plugins/Hub/PluginHub.cs new file mode 100644 index 0000000..07bab8d --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Plugins/Hub/PluginHub.cs @@ -0,0 +1,449 @@ +using System.Net.Http; +using System.Text; +using System.Windows.Threading; +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; +using FourFoldAccountManager.Desktop.Plugins.Web; + +namespace FourFoldAccountManager.Desktop.Plugins.Hub; + +// The plugin hub as the app sees it: checks the catalog, installs and updates plugins, stops the ones that were +// pulled, and tells the plugin manager which installed plugins may run. Create and use it on the UI thread. Nothing +// here throws into the app: a failure leaves things as they were and shows in ViewState. +public sealed class PluginHub : IDisposable +{ + // A hub page that is opened again and again checks the hub at most this often. + private const long MinimumGapMilliseconds = 60_000; + + private const string RemoveFailed = "The plugin couldn't be removed."; + + // How long one whole download, body included, may take. The client's own timeout covers only the wait for the + // response headers, so a connection that goes quiet partway through a body would otherwise hold the gate, and with + // it every other hub operation, until the app is restarted. + private static readonly TimeSpan DownloadLimit = TimeSpan.FromMinutes(2); + + private readonly HubStore _store; + private readonly CommunityPluginManager _manager; + + // Its timeout bounds only the wait for a response to start; DownloadLimit bounds a whole download. + private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(60) }; + private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromHours(6) }; + + // Start, refresh, install and uninstall run one at a time. Each swaps plugin folders and tells the manager what may + // run; interleaved, one would load a plugin from the folder another is replacing, or list one that is being removed. + private readonly SemaphoreSlim _gate = new(1, 1); + + // Plugins being installed, updated or removed, from the click until the operation ends, so a second click does + // nothing and the page shows the plugin as busy while it waits for its turn. + private readonly HashSet _busy = new(StringComparer.Ordinal); + private readonly Dictionary _errors = new(StringComparer.Ordinal); + private HubCatalog? _catalog; + private IReadOnlyList _installed = []; + private IReadOnlyList _pulled = []; + private bool _loading; + private bool _unreachable; + private bool _disposed; + private long? _lastCheck; + + public PluginHub(LocalDataPaths paths, CommunityPluginManager manager) + { + _store = new HubStore(paths); + _manager = manager; + _http.DefaultRequestHeaders.UserAgent.ParseAdd("FourFoldAccountManager"); + _timer.Tick += (_, _) => _ = RefreshAsync(userAsked: false); + } + + public event Action? Changed; + + // A plugin was uninstalled; its cards and ids should go from the saved settings. + public event Action? Uninstalled; + + public HubViewState ViewState => new( + _loading, + _unreachable, + _catalog?.Plugins ?? [], + _installed.Select(plugin => plugin.Id).ToHashSet(StringComparer.Ordinal), + new HashSet(_busy, StringComparer.Ordinal), + new Dictionary(_errors, StringComparer.Ordinal), + _pulled); + + // Reads what is installed and the last catalog from disk and starts the plugins that may run. The hub itself is + // contacted only when something is installed; otherwise not until the hub page is opened. + public Task StartAsync() => RunAsync(StartCoreAsync); + + // Downloads the catalog, installs approved updates, and stops plugins that were pulled. + public Task RefreshAsync(bool userAsked) + { + var askedAt = Environment.TickCount64; + return RunAsync(async () => + { + if (IsDue(userAsked, askedAt)) + { + await RefreshCoreAsync(); + } + }); + } + + public async Task InstallAsync(string id) + { + if (_disposed || _catalog?.Plugins.Any(plugin => plugin.Id == id) != true || !_busy.Add(id)) + { + return; + } + + _errors.Remove(id); + try + { + Notify(); + await RunAsync(async () => + { + // The catalog may have changed while this waited for its turn. + if (_catalog?.Plugins.FirstOrDefault(plugin => plugin.Id == id) is { } listed) + { + await InstallCoreAsync(listed); + PushLoads(); + } + }); + } + finally + { + _busy.Remove(id); + Notify(); + } + } + + public async Task UninstallAsync(string id) + { + if (_disposed || !_busy.Add(id)) + { + return; + } + + _errors.Remove(id); + try + { + Notify(); + await RunAsync(async () => + { + // Only a plugin the record holds is removed: an uninstall also deletes the plugin's saved settings. + if (_installed.Any(plugin => plugin.Id == id)) + { + await RemoveAsync(id); + PushLoads(); + } + }); + } + finally + { + _busy.Remove(id); + Notify(); + } + } + + // Doesn't wait for the gate: an operation that holds it finds _disposed set and stops at its next step, and the + // download it may be waiting on ends when the client is disposed. + public void Dispose() + { + _disposed = true; + _timer.Stop(); + _http.Dispose(); + } + + // Runs one operation with the gate held. An operation that gets its turn after Dispose does nothing. + private async Task RunAsync(Func operation) + { + await _gate.WaitAsync(); + try + { + if (!_disposed) + { + await operation(); + } + } + catch (Exception) + { + // Every operation records its own failures where the hub page can show them; this is the last stop, so + // nothing reaches the app. + } + finally + { + _gate.Release(); + } + } + + // A refresh that waited for its turn runs only if it is still due: a user's request is met by any check that came + // back after the request was made, and a routine one by a check within the last minute. + private bool IsDue(bool userAsked, long askedAt) => + _lastCheck is not { } last || + (userAsked ? last < askedAt : Environment.TickCount64 - last >= MinimumGapMilliseconds); + + // Gate held. + private async Task StartCoreAsync() + { + try + { + var (installed, catalog) = await Task.Run(() => + { + _store.CleanUp(); + return (_store.LoadInstalled(), _store.LoadCatalog()); + }); + if (_disposed) + { + return; + } + + _installed = installed; + _catalog = catalog; + PushLoads(); + if (_installed.Count > 0) + { + await RefreshCoreAsync(); + } + } + catch (Exception) + { + // The record of installed plugins can't be read right now. Hub plugins stay off for this session, and + // nothing is written over it. + } + } + + // Gate held. Loading is true only while this runs, not while a refresh waits for its turn. + private async Task RefreshCoreAsync() + { + _loading = true; + try + { + Notify(); + var bytes = await DownloadAsync(HubAddresses.Catalog, HubLimits.MaximumCatalogBytes); + if (_disposed) + { + return; + } + + _lastCheck = Environment.TickCount64; + var text = bytes is null ? null : Encoding.UTF8.GetString(bytes); + if (HubCatalogJson.Parse(text) is not { } catalog) + { + // The last good catalog stays in use. + _unreachable = true; + return; + } + + _unreachable = false; + _catalog = catalog; + try + { + await _store.SaveCatalogAsync(text!, CancellationToken.None); + } + catch (Exception) + { + // Offline starts fall back to the older copy; the next check saves again. + } + + try + { + // Approved updates install without asking, and an install a crash left without its files is repaired. + var due = HubPolicy.Updates(catalog, _installed) + .Concat(catalog.Plugins.Where(plugin => + _installed.Any(other => other.Id == plugin.Id) && !_store.IsIntact(plugin.Id))) + .DistinctBy(plugin => plugin.Id) + .ToArray(); + foreach (var plugin in due) + { + if (_disposed) + { + return; + } + + // A plugin the user has already asked to install or remove is theirs to finish. + if (!_busy.Add(plugin.Id)) + { + continue; + } + + try + { + await InstallCoreAsync(plugin); + } + finally + { + _busy.Remove(plugin.Id); + Notify(); + } + } + } + finally + { + // However the updates end: a plugin that was swapped and stopped runs again, and one the new catalog + // pulled stops. Once, after all of them, so a plugin waiting for its own update isn't restarted early. + PushLoads(); + } + } + catch (Exception) + { + _unreachable = true; + } + finally + { + _loading = false; + Notify(); + } + } + + // Gate held, and the plugin's id is in _busy. Downloads, checks and installs one listed plugin over whatever + // version is there. A failure leaves the installed version in place and records a reason for the hub page. The + // caller loads the plugin again afterwards (PushLoads). + private async Task InstallCoreAsync(HubPlugin plugin) + { + _errors.Remove(plugin.Id); + try + { + Notify(); + var package = await DownloadAsync( + HubAddresses.Package(plugin.Id, plugin.Commit), Math.Min(plugin.Size, HubLimits.MaximumPackageBytes)); + if (_disposed) + { + return; + } + + if (package is null) + { + _errors[plugin.Id] = "The download failed."; + return; + } + + var (reason, staging) = await Task.Run(() => + { + var refused = _store.Stage(plugin, package, out var folder); + return (refused, folder); + }); + if (_disposed) + { + // The staging folder is left for the next start's CleanUp. + return; + } + + if (reason is not null) + { + _errors[plugin.Id] = reason; + return; + } + + // Nothing may be running from the folder while it is swapped. + _manager.Unload(plugin.Id); + // Off the UI thread: the swap moves folders and flushes the record to disk. + await Task.Run(() => _store.CommitAsync(plugin, staging, CancellationToken.None)); + try + { + _installed = _store.LoadInstalled(); + } + catch (Exception) + { + // The plugin is installed; only the re-read failed. The list stays as it was, and is read again at the + // next install, uninstall or start. That is no failure to report. + } + } + catch (Exception) + { + _errors[plugin.Id] = "The plugin couldn't be installed."; + } + } + + // One whole download under DownloadLimit. Null when it fails, is cancelled or runs out of time. + private async Task DownloadAsync(Uri address, long maximumBytes) + { + using var limit = new CancellationTokenSource(DownloadLimit); + return await HubHttp.DownloadAsync(_http, address, maximumBytes, limit.Token); + } + + // Gate held, and the plugin's id is in _busy. The record is written first by the store, so a step that fails later + // still takes the plugin out of the record. What the manager clears and forgets, and what the saved settings forget, + // follow the record as it is now, not how the removal ended: nothing of the plugin's is wiped while it is still + // installed. + private async Task RemoveAsync(string id) + { + try + { + // Nothing may be running from the folder, or holding its settings file, while they are deleted. + _manager.Unload(id); + // Off the UI thread: the delete walks up to 500 files and the record is flushed to disk. + await Task.Run(() => _store.UninstallAsync(id, CancellationToken.None)); + } + catch (Exception) + { + _errors[id] = RemoveFailed; + } + finally + { + try + { + _installed = _store.LoadInstalled(); + } + catch (Exception) + { + // Whether the plugin is still recorded can't be told, so the page says it couldn't be removed. + _errors[id] = RemoveFailed; + } + } + + if (!_disposed && _installed.All(plugin => plugin.Id != id)) + { + try + { + await _manager.ClearBrowserDataAsync(id); + } + catch (Exception) + { + // Best effort: the plugin is gone from the record either way, and its settings must still be forgotten. + } + + // The manager may have been disposed while the browser data was clearing. + if (!_disposed) + { + _manager.Forget(id); + Uninstalled?.Invoke(id); + } + } + } + + // Gate held. Tells the manager which installed plugins may run, and works out which ones the hub no longer lists. + private void PushLoads() + { + if (_disposed) + { + return; + } + + _pulled = _installed + .Select(plugin => (plugin.Id, Reason: HubPolicy.PulledReason(_catalog, plugin.Id))) + .Where(entry => entry.Reason is not null) + .Select(entry => new HubPulledPlugin( + entry.Id, + PluginManifestReader.Read(_store.FolderOf(entry.Id)).Manifest?.Name ?? entry.Id, + entry.Reason!)) + .ToArray(); + // Checked while something is installed; with nothing installed there is nothing to keep up to date. + if (_installed.Count > 0) + { + _timer.Start(); + } + else + { + _timer.Stop(); + } + + // Not awaited: it finishes when every plugin has started, and one that hangs must not hold up the hub. + _ = _manager.SetHubPluginsAsync(HubPolicy.Loads(_catalog, _installed, _store.FolderOf)); + Notify(); + } + + // Nothing is raised after Dispose: the window and the manager it would reach are going away. + private void Notify() + { + if (!_disposed) + { + Changed?.Invoke(); + } + } +} diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs index c6af14a..6bf301a 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/CommunityPluginManager.cs @@ -4,13 +4,14 @@ using FourFoldAccountManager.Core.Data; using FourFoldAccountManager.Core.Models; using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; namespace FourFoldAccountManager.Desktop.Plugins.Web; public sealed record RejectedPlugin(string FolderName, string Reason); -// Loads community plugins from the dev plugins folder while developer mode is on, runs the ones that are switched on, -// and reloads a plugin when its files change. Create and use it on the UI thread. +// Runs community plugins from two places: the plugins installed from the hub, and, while developer mode is on, the +// dev plugins folder (reloading a plugin when its files change). Create and use it on the UI thread. public sealed class CommunityPluginManager : IDisposable { private readonly LocalDataPaths _paths; @@ -21,12 +22,25 @@ public sealed class CommunityPluginManager : IDisposable private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher; private readonly DispatcherTimer _reloadTimer; private readonly HashSet _changedFolders = new(StringComparer.OrdinalIgnoreCase); - private readonly List _plugins = []; + private readonly List _dev = []; + private readonly List _hub = []; + private readonly Dictionary _hubLoadOf = []; private readonly List _rejected = []; + + // One settings store per plugin id, so a hub plugin, its update and a dev copy of it never write the same file + // from two stores. + private readonly Dictionary _storages = new(StringComparer.Ordinal); + private IReadOnlyList _hubLoads = []; private FileSystemWatcher? _watcher; private bool _disposed; + private bool _changedQueued; + private string? _folderError; + private string? _startError; private PanelSettings _settings = PanelSettings.Default; + // False until the first ApplyAsync: before that _settings is only the default, which switches everything on. + private bool _settingsGiven; + public CommunityPluginManager(LocalDataPaths paths, IPluginHostData host, Panel parkingHost, PluginCardStore cards) { _paths = paths; @@ -48,18 +62,19 @@ public CommunityPluginManager(LocalDataPaths paths, IPluginHostData host, Panel }; } - public IReadOnlyList Plugins => _plugins; + // Dev-folder plugins first, then hub plugins. + public IReadOnlyList Plugins => [.. _dev, .. _hub]; public IReadOnlyList Rejected => _rejected; - // Set when the dev folder can't be read or the plugin browser can't start; the plugin list shows it. - public string? StartupError { get; private set; } + // Set when the dev folder can't be read or a plugin can't start; the plugin list shows it. + public string? StartupError => _folderError ?? _startError; // Raised when the set of plugins, or whether one is running, changed. public event Action? Changed; - // Matches what is loaded and running to the settings. Never throws: a folder that can't be read, or a plugin that - // can't start, is reported through StartupError. + // Matches the dev-folder plugins, and what is running, to the settings. Never throws: a folder that can't be + // read, or a plugin that can't start, is reported through StartupError. public async Task ApplyAsync(PanelSettings settings) { // A click while the window is closing must not build new web views. @@ -69,34 +84,33 @@ public async Task ApplyAsync(PanelSettings settings) } _settings = settings; + _settingsGiven = true; if (!settings.PluginDeveloperMode) { - var hadState = _plugins.Count > 0 || _rejected.Count > 0 || StartupError is not null; - UnloadAll(); - StartupError = null; - if (hadState) + if (_dev.Count > 0 || _rejected.Count > 0 || _watcher is not null || _folderError is not null) { + UnloadDev(); + _folderError = null; + // A hub plugin that a dev copy was standing in for comes back. + ReconcileHub(); Changed?.Invoke(); } - - return; } - - if (_watcher is null) + else if (_watcher is null) { try { Directory.CreateDirectory(_paths.DevPluginsRoot); Rescan(changedFolders: null); StartWatching(); + _folderError = null; } catch (Exception) { AbandonLoad(); - Changed?.Invoke(); - return; } + ReconcileHub(); Changed?.Invoke(); } @@ -106,9 +120,56 @@ public async Task ApplyAsync(PanelSettings settings) } } + // The installed hub plugins that may run. Never throws. + public async Task SetHubPluginsAsync(IReadOnlyList loads) + { + if (_disposed) + { + return; + } + + _hubLoads = loads; + ReconcileHub(); + Changed?.Invoke(); + if (await SyncRunningAsync()) + { + Changed?.Invoke(); + } + } + + // Stops a hub plugin and lets go of its folder, before the folder is swapped or deleted. It stays unloaded until + // the next SetHubPluginsAsync. + public void Unload(string id) + { + // After Dispose the plugins are gone for good; reconciling would load the other hub plugins again. + if (_disposed) + { + return; + } + + _hubLoads = _hubLoads.Where(load => load.Id != id).ToArray(); + ReconcileHub(); + Changed?.Invoke(); + } + + // After an uninstall deleted the plugin's settings file: the store that cached it must not write it back. + public void Forget(string id) => _storages.Remove(id); + + // Best effort, and bounded: an uninstall that awaits this must not hang if the borrowed web view never starts. + public async Task ClearBrowserDataAsync(string id) + { + if (_disposed) + { + return; + } + + await Task.WhenAny( + _browser.ClearOriginAsync(_parkingHost, PluginNetworkPolicy.Origin(id)), Task.Delay(TimeSpan.FromSeconds(10))); + } + public void PostEvent(string name, object? data) { - foreach (var plugin in _plugins) + foreach (var plugin in Plugins) { plugin.PostEvent(name, data); } @@ -117,7 +178,108 @@ public void PostEvent(string name, object? data) public void Dispose() { _disposed = true; - UnloadAll(); + UnloadDev(); + foreach (var plugin in _hub) + { + plugin.Dispose(); + } + + _hub.Clear(); + _hubLoadOf.Clear(); + } + + // Makes the loaded hub plugins match the loads that may run and aren't stood in for by a dev plugin. A load whose + // folder, commit or trust changed is a different load, so its plugin is replaced. + private void ReconcileHub() + { + var wanted = HubPolicy.Visible(_hubLoads, _dev.Select(plugin => plugin.Manifest.Id).ToHashSet(StringComparer.Ordinal)); + foreach (var plugin in _hub.ToArray()) + { + if (!wanted.Contains(_hubLoadOf[plugin])) + { + plugin.Dispose(); + _hub.Remove(plugin); + _hubLoadOf.Remove(plugin); + } + } + + foreach (var load in wanted) + { + if (_hubLoadOf.ContainsValue(load)) + { + continue; + } + + // An install that was damaged on disk simply doesn't load; the next hub check installs it again. + var manifest = PluginManifestReader.Read(load.Folder).Manifest; + if (manifest is null || manifest.Id != load.Id) + { + continue; + } + + try + { + var plugin = Create(manifest, load.Trust); + _hub.Add(plugin); + _hubLoadOf[plugin] = load; + } + catch (Exception) + { + // One plugin that can't be loaded must never take the others down. + } + } + + // A replaced plugin was appended; the list keeps the order of the loads, so an update never moves a plugin. + var order = wanted.ToList(); + var ordered = _hub.OrderBy(plugin => order.IndexOf(_hubLoadOf[plugin])).ToArray(); + _hub.Clear(); + _hub.AddRange(ordered); + } + + private WebPlugin Create(PluginManifest manifest, PluginTrust trust) + { + if (!_storages.TryGetValue(manifest.Id, out var storage)) + { + storage = new PluginStorage(Path.Combine(_paths.PluginDataRoot, manifest.Id + ".json")); + _storages[manifest.Id] = storage; + } + + var plugin = new WebPlugin(manifest, trust, _browser, _parkingHost, _host, _cards, storage); + // A plugin stops or restarts by itself (a flood, a crash, its Reload button). That can happen inside a web view + // event or mid-start, and Changed re-renders the sidebar, so it is raised later, once for however many plugins + // changed in the meantime. + plugin.RunningChanged += () => + { + if (_changedQueued) + { + return; + } + + _changedQueued = true; + _dispatcher.BeginInvoke(() => + { + _changedQueued = false; + if (!_disposed) + { + // The Reload notice starts a plugin directly. If the user switched it off while it was starting, + // the sync has already passed, so it is stopped here. Stopping raises RunningChanged and queues + // one more pass, which finds nothing running that is switched off. + if (_settingsGiven) + { + foreach (var loaded in Plugins) + { + if (loaded.IsRunning && !PluginLayoutPolicy.IsEnabled(_settings, loaded.Descriptor.Id)) + { + loaded.Stop(); + } + } + } + + Changed?.Invoke(); + } + }); + }; + return plugin; } // Re-reads the dev folder. A plugin whose folder is in changedFolders (or every plugin, when it is null) is @@ -127,12 +289,16 @@ private void Rescan(IReadOnlySet? changedFolders) var folders = Directory.Exists(_paths.DevPluginsRoot) ? Directory.GetDirectories(_paths.DevPluginsRoot).OrderBy(folder => folder, StringComparer.OrdinalIgnoreCase).ToArray() : []; - var kept = _plugins + var kept = _dev .Where(plugin => folders.Contains(plugin.Manifest.Folder, StringComparer.OrdinalIgnoreCase) && changedFolders is not null && !changedFolders.Contains(Path.GetFileName(plugin.Manifest.Folder))) .ToList(); - Unload(_plugins.Except(kept).ToArray()); + foreach (var plugin in _dev.Except(kept).ToArray()) + { + plugin.Dispose(); + } + _rejected.Clear(); foreach (var folder in folders) { @@ -155,90 +321,58 @@ changedFolders is not null && continue; } - WebPlugin webPlugin; try { - webPlugin = new WebPlugin(manifest, PluginTrust.Developer, _browser, _parkingHost, _host, _cards, _paths); + kept.Add(Create(manifest, PluginTrust.Developer)); } catch (Exception) { // One folder that can't be loaded must never take the others down. _rejected.Add(new RejectedPlugin(folderName, "The plugin couldn't be loaded.")); - continue; } - - // A plugin stops or restarts by itself (a flood, a crash, its Reload button). That can happen inside a web - // view event or while SyncRunningAsync is mid-loop, and Changed re-renders the sidebar, so it is raised later. - webPlugin.RunningChanged += () => _dispatcher.BeginInvoke(() => - { - if (!_disposed) - { - Changed?.Invoke(); - } - }); - kept.Add(webPlugin); } - _plugins.Clear(); - _plugins.AddRange(kept.OrderBy(plugin => plugin.Manifest.Folder, StringComparer.OrdinalIgnoreCase)); + _dev.Clear(); + _dev.AddRange(kept.OrderBy(plugin => plugin.Manifest.Folder, StringComparer.OrdinalIgnoreCase)); } - private void Unload(IReadOnlyList plugins) + private void UnloadDev() { - foreach (var plugin in plugins) + StopWatching(); + foreach (var plugin in _dev) { plugin.Dispose(); - _plugins.Remove(plugin); } - } - private void UnloadAll() - { - StopWatching(); - Unload(_plugins.ToArray()); + _dev.Clear(); _rejected.Clear(); } - // The dev folder can't be read or watched. Nothing stays half-loaded, and the next apply tries again. + // The dev folder can't be read or watched. No dev plugin stays half-loaded, and the next apply tries again. private void AbandonLoad() { - UnloadAll(); - StartupError = "The dev plugins folder couldn't be read."; + UnloadDev(); + _folderError = "The dev plugins folder couldn't be read."; } // Starts switched-on plugins and stops switched-off ones. Returns whether anything changed. private async Task SyncRunningAsync() { - var changed = StartupError is not null; - StartupError = null; - foreach (var plugin in _plugins.ToArray()) + // Until the user's settings are known, a plugin they switched off could be started; ApplyAsync starts them all. + if (!_settingsGiven) { - // A reload or developer mode switching off during an earlier await disposed this one. - if (!_plugins.Contains(plugin)) - { - continue; - } + return false; + } + var changed = _startError is not null; + _startError = null; + var starts = new List>(); + foreach (var plugin in Plugins) + { var shouldRun = PluginLayoutPolicy.IsEnabled(_settings, plugin.Descriptor.Id); if (shouldRun && !plugin.IsRunning) { - try - { - await plugin.StartAsync(); - // The user may have switched it off while it was starting. - if (plugin.IsRunning && !PluginLayoutPolicy.IsEnabled(_settings, plugin.Descriptor.Id)) - { - plugin.Stop(); - } - - // A start that was abandoned (the plugin was stopped meanwhile) returns normally, so ask the plugin. - changed |= plugin.IsRunning; - } - catch (Exception) - { - StartupError = "Community plugins couldn't start."; - changed = true; - } + starts.Add(StartAsync(plugin)); } else if (!shouldRun && plugin.IsRunning) { @@ -247,9 +381,37 @@ private async Task SyncRunningAsync() } } + // Side by side, so one plugin that hangs while starting can't hold up the rest. + foreach (var started in await Task.WhenAll(starts)) + { + changed |= started; + } + return changed; } + // Starts one plugin. A plugin disposed meanwhile (a reload, an update, developer mode switching off) refuses to + // start, and one that was abandoned mid-start returns normally, so the answer is whether it is running now. + private async Task StartAsync(WebPlugin plugin) + { + try + { + await plugin.StartAsync(); + // The user may have switched it off while it was starting. + if (plugin.IsRunning && !PluginLayoutPolicy.IsEnabled(_settings, plugin.Descriptor.Id)) + { + plugin.Stop(); + } + + return plugin.IsRunning; + } + catch (Exception) + { + _startError = "Community plugins couldn't start."; + return true; + } + } + private void StartWatching() { var watcher = new FileSystemWatcher(_paths.DevPluginsRoot) @@ -332,10 +494,10 @@ private async Task ReloadChangedAsync() { // A tick on the UI thread must never take the app down, whatever state the folder was left in. AbandonLoad(); - Changed?.Invoke(); - return; } + // A dev plugin that appeared or went away changes which hub plugins it stands in for. + ReconcileHub(); // Before the plugins start, so the strip never shows the ones that were just disposed. Changed?.Invoke(); await SyncRunningAsync(); diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs index 1f43b54..1779d7f 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs @@ -9,6 +9,7 @@ namespace FourFoldAccountManager.Desktop.Plugins.Web; // message gets an error reply (or none) and never throws into the app. internal sealed class PluginApi( PluginManifest manifest, + PluginTrust trust, IPluginHostData host, PluginStorage storage, PluginHttpFetcher http, @@ -279,11 +280,18 @@ private void OpenExternal(string url) { // A "user@" prefix can make a link read as a trusted site while it goes somewhere else. if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps || - uri.UserInfo.Length > 0 || PluginNetworkPolicy.IsLocalHost(uri.IdnHost)) + uri.UserInfo.Length > 0 || TryGetIdnHost(uri) is not { } idnHost || PluginNetworkPolicy.IsLocalHost(idnHost)) { throw new PluginApiException("invalid-argument", "Only https links can be opened."); } + // A plugin can send the user only where it may go itself: the sites it declared, or anywhere once the hub has + // cleared it for any website. That list is what the hub shows and what was reviewed. + if (PluginNetworkPolicy.IsPluginHost(idnHost) || !PluginNetworkPolicy.IsAllowed(uri, manifest, trust)) + { + throw new PluginApiException("site-not-allowed", "A plugin can only open links on the sites it declares."); + } + if (!host.IsPanelShowing(manifest.Id)) { throw new PluginApiException("unavailable", "A link can only be opened while the plugin's panel is showing."); @@ -297,6 +305,20 @@ private void OpenExternal(string url) } _lastOpened = now; - host.OpenInBrowser(uri); + // The browser gets the host as it was checked (its xn-- form), not a Unicode or fullwidth spelling of it. + host.OpenInBrowser(new UriBuilder(uri) { Host = idnHost }.Uri); + } + + // IdnHost throws for some invalid international host names; such a link is a bad argument, not a failure. + private static string? TryGetIdnHost(Uri uri) + { + try + { + return uri.IdnHost; + } + catch (UriFormatException) + { + return null; + } } } diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs index 33b7447..1d35eab 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginBrowser.cs @@ -1,6 +1,9 @@ using System.IO; +using System.Text.Json; +using System.Windows.Controls; using FourFoldAccountManager.Core.Data; using Microsoft.Web.WebView2.Core; +using Microsoft.Web.WebView2.Wpf; namespace FourFoldAccountManager.Desktop.Plugins.Web; @@ -30,4 +33,40 @@ public async Task GetEnvironmentAsync() throw; } } + + // Removes everything the plugin browser stored for one plugin's address (cookies, IndexedDB, caches), after the + // plugin is uninstalled. It needs a web view to ask through, so it borrows a blank one for a moment. Best effort: + // data left behind takes disk space and nothing else. + public async Task ClearOriginAsync(Panel parkingHost, Uri origin) + { + // No plugin has ever run, so there is nothing to clear and no reason to start a browser. + if (!Directory.Exists(paths.PluginWebViewUserDataRoot)) + { + return; + } + + WebView2CompositionControl? view = null; + try + { + view = new WebView2CompositionControl(); + parkingHost.Children.Add(view); + await view.EnsureCoreWebView2Async(await GetEnvironmentAsync()); + await view.CoreWebView2.CallDevToolsProtocolMethodAsync( + "Storage.clearDataForOrigin", + JsonSerializer.Serialize(new { origin = origin.GetLeftPart(UriPartial.Authority), storageTypes = "all" })); + } + catch (Exception) + { + // Left behind; see above. + } + finally + { + // Null when the control could not even be created. + if (view is not null) + { + parkingHost.Children.Remove(view); + view.Dispose(); + } + } + } } diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs index 2cd2e81..666307b 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/WebPlugin.cs @@ -3,7 +3,6 @@ using System.Text.Json; using System.Windows; using System.Windows.Controls; -using FourFoldAccountManager.Core.Data; using FourFoldAccountManager.Core.Plugins; using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.Wpf; @@ -71,16 +70,14 @@ public WebPlugin( Panel parkingHost, IPluginHostData host, PluginCardStore cards, - LocalDataPaths paths) + PluginStorage storage) { Manifest = manifest; _trust = trust; _browser = browser; _parkingHost = parkingHost; _http = new PluginHttpFetcher(manifest, trust); - _api = new PluginApi( - manifest, host, new PluginStorage(Path.Combine(paths.PluginDataRoot, manifest.Id + ".json")), _http, cards, - TimeProvider.System); + _api = new PluginApi(manifest, trust, host, storage, _http, cards, TimeProvider.System); _contentSecurityPolicy = PluginNetworkPolicy.BuildContentSecurityPolicy(manifest, trust); // A plugin with no icon image shows the default Segoe glyph, a puzzle piece. Descriptor = new PluginDescriptor(manifest.Id, manifest.Name, manifest.ShortLabel, "\uEA86", [], []) @@ -88,11 +85,10 @@ public WebPlugin( Cards = manifest.Cards.Select(card => new PluginCardDescriptor(card.Id, card.Name, card.Scope)).ToArray(), IconPath = manifest.Icon is null ? null : Path.Combine(manifest.Folder, manifest.Icon), Badge = trust == PluginTrust.Developer ? "DEV" : null, - // IdnHost, so a look-alike Unicode host name shows as its real xn-- form. - Detail = PluginNetworkPolicy.AllowsAnySite(manifest, trust) ? "Can contact: any website" - : manifest.Sites.Count == 0 ? "Can contact: no websites" - : "Can contact: " + string.Join(", ", manifest.Sites.Select(site => - site.IsDefaultPort ? site.IdnHost : $"{site.IdnHost}:{site.Port}")) + Detail = $"by {manifest.Author}\n" + + (PluginNetworkPolicy.AllowsAnySite(manifest, trust) ? "Can contact: any website" + : manifest.Sites.Count == 0 ? "Can contact: no websites" + : "Can contact: " + string.Join(", ", manifest.Sites.Select(PluginNetworkPolicy.SiteLabel))) }; var reload = new Button { Content = "Reload", Height = 30, Padding = new Thickness(12, 0, 12, 0) }; @@ -110,7 +106,62 @@ public WebPlugin( } }; _viewHost.Children.Add(_stoppedNotice); - _root = new Border { BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(9), Child = _viewHost }; + // Everything in the page below is drawn by the plugin, so this bar, drawn by FourFold, says whose page it is. + var barName = new TextBlock + { + Text = manifest.Name, + FontSize = 11, + FontWeight = FontWeights.SemiBold, + MaxWidth = 100, + VerticalAlignment = VerticalAlignment.Center, + TextTrimming = TextTrimming.CharacterEllipsis + }; + var barAuthor = new TextBlock + { + Text = "by " + manifest.Author, + FontSize = 11, + Margin = new Thickness(6, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center, + TextTrimming = TextTrimming.CharacterEllipsis + }; + barAuthor.SetResourceReference(TextBlock.ForegroundProperty, "Brush.TextMuted"); + var barTagText = new TextBlock + { + Text = trust == PluginTrust.Developer ? "DEV" : "COMMUNITY", + FontSize = 9, + FontWeight = FontWeights.Bold + }; + barTagText.SetResourceReference(TextBlock.ForegroundProperty, "Brush.TextMuted"); + var barTag = new Border + { + Child = barTagText, + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(3), + Padding = new Thickness(5, 0, 5, 0), + Margin = new Thickness(8, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center + }; + barTag.SetResourceReference(Border.BorderBrushProperty, "Brush.BorderStrong"); + DockPanel.SetDock(barTag, Dock.Right); + DockPanel.SetDock(barName, Dock.Left); + var bar = new Border + { + Height = 24, + Padding = new Thickness(9, 0, 9, 0), + BorderThickness = new Thickness(0, 0, 0, 1), + CornerRadius = new CornerRadius(8, 8, 0, 0), + // The tag stays first, so it is measured first and can never be squeezed out. + Child = new DockPanel { Children = { barTag, barName, barAuthor } } + }; + bar.SetResourceReference(Border.BackgroundProperty, "Brush.SurfaceRaised"); + bar.SetResourceReference(Border.BorderBrushProperty, "Brush.Border"); + var layout = new Grid(); + layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + layout.RowDefinitions.Add(new RowDefinition()); + layout.Children.Add(bar); + Grid.SetRow(_viewHost, 1); + layout.Children.Add(_viewHost); + _root = new Border { BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(9), Child = layout }; _root.SetResourceReference(Border.BackgroundProperty, "Brush.Surface"); _root.SetResourceReference(Border.BorderBrushProperty, "Brush.Border"); // The view lives in the panel while the panel is on screen, and in the parking host the rest of the time. A web diff --git a/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs b/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs index 7652ea1..2268b3a 100644 --- a/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/Views/PluginSidebar.xaml.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; @@ -5,8 +6,11 @@ using System.Windows.Media; using System.Windows.Media.Imaging; using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Overlay; using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Core.Plugins.Hub; using FourFoldAccountManager.Desktop.Plugins; +using FourFoldAccountManager.Desktop.Plugins.Hub; using FourFoldAccountManager.Desktop.Plugins.Web; namespace FourFoldAccountManager.Desktop.Views; @@ -18,6 +22,10 @@ public partial class PluginSidebar : UserControl private const string IconFont = "Segoe Fluent Icons, Segoe MDL2 Assets"; // A private drag format, so only a strip icon can be dropped on the strip. private const string DragFormat = "FourFold.PluginId"; + // The hub page builds every row it shows each time it refreshes, so it shows only this many matches. Installed + // plugins sort first, so they are among them unless more than 50 are installed. A virtualising list is the upgrade + // if the hub outgrows this. + private const int HubRowLimit = 50; private IReadOnlyList _plugins = []; private PanelSettings _settings = PanelSettings.Default; private bool _showingList; @@ -28,6 +36,13 @@ public partial class PluginSidebar : UserControl private string? _pressedId; private IReadOnlyList _rejected = []; private string? _communityError; + private HubViewState _hub = HubViewState.Empty; + private bool _showingHub; + private string? _hubExpandedId; + private Grid? _hubPage; + private TextBox? _hubSearch; + private Button? _hubRefresh; + private StackPanel? _hubRows; public PluginSidebar() { @@ -43,6 +58,12 @@ public PluginSidebar() public event Action? OpenDevFolderRequested; // Opening the plugin list from a closed panel counts as opening the panel. public event Action? PanelOpenRequested; + // The hub page was opened; a good moment to check the hub. + public event Action? HubOpened; + public event Action? HubRetryRequested; + public event Action? HubInstallRequested; + public event Action? HubUninstallRequested; + public event Action? HubSourceRequested; // In the tools window the panel never closes, since a window that's just a strip would be odd. Moving between the // main window and the tools window starts from the plugin view, not the plugin list or a settings page. @@ -58,6 +79,7 @@ public bool StayOpen _stayOpen = value; _showingList = false; _settingsFor = null; + _showingHub = false; Render(_settings); } } @@ -75,6 +97,12 @@ public void SetCommunityState(IReadOnlyList rejected, string? st Render(_settings); } + public void SetHubState(HubViewState state) + { + _hub = state; + Render(_settings); + } + // True while this plugin's panel is the page on screen. public bool IsShowing(string pluginId) => IsVisible && !_showingList && ShownPlugin()?.Descriptor.Id == pluginId; @@ -158,7 +186,9 @@ private void RenderPage(IFourFoldPlugin? shown) PanelColumn.Width = !visible ? new GridLength(0) : _stayOpen ? new GridLength(1, GridUnitType.Star) : new GridLength(250); PanelGapColumn.Width = new GridLength(visible ? 6 : 0); - BackButton.Visibility = _showingList && _settingsFor is not null ? Visibility.Visible : Visibility.Collapsed; + BackButton.Visibility = _showingList && (_settingsFor is not null || _showingHub) + ? Visibility.Visible + : Visibility.Collapsed; // A plugin's panel carries its own header, so only the plugin list and settings pages get the host's. var showingPlugin = !_showingList && shown is not null; @@ -170,6 +200,12 @@ private void RenderPage(IFourFoldPlugin? shown) TitleText.Text = "Settings"; PageHost.Content = settingsPlugin.SettingsPage; } + else if (_showingList && _showingHub) + { + KickerText.Text = "PLUGINS"; + TitleText.Text = "Plugin hub"; + PageHost.Content = HubPage(); + } else if (_showingList) { KickerText.Text = "PLUGINS"; @@ -193,6 +229,21 @@ private void RenderPage(IFourFoldPlugin? shown) private UIElement BuildPluginList() { var list = new StackPanel(); + var hubButton = new Button + { + Content = "Plugin hub", + Height = 30, + Margin = new Thickness(0, 0, 0, 10), + Style = (Style)FindResource("AppButtonStyle") + }; + hubButton.Click += (_, _) => + { + _showingHub = true; + _hubExpandedId = null; + Render(_settings); + HubOpened?.Invoke(); + }; + list.Children.Add(hubButton); foreach (var descriptor in PluginLayoutPolicy.Ordered(_settings, Descriptors)) { var plugin = Find(descriptor.Id)!; @@ -267,6 +318,55 @@ private UIElement BuildPluginList() list.Children.Add(border); } + // An installed plugin the hub no longer lists: it can't run, so it has no switch, only its reason and a way out. + foreach (var pulled in _hub.Pulled) + { + var name = new TextBlock { Text = pulled.Name, VerticalAlignment = VerticalAlignment.Center }; + name.SetResourceReference(TextBlock.ForegroundProperty, "Brush.TextMuted"); + var uninstall = new Button + { + Content = "Uninstall", + Padding = new Thickness(8, 0, 8, 0), + Margin = new Thickness(6, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center, + IsEnabled = !_hub.Busy.Contains(pulled.Id), + Style = (Style)FindResource("AppButtonStyle") + }; + AutomationProperties.SetName(uninstall, $"Uninstall {pulled.Name}"); + uninstall.Click += (_, _) => HubUninstallRequested?.Invoke(pulled.Id); + var row = new Grid(); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + // The hub's stock reasons already say it; only a maintainer's own reason needs the lead-in. + var block = CreateNameBlock( + name, + null, + pulled.Reason is HubPolicy.RemovedReason or HubPolicy.UnlistedReason + ? pulled.Reason + : "Removed from the hub. " + pulled.Reason, + detailBrush: "Brush.Danger"); + // A failed removal shows why, on its own line under the reason. + if (_hub.Errors.TryGetValue(pulled.Id, out var removalError)) + { + block.Children.Add(HubNote(removalError, "Brush.Danger")); + } + + row.Children.Add(block); + Grid.SetColumn(uninstall, 1); + row.Children.Add(uninstall); + var border = new Border + { + Padding = new Thickness(10, 8, 10, 8), + Margin = new Thickness(0, 0, 0, 6), + CornerRadius = new CornerRadius(6), + BorderThickness = new Thickness(1), + Child = row + }; + border.SetResourceReference(Border.BackgroundProperty, "Brush.SurfaceRaised"); + border.SetResourceReference(Border.BorderBrushProperty, "Brush.Border"); + list.Children.Add(border); + } + if (_communityError is not null) { var error = new TextBlock { Text = _communityError, FontSize = 11, TextWrapping = TextWrapping.Wrap }; @@ -331,6 +431,357 @@ private UIElement BuildPluginList() }; } + // The hub page is built once and kept, so what is typed in the search box survives every refresh of the rows. + private UIElement HubPage() + { + if (_hubPage is null) + { + _hubSearch = new TextBox { Style = (Style)FindResource("InputStyle") }; + AutomationProperties.SetName(_hubSearch, "Search plugins"); + var hint = new TextBlock + { + Text = "Search plugins", + IsHitTestVisible = false, + Margin = new Thickness(10, 0, 0, 0), + VerticalAlignment = VerticalAlignment.Center + }; + hint.SetResourceReference(TextBlock.ForegroundProperty, "Brush.TextMuted"); + _hubSearch.TextChanged += (_, _) => + { + hint.Visibility = string.IsNullOrWhiteSpace(_hubSearch.Text) ? Visibility.Visible : Visibility.Collapsed; + RebuildHubRows(); + }; + // The same request as "Try again": check the hub now. It is never disabled, so it keeps the keyboard + // focus; a click while a check is under way is answered by that check. + _hubRefresh = new Button + { + Padding = new Thickness(10, 0, 10, 0), + Margin = new Thickness(6, 0, 0, 0), + MinWidth = 82, + Style = (Style)FindResource("AppButtonStyle") + }; + AutomationProperties.SetName(_hubRefresh, "Refresh the plugin hub"); + _hubRefresh.Click += (_, _) => HubRetryRequested?.Invoke(); + Grid.SetColumn(_hubRefresh, 1); + var searchArea = new Grid { Margin = new Thickness(0, 0, 0, 8) }; + searchArea.ColumnDefinitions.Add(new ColumnDefinition()); + searchArea.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + searchArea.Children.Add(_hubSearch); + searchArea.Children.Add(hint); + searchArea.Children.Add(_hubRefresh); + + _hubRows = new StackPanel(); + var scroll = new ScrollViewer + { + Content = _hubRows, + VerticalScrollBarVisibility = ScrollBarVisibility.Auto, + HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled + }; + Grid.SetRow(scroll, 1); + _hubPage = new Grid(); + _hubPage.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + _hubPage.RowDefinitions.Add(new RowDefinition()); + _hubPage.Children.Add(searchArea); + _hubPage.Children.Add(scroll); + } + + RebuildHubRows(); + return _hubPage; + } + + // Rebuilding drops the button that has the keyboard focus, so the focus is put back afterwards. Focus that was + // somewhere else (the search box while typing) is left alone. + private void RebuildHubRows() + { + if (_hubRows is null || _hubSearch is null || _hubRefresh is null) + { + return; + } + + _hubRefresh.Content = _hub.Loading ? "Checking…" : "Refresh"; + string? focusedName = null; + string? focusedRowId = null; + if (_hubRows.IsKeyboardFocusWithin && Keyboard.FocusedElement is DependencyObject focused) + { + focusedName = AutomationProperties.GetName(focused); + focusedRowId = _hubRows.Children.OfType().FirstOrDefault(row => row.IsKeyboardFocusWithin)?.Tag as string; + } + + FillHubRows(); + if (focusedName is not null) + { + RestoreHubFocus(focusedName, focusedRowId); + } + } + + // Focus goes to the button with the same name in the same row, else that row's Details button, else (the row is + // gone) the search box. A Details button keeps its name when it reads "Less", so it is found again. + private void RestoreHubFocus(string name, string? rowId) + { + FrameworkElement? scope = _hubRows; + if (rowId is not null) + { + scope = _hubRows!.Children.OfType().FirstOrDefault(row => row.Tag as string == rowId); + } + + var buttons = scope is null ? [] : HubButtons(scope).Where(button => button.IsEnabled).ToList(); + UIElement? target = buttons.FirstOrDefault(button => AutomationProperties.GetName(button) == name) ?? + (rowId is null ? null : buttons.FirstOrDefault()); + (target ?? _hubSearch)?.Focus(); + } + + // Every button below the element, in order. A row's first button is its Details button. + private static IEnumerable