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 new file mode 100644 index 0000000..01df8c6 --- /dev/null +++ b/PLUGIN_AUTHORS.md @@ -0,0 +1,462 @@ +# FourFold plugin author guide + +This guide is for people who want to build a FourFold plugin. You need HTML, CSS and JavaScript. Nothing else. + +## What a plugin is + +A plugin is a folder with a `plugin.json` file and ordinary web files: HTML, JavaScript, CSS, images. FourFold shows the plugin's icon in the plugin strip. Clicking the icon opens the plugin's page as a panel. + +The page runs in its own sandboxed browser. It talks to FourFold only through `window.fourfold`, a small API that gives it: + +- read-only data from FourFold: the accounts, their XP and stats, and the timer (never logins); +- web requests to the sites the plugin declares; +- a small private store; +- overlay cards, drawn by FourFold. + +The page keeps running while its panel is closed, so its cards stay up to date. It stops when the user switches the plugin off or closes FourFold. 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. 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`. +4. Copy the `samples/goal-tracker` folder into it, so that `plugin.json` sits at `dev-plugins\goal-tracker\plugin.json`. The [`samples`](samples) folder is in the GitHub repository, not in the release download. +5. The plugin appears in the strip and the plugin list with a **DEV** badge. + +When you build on a copy of a sample, change its `id` and `author` in `plugin.json` first. + +The other sample, `samples/sandbox-check`, contacts example.com each time it runs. See [Check your own plugin](#check-your-own-plugin). + +Every folder directly inside `dev-plugins` is one plugin. + +- **Saving a file** in a plugin's folder reloads the plugin within about a second. A changed `plugin.json` is read again, including its cards and sites. +- **A rejected `plugin.json`** still gets a row in the plugin list, with the folder name and the reason. Fix the file and it loads. +- **Right-click, Inspect** opens the browser developer tools. This works for plugins in the dev folder only. Blocked requests show up in the console, and so does a rejected call that your code doesn't catch. +- **F5** reloads the plugin's page. +- **Developer mode off** stops every dev plugin and removes it from the strip. Order and on/off state are kept. + +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 + +```json +{ + "id": "cody.goal-tracker", + "name": "Goal tracker", + "shortLabel": "Goals", + "version": "1.0.0", + "author": "Cody", + "description": "Tracks a level goal per account.", + "apiVersion": 1, + "panel": "index.html", + "icon": "icon.png", + "sites": ["https://wiki.example.com"], + "anySite": false, + "cards": [{ "id": "goal", "name": "Goal", "scope": "account" }] +} +``` + +A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, and the plugin list shows the reason. Text values are trimmed. The `name`, `shortLabel`, `author` and `description` fields, and a card's `name`, can't contain control characters (a line break or a bell character, say) or invisible formatting characters (a right-to-left override, say), because FourFold shows them. Fields not listed here are ignored. The file can be at most 64 KB, and it is never served to your page. + +| Field | Required | Rule | +|---|---|---| +| `id` | yes | `author.plugin-name`. Lowercase letters and digits, with single dashes allowed between them, in parts joined by dots. At least one dot, at most 64 characters. The first part can't be a Windows device name (`con`, `prn`, `aux`, `nul`, `com0` to `com9`, `lpt0` to `lpt9`), and an id can't begin with the label `xn` (`xn.tools` is rejected). With each dot written as `--`, the id can be at most 63 characters. Two plugins can't share an id. | +| `name` | yes | 1 to 40 characters. | +| `shortLabel` | yes | 1 to 8 characters, shown on the strip. | +| `version` | yes | `MAJOR.MINOR.PATCH`, digits only, such as `1.0.0`. | +| `author` | yes | 1 to 40 characters. | +| `description` | no | At most 200 characters. | +| `apiVersion` | yes | A whole number. FourFold supports `1`. A higher number is rejected with "Update FourFold to use this plugin." | +| `panel` | yes | Path to an existing `.html` file inside the plugin folder. Forward slashes only. | +| `icon` | no | Path to a `.png` 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`. 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`: + +| Field | Required | Rule | +|---|---|---| +| `id` | yes | Lowercase letters and digits, with single dashes allowed between them. 1 to 32 characters. Unique in the plugin. | +| `name` | yes | 1 to 24 characters. It is the card's title. | +| `scope` | yes | `account` (one card per open account) or `global` (one card). | + +## The API + +`window.fourfold` is there before your scripts run. It is frozen, so you can't change it. + +- Every call returns a promise. +- An `on...` call takes a callback and returns a function that stops the callback. +- A call that is refused rejects with an `Error`. Its `code` property is one of the [error codes](#error-codes) and its `message` says which rule was broken. +- A rejected call never stops your plugin. +- Events can arrive in bursts (`xp.onUpdated` fires once per account), so a handler can start while the last run is still waiting for answers. Run redraws one after another, as the `queue` in `samples/goal-tracker/app.js` does. + +### Accounts + +```js +const accounts = await fourfold.accounts.list(); +for (const account of accounts) { + console.log(account.label, account.inGameName, account.isOpen); +} +fourfold.accounts.onChanged(render); +``` + +`fourfold.accounts.list()` returns `[{ id, label, inGameName, isOpen }]`. + +| Field | Type | Meaning | +|---|---|---| +| `id` | string | The account's id. Pass it to the calls below. | +| `label` | string | The account's label in FourFold. | +| `inGameName` | string or null | The account's public in-game name. It is `null` unless the user has filled in that account's **Ranking username**. When it is set, this is the name read from the account's profile page, or the Ranking username itself until the profile has been read. It never comes from the saved login. | +| `isOpen` | boolean | `true` while the account's game is open. | + +`fourfold.accounts.onChanged(callback)` calls `callback` when an account is added, removed, relabeled, opened or closed. The callback gets no data. A change to `inGameName` alone doesn't fire it. + +### XP + +```js +const xp = await fourfold.xp.get(account.id); +title.textContent = `${account.label}: ${xp.className ?? 'no class yet'} ${xp.level ?? ''}`; +fourfold.xp.onUpdated(({ accountId }) => console.log('new XP data for', accountId)); +``` + +`fourfold.xp.get(accountId)` returns: + +| Field | Type | Meaning | +|---|---|---| +| `className` | string or null | The active class. | +| `level` | number or null | The active class's level. | +| `currentXp` | number or null | XP earned so far toward the next level. | +| `nextLevelXp` | number or null | XP the current level needs in total. | +| `xpUntilNextLevel` | number or null | `nextLevelXp - currentXp`. | +| `hoursUntilNextLevel` | number or null | At the current XP/hr. `null` when there is no rate yet. | +| `xpPerHour` | number or null | The current rate. | +| `sessionXp` | number | XP gained this session. `0` when unknown. | +| `classes` | array | `{ className, level, currentXp, nextLevelXp }` for every class. May be empty. | +| `updatedAt` | string or null | Time of the last successful read, as an ISO 8601 date. | +| `isStale` | boolean | `true` when there is no XP data yet, when the last read failed, and for a closed account. | + +FourFold reads an account's XP only while that account is open, and only if FourFold's own XP tracker can read it. If the XP tracker plugin shows no data for an account, neither will yours. For a closed account the number and text fields are `null`, `classes` is empty and `isStale` is `true`. An id that isn't one of the user's accounts is rejected with `invalid-argument`. + +`fourfold.xp.onUpdated(callback)` calls `callback({ accountId })` when that account's XP data changes, about once a minute for each open account. + +### Stats + +```js +const stats = await fourfold.stats.get(account.id); +if (stats) console.log(stats.className, stats.level, stats.hp, stats.attack); +``` + +`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. An unknown account id is rejected with `invalid-argument`. + +### Timer + +```js +let timer = await fourfold.timer.get(); +let readAt = performance.now(); +fourfold.timer.onChanged(async () => { timer = await fourfold.timer.get(); readAt = performance.now(); }); +const elapsedMs = () => timer.state === 'running' ? timer.elapsedMs + (performance.now() - readAt) : timer.elapsedMs; +``` + +`fourfold.timer.get()` returns `{ state, elapsedMs, laps }`. + +- `state` is `"ready"`, `"running"` or `"finished"`. +- `elapsedMs` is the time on the timer when you asked. +- `laps` is `[{ number, lapMs, totalMs }]`. + +`fourfold.timer.onChanged(callback)` fires when the timer starts, splits, finishes or resets. It doesn't fire on every tick. Animate the time yourself from `elapsedMs`, as above. + +### Web requests + +```js +const response = await fourfold.http.fetch('https://example.com/'); +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` 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. +- **No shared state:** no cookies are kept or sent, and no FourFold credentials are attached. +- **Redirects:** followed up to 5 times. Each one must go to an allowed site. Your headers are not sent again once a redirect leaves the original host or port. `301` and `302` on a `POST`, and `303`, turn the request into a `GET`. +- **Response:** `status` is the HTTP status. A `404` or `500` still resolves, so check `status`. `headers` is an object of the response headers (`Set-Cookie` is left out). Header names come in whatever case the server used, so compare them case-insensitively. `text` is the body read as UTF-8, so it only suits text. +- **Limits:** at most 60 requests a minute (each redirect counts), a 15 second timeout, a 2 MB response. + +### Opening a link + +```js +button.addEventListener('click', () => { + fourfold.openExternal('https://wiki.example.com/').catch(error => console.warn(error.code)); +}); +``` + +`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`. + +- 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 + +```js +const goals = (await fourfold.storage.get('goals')) ?? {}; +await fourfold.storage.set('goals', goals); +await fourfold.storage.remove('goals'); +``` + +Each plugin has a private key-value store that is kept between runs. + +- `fourfold.storage.get(key)` returns the value, or `null` if there is none. +- `fourfold.storage.set(key, value)` saves any JSON value. `undefined` is rejected with `invalid-argument`. +- `fourfold.storage.remove(key)` deletes a key. +- Keys are 1 to 64 characters. +- Everything a plugin stores is capped at 256 KB, measured as the saved file. A `set` that would pass the cap is rejected with `limit-exceeded` and leaves existing data as it was. +- `set` and `remove` together are limited to 120 a minute (`limit-exceeded`). +- The data is saved in `%LOCALAPPDATA%\FourFoldAccountManager\plugin-data\.json`. If that file can't be read at the moment (it is locked, say), the call is rejected with `unavailable`. A missing or damaged file loads as empty. + +The page's own browser storage (IndexedDB, the Cache API, `localStorage`) is capped at about 5 MB per plugin, and a write past the cap fails with a `QuotaExceededError`. Keep settings in `fourfold.storage`: it is the supported place for them. + +### Card calls + +```js +await fourfold.cards.set('goal', account.id, { + summary: 'Level 12 of 50', + rows: [{ label: 'Level', value: '12 / 50', progress: 0.24 }] +}); +await fourfold.cards.clear('goal', account.id); +``` + +`fourfold.cards.set(cardId, accountId, { summary, rows })` and `fourfold.cards.clear(cardId, accountId)` fill and empty a card you declared in `plugin.json`. See [Cards](#cards). + +### Look and identity + +`fourfold.theme` holds FourFold's colors as hex strings. They are also set as CSS variables on `:root` before your page paints, so plain CSS can use them. The palette is fixed while the plugin runs. + +| `fourfold.theme` | CSS variable | Value | +|---|---|---| +| `background` | `--ff-background` | `#101419` | +| `surface` | `--ff-surface` | `#171D24` | +| `surfaceRaised` | `--ff-surface-raised` | `#1D252F` | +| `border` | `--ff-border` | `#29333E` | +| `text` | `--ff-text` | `#F2F0E9` | +| `textMuted` | `--ff-text-muted` | `#98A4B1` | +| `accent` | `--ff-accent` | `#E7C16B` | +| `danger` | `--ff-danger` | `#E57777` | + +```css +body { background: var(--ff-surface); color: var(--ff-text); } +``` + +`fourfold.plugin` is `{ id, version, apiVersion }`, copied from your `plugin.json`. + +### Error codes + +| Code | When | +|---|---| +| `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. `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 recent click or key press, or no panel showing, or an unexpected failure. | + +### Limits + +| What | Limit | +|---|---| +| One message from your page to FourFold | 512 KB. A larger one isn't sent: the call is rejected with `limit-exceeded`. | +| Calls waiting for an answer at once | 32. More are rejected with `limit-exceeded`. | +| `http.fetch` | 60 requests a minute, 5 redirects, 15 seconds, 2 MB response. | +| Storage | 256 KB in all, 120 writes a minute, keys up to 64 characters. | +| Browser storage | About 5 MB per plugin in IndexedDB, the Cache API and `localStorage`. | +| `openExternal` | One link every 2 seconds. | +| Card text | Summary up to 40 characters, up to 8 rows, label and value up to 40 characters each. | +| Card redraws | At most four a second. | +| One served file | 8 MB. | +| Flood stop | More than 2,000 requests or messages, more than 8 MB of messages, or more than 64 MB of replies, in a second. See [When a plugin is stopped](#when-a-plugin-is-stopped). | + +## The sandbox + +### Where your page runs + +FourFold serves your plugin folder at its own web address: + +``` +https://.fourfoldplugin/ +``` + +For `cody.goal-tracker` that is `https://cody--goal-tracker.fourfoldplugin/`. It is the `Origin` that a declared site sees on your page's requests, which matters for CORS. No plugin can reach another plugin's address. + +Use relative paths in your HTML. FourFold serves: + +- only files inside the plugin folder; +- only `GET` requests; +- only these file types: `.html`, `.js`, `.mjs`, `.css`, `.json`, `.txt`, `.png`, `.jpg`, `.jpeg`, `.gif`, `.svg`, `.webp`, `.woff2`; +- files up to 8 MB each, never `plugin.json`. + +Anything else gets a 404. + +### What a page may load + +Every response carries a content security policy. For a plugin that declares `https://example.com`, it is: + +``` +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' +``` + +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: + +- **Scripts** come only from your own files. There are no inline ` + + diff --git a/samples/goal-tracker/plugin.json b/samples/goal-tracker/plugin.json new file mode 100644 index 0000000..b09a961 --- /dev/null +++ b/samples/goal-tracker/plugin.json @@ -0,0 +1,11 @@ +{ + "id": "fourfold.goal-tracker", + "name": "Goal tracker", + "shortLabel": "Goals", + "version": "1.0.0", + "author": "FourFold", + "description": "Tracks a level goal per account and shows progress on a card.", + "apiVersion": 1, + "panel": "index.html", + "cards": [{ "id": "goal", "name": "Goal", "scope": "account" }] +} diff --git a/samples/goal-tracker/style.css b/samples/goal-tracker/style.css new file mode 100644 index 0000000..adfee82 --- /dev/null +++ b/samples/goal-tracker/style.css @@ -0,0 +1,9 @@ +body { margin: 0; padding: 14px; background: var(--ff-surface); color: var(--ff-text); font: 13px "Segoe UI", sans-serif; } +h1 { margin: 0 0 4px; font-size: 16px; font-weight: 600; } +.muted { color: var(--ff-text-muted); margin: 0 0 12px; } +.account { background: var(--ff-surface-raised); border: 1px solid var(--ff-border); border-radius: 6px; padding: 10px; margin-bottom: 8px; } +.account h2 { margin: 0 0 6px; font-size: 13px; } +.account label { color: var(--ff-text-muted); margin-right: 6px; } +.account input { width: 64px; background: var(--ff-background); color: var(--ff-text); border: 1px solid var(--ff-border); border-radius: 4px; padding: 3px 6px; } +.bar { height: 4px; border-radius: 2px; background: var(--ff-border); margin-top: 8px; } +.bar > div { height: 100%; border-radius: 2px; background: var(--ff-accent); } diff --git a/samples/sandbox-check/check.js b/samples/sandbox-check/check.js new file mode 100644 index 0000000..c2d0537 --- /dev/null +++ b/samples/sandbox-check/check.js @@ -0,0 +1,118 @@ +// Each check tries something a plugin must not be able to do. PASS means FourFold stopped it. +const results = document.getElementById('results'); +const violations = []; +document.addEventListener('securitypolicyviolation', event => + violations.push({ directive: event.effectiveDirective, blocked: event.blockedURI })); +const settle = () => new Promise(resolve => setTimeout(resolve, 1000)); +const violated = (directive, blocked = '') => + violations.filter(found => found.directive.startsWith(directive) && found.blocked.startsWith(blocked)).length; + +function report(name, passed, detail = '') { + const item = document.createElement('li'); + item.textContent = `${passed ? 'PASS' : 'FAIL'}: ${name}${detail ? ` (${detail})` : ''}`; + item.style.color = passed ? 'var(--ff-accent)' : 'var(--ff-danger)'; + results.append(item); +} + +async function rejects(name, action, expectedCode) { + try { + await action(); + report(name, false, 'it was allowed'); + } catch (error) { + report(name, !expectedCode || error.code === expectedCode, error.code ?? error.message); + } +} + +async function run() { + report('Inline script is blocked', window.inlineScriptRan !== true); + + let evalRan = false; + try { evalRan = new Function('return true')(); } catch { /* blocked */ } + report('eval is blocked', evalRan !== true); + + // These are stopped by the content security policy, which reports each one as a violation. + const remote = document.createElement('script'); + remote.src = 'https://example.com/remote.js'; + document.head.append(remote); + fetch('https://example.org/').catch(() => {}); + try { new WebSocket('wss://example.org/').onerror = () => {}; } catch { /* also blocked */ } + const frame = document.createElement('iframe'); + frame.src = 'https://example.com/'; + frame.hidden = true; + document.body.append(frame); + const popup = window.open('https://example.com/'); + let workerMade = false; + try { new Worker('check.js'); workerMade = true; } catch { /* blocked */ } + let serviceWorkerRegistered = false; + try { + await navigator.serviceWorker.register('check.js'); + serviceWorkerRegistered = true; + } catch { /* blocked */ } + await settle(); + report('A script from another site is blocked, even a declared one', + violated('script-src-elem', 'https://example.com') > 0); + report('Page fetch and WebSocket to an undeclared site are blocked', violated('connect-src') >= 2); + report('Frames are blocked', violated('frame-src') > 0); + report('Web Workers are blocked', !workerMade || violated('worker-src') > 0); + report('Service workers are blocked', !serviceWorkerRegistered); + report('WebRTC is removed', typeof RTCPeerConnection === 'undefined'); + report('alert() shows nothing (check by eye)', alert('This should not appear') === undefined); + + // If window.close() worked, FourFold would be closing instead of getting here. + let stillRunning = false; + window.close(); + stillRunning = true; + report('window.close() does nothing', stillRunning); + + // A sandboxed frame's window has a close() the injected library doesn't replace. FourFold itself must ignore it. + let stillRunningAfterFrame = false; + try { + const sandboxed = document.createElement('iframe'); + sandboxed.sandbox = ''; + sandboxed.hidden = true; + document.body.append(sandboxed); + sandboxed.contentWindow.close.call(window); + } catch { /* refused, which is fine too */ } + stillRunningAfterFrame = true; + report('window.close() through a sandboxed frame does nothing', stillRunningAfterFrame); + + report('New windows are blocked', popup === null || popup.closed); + + await rejects('FourFold-run fetch to an undeclared site is refused', + () => fourfold.http.fetch('https://example.org/'), 'site-not-allowed'); + await rejects('FourFold-run fetch to the local network is refused', + () => fourfold.http.fetch('https://localhost/'), 'site-not-allowed'); + await rejects('Only GET and POST are accepted', + () => fourfold.http.fetch('https://example.com/', { method: 'DELETE' }), 'invalid-argument'); + + try { + const response = await fourfold.http.fetch('https://example.com/'); + report('FourFold-run fetch to a declared site works', response.status === 200, `status ${response.status}`); + } catch (error) { + report('FourFold-run fetch to a declared site works', false, error.code ?? error.message); + } + + await rejects('An undeclared card is refused', + () => fourfold.cards.set('nope', null, { rows: [] }), 'not-declared'); + await rejects('openExternal is refused while the checks run', () => fourfold.openExternal('https://example.com/')); + + await fourfold.storage.set('probe', { at: Date.now() }); + report('Storage round-trips', (await fourfold.storage.get('probe')) !== null); + await rejects('Storage over 256 KB is refused', + () => fourfold.storage.set('big', 'x'.repeat(300 * 1024)), 'limit-exceeded'); + + // FourFold answers a read at once, so these may never overlap: each is answered, or refused past 32 at a time. + const many = await Promise.allSettled(Array.from({ length: 40 }, () => fourfold.storage.get('probe'))); + report('More than 32 calls at once are refused or answered', + many.every(result => result.status === 'fulfilled' || result.reason.code === 'limit-exceeded')); +} + +document.getElementById('open').addEventListener('click', () => fourfold.openExternal('https://example.com/')); +document.getElementById('leave').addEventListener('click', () => { location.href = 'https://example.com/'; }); +document.getElementById('flood').addEventListener('click', () => { + // Large messages first, so the budget for message text trips whatever the machine's speed. + const pad = 'x'.repeat(500000); + for (let i = 0; i < 20; i++) window.chrome.webview.postMessage({ id: -1 - i, method: 'timer.get', pad }); + for (let i = 0; i < 20000; i++) window.chrome.webview.postMessage({ id: -100 - i, method: 'timer.get' }); +}); +run().catch(error => report('The check itself ran', false, error.message)); diff --git a/samples/sandbox-check/index.html b/samples/sandbox-check/index.html new file mode 100644 index 0000000..ed62fd8 --- /dev/null +++ b/samples/sandbox-check/index.html @@ -0,0 +1,18 @@ + + + + + Sandbox check + + +

Sandbox check

+

Every line should say PASS.

+

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

+ + + + + + + + diff --git a/samples/sandbox-check/plugin.json b/samples/sandbox-check/plugin.json new file mode 100644 index 0000000..fb49081 --- /dev/null +++ b/samples/sandbox-check/plugin.json @@ -0,0 +1,11 @@ +{ + "id": "fourfold.sandbox-check", + "name": "Sandbox check", + "shortLabel": "Sandbox", + "version": "1.0.0", + "author": "FourFold", + "description": "Tries everything a plugin must not be able to do, and reports PASS or FAIL.", + "apiVersion": 1, + "panel": "index.html", + "sites": ["https://example.com"] +} diff --git a/src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginCardTests.cs b/src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginCardTests.cs new file mode 100644 index 0000000..448b5e1 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginCardTests.cs @@ -0,0 +1,76 @@ +using System.Text.Json.Nodes; +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Models; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Data; + +public sealed class SettingsStorePluginCardTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"fourfold-settings-{Guid.NewGuid():N}"); + private readonly SettingsStore _store; + + public SettingsStorePluginCardTests() + { + Directory.CreateDirectory(_root); + _store = new SettingsStore(new LocalDataPaths(_root)); + } + + private string SettingsPath => Path.Combine(_root, "settings.json"); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + [Fact] + public async Task PluginCardsAndDeveloperModeRoundTripThroughSaveAndLoad() + { + var accountId = Guid.NewGuid(); + var cards = new[] + { + new OverlayCardPlacement(OverlayAddOnKind.Plugin, accountId, true, new OverlayBounds(0.1, 0.2, 0.3, 0.1)) + { + PluginCard = "cody.goal-tracker/goal" + }, + new OverlayCardPlacement(OverlayAddOnKind.Plugin, null, false, null) + { + PluginCard = "cody.goal-tracker/summary" + } + }; + + await _store.SaveAsync(PanelSettings.Default with { PluginDeveloperMode = true, OverlayCards = cards }); + var loaded = await _store.LoadAsync(); + + Assert.True(loaded.PluginDeveloperMode); + Assert.Equal(cards, loaded.OverlayCards); + } + + [Fact] + public async Task MalformedPluginCardsAreDroppedWithoutLosingOtherSettings() + { + var accountId = Guid.NewGuid(); + await _store.SaveAsync(PanelSettings.Default with { ShowOverlaysInTheatreMode = false }); + var json = JsonNode.Parse(await File.ReadAllTextAsync(SettingsPath))!.AsObject(); + json["overlayCards"] = new JsonArray + { + new JsonObject { ["kind"] = 4, ["accountId"] = null, ["enabled"] = true }, + new JsonObject { ["kind"] = 4, ["accountId"] = null, ["enabled"] = true, ["pluginCard"] = "" }, + new JsonObject { ["kind"] = 4, ["accountId"] = null, ["enabled"] = true, ["pluginCard"] = "Not Valid" }, + new JsonObject { ["kind"] = 4, ["accountId"] = null, ["enabled"] = true, ["pluginCard"] = 7 }, + new JsonObject + { + ["kind"] = 0, ["accountId"] = accountId.ToString(), ["enabled"] = true, + ["pluginCard"] = "cody.goal-tracker/goal" + }, + new JsonObject + { + ["kind"] = 4, ["accountId"] = null, ["enabled"] = true, ["pluginCard"] = "cody.goal-tracker/summary" + } + }; + await File.WriteAllTextAsync(SettingsPath, json.ToJsonString()); + + var loaded = await _store.LoadAsync(); + + Assert.False(loaded.ShowOverlaysInTheatreMode); + var kept = Assert.Single(loaded.OverlayCards); + Assert.Equal("cody.goal-tracker/summary", kept.PluginCard); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginTests.cs b/src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginTests.cs new file mode 100644 index 0000000..05cb051 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Data/SettingsStorePluginTests.cs @@ -0,0 +1,89 @@ +using System.Text.Json.Nodes; +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Models; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Data; + +public sealed class SettingsStorePluginTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"fourfold-settings-{Guid.NewGuid():N}"); + private readonly SettingsStore _store; + + public SettingsStorePluginTests() + { + Directory.CreateDirectory(_root); + _store = new SettingsStore(new LocalDataPaths(_root)); + } + + private string SettingsPath => Path.Combine(_root, "settings.json"); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + [Fact] + public async Task PluginLayoutRoundTripsThroughSaveAndLoad() + { + await _store.SaveAsync(PanelSettings.Default with + { + PluginOrder = ["timer", "xp-tracker", "someone.community-plugin"], + DisabledPlugins = ["stats"], + OpenPlugin = "timer", + PluginsSidebarExpanded = false, + PluginStripVisible = false + }); + + var loaded = await _store.LoadAsync(); + + Assert.False(loaded.PluginStripVisible); + Assert.Equal(["timer", "xp-tracker", "someone.community-plugin"], loaded.PluginOrder); + Assert.Equal(["stats"], loaded.DisabledPlugins); + Assert.Equal("timer", loaded.OpenPlugin); + Assert.False(loaded.PluginsSidebarExpanded); + } + + [Fact] + public async Task MalformedPluginValuesLoadAsDefaultsWithoutLosingOtherSettings() + { + await WriteSettingsAsync(json => + { + json["showOverlaysInTheatreMode"] = false; + json["pluginOrder"] = "stats"; + json["disabledPlugins"] = new JsonArray { 1, null, " ", "timer", "timer" }; + json["openPlugin"] = 5; + }); + + var loaded = await _store.LoadAsync(); + + Assert.False(loaded.ShowOverlaysInTheatreMode); + Assert.Empty(loaded.PluginOrder); + Assert.Equal(["timer"], loaded.DisabledPlugins); + Assert.Equal("xp-tracker", loaded.OpenPlugin); + } + + [Fact] + public async Task OlderSettingsWithoutPluginFieldsKeepTheirHiddenSidebar() + { + await WriteSettingsAsync(json => + { + json.Remove("pluginOrder"); + json.Remove("disabledPlugins"); + json.Remove("openPlugin"); + json["pluginsSidebarExpanded"] = false; + }); + + var loaded = await _store.LoadAsync(); + + Assert.False(loaded.PluginsSidebarExpanded); + Assert.Empty(loaded.PluginOrder); + Assert.Empty(loaded.DisabledPlugins); + Assert.Equal("xp-tracker", loaded.OpenPlugin); + } + + private async Task WriteSettingsAsync(Action edit) + { + await _store.SaveAsync(PanelSettings.Default); + var json = JsonNode.Parse(await File.ReadAllTextAsync(SettingsPath))!.AsObject(); + edit(json); + await File.WriteAllTextAsync(SettingsPath, json.ToJsonString()); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Overlay/OverlayCardPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Overlay/OverlayCardPolicyTests.cs index 7f2182e..ab48be6 100644 --- a/src/FourFoldAccountManager.Core.Tests/Overlay/OverlayCardPolicyTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Overlay/OverlayCardPolicyTests.cs @@ -131,4 +131,17 @@ public void MovingACardBetweenTheGameAndFloatingKeepsOnePlaceAndBothPositions() Assert.Equal(floatingSpot, returnedCard.FloatingBounds); Assert.True(OverlayCardPolicy.Get(returned, timerKey)!.Enabled); } + + [Fact] + public void TwoCardsFromOnePluginAreKeptApartThroughALoad() + { + var one = new OverlayCardKey(OverlayAddOnKind.Plugin, null, "cody.goal-tracker/one"); + var two = new OverlayCardKey(OverlayAddOnKind.Plugin, null, "cody.goal-tracker/two"); + + var settings = OverlayCardPolicy.WithEnabled(PanelSettings.Default, one, true); + settings = OverlayCardPolicy.WithBounds(settings, two, Second); + var loaded = OverlayCardPolicy.Normalize(settings.OverlayCards, null); + + Assert.Equal(["cody.goal-tracker/one", "cody.goal-tracker/two"], loaded.Select(card => card.PluginCard)); + } } 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(@"(?"); + File.WriteAllText(Path.Combine(folder, "js", "app.js"), ""); + File.WriteAllText(Path.Combine(folder, "run.exe"), ""); + File.WriteAllText(Path.Combine(folder, "plugin.json"), "{}"); + File.WriteAllText(Path.Combine(_root, "secret.txt"), "outside the plugin"); + _manifest = new PluginManifest("cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, + "index.html", null, [], false, []) { Folder = folder }; + } + + public void Dispose() => Directory.Delete(_root, recursive: true); + + [Theory] + [InlineData("/", "index.html", "text/html; charset=utf-8")] + [InlineData("/index.html", "index.html", "text/html; charset=utf-8")] + [InlineData("/js/app.js", "app.js", "text/javascript; charset=utf-8")] + public void FilesInsideThePluginFolderAreServedWithAFixedContentType(string urlPath, string fileName, string type) + { + Assert.True(PluginFileServer.TryResolve(_manifest, urlPath, out var filePath, out var contentType)); + Assert.Equal(fileName, Path.GetFileName(filePath)); + Assert.Equal(type, contentType); + } + + [Theory] + [InlineData("/../secret.txt")] + [InlineData("/%2e%2e/secret.txt")] + [InlineData("/js/../../secret.txt")] + [InlineData("/..%5csecret.txt")] + [InlineData("/C:/Windows/win.ini")] + [InlineData("/run.exe")] + [InlineData("/missing.html")] + [InlineData("/plugin.json")] + [InlineData("/PLUGIN.JSON")] + [InlineData("/js/../plugin.json")] + [InlineData("/index.html:x")] + [InlineData("/index.html:x.js")] + [InlineData("/index.html::$DATA")] + public void PathsOutsideTheFolderUnknownTypesAndMissingFilesAreRefused(string urlPath) => + Assert.False(PluginFileServer.TryResolve(_manifest, urlPath, out _, out _)); +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs new file mode 100644 index 0000000..ce10151 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginHttpFetcherTests.cs @@ -0,0 +1,522 @@ +using System.Net; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginHttpFetcherTests +{ + private static readonly PluginManifest Manifest = new( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, + [new Uri("https://wiki.example.com")], false, []); + + private static readonly PluginManifest MultiSiteManifest = new( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, + [new Uri("https://wiki.example.com"), new Uri("https://cdn.example.net")], false, []); + + private static PluginHttpRequest Get(string url) => new(url, "GET", null, null); + + [Fact] + public async Task AnUndeclaredSiteIsRefusedWithoutSendingAnything() + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://attacker.example.net/steal"))); + + Assert.Equal("site-not-allowed", error.Code); + Assert.Empty(handler.Requests); + } + + [Fact] + public async Task ARedirectToAnUndeclaredSiteIsRefusedAndOneToADeclaredSiteIsFollowed() + { + var handler = new FakeHandler(request => request.RequestUri!.AbsolutePath switch + { + "/out" => Redirect("https://attacker.example.net/"), + "/in" => Redirect("/page"), + _ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("page text") } + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/out"))); + var followed = await fetcher.FetchAsync(Get("https://wiki.example.com/in")); + + Assert.Equal("site-not-allowed", error.Code); + Assert.DoesNotContain(handler.Requests, uri => uri.Host == "attacker.example.net"); + Assert.Equal((200, "page text"), (followed.Status, followed.Text)); + } + + [Fact] + public async Task MoreThanFiveRedirectsAreRefused() + { + var handler = new FakeHandler(_ => Redirect("/again")); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/loop"))); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal(6, handler.Requests.Count); + } + + [Fact] + public async Task ForbiddenHeadersAreDroppedAndOthersAreSent() + { + HttpRequestMessage? sent = null; + var handler = new FakeHandler(request => + { + sent = request; + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/api", "GET", + new Dictionary + { + ["Cookie"] = "session=1", + ["cookie"] = "lowercase=1", + ["Host"] = "attacker.example.net", + ["Sec-Fetch-Site"] = "same-origin", + ["SEC-Fetch-Mode"] = "cors", + ["Proxy-Authorization"] = "Basic x", + ["proxy-connection"] = "keep-alive", + ["Connection"] = "close", + ["X-Keep"] = "yes" + }, null)); + + Assert.NotNull(sent); + Assert.False(sent.Headers.Contains("Cookie")); + Assert.False(sent.Headers.Contains("cookie")); + Assert.False(sent.Headers.Contains("Sec-Fetch-Site")); + Assert.False(sent.Headers.Contains("SEC-Fetch-Mode")); + Assert.False(sent.Headers.Contains("Proxy-Authorization")); + Assert.False(sent.Headers.Contains("proxy-connection")); + Assert.False(sent.Headers.Contains("Connection")); + Assert.Null(sent.Headers.Host); + Assert.Null(sent.Content); + Assert.Equal("yes", sent.Headers.GetValues("X-Keep").Single()); + } + + [Fact] + public async Task ARequestCarriesTheFourFoldUserAgentUnlessThePluginSetsItsOwn() + { + var sent = new List(); + var handler = new FakeHandler(request => + { + sent.Add(request); + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(Get("https://wiki.example.com/api")); + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/api", "GET", + new Dictionary { ["user-agent"] = "mine/2" }, null)); + + Assert.Equal("FourFold-Plugin/1", sent[0].Headers.GetValues("User-Agent").Single()); + Assert.Equal("mine/2", sent[1].Headers.GetValues("User-Agent").Single()); + } + + [Fact] + public async Task AResponseOverTwoMegabytesIsRefused() + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new ByteArrayContent(new byte[PluginHttpFetcher.MaximumResponseBytes + 1]) + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/big"))); + + Assert.Equal("limit-exceeded", error.Code); + } + + [Fact] + public async Task AStreamedResponseOverTwoMegabytesIsRefused() + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new UnknownLengthContent(new byte[PluginHttpFetcher.MaximumResponseBytes + 1]) + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/big"))); + + Assert.Equal("limit-exceeded", error.Code); + } + + [Fact] + public async Task TheSixtyFirstRequestInAMinuteIsRefusedAndAllowedAgainLater() + { + var clock = new FakeClock(); + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler, clock); + for (var count = 0; count < 60; count++) + { + await fetcher.FetchAsync(Get("https://wiki.example.com/")); + } + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + clock.Advance(TimeSpan.FromSeconds(61)); + await fetcher.FetchAsync(Get("https://wiki.example.com/")); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal(61, handler.Requests.Count); + } + + [Fact] + public async Task OnlyGetAndPostAreAccepted() + { + using var fetcher = new PluginHttpFetcher( + Manifest, PluginTrust.Developer, new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK))); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "DELETE", null, null))); + + Assert.Equal("invalid-argument", error.Code); + } + + [Theory] + [InlineData("192.168.1.5")] + [InlineData("127.0.0.1")] + [InlineData("8.8.8.8,10.0.0.7")] + public async Task AHostThatResolvesToTheLocalNetworkIsRefused(string addresses) + { + var resolved = addresses.Split(',').Select(IPAddress.Parse).ToArray(); + + var error = await Assert.ThrowsAsync(() => + PluginHttpFetcher.ResolvePublicAddressesAsync( + "wiki.example.com", (_, _) => Task.FromResult(resolved), CancellationToken.None)); + + Assert.Equal("site-not-allowed", error.Code); + } + + [Fact] + public async Task AHostThatResolvesToPublicAddressesReturnsThemAll() + { + var expected = new[] { IPAddress.Parse("8.8.8.8"), IPAddress.Parse("1.1.1.1") }; + var result = await PluginHttpFetcher.ResolvePublicAddressesAsync( + "wiki.example.com", (_, _) => Task.FromResult(expected), CancellationToken.None); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("v\r\nCookie: x")] + [InlineData("v\nHost: evil")] + [InlineData("v\rX: y")] + [InlineData("café")] + public async Task AHeaderValueWithALineBreakIsRefusedAndNothingIsSent(string invalidValue) + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "GET", + new Dictionary { ["X-Test"] = invalidValue }, null))); + + Assert.Equal("invalid-argument", error.Code); + Assert.Empty(handler.Requests); + } + + [Theory] + [InlineData("bad name")] + [InlineData("X:Y")] + [InlineData("")] + [InlineData("Cookie ")] + public async Task AnInvalidHeaderNameIsRefused(string invalidName) + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "POST", + new Dictionary { [invalidName] = "value" }, "body"))); + + Assert.Equal("invalid-argument", error.Code); + Assert.Empty(handler.Requests); + } + + [Fact] + public async Task ARequestThatTakesTooLongIsRefused() + { + var handler = new HangingHandler(); + using var fetcher = new PluginHttpFetcher( + Manifest, PluginTrust.Developer, handler, timeout: TimeSpan.FromMilliseconds(100)); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + + Assert.Equal("unavailable", error.Code); + } + + [Fact] + public async Task AMalformedRedirectIsRefusedCleanly() + { + var handler = new FakeHandler(_ => + { + var response = new HttpResponseMessage(HttpStatusCode.Found); + response.Headers.TryAddWithoutValidation("Location", "//host:99999/"); + return response; + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + + Assert.Equal("unavailable", error.Code); + } + + [Fact] + public async Task ABrokenBodyIsRefusedCleanly() + { + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new ThrowingContent() + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + + Assert.Equal("unavailable", error.Code); + } + + [Fact] + public async Task PluginHeadersAreNotForwardedToAnotherHost() + { + var capturedHeaders = new List<(Uri, bool hasAuth)>(); + var handler = new FakeHandler(request => + { + var hasAuth = request.Headers.Contains("Authorization"); + capturedHeaders.Add((request.RequestUri!, hasAuth)); + + if (request.RequestUri!.Host == "wiki.example.com") + { + return Redirect("https://cdn.example.net/x"); + } + + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + }); + using var fetcher = new PluginHttpFetcher(MultiSiteManifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "GET", + new Dictionary { ["Authorization"] = "Bearer t" }, null)); + + Assert.Equal(2, capturedHeaders.Count); + Assert.True(capturedHeaders[0].hasAuth, "First request should have Authorization"); + Assert.False(capturedHeaders[1].hasAuth, "Second request to different host should not have Authorization"); + } + + [Fact] + public async Task RedirectHopsCountTowardsTheRateLimit() + { + var clock = new FakeClock(); + var requestCount = 0; + var handler = new FakeHandler(_ => + { + requestCount++; + // Each fetch can have up to 5 redirects (6 total requests), so 10 fetches = 60 requests + var withinFetch = requestCount % 6; + if (withinFetch != 0) + { + return Redirect("/again"); + } + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler, clock); + + // Make 10 successful fetches (each with 6 requests = 60 total) + for (var i = 0; i < 10; i++) + { + await fetcher.FetchAsync(Get("https://wiki.example.com/start")); + } + + // The 11th fetch should hit the rate limit + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/start"))); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal(60, requestCount); + } + + [Fact] + public async Task PluginHeadersAreNotSentAgainAfterReturningToTheOriginalHost() + { + var capturedHeaders = new List<(Uri, bool hasAuth)>(); + var handler = new FakeHandler(request => + { + var hasAuth = request.Headers.Contains("Authorization"); + capturedHeaders.Add((request.RequestUri!, hasAuth)); + + if (request.RequestUri!.Host == "wiki.example.com" && request.RequestUri.AbsolutePath == "/start") + { + return Redirect("https://cdn.example.net/x"); + } + + if (request.RequestUri!.Host == "cdn.example.net") + { + return Redirect("https://wiki.example.com/back"); + } + + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + }); + using var fetcher = new PluginHttpFetcher(MultiSiteManifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/start", "GET", + new Dictionary { ["Authorization"] = "Bearer t" }, null)); + + Assert.Equal(3, capturedHeaders.Count); + Assert.True(capturedHeaders[0].hasAuth, "First request (wiki) should have Authorization"); + Assert.False(capturedHeaders[1].hasAuth, "Second request (cdn) should not have Authorization"); + Assert.False(capturedHeaders[2].hasAuth, "Third request (back to wiki) should not have Authorization"); + } + + [Fact] + public async Task PluginHeadersAreNotSentToAnotherPortOnTheSameHost() + { + var manifest = MultiSiteManifest with + { + Sites = [new Uri("https://wiki.example.com"), new Uri("https://wiki.example.com:8443")] + }; + var sawAuth = new List(); + var handler = new FakeHandler(request => + { + sawAuth.Add(request.Headers.Contains("Authorization")); + return request.RequestUri!.Port == 443 + ? Redirect("https://wiki.example.com:8443/x") + : new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + }); + using var fetcher = new PluginHttpFetcher(manifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/start", "GET", + new Dictionary { ["Authorization"] = "Bearer t" }, null)); + + Assert.Equal([true, false], sawAuth); + } + + [Fact] + public async Task FramingHeadersFromThePluginAreIgnoredOnAPost() + { + HttpRequestMessage? sent = null; + long? contentLength = null; + var handler = new FakeHandler(request => + { + sent = request; + contentLength = sent.Content?.Headers.ContentLength; + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler); + + await fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "POST", + new Dictionary + { + ["Content-Length"] = "999", + ["Transfer-Encoding"] = "chunked", + ["Connection"] = "close", + ["X-Keep"] = "1" + }, "hello")); + + Assert.NotNull(sent); + Assert.Equal(5, contentLength); + Assert.True(sent.Headers.TransferEncodingChunked != true); + Assert.False(sent.Headers.Contains("Transfer-Encoding")); + Assert.False(sent.Headers.Contains("Connection")); + Assert.Equal("1", sent.Headers.GetValues("X-Keep").Single()); + } + + [Fact] + public async Task AnInvalidRequestDoesNotUseTheRateLimit() + { + var clock = new FakeClock(); + var handler = new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)); + using var fetcher = new PluginHttpFetcher(Manifest, PluginTrust.Developer, handler, clock); + + // Make 60 invalid requests (invalid header values) — none should consume rate slots + for (var i = 0; i < 60; i++) + { + await Assert.ThrowsAsync( + () => fetcher.FetchAsync(new PluginHttpRequest("https://wiki.example.com/", "GET", + new Dictionary { ["X-Test"] = "v\r\nCookie: x" }, null))); + } + + // Now make 60 valid requests — all should succeed + for (var i = 0; i < 60; i++) + { + await fetcher.FetchAsync(Get("https://wiki.example.com/")); + } + + // The 61st valid request should hit the rate limit + var error = await Assert.ThrowsAsync( + () => fetcher.FetchAsync(Get("https://wiki.example.com/"))); + + Assert.Equal("limit-exceeded", error.Code); + } + + private static HttpResponseMessage Redirect(string location) => + new(HttpStatusCode.Found) { Headers = { Location = new Uri(location, UriKind.RelativeOrAbsolute) } }; + + private sealed class FakeHandler(Func respond) : HttpMessageHandler + { + public List Requests { get; } = []; + + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request.RequestUri!); + return Task.FromResult(respond(request)); + } + } + + private sealed class HangingHandler : HttpMessageHandler + { + protected override async Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + { + await Task.Delay(Timeout.Infinite, cancellationToken); + return new HttpResponseMessage(HttpStatusCode.OK); + } + } + + private sealed class UnknownLengthContent(byte[] data) : HttpContent + { + protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context) + { + await stream.WriteAsync(data); + } + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + } + + private sealed class ThrowingContent : HttpContent + { + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) + { + throw new InvalidDataException("broken"); + } + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; + } + } + + private sealed class FakeClock : TimeProvider + { + private DateTimeOffset _now = new(2026, 10, 3, 12, 0, 0, TimeSpan.Zero); + + public override DateTimeOffset GetUtcNow() => _now; + + public void Advance(TimeSpan by) => _now += by; + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginLayoutPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginLayoutPolicyTests.cs new file mode 100644 index 0000000..3c31a45 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginLayoutPolicyTests.cs @@ -0,0 +1,27 @@ +using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginLayoutPolicyTests +{ + [Fact] + public void MovingAPluginKeepsTheSlotsOfUnloadedAndSwitchedOffPlugins() + { + // "missing" is saved but not loaded right now, and "off" is loaded but switched off; both must stay where they + // are, or the user's saved order is silently rewritten. + var settings = PanelSettings.Default with + { + PluginOrder = ["a", "missing", "off", "b"], + DisabledPlugins = ["off"] + }; + PluginDescriptor[] known = [Descriptor("a"), Descriptor("off"), Descriptor("b")]; + + var moved = PluginLayoutPolicy.WithMoved(settings, known, "b", 0); + + Assert.Equal(["b", "missing", "off", "a"], moved.PluginOrder); + } + + private static PluginDescriptor Descriptor(string id) => new(id, id, id, "", [], []); +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs new file mode 100644 index 0000000..2d728c6 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -0,0 +1,222 @@ +using System.Buffers.Binary; +using System.Text; +using FourFoldAccountManager.Core.Overlay; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginManifestReaderTests : IDisposable +{ + private readonly string _folder = Path.Combine(Path.GetTempPath(), $"fourfold-plugin-{Guid.NewGuid():N}"); + private readonly string _outsideFile; + private readonly string _evilFolder; + + public PluginManifestReaderTests() + { + Directory.CreateDirectory(_folder); + File.WriteAllText(Path.Combine(_folder, "index.html"), ""); + Directory.CreateDirectory(Path.Combine(_folder, "sub")); + File.WriteAllText(Path.Combine(_folder, "sub", "index.html"), ""); + + var parentFolder = Path.GetDirectoryName(_folder)!; + var pluginFolderName = Path.GetFileName(_folder); + _outsideFile = Path.Combine(parentFolder, $"outside-{Guid.NewGuid():N}.html"); + _evilFolder = Path.Combine(parentFolder, $"{pluginFolderName}-evil"); + + File.WriteAllText(_outsideFile, ""); + Directory.CreateDirectory(_evilFolder); + File.WriteAllText(Path.Combine(_evilFolder, "index.html"), ""); + } + + public void Dispose() + { + Directory.Delete(_folder, recursive: true); + if (File.Exists(_outsideFile)) + { + File.Delete(_outsideFile); + } + if (Directory.Exists(_evilFolder)) + { + Directory.Delete(_evilFolder, recursive: true); + } + } + + private PluginManifestResult Read(string json) + { + File.WriteAllText(Path.Combine(_folder, "plugin.json"), json); + return PluginManifestReader.Read(_folder); + } + + private PluginManifestResult ReadWithIcon(byte[] iconBytes) + { + File.WriteAllBytes(Path.Combine(_folder, "icon.png"), iconBytes); + return Read(Manifest(", \"icon\": \"icon.png\"")); + } + + // The first 24 bytes of a PNG: the signature, the IHDR chunk's length and name, then its width and height. + private static byte[] PngHeader(uint width, uint height) + { + var header = new byte[24]; + new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }.CopyTo(header, 0); + BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(8), 13); + "IHDR"u8.CopyTo(header.AsSpan(12)); + BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(16), width); + BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(20), height); + return header; + } + + private static string Manifest(string overrides = "") => $$""" + { + "id": "cody.goal-tracker", "name": "Goal tracker", "shortLabel": "Goals", "version": "1.0.0", + "author": "Cody", "apiVersion": 1, "panel": "index.html", + "sites": ["https://wiki.example.com"], + "cards": [{ "id": "goal", "name": "Goal", "scope": "account" }] + {{overrides}} + } + """; + + [Fact] + public void AValidManifestLoadsWithItsSitesAndCards() + { + var result = Read(Manifest()); + + Assert.Null(result.Error); + var manifest = Assert.IsType(result.Manifest); + Assert.Equal("cody.goal-tracker", manifest.Id); + Assert.Equal([new Uri("https://wiki.example.com")], manifest.Sites); + Assert.False(manifest.AnySite); + Assert.Equal([new PluginCardManifest("goal", "Goal", OverlayAddOnScope.Account)], manifest.Cards); + Assert.Equal(_folder, manifest.Folder); + } + + [Theory] + [InlineData("\"id\": \"goaltracker\"")] + [InlineData("\"id\": \"Cody.Goal\"")] + [InlineData("\"id\": \"cody..goal\"")] + [InlineData("\"id\": \"timer\"")] + [InlineData("\"id\": \"xn.foo\"")] + [InlineData("\"id\": \"nul.tools\"")] + [InlineData("\"id\": \"com1.tools\"")] + [InlineData("\"id\": \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"")] + [InlineData("\"apiVersion\": 2")] + [InlineData("\"apiVersion\": \"1\"")] + [InlineData("\"panel\": \"missing.html\"")] + [InlineData("\"panel\": \"plugin.json\"")] + [InlineData("\"panel\": \"sub\\\\index.html\"")] + [InlineData("\"shortLabel\": \"Far too long\"")] + [InlineData("\"version\": \"1.0\"")] + [InlineData("\"sites\": [\"http://wiki.example.com\"]")] + [InlineData("\"sites\": [\"https://wiki.example.com/path\"]")] + [InlineData("\"sites\": [\"https://192.168.1.10\"]")] + [InlineData("\"sites\": [\"https://localhost\"]")] + [InlineData("\"sites\": [\"https://app.localhost\"]")] + [InlineData("\"sites\": [\"https://localhost.\"]")] + [InlineData("\"sites\": [\"https://127.0.0.1.\"]")] + [InlineData("\"sites\": [\"https://app.localhost.\"]")] + [InlineData("\"sites\": [\"https://x.fourfoldplugin\"]")] + [InlineData("\"sites\": [\"https://printer.local\"]")] + [InlineData("\"sites\": [\"https://nas.lan\"]")] + [InlineData("\"sites\": [\"https://router\"]")] + // The JSON escape \u0007 (a bell character) is what the file holds, so it is the reader's control-character rule + // that rejects these, not the JSON parser. + [InlineData("\"name\": \"Goal\\u0007tracker\"")] + [InlineData("\"cards\": [{ \"id\": \"goal\", \"name\": \"Go\\u0007al\", \"scope\": \"account\" }]")] + // U+202E is a right-to-left override, which would make FourFold draw the rest of the name backwards. + [InlineData("\"name\": \"Goal\\u202Etracker\"")] + // A zero-width joiner in a host makes Uri.IdnHost throw rather than return a name. + [InlineData("\"sites\": [\"https://a\u200Db.example\"]")] + // Uri's conversion turns look-alike characters into punctuation (U+FE64 into "<", U+FF5C into "|"), and "_" isn't a + // host name character, so a site must be plain letters, digits, dots and dashes once converted. + [InlineData("\"sites\": [\"https://a\uFE64b.example.com\"]")] + [InlineData("\"sites\": [\"https://x\uFF5Cy.example.com\"]")] + [InlineData("\"sites\": [\"https://a_b.example.com\"]")] + [InlineData("\"cards\": [{ \"id\": \"Goal\", \"name\": \"Goal\", \"scope\": \"account\" }]")] + [InlineData("\"cards\": [{ \"id\": \"goal\", \"name\": \"Goal\", \"scope\": \"panel\" }]")] + [InlineData("\"cards\": [{ \"id\": \"a\", \"name\": \"A\", \"scope\": \"global\" }, { \"id\": \"a\", \"name\": \"B\", \"scope\": \"global\" }]")] + public void AManifestThatBreaksARuleIsRejectedWithAReason(string overridingField) + { + // A later duplicate key wins in System.Text.Json, so appending the field overrides the valid value. + var result = Read(Manifest("," + overridingField)); + + Assert.Null(result.Manifest); + Assert.False(string.IsNullOrWhiteSpace(result.Error)); + } + + [Theory] + [InlineData("https://b\u00FCcher.example", "xn--bcher-kva.example")] + [InlineData("https://xn--bcher-kva.example", "xn--bcher-kva.example")] + [InlineData("https://Wiki.Example.com:8443", "wiki.example.com")] + public void ASiteThatIsAPlainHostNameIsAccepted(string site, string host) + { + var result = Read(Manifest(", \"sites\": [\"" + site + "\"]")); + + Assert.Null(result.Error); + Assert.Equal(host, Assert.Single(result.Manifest!.Sites).IdnHost); + } + + [Fact] + public void AMissingOrBrokenManifestIsRejectedWithAReason() + { + Assert.Equal("plugin.json is missing.", PluginManifestReader.Read(_folder).Error); + Assert.Equal("plugin.json isn't valid JSON.", Read("{ not json").Error); + } + + [Fact] + public void AnOversizedManifestIsRejectedWithoutBeingRead() + { + var result = Read(Manifest() + new string(' ', 70 * 1024)); + + Assert.Null(result.Manifest); + Assert.Equal("plugin.json is too large.", result.Error); + } + + [Fact] + public void AnIconThatDeclaresAHugeImageIsRejectedWithoutBeingDecoded() + { + // A 274-byte PNG declaring 1 by 100000 pixels made the app commit 215 MB the moment it drew the strip. + var result = ReadWithIcon(PngHeader(width: 1, height: 100000)); + + Assert.Null(result.Manifest); + Assert.Contains("icon", result.Error); + Assert.Null(ReadWithIcon(PngHeader(width: 100000, height: 1)).Manifest); + } + + [Fact] + public void AnIconThatIsNotAPngIsRejectedWhateverItIsNamed() + { + var result = ReadWithIcon(Encoding.ASCII.GetBytes("This is text, not a PNG image.")); + + Assert.Null(result.Manifest); + Assert.Contains("icon", result.Error); + } + + [Fact] + public void AnIconWithASmallPngHeaderIsAccepted() + { + var result = ReadWithIcon(PngHeader(width: 64, height: 64)); + + Assert.Null(result.Error); + Assert.Equal("icon.png", result.Manifest!.Icon); + } + + [Fact] + public void AManifestReferencingAnOutsideFileIsRejected() + { + var relativePath = Path.Combine("..", Path.GetFileName(_outsideFile)); + var result = Read(Manifest($", \"panel\": \"{relativePath.Replace("\\", "/")}\"")); + + Assert.Null(result.Manifest); + Assert.False(string.IsNullOrWhiteSpace(result.Error)); + } + + [Fact] + public void AManifestReferencingASiblingFolderIsRejected() + { + var folderName = Path.GetFileName(_evilFolder); + var result = Read(Manifest($", \"panel\": \"../{folderName}/index.html\"")); + + Assert.Null(result.Manifest); + Assert.False(string.IsNullOrWhiteSpace(result.Error)); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs new file mode 100644 index 0000000..67d8a40 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginNetworkPolicyTests.cs @@ -0,0 +1,145 @@ +using System.Net; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginNetworkPolicyTests +{ + private static PluginManifest Manifest(bool anySite = false) => new( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, + [new Uri("https://wiki.example.com"), new Uri("https://api.example.com:8443")], anySite, []); + + [Theory] + [InlineData("https://cody--goal-tracker.fourfoldplugin/app.js", true)] + [InlineData("https://wiki.example.com/page?x=1", true)] + [InlineData("https://WIKI.example.com/page", true)] + [InlineData("https://api.example.com:8443/v1", true)] + [InlineData("https://api.example.com/v1", false)] + [InlineData("https://other.example.com/", false)] + [InlineData("https://evil-wiki.example.com.attacker.net/", false)] + [InlineData("http://wiki.example.com/page", false)] + [InlineData("https://other--plugin.fourfoldplugin/app.js", false)] + [InlineData("file:///C:/Windows/win.ini", false)] + public void ADefaultPluginReachesOnlyItsOwnFilesAndDeclaredSites(string url, bool allowed) => + Assert.Equal(allowed, PluginNetworkPolicy.IsAllowed(new Uri(url), Manifest(), PluginTrust.Developer)); + + [Theory] + [InlineData("https://localhost/")] + [InlineData("https://app.localhost/")] + [InlineData("https://127.0.0.1/")] + [InlineData("https://10.1.2.3/")] + [InlineData("https://172.16.0.9/")] + [InlineData("https://192.168.1.1/")] + [InlineData("https://169.254.10.10/")] + [InlineData("https://[::1]/")] + [InlineData("https://[fd00::1]/")] + [InlineData("https://[fe80::1]/")] + [InlineData("https://[::ffff:192.168.1.1]/")] + [InlineData("https://localhost./")] + [InlineData("https://127.0.0.1./")] + [InlineData("https://192.168.1.1./")] + [InlineData("https://100.64.1.1/")] + [InlineData("https://[::127.0.0.1]/")] + [InlineData("https://[64:ff9b::7f00:1]/")] + [InlineData("https://[2002:7f00:1::]/")] + public void TheLocalNetworkIsNeverReachableEvenWithAnySite(string url) => + Assert.False(PluginNetworkPolicy.IsAllowed(new Uri(url), Manifest(anySite: true), PluginTrust.Verified)); + + [Fact] + public void ThePluginNamespaceIsNeverAnOrdinarySite() + { + var manifestWithPluginHost = new PluginManifest( + "cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, "index.html", null, + [new Uri("https://wiki.example.com"), new Uri("https://other--plugin.fourfoldplugin")], true, []); + + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://other--plugin.fourfoldplugin/app.js"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://fourfoldplugin/"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://x.y.fourfoldplugin/"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://cody--goal-tracker.fourfoldplugin./"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://cody--goal-tracker.fourfoldplugin:8443/"), manifestWithPluginHost, PluginTrust.Verified)); + Assert.True(PluginNetworkPolicy.IsAllowed( + new Uri("https://cody--goal-tracker.fourfoldplugin/app.js"), manifestWithPluginHost, PluginTrust.Verified)); + } + + [Fact] + public void AnySiteNeedsTrustAndNeverAllowsOutsideScriptsOrPlainHttp() + { + var any = new Uri("https://anything.example.org/data.json"); + + Assert.True(PluginNetworkPolicy.IsAllowed(any, Manifest(anySite: true), PluginTrust.Verified)); + Assert.True(PluginNetworkPolicy.IsAllowed(any, Manifest(anySite: true), PluginTrust.Developer)); + Assert.False(PluginNetworkPolicy.IsAllowed(any, Manifest(anySite: true), PluginTrust.Standard)); + Assert.False(PluginNetworkPolicy.IsAllowed(any, Manifest(anySite: true), PluginTrust.Verified, isScript: true)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("https://wiki.example.com/lib.js"), Manifest(), PluginTrust.Developer, isScript: true)); + Assert.False(PluginNetworkPolicy.IsAllowed( + new Uri("http://anything.example.org/"), Manifest(anySite: true), PluginTrust.Verified)); + } + + [Fact] + public void TheContentSecurityPolicyNamesOnlyDeclaredSitesAndNeverAllowsInlineScriptOrEval() + { + var policy = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(), PluginTrust.Developer); + Assert.Equal( + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://wiki.example.com https://api.example.com:8443; connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'", + policy); + + var anySite = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(anySite: true), PluginTrust.Verified); + Assert.Equal( + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https:; connect-src 'self' https: wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'", + anySite); + + var untrusted = PluginNetworkPolicy.BuildContentSecurityPolicy(Manifest(anySite: true), PluginTrust.Standard); + Assert.Equal( + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://wiki.example.com https://api.example.com:8443; connect-src 'self' https://wiki.example.com https://api.example.com:8443 wss://wiki.example.com wss://api.example.com:8443; frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'", + untrusted); + + var noSites = new PluginManifest("cody.goal-tracker", "Goal tracker", "Goals", "1.0.0", "Cody", "", 1, + "index.html", null, [], false, []); + var nositespolicy = PluginNetworkPolicy.BuildContentSecurityPolicy(noSites, PluginTrust.Developer); + Assert.Equal( + "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'", + nositespolicy); + } + + [Theory] + [InlineData("8.8.8.8", false)] + [InlineData("172.32.0.1", false)] + [InlineData("172.31.255.255", true)] + [InlineData("0.0.0.0", true)] + [InlineData("100.63.255.255", false)] + [InlineData("100.64.0.0", true)] + [InlineData("100.127.255.255", true)] + [InlineData("100.128.0.0", false)] + public void LocalAddressRangesAreRecognised(string address, bool local) => + Assert.Equal(local, PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse(address))); + + [Fact] + public void AnIpv6ScopeIdDoesNotHideALocalAddress() + { + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("::1%1"))); + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("fe80::1%5"))); + } + + [Fact] + public void AnIpv6AddressEmbeddingAPublicIpv4IsNotLocal() + { + Assert.False(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("64:ff9b::808:808"))); + Assert.False(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("2002:808:808::"))); + Assert.False(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("::ffff:0:8.8.8.8"))); + } + + [Fact] + public void AnIpv6AddressEmbeddingALocalIpv4IsLocal() + { + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("64:ff9b::c0a8:1"))); + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("2002:a00:1::"))); + Assert.True(PluginNetworkPolicy.IsLocalAddress(IPAddress.Parse("::ffff:0:127.0.0.1"))); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs new file mode 100644 index 0000000..b40a48b --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginPackageTests.cs @@ -0,0 +1,204 @@ +using System.IO.Compression; +using FourFoldAccountManager.Core.Plugins.Hub; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginPackageTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "fourfold-package-" + Guid.NewGuid().ToString("N")); + + public PluginPackageTests() => Directory.CreateDirectory(_root); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + private static byte[] Zip(params (string Name, byte[] Content)[] entries) => Zip(null, entries); + + private static byte[] Zip(Action? configure, params (string Name, byte[] Content)[] entries) + { + using var buffer = new MemoryStream(); + using (var archive = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (var (name, content) in entries) + { + var entry = archive.CreateEntry(name); + configure?.Invoke(entry); + using var stream = entry.Open(); + stream.Write(content); + } + } + + return buffer.ToArray(); + } + + [Fact] + public void APackageThatDoesNotMatchTheCatalogIsRefused() + { + var package = Zip(("plugin.json", "{}"u8.ToArray())); + var hash = PluginPackage.Sha256(package); + + Assert.True(PluginPackage.Matches(package, package.Length, hash)); + Assert.False(PluginPackage.Matches(package, package.Length + 1, hash)); + Assert.False(PluginPackage.Matches(package, package.Length, new string('0', 64))); + Assert.False(PluginPackage.Matches([.. package, 0], package.Length, hash)); + } + + [Theory] + [InlineData("../evil.txt")] + [InlineData("a/../../evil.txt")] + [InlineData("/evil.txt")] + [InlineData("C:/evil.txt")] + [InlineData("./evil.txt")] + public void AnEntryThatEscapesTheFolderIsRefused(string name) + { + var target = Path.Combine(_root, "inner", "plugin"); + + Assert.Throws( + () => PluginPackage.Extract(Zip((name, new byte[] { 1 })), target)); + + Assert.Empty(Directory.EnumerateFiles(_root, "evil.txt", SearchOption.AllDirectories)); + } + + [Fact] + public void TooManyFilesOrTooMuchDataIsRefused() + { + var many = Enumerable.Range(0, HubLimits.MaximumPackageFiles + 1) + .Select(index => ($"file{index}.txt", new byte[] { 1 })) + .ToArray(); + Assert.Throws(() => PluginPackage.Extract(Zip(many), Path.Combine(_root, "many"))); + + // Zeros compress to almost nothing, so the package is small and only the unpacked size gives it away. + var large = Zip(("big.txt", new byte[HubLimits.MaximumUnpackedBytes + 1])); + Assert.True(large.Length < 100_000); + Assert.Throws(() => PluginPackage.Extract(large, Path.Combine(_root, "large"))); + + // 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.Tests/Plugins/PluginStorageTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs new file mode 100644 index 0000000..c22c64f --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginStorageTests.cs @@ -0,0 +1,159 @@ +using System.Text; +using System.Text.Json; +using FourFoldAccountManager.Core.Plugins; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Plugins; + +public sealed class PluginStorageTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"fourfold-storage-{Guid.NewGuid():N}"); + + private string FilePath => Path.Combine(_root, "cody.goal-tracker.json"); + + public void Dispose() + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, recursive: true); + } + } + + private static JsonElement Json(string json) => JsonDocument.Parse(json).RootElement.Clone(); + + [Fact] + public async Task ValuesSurviveANewInstanceReadingTheSameFile() + { + await new PluginStorage(FilePath).SetAsync("goals", Json("""{"level":50}""")); + + var loaded = await new PluginStorage(FilePath).GetAsync("goals"); + + Assert.Equal(50, loaded!.Value.GetProperty("level").GetInt32()); + Assert.Null(await new PluginStorage(FilePath).GetAsync("missing")); + } + + [Fact] + public async Task AWriteOverTheSizeCapIsRejectedAndKeepsExistingData() + { + var storage = new PluginStorage(FilePath); + await storage.SetAsync("kept", Json("\"safe\"")); + var tooBig = Json("\"" + new string('x', PluginStorage.MaximumBytes) + "\""); + + var error = await Assert.ThrowsAsync(() => storage.SetAsync("big", tooBig)); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal("safe", (await new PluginStorage(FilePath).GetAsync("kept"))!.Value.GetString()); + Assert.Null(await new PluginStorage(FilePath).GetAsync("big")); + } + + [Fact] + public async Task AValueThatOnlyFitsWhenCompactIsRejected() + { + // A JSON array of 40,000 ones is ~80 KB compact (under cap) but ~320 KB indented (over cap). + // This test proves the size check measures indented JSON, not compact. + var json = "[" + string.Join(",", Enumerable.Repeat("1", 40000)) + "]"; + var compactBytes = Encoding.UTF8.GetByteCount(json); + Assert.True(compactBytes < PluginStorage.MaximumBytes, + $"Compact size {compactBytes} must be under {PluginStorage.MaximumBytes} to test the boundary"); + + var storage = new PluginStorage(FilePath); + await storage.SetAsync("kept", Json("\"safe\"")); + var largeArray = Json(json); + + var error = await Assert.ThrowsAsync(() => storage.SetAsync("list", largeArray)); + + Assert.Equal("limit-exceeded", error.Code); + Assert.Equal("safe", (await new PluginStorage(FilePath).GetAsync("kept"))!.Value.GetString()); + Assert.Null(await new PluginStorage(FilePath).GetAsync("list")); + } + + [Fact] + public async Task AnAllowedWriteStaysWithinTheCapOnDisk() + { + // A JSON array of 20,000 ones is ~160 KB indented (under cap). + var json = "[" + string.Join(",", Enumerable.Repeat("1", 20000)) + "]"; + var storage = new PluginStorage(FilePath); + + var largeArray = Json(json); + await storage.SetAsync("list", largeArray); + + // Verify the file size is within the cap + Assert.True(new FileInfo(FilePath).Length <= PluginStorage.MaximumBytes); + + // Verify the data persists and reads back correctly + var loaded = await new PluginStorage(FilePath).GetAsync("list"); + Assert.NotNull(loaded); + var array = loaded.Value.EnumerateArray().ToList(); + Assert.Equal(20000, array.Count); + } + + [Theory] + [InlineData("")] + [InlineData("this-key-is-longer-than-the-sixty-four-characters-a-plugin-key-may-be")] + public async Task ABadKeyIsRejected(string key) + { + var error = await Assert.ThrowsAsync( + () => new PluginStorage(FilePath).SetAsync(key, Json("1"))); + + Assert.Equal("invalid-argument", error.Code); + } + + [Fact] + public async Task AnUnreadableStoreLoadsAsEmptyAndCanBeWrittenAgain() + { + Directory.CreateDirectory(_root); + await File.WriteAllTextAsync(FilePath, "{ not json"); + var storage = new PluginStorage(FilePath); + + Assert.Null(await storage.GetAsync("goals")); + await storage.SetAsync("goals", Json("1")); + Assert.Equal(1, (await new PluginStorage(FilePath).GetAsync("goals"))!.Value.GetInt32()); + } + + [Fact] + public async Task RemoveDeletesOnlyThatKey() + { + var storage = new PluginStorage(FilePath); + await storage.SetAsync("a", Json("1")); + await storage.SetAsync("b", Json("2")); + + await storage.RemoveAsync("a"); + + Assert.Null(await new PluginStorage(FilePath).GetAsync("a")); + Assert.Equal(2, (await new PluginStorage(FilePath).GetAsync("b"))!.Value.GetInt32()); + } + + [Fact] + public async Task ALockedStoreIsNotTreatedAsEmptyAndKeepsItsData() + { + // Write key "a" with one instance + var storage1 = new PluginStorage(FilePath); + await storage1.SetAsync("a", Json("1")); + + // Lock the file to simulate a transient read failure + FileStream? lockStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None); + try + { + // With a NEW PluginStorage instance, GetAsync should throw "unavailable" + var storage2 = new PluginStorage(FilePath); + var error = await Assert.ThrowsAsync(() => storage2.GetAsync("a")); + Assert.Equal("unavailable", error.Code); + + // Dispose the lock + lockStream.Dispose(); + lockStream = null; + + // With that same instance, SetAsync should now succeed + await storage2.SetAsync("b", Json("2")); + + // A fresh instance should read both "a" and "b" + var storage3 = new PluginStorage(FilePath); + Assert.Equal(1, (await storage3.GetAsync("a"))!.Value.GetInt32()); + Assert.Equal(2, (await storage3.GetAsync("b"))!.Value.GetInt32()); + } + finally + { + lockStream?.Dispose(); + } + } +} diff --git a/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs b/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs index 9f09d94..8b244c6 100644 --- a/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs +++ b/src/FourFoldAccountManager.Core/Data/LocalDataPaths.cs @@ -16,6 +16,12 @@ public LocalDataPaths(string? root = null) XpTrackerFilePath = Path.Combine(DataRoot, "xp-tracker.json"); LeaderboardStateFilePath = Path.Combine(DataRoot, "leaderboard-state.json"); WebViewUserDataRoot = Path.Combine(DataRoot, "WebView2"); + DevPluginsRoot = Path.Combine(DataRoot, "dev-plugins"); + PluginDataRoot = Path.Combine(DataRoot, "plugin-data"); + PluginWebViewUserDataRoot = Path.Combine(DataRoot, "PluginWebView2"); + HubPluginsRoot = Path.Combine(DataRoot, "plugins"); + HubCatalogFilePath = Path.Combine(DataRoot, "hub", "catalog.json"); + HubInstalledFilePath = Path.Combine(DataRoot, "hub", "installed.json"); } public string DataRoot { get; } @@ -29,4 +35,22 @@ public LocalDataPaths(string? root = null) public string LeaderboardStateFilePath { get; } public string WebViewUserDataRoot { get; } + + // Plugin authors' work-in-progress plugins, loaded while developer mode is on. + public string DevPluginsRoot { get; } + + // One JSON file of private storage per community plugin. + public string PluginDataRoot { get; } + + // The plugin browser's own data folder, separate from the game profiles in WebViewUserDataRoot. + public string PluginWebViewUserDataRoot { get; } + + // 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/Data/SettingsStore.cs b/src/FourFoldAccountManager.Core/Data/SettingsStore.cs index 1552338..895f93a 100644 --- a/src/FourFoldAccountManager.Core/Data/SettingsStore.cs +++ b/src/FourFoldAccountManager.Core/Data/SettingsStore.cs @@ -3,6 +3,7 @@ using FourFoldAccountManager.Core.Models; using FourFoldAccountManager.Core.Overlay; using FourFoldAccountManager.Core.Panel; +using FourFoldAccountManager.Core.Plugins; namespace FourFoldAccountManager.Core.Data; @@ -116,7 +117,10 @@ private static PanelSettings Validate(PanelSettings? settings) ToolsWindow = settings.ToolsWindow is { IsUsable: true } ? settings.ToolsWindow : null, SecondMonitorMode = Enum.IsDefined(settings.SecondMonitorMode) ? settings.SecondMonitorMode - : SecondMonitorMode.AccountToolsWindow + : SecondMonitorMode.AccountToolsWindow, + PluginOrder = PluginLayoutPolicy.CleanIds(settings.PluginOrder), + DisabledPlugins = PluginLayoutPolicy.CleanIds(settings.DisabledPlugins), + OpenPlugin = string.IsNullOrWhiteSpace(settings.OpenPlugin) ? BuiltInPlugins.XpTrackerId : settings.OpenPlugin }; } diff --git a/src/FourFoldAccountManager.Core/Models/LenientStringJsonConverter.cs b/src/FourFoldAccountManager.Core/Models/LenientStringJsonConverter.cs new file mode 100644 index 0000000..c035037 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Models/LenientStringJsonConverter.cs @@ -0,0 +1,18 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace FourFoldAccountManager.Core.Models; + +// A value with the wrong JSON type (a number or object where a string belongs) reads as null instead of failing the +// whole PanelSettings load; SettingsStore then falls back to that setting's default. +public sealed class LenientStringJsonConverter : JsonConverter +{ + public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var element = JsonElement.ParseValue(ref reader); + return element.ValueKind == JsonValueKind.String ? element.GetString() : null; + } + + public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) => + JsonSerializer.Serialize(writer, value, options); +} diff --git a/src/FourFoldAccountManager.Core/Models/OverlayAddOnKind.cs b/src/FourFoldAccountManager.Core/Models/OverlayAddOnKind.cs index 2dc2541..944b023 100644 --- a/src/FourFoldAccountManager.Core/Models/OverlayAddOnKind.cs +++ b/src/FourFoldAccountManager.Core/Models/OverlayAddOnKind.cs @@ -6,5 +6,7 @@ public enum OverlayAddOnKind Xp = 0, Timer = 1, Stats = 2, - XpCalc = 3 + XpCalc = 3, + // A community plugin's card; OverlayCardPlacement.PluginCard says which. + Plugin = 4 } diff --git a/src/FourFoldAccountManager.Core/Models/OverlayCardPlacement.cs b/src/FourFoldAccountManager.Core/Models/OverlayCardPlacement.cs index 24499c6..0589d21 100644 --- a/src/FourFoldAccountManager.Core/Models/OverlayCardPlacement.cs +++ b/src/FourFoldAccountManager.Core/Models/OverlayCardPlacement.cs @@ -2,7 +2,7 @@ namespace FourFoldAccountManager.Core.Models; -public readonly record struct OverlayCardKey(OverlayAddOnKind Kind, Guid? AccountId); +public readonly record struct OverlayCardKey(OverlayAddOnKind Kind, Guid? AccountId, string? PluginCard = null); public sealed record OverlayCardPlacement( OverlayAddOnKind Kind, @@ -11,7 +11,11 @@ public sealed record OverlayCardPlacement( OverlayBounds? Bounds) { [JsonIgnore] - public OverlayCardKey Key => new(Kind, AccountId); + public OverlayCardKey Key => new(Kind, AccountId, PluginCard); + + // "/" when Kind is Plugin; null for FourFold's own cards. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? PluginCard { get; init; } // Shown as its own floating window instead of over the game. Only meaningful while Enabled. public bool IsFloating { get; init; } diff --git a/src/FourFoldAccountManager.Core/Models/PanelSettings.cs b/src/FourFoldAccountManager.Core/Models/PanelSettings.cs index 61b9478..2047b69 100644 --- a/src/FourFoldAccountManager.Core/Models/PanelSettings.cs +++ b/src/FourFoldAccountManager.Core/Models/PanelSettings.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using FourFoldAccountManager.Core.Plugins; namespace FourFoldAccountManager.Core.Models; @@ -22,8 +23,27 @@ public PanelSettings(PanelLayout layout, IReadOnlyList slotAccountIds) public bool ShowFullScreenExitButton { get; init; } = true; + // Whether the plugin panel is open beside the strip. The name and JSON key predate the strip, so existing settings + // files keep their shown-or-hidden choice. public bool PluginsSidebarExpanded { get; init; } = true; + // Whether the whole plugin strip and its panel show in the main window; the toolbar button toggles it. + public bool PluginStripVisible { get; init; } = true; + + // Loads community plugins from the dev plugins folder, for plugin authors. + public bool PluginDeveloperMode { get; init; } + + // Plugin ids in strip order. Empty means the built-in order. Unknown ids are kept for plugins that may return. + [JsonConverter(typeof(LenientListJsonConverter))] + public IReadOnlyList PluginOrder { get; init; } = Array.Empty(); + + [JsonConverter(typeof(LenientListJsonConverter))] + public IReadOnlyList DisabledPlugins { get; init; } = Array.Empty(); + + // The plugin last opened; the panel shows it when PluginsSidebarExpanded is true. + [JsonConverter(typeof(LenientStringJsonConverter))] + public string? OpenPlugin { get; init; } = BuiltInPlugins.XpTrackerId; + public bool ShowOverlaysInTheatreMode { get; init; } = true; public bool BlockStorePages { get; init; } diff --git a/src/FourFoldAccountManager.Core/Models/PluginKind.cs b/src/FourFoldAccountManager.Core/Models/PluginKind.cs deleted file mode 100644 index 4ed3a73..0000000 --- a/src/FourFoldAccountManager.Core/Models/PluginKind.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace FourFoldAccountManager.Core.Models; - -public enum PluginKind -{ - XpTracker, - ClassComparison, - XpCalculator, - Timer -} diff --git a/src/FourFoldAccountManager.Core/Models/ToolsWindowPlacement.cs b/src/FourFoldAccountManager.Core/Models/ToolsWindowPlacement.cs index 0f90fbe..d0523e0 100644 --- a/src/FourFoldAccountManager.Core/Models/ToolsWindowPlacement.cs +++ b/src/FourFoldAccountManager.Core/Models/ToolsWindowPlacement.cs @@ -12,7 +12,7 @@ public sealed record ToolsWindowPlacement( double Height, bool IsMaximized) { - public const double DefaultWidth = 300; + public const double DefaultWidth = 360; public const double DefaultHeight = 640; public const double MinimumWidth = 260; public const double MinimumHeight = 400; diff --git a/src/FourFoldAccountManager.Core/Overlay/OverlayAddOnCatalog.cs b/src/FourFoldAccountManager.Core/Overlay/OverlayAddOnCatalog.cs index 2649414..cb8706c 100644 --- a/src/FourFoldAccountManager.Core/Overlay/OverlayAddOnCatalog.cs +++ b/src/FourFoldAccountManager.Core/Overlay/OverlayAddOnCatalog.cs @@ -37,6 +37,11 @@ public static bool TryGet(OverlayAddOnKind kind, [NotNullWhen(true)] out Overlay public static int IndexOf(OverlayAddOnKind kind) { + if (kind == OverlayAddOnKind.Plugin) + { + return All.Count; + } + for (var index = 0; index < All.Count; index++) { if (All[index].Kind == kind) diff --git a/src/FourFoldAccountManager.Core/Overlay/OverlayCardPolicy.cs b/src/FourFoldAccountManager.Core/Overlay/OverlayCardPolicy.cs index 0d0d78c..1eac9b2 100644 --- a/src/FourFoldAccountManager.Core/Overlay/OverlayCardPolicy.cs +++ b/src/FourFoldAccountManager.Core/Overlay/OverlayCardPolicy.cs @@ -1,4 +1,5 @@ using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Plugins; namespace FourFoldAccountManager.Core.Overlay; @@ -9,10 +10,17 @@ public static class OverlayCardPolicy public const double CascadeStep = 16; public static bool IsValidKey(OverlayCardKey key) => - OverlayAddOnCatalog.TryGet(key.Kind, out var definition) && - (definition.Scope == OverlayAddOnScope.Account - ? key.AccountId is { } accountId && accountId != Guid.Empty - : key.AccountId is null); + key.Kind == OverlayAddOnKind.Plugin + // A plugin card's scope is only known while its plugin is loaded, so either scope is valid here. + ? PluginCardId.IsValid(key.PluginCard) && key.AccountId != Guid.Empty + : key.PluginCard is null && + OverlayAddOnCatalog.TryGet(key.Kind, out var definition) && + (definition.Scope == OverlayAddOnScope.Account + ? key.AccountId is { } accountId && accountId != Guid.Empty + : key.AccountId is null); + + private static OverlayCardPlacement NewPlacement(OverlayCardKey key, bool enabled) => + new(key.Kind, key.AccountId, enabled, null) { PluginCard = key.PluginCard }; // Settings files may be old or hand-edited; normalize instead of rejecting them. public static IReadOnlyList Normalize( @@ -66,7 +74,7 @@ public static IReadOnlyList RemoveAccount( // Showing a card over the game stops it floating, so a card is only ever in one place. public static PanelSettings WithEnabled(PanelSettings settings, OverlayCardKey key, bool enabled) => Upsert(settings, key, existing => - (existing ?? new OverlayCardPlacement(key.Kind, key.AccountId, false, null)) with + (existing ?? NewPlacement(key, false)) with { Enabled = enabled, IsFloating = false @@ -75,7 +83,7 @@ public static PanelSettings WithEnabled(PanelSettings settings, OverlayCardKey k // Ticking a card in the floating checklist floats it and takes it off the game; unticking switches it off. public static PanelSettings WithFloating(PanelSettings settings, OverlayCardKey key, bool show) => Upsert(settings, key, existing => - (existing ?? new OverlayCardPlacement(key.Kind, key.AccountId, false, null)) with + (existing ?? NewPlacement(key, false)) with { Enabled = show, IsFloating = show @@ -90,7 +98,7 @@ public static PanelSettings WithFloatingBounds(PanelSettings settings, OverlayCa } return Upsert(settings, key, existing => - (existing ?? new OverlayCardPlacement(key.Kind, key.AccountId, true, null) { IsFloating = true }) with + (existing ?? NewPlacement(key, true) with { IsFloating = true }) with { FloatingBounds = bounds }); @@ -115,7 +123,7 @@ public static PanelSettings WithBounds(PanelSettings settings, OverlayCardKey ke } return Upsert(settings, key, existing => - (existing ?? new OverlayCardPlacement(key.Kind, key.AccountId, true, null)) with { Bounds = bounds }); + (existing ?? NewPlacement(key, true)) with { Bounds = bounds }); } private static PanelSettings Upsert( diff --git a/src/FourFoldAccountManager.Core/Plugins/BuiltInPlugins.cs b/src/FourFoldAccountManager.Core/Plugins/BuiltInPlugins.cs new file mode 100644 index 0000000..e9860ae --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/BuiltInPlugins.cs @@ -0,0 +1,28 @@ +using FourFoldAccountManager.Core.Models; + +namespace FourFoldAccountManager.Core.Plugins; + +public static class BuiltInPlugins +{ + public const string XpTrackerId = "xp-tracker"; + public const string StatsId = "stats"; + public const string XpCalcId = "xp-calc"; + public const string TimerId = "timer"; + + // Icons are Segoe glyphs: AreaChart, ReportDocument, Calculator, Stopwatch. + public static PluginDescriptor XpTracker { get; } = + new(XpTrackerId, "XP tracker", "XP", "\uE9D2", [OverlayAddOnKind.Xp], []); + + public static PluginDescriptor Stats { get; } = + new(StatsId, "Stats", "Stats", "\uE9F9", [OverlayAddOnKind.Stats], []); + + public static PluginDescriptor XpCalc { get; } = + new(XpCalcId, "XP calc", "XP calc", "\uE8EF", [OverlayAddOnKind.XpCalc], []); + + public static PluginDescriptor Timer { get; } = + new(TimerId, "Timer", "Timer", "\uE916", [OverlayAddOnKind.Timer], + [GlobalShortcutAction.TimerSplit, GlobalShortcutAction.TimerFinish, GlobalShortcutAction.TimerReset]); + + // Default strip order. + public static IReadOnlyList All { get; } = Array.AsReadOnly([XpTracker, Stats, XpCalc, Timer]); +} 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/PluginApiException.cs b/src/FourFoldAccountManager.Core/Plugins/PluginApiException.cs new file mode 100644 index 0000000..f5692e0 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginApiException.cs @@ -0,0 +1,8 @@ +namespace FourFoldAccountManager.Core.Plugins; + +// A plugin API call that was refused. Code is one of: invalid-argument, not-declared, site-not-allowed, +// limit-exceeded, unavailable. The message is shown to the plugin's author. +public sealed class PluginApiException(string code, string message) : Exception(message) +{ + public string Code { get; } = code; +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs b/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs new file mode 100644 index 0000000..5bc66e0 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginCardId.cs @@ -0,0 +1,14 @@ +using System.Text.RegularExpressions; + +namespace FourFoldAccountManager.Core.Plugins; + +// A community plugin's card is identified by "/", for example "cody.goal-tracker/goal". +public static partial class PluginCardId +{ + [GeneratedRegex("^" + PluginManifestReader.IdPattern + "/" + PluginManifestReader.CardIdPattern + @"\z")] + private static partial Regex Pattern(); + + public static string Create(string pluginId, string cardId) => $"{pluginId}/{cardId}"; + + public static bool IsValid(string? value) => value is { Length: <= 97 } && Pattern().IsMatch(value); +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs b/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs new file mode 100644 index 0000000..33c036a --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginDescriptor.cs @@ -0,0 +1,29 @@ +using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins; + +public sealed record PluginCardDescriptor(string Id, string Name, OverlayAddOnScope Scope); + +// Everything the strip, the plugin list and the "off" rules need to know about a plugin, with no UI. +public sealed record PluginDescriptor( + string Id, + string Name, + string ShortLabel, + string Icon, + IReadOnlyList OverlayCards, + IReadOnlyList Shortcuts) +{ + // The cards a community plugin declared. FourFold's own plugins use OverlayCards instead. + public IReadOnlyList Cards { get; init; } = []; + + // A community plugin's icon image; when null the strip shows the Icon glyph. + public string? IconPath { get; init; } + + // A short tag beside the plugin's name in the plugin list, such as "DEV". + public string? Badge { get; init; } + + // 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 new file mode 100644 index 0000000..76232d7 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginFileServer.cs @@ -0,0 +1,65 @@ +namespace FourFoldAccountManager.Core.Plugins; + +// Maps a request path on a plugin's origin to a file in its folder. Only known static file types are served, and +// never plugin.json or anything outside the folder. +public static class PluginFileServer +{ + private static readonly Dictionary ContentTypes = new(StringComparer.OrdinalIgnoreCase) + { + [".html"] = "text/html; charset=utf-8", + [".js"] = "text/javascript; charset=utf-8", + [".mjs"] = "text/javascript; charset=utf-8", + [".css"] = "text/css; charset=utf-8", + [".json"] = "application/json; charset=utf-8", + [".txt"] = "text/plain; charset=utf-8", + [".png"] = "image/png", + [".jpg"] = "image/jpeg", + [".jpeg"] = "image/jpeg", + [".gif"] = "image/gif", + [".svg"] = "image/svg+xml", + [".webp"] = "image/webp", + [".woff2"] = "font/woff2" + }; + + // 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; + contentType = string.Empty; + if (urlPath is null) + { + return false; + } + + string relative; + try + { + relative = Uri.UnescapeDataString(urlPath).TrimStart('/'); + } + catch (UriFormatException) + { + return false; + } + + if (relative.Length == 0) + { + relative = manifest.Panel; + } + + // A backslash is a path separator on Windows, so "..\" would climb just like "../". + if (relative.Contains('\\') || relative.Contains(':') || + !PluginPaths.TryResolveInside(manifest.Folder, relative, out var resolved) || + !ContentTypes.TryGetValue(Path.GetExtension(resolved), out var type) || + Path.GetFileName(resolved).Equals("plugin.json", StringComparison.OrdinalIgnoreCase) || + !File.Exists(resolved)) + { + return false; + } + + filePath = resolved; + contentType = type; + return true; + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs new file mode 100644 index 0000000..fc6fa95 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginHttpFetcher.cs @@ -0,0 +1,308 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; + +namespace FourFoldAccountManager.Core.Plugins; + +public sealed record PluginHttpRequest( + string Url, + string? Method, + IReadOnlyDictionary? Headers, + string? Body); + +public sealed record PluginHttpResponse(int Status, IReadOnlyDictionary Headers, string Text); + +// Makes a web request on a plugin's behalf, because most sites refuse cross-origin requests from a page. Every URL +// (and every redirect) passes the same site rules as the plugin's page, no cookies or credentials are ever attached, +// and the connection only goes to an address checked to be outside the local network. +public sealed class PluginHttpFetcher : IDisposable +{ + public const int MaximumResponseBytes = 2 * 1024 * 1024; + + public const int MaximumRedirects = 5; + + public const int MaximumRequestsPerMinute = 60; + + public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(15); + + private const string HeaderSeparators = "()<>@,;:\\\"/[]?={}"; + + // Many public APIs refuse a request that has no User-Agent. This is a FourFold default, not a plugin header, so it + // goes on every hop (a redirect to another host drops the plugin's headers, not this), and a plugin's own wins. + private const string DefaultUserAgent = "FourFold-Plugin/1"; + + private static readonly string[] ForbiddenHeaders = + ["Cookie", "Host", "Content-Length", "Transfer-Encoding", "Connection"]; + + private readonly PluginManifest _manifest; + private readonly PluginTrust _trust; + private readonly HttpClient _http; + private readonly TimeProvider _clock; + private readonly TimeSpan _timeout; + private readonly Queue _recent = new(); + + public PluginHttpFetcher( + PluginManifest manifest, PluginTrust trust, HttpMessageHandler? handler = null, TimeProvider? clock = null, + TimeSpan? timeout = null) + { + _manifest = manifest; + _trust = trust; + _clock = clock ?? TimeProvider.System; + _timeout = timeout ?? RequestTimeout; + _http = new HttpClient(handler ?? CreateHandler()) { Timeout = Timeout.InfiniteTimeSpan }; + } + + public async Task FetchAsync( + PluginHttpRequest request, CancellationToken cancellationToken = default) + { + var method = (request.Method ?? "GET").ToUpperInvariant() switch + { + "GET" => HttpMethod.Get, + "POST" => HttpMethod.Post, + _ => throw new PluginApiException("invalid-argument", "Only GET and POST requests are supported.") + }; + if (!Uri.TryCreate(request.Url, UriKind.Absolute, out var uri)) + { + throw new PluginApiException("invalid-argument", "The URL isn't valid."); + } + + ValidateHeaders(request.Headers); + EnsureAllowed(uri); + TakeRateSlot(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(_timeout); + var body = request.Body; + var originalHost = uri.IdnHost; + var originalPort = uri.Port; + var forwardHeaders = true; + try + { + for (var redirects = 0; ; redirects++) + { + using var message = new HttpRequestMessage(method, uri); + if (method == HttpMethod.Post) + { + message.Content = new StringContent(body ?? string.Empty, Encoding.UTF8); + } + + // Don't forward plugin headers to a different host or port; once headers are dropped, keep them dropped. + if (uri.Port != originalPort || + !uri.IdnHost.Equals(originalHost, StringComparison.OrdinalIgnoreCase)) + { + forwardHeaders = false; + } + + ApplyHeaders(message, forwardHeaders ? request.Headers : null); + using var response = await _http.SendAsync( + message, HttpCompletionOption.ResponseHeadersRead, timeout.Token); + if ((int)response.StatusCode is 301 or 302 or 303 or 307 or 308 && + response.Headers.Location is { } location) + { + if (redirects >= MaximumRedirects) + { + throw new PluginApiException("limit-exceeded", "The request was redirected too many times."); + } + + if (!Uri.TryCreate(uri, location, out var next)) + { + throw new PluginApiException("unavailable", "The site sent a redirect that isn't valid."); + } + + uri = next; + EnsureAllowed(uri); + TakeRateSlot(); + if ((int)response.StatusCode == 303 || + (method == HttpMethod.Post && (int)response.StatusCode is 301 or 302)) + { + method = HttpMethod.Get; + body = null; + } + + continue; + } + + var text = await ReadTextAsync(response, timeout.Token); + text = text.TrimStart('\uFEFF'); + return new PluginHttpResponse( + (int)response.StatusCode, FlattenHeaders(response), text); + } + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new PluginApiException("unavailable", "The request took too long."); + } + catch (HttpRequestException exception) when (exception.InnerException is PluginApiException refused) + { + throw new PluginApiException(refused.Code, refused.Message); + } + catch (Exception exception) when (exception is not PluginApiException and not OperationCanceledException) + { + throw new PluginApiException("unavailable", "The request failed."); + } + } + + // A header name must be an HTTP token, and a value printable ASCII or a tab: no line breaks, control characters + // or non-ASCII, any of which could smuggle extra headers or a second request onto the connection. + private static void ValidateHeaders(IReadOnlyDictionary? headers) + { + foreach (var (name, value) in headers ?? new Dictionary()) + { + var validName = name.Length > 0 && + name.All(character => character is > ' ' and < '\x7f' && !HeaderSeparators.Contains(character)); + var validValue = value is not null && + value.All(character => character == '\t' || character is >= ' ' and <= '~'); + if (!validName || !validValue) + { + throw new PluginApiException("invalid-argument", "A request header's name or value isn't valid."); + } + } + } + + // Refuses a host when any address it resolves to is on the local network, and returns all addresses outside + // the local network, so the addresses that were checked are the addresses that are used. + public static async Task ResolvePublicAddressesAsync( + string host, + Func> resolve, + CancellationToken cancellationToken) + { + var addresses = await resolve(host, cancellationToken); + if (addresses.Length == 0 || addresses.Any(PluginNetworkPolicy.IsLocalAddress)) + { + throw new PluginApiException("site-not-allowed", "Plugins can't reach the local network."); + } + + return addresses; + } + + public void Dispose() => _http.Dispose(); + + private void EnsureAllowed(Uri uri) + { + if (PluginNetworkPolicy.IsOwnOrigin(uri, _manifest.Id) || + !PluginNetworkPolicy.IsAllowed(uri, _manifest, _trust)) + { + throw new PluginApiException( + "site-not-allowed", $"{uri.Host} isn't one of this plugin's declared sites."); + } + } + + private void TakeRateSlot() + { + lock (_recent) + { + var now = _clock.GetUtcNow(); + while (_recent.Count > 0 && now - _recent.Peek() >= TimeSpan.FromSeconds(60)) + { + _recent.Dequeue(); + } + + if (_recent.Count >= MaximumRequestsPerMinute) + { + throw new PluginApiException("limit-exceeded", "A plugin can make at most 60 requests a minute."); + } + + _recent.Enqueue(now); + } + } + + private static void ApplyHeaders(HttpRequestMessage message, IReadOnlyDictionary? headers) + { + foreach (var (name, value) in headers ?? new Dictionary()) + { + if (ForbiddenHeaders.Contains(name, StringComparer.OrdinalIgnoreCase) || + name.StartsWith("Proxy-", StringComparison.OrdinalIgnoreCase) || + name.StartsWith("Sec-", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + // Content headers (such as Content-Type) belong on the body, not the request. + if (!message.Headers.TryAddWithoutValidation(name, value) && message.Content is not null) + { + message.Content.Headers.Remove(name); + message.Content.Headers.TryAddWithoutValidation(name, value); + } + } + + if (!message.Headers.Contains("User-Agent")) + { + message.Headers.TryAddWithoutValidation("User-Agent", DefaultUserAgent); + } + } + + private static Dictionary FlattenHeaders(HttpResponseMessage response) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (name, values) in response.Headers.Concat(response.Content.Headers)) + { + if (!name.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)) + { + result[name] = string.Join(", ", values); + } + } + + return result; + } + + private static async Task ReadTextAsync(HttpResponseMessage response, CancellationToken cancellationToken) + { + if (response.Content.Headers.ContentLength > MaximumResponseBytes) + { + throw new PluginApiException("limit-exceeded", "The response is larger than 2 MB."); + } + + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using var buffer = new MemoryStream(); + var chunk = new byte[16 * 1024]; + int read; + while ((read = await stream.ReadAsync(chunk, cancellationToken)) > 0) + { + if (buffer.Length + read > MaximumResponseBytes) + { + throw new PluginApiException("limit-exceeded", "The response is larger than 2 MB."); + } + + buffer.Write(chunk, 0, read); + } + + return Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length); + } + + // No cookies, no redirects the fetcher hasn't checked, no system proxy (the address check must see the real + // host), and a connection only to addresses outside the local network. + private static SocketsHttpHandler CreateHandler() => new() + { + AllowAutoRedirect = false, + UseCookies = false, + UseProxy = false, + AutomaticDecompression = DecompressionMethods.All, + ConnectCallback = async (context, cancellationToken) => + { + var addresses = await ResolvePublicAddressesAsync( + context.DnsEndPoint.Host, Dns.GetHostAddressesAsync, cancellationToken); + + Exception? lastException = null; + foreach (var address in addresses) + { + var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + await socket.ConnectAsync(new IPEndPoint(address, context.DnsEndPoint.Port), cancellationToken); + return new NetworkStream(socket, ownsSocket: true); + } + catch (OperationCanceledException) + { + socket.Dispose(); + throw; + } + catch (Exception exception) + { + lastException = exception; + socket.Dispose(); + } + } + + throw lastException ?? new SocketException(); + } + }; +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs new file mode 100644 index 0000000..7df82cb --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginLayoutPolicy.cs @@ -0,0 +1,103 @@ +using FourFoldAccountManager.Core.Models; + +namespace FourFoldAccountManager.Core.Plugins; + +public static class PluginLayoutPolicy +{ + // 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) + { + var rank = new Dictionary(StringComparer.Ordinal); + foreach (var id in settings.PluginOrder) + { + rank.TryAdd(id, rank.Count); + } + + return known + .Select((plugin, index) => (plugin, index, rank: rank.GetValueOrDefault(plugin.Id, int.MaxValue))) + .OrderBy(entry => entry.rank) + .ThenBy(entry => entry.index) + .Select(entry => entry.plugin) + .ToArray(); + } + + public static bool IsEnabled(PanelSettings settings, string id) => + !settings.DisabledPlugins.Contains(id, StringComparer.Ordinal); + + public static bool IsCardSuppressed(PanelSettings settings, OverlayAddOnKind kind) => + BuiltInPlugins.All.Any(plugin => plugin.OverlayCards.Contains(kind) && !IsEnabled(settings, plugin.Id)); + + public static bool IsShortcutSuppressed(PanelSettings settings, GlobalShortcutAction action) => + BuiltInPlugins.All.Any(plugin => plugin.Shortcuts.Contains(action) && !IsEnabled(settings, plugin.Id)); + + // The saved open plugin when it is known and switched on; otherwise null. + public static PluginDescriptor? OpenPlugin(PanelSettings settings, IReadOnlyList known) => + known.FirstOrDefault(plugin => plugin.Id == settings.OpenPlugin && IsEnabled(settings, plugin.Id)); + + // Returns the same instance when nothing changes, so callers can skip the save. + public static PanelSettings WithEnabled(PanelSettings settings, string id, bool enabled) + { + if (IsEnabled(settings, id) == enabled) + { + return settings; + } + + var others = settings.DisabledPlugins.Where(other => other != id); + var next = settings with + { + DisabledPlugins = Array.AsReadOnly((enabled ? others : others.Append(id)).ToArray()) + }; + // Switching off the open plugin closes the panel. + return !enabled && settings.OpenPlugin == id ? next with { PluginsSidebarExpanded = false } : next; + } + + // Moves a plugin to index among the strip's icons (known, switched-on plugins, in order). Every other saved id + // keeps its slot: switched-off plugins, and plugins that aren't loaded right now. + public static PanelSettings WithMoved( + PanelSettings settings, IReadOnlyList known, string id, int index) + { + var knownIds = known.Select(plugin => plugin.Id).ToHashSet(StringComparer.Ordinal); + var full = settings.PluginOrder + .Concat(known.Select(plugin => plugin.Id) + .Where(knownId => !settings.PluginOrder.Contains(knownId, StringComparer.Ordinal))) + .ToList(); + bool OnStrip(string other) => knownIds.Contains(other) && IsEnabled(settings, other); + + var strip = full.Where(OnStrip).ToList(); + if (!strip.Remove(id)) + { + return settings; + } + + strip.Insert(Math.Clamp(index, 0, strip.Count), id); + var order = new List(full.Count); + var nextStripId = 0; + foreach (var other in full) + { + order.Add(OnStrip(other) ? strip[nextStripId++] : other); + } + + return order.SequenceEqual(settings.PluginOrder) + ? settings + : settings with { PluginOrder = Array.AsReadOnly(order.ToArray()) }; + } + + public static PanelSettings WithOpened(PanelSettings settings, string id) => + settings.OpenPlugin == id && settings.PluginsSidebarExpanded + ? settings + : settings with { OpenPlugin = id, PluginsSidebarExpanded = true }; + + 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 256 ids stay. + public static IReadOnlyList CleanIds(IReadOnlyList? ids) => + Array.AsReadOnly((ids ?? Array.Empty()) + .Where(id => !string.IsNullOrWhiteSpace(id)) + .Distinct(StringComparer.Ordinal) + .Take(MaximumIds) + .ToArray()); +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifest.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifest.cs new file mode 100644 index 0000000..68cf887 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifest.cs @@ -0,0 +1,26 @@ +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins; + +public sealed record PluginCardManifest(string Id, string Name, OverlayAddOnScope Scope); + +// A validated plugin.json. Sites are origins (scheme, host and port only). +public sealed record PluginManifest( + string Id, + string Name, + string ShortLabel, + string Version, + string Author, + string Description, + int ApiVersion, + string Panel, + string? Icon, + IReadOnlyList Sites, + bool AnySite, + IReadOnlyList Cards) +{ + // The plugin's folder on disk. + public string Folder { get; init; } = string.Empty; +} + +public sealed record PluginManifestResult(PluginManifest? Manifest, string? Error); diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs new file mode 100644 index 0000000..95a278b --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -0,0 +1,338 @@ +using System.Buffers.Binary; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.RegularExpressions; +using FourFoldAccountManager.Core.Overlay; + +namespace FourFoldAccountManager.Core.Plugins; + +public static partial class PluginManifestReader +{ + public const int SupportedApiVersion = 1; + + // author.plugin-name: lowercase letters, digits and dashes in dot-separated parts, with at least one dot. + public const string IdPattern = @"[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+"; + + public const string CardIdPattern = "[a-z0-9]+(-[a-z0-9]+)*"; + + // 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; + + [GeneratedRegex("^" + IdPattern + @"\z")] + private static partial Regex IdRegex(); + + [GeneratedRegex("^" + CardIdPattern + @"\z")] + private static partial Regex CardIdRegex(); + + [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 + // file "nul.tools.json" that silently swallows every write. + [GeneratedRegex("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$")] + private static partial Regex DeviceNameRegex(); + + // 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. + public static PluginManifestResult Read(string folder) + { + try + { + return ReadManifest(folder); + } + catch (Exception) + { + return Reject("plugin.json couldn't be read."); + } + } + + private static PluginManifestResult ReadManifest(string folder) + { + var path = Path.Combine(folder, "plugin.json"); + if (!File.Exists(path)) + { + return Reject("plugin.json is missing."); + } + + if (new FileInfo(path).Length > MaximumManifestBytes) + { + return Reject("plugin.json is too large."); + } + + JsonDocument document; + try + { + document = JsonDocument.Parse(File.ReadAllText(path)); + } + catch (Exception exception) when (exception is JsonException or IOException or UnauthorizedAccessException) + { + return Reject("plugin.json isn't valid JSON."); + } + + try + { + using (document) + { + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return Reject("plugin.json isn't valid JSON."); + } + + var id = Text(root, "id"); + if (id is 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."); + } + + if (!IsValidId(id)) + { + return Reject("The id must look like author.plugin-name (lowercase letters, digits, dots and dashes)."); + } + + if (!InRange(Text(root, "name"), 1, 40, out var name)) + { + return Reject("The name must be 1 to 40 characters."); + } + + if (!InRange(Text(root, "shortLabel"), 1, 8, out var shortLabel)) + { + return Reject("The shortLabel must be 1 to 8 characters."); + } + + var version = Text(root, "version"); + if (!IsVersion(version)) + { + return Reject("The version must look like 1.0.0."); + } + + if (!InRange(Text(root, "author"), 1, 40, out var author)) + { + return Reject("The author must be 1 to 40 characters."); + } + + var description = Text(root, "description") ?? string.Empty; + if (description.Length > 200) + { + return Reject("The description must be at most 200 characters."); + } + + if (new[] { name, shortLabel, author, description }.Any(PluginText.HasUnsafeCharacter)) + { + return Reject("The name, shortLabel, author and description can't contain control characters or invisible formatting characters."); + } + + if (!root.TryGetProperty("apiVersion", out var apiElement) || apiElement.ValueKind != JsonValueKind.Number || + !apiElement.TryGetInt32(out var apiVersion) || apiVersion < 1) + { + return Reject("The apiVersion must be a whole number."); + } + + if (apiVersion > SupportedApiVersion) + { + return Reject(NeedsNewerFourFold); + } + + var panel = Text(root, "panel"); + if (panel is null || panel.Contains('\\') || !panel.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || + !PluginPaths.TryResolveInside(folder, panel, out var panelPath) || !File.Exists(panelPath)) + { + return Reject("The panel must be an .html file inside the plugin folder."); + } + + var icon = Text(root, "icon"); + if (icon is not null && + (icon.Contains('\\') || !icon.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || + !PluginPaths.TryResolveInside(folder, icon, out var iconPath) || !File.Exists(iconPath) || + new FileInfo(iconPath).Length > MaximumIconBytes || !IsSmallPng(iconPath))) + { + return Reject("The icon must be a PNG inside the plugin folder, at most 256 by 256 pixels and 64 KB."); + } + + if (!TryReadSites(root, out var sites, out var siteError)) + { + return Reject(siteError); + } + + var anySite = root.TryGetProperty("anySite", out var anySiteElement) && + anySiteElement.ValueKind == JsonValueKind.True; + if (!TryReadCards(root, out var cards, out var cardError)) + { + return Reject(cardError); + } + + return new PluginManifestResult( + new PluginManifest(id, name, shortLabel, version, author, description, apiVersion, panel, icon, + sites, anySite, cards) { Folder = folder }, + null); + } + } + catch (InvalidOperationException) + { + return Reject("plugin.json isn't valid JSON."); + } + } + + private static PluginManifestResult Reject(string reason) => new(null, reason); + + internal static string? Text(JsonElement root, string property) => + root.TryGetProperty(property, out var element) && element.ValueKind == JsonValueKind.String + ? element.GetString()?.Trim() + : null; + + internal static bool InRange(string? value, int minimum, int maximum, out string result) + { + result = value ?? string.Empty; + return result.Length >= minimum && result.Length <= maximum; + } + + // The app decodes the icon on every render of the strip, and a tiny file can declare an enormous image (a 274-byte + // PNG declaring 1 by 100000 pixels made it commit 215 MB), so the header is checked first, not the file's content. + // A PNG's first 24 bytes are the signature, then the IHDR chunk's length and name, then its width and height. + private static bool IsSmallPng(string path) + { + Span header = stackalloc byte[24]; + using var stream = File.OpenRead(path); + return stream.ReadAtLeast(header, header.Length, throwOnEndOfStream: false) == header.Length && + header[..8].SequenceEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }) && + header[12..16].SequenceEqual("IHDR"u8) && + BinaryPrimitives.ReadUInt32BigEndian(header[16..]) is >= 1 and <= 256 && + BinaryPrimitives.ReadUInt32BigEndian(header[20..]) is >= 1 and <= 256; + } + + 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."; + if (!root.TryGetProperty("sites", out var element) || element.ValueKind == JsonValueKind.Null) + { + return true; + } + + if (element.ValueKind != JsonValueKind.Array) + { + return false; + } + + var result = new List(); + foreach (var item in element.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.String || + !Uri.TryCreate(item.GetString(), UriKind.Absolute, out var uri) || + uri.Scheme != Uri.UriSchemeHttps || uri.AbsolutePath != "/" || uri.Query.Length > 0 || + uri.Fragment.Length > 0 || uri.UserInfo.Length > 0 || uri.HostNameType != UriHostNameType.Dns || + PluginNetworkHosts.IsLocalName(uri.IdnHost) || uri.IdnHost.EndsWith('.') || + IsIpLikeHost(uri.IdnHost) || !IsPlainHost(uri.IdnHost) || PluginNetworkPolicy.IsPluginHost(uri.IdnHost)) + { + return false; + } + + result.Add(new Uri(uri.GetLeftPart(UriPartial.Authority))); + } + + if (result.Count > 10) + { + error = "A plugin can declare at most 10 sites."; + return false; + } + + sites = Array.AsReadOnly(result.Distinct().ToArray()); + return true; + } + + // 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; + return lastLabel.Length > 0 && lastLabel.All(c => c >= '0' && c <= '9'); + } + + private static bool TryReadCards(JsonElement root, out IReadOnlyList cards, out string error) + { + cards = []; + error = "Each card needs an id (lowercase letters, digits, dashes), a name (1 to 24 characters, no control or invisible formatting characters) and a scope of account or global."; + if (!root.TryGetProperty("cards", out var element) || element.ValueKind == JsonValueKind.Null) + { + return true; + } + + if (element.ValueKind != JsonValueKind.Array) + { + return false; + } + + var result = new List(); + foreach (var item in element.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.Object) + { + return false; + } + + var id = Text(item, "id"); + var scope = Text(item, "scope"); + if (id is null || id.Length > 32 || !CardIdRegex().IsMatch(id) || + !InRange(Text(item, "name"), 1, 24, out var name) || PluginText.HasUnsafeCharacter(name) || + scope is not ("account" or "global") || result.Any(card => card.Id == id)) + { + return false; + } + + result.Add(new PluginCardManifest(id, name, + scope == "account" ? OverlayAddOnScope.Account : OverlayAddOnScope.Global)); + } + + if (result.Count > 6) + { + error = "A plugin can declare at most 6 cards."; + return false; + } + + cards = Array.AsReadOnly(result.ToArray()); + return true; + } +} + +// Host-name checks shared by the manifest reader and the network policy. +public static class PluginNetworkHosts +{ + // Names that only mean something on the user's own network: localhost, mDNS (.local), common intranet endings, and + // a single-label name such as "router". An IPv6 literal has colons and no dots, so it isn't a single-label name. + public static bool IsLocalName(string host) + { + var trimmed = host.TrimEnd('.'); + return trimmed.Equals("localhost", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".local", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".internal", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".lan", StringComparison.OrdinalIgnoreCase) || + trimmed.EndsWith(".home.arpa", StringComparison.OrdinalIgnoreCase) || + (trimmed.Length > 0 && !trimmed.Contains('.') && !trimmed.Contains(':')); + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs new file mode 100644 index 0000000..268de4f --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginNetworkPolicy.cs @@ -0,0 +1,145 @@ +using System.Net; +using System.Net.Sockets; + +namespace FourFoldAccountManager.Core.Plugins; + +// What a community plugin may load or contact. The same rules back the Content-Security-Policy header, the request +// handler's second check, and the FourFold-run fetch. +public static class PluginNetworkPolicy +{ + // Every plugin page lives under this made-up top-level name, one domain per plugin. + public const string OriginSuffix = "fourfoldplugin"; + + // "--" can't appear in a plugin id, so replacing the dots keeps every id's host unique. + public static string OriginHost(string pluginId) => $"{pluginId.Replace(".", "--")}.{OriginSuffix}"; + + public static Uri Origin(string pluginId) => new($"https://{OriginHost(pluginId)}/"); + + public static bool IsOwnOrigin(Uri uri, string pluginId) => + uri.IsAbsoluteUri && uri.Scheme == Uri.UriSchemeHttps && uri.IsDefaultPort && + uri.Host.Equals(OriginHost(pluginId), StringComparison.OrdinalIgnoreCase); + + // True for any host in the plugin namespace, whichever plugin it belongs to. + public static bool IsPluginHost(string host) + { + var name = host.TrimEnd('.'); + return name.Equals(OriginSuffix, StringComparison.OrdinalIgnoreCase) || + name.EndsWith("." + OriginSuffix, StringComparison.OrdinalIgnoreCase); + } + + // 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); + + // Loopback, private, link-local, carrier-grade NAT and unspecified addresses, in any spelling: a plugin must never + // reach the user's own network. + public static bool IsLocalAddress(IPAddress address) + { + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + // Rebuilding from the bytes drops any scope id, so "::1%1" is still loopback. + var bytes = address.GetAddressBytes(); + address = new IPAddress(bytes); + if (address.IsIPv4MappedToIPv6) + { + return IsLocalAddress(address.MapToIPv4()); + } + + if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.IPv6Any) || address.IsIPv6LinkLocal || + address.IsIPv6UniqueLocal || address.IsIPv6SiteLocal) + { + return true; + } + + // An IPv6 address that embeds an IPv4 address reaches that IPv4 host: IPv4-compatible (::a.b.c.d), + // SIIT (::ffff:0:a.b.c.d), NAT64 (64:ff9b::a.b.c.d) and 6to4 (2002:AABB:CCDD::). + byte[]? embedded = + AllZero(bytes, 0, 12) ? bytes[12..16] + : AllZero(bytes, 0, 8) && bytes[8] == 0xff && bytes[9] == 0xff && bytes[10] == 0 && bytes[11] == 0 ? bytes[12..16] + : bytes[0] == 0x00 && bytes[1] == 0x64 && bytes[2] == 0xff && bytes[3] == 0x9b && AllZero(bytes, 4, 8) ? bytes[12..16] + : bytes[0] == 0x20 && bytes[1] == 0x02 ? bytes[2..6] + : null; + return embedded is not null && IsLocalAddress(new IPAddress(embedded)); + } + + var octets = address.GetAddressBytes(); + return octets[0] switch + { + 0 or 10 or 127 => true, + 100 => octets[1] is >= 64 and <= 127, + 169 => octets[1] == 254, + 172 => octets[1] is >= 16 and <= 31, + 192 => octets[1] == 168, + _ => false + }; + + static bool AllZero(byte[] value, int start, int count) => value.AsSpan(start, count).IndexOfAnyExcept((byte)0) < 0; + } + + public static bool IsLocalHost(string host) + { + var normalized = host.Trim('[', ']').TrimEnd('.'); + return PluginNetworkHosts.IsLocalName(normalized) || + (IPAddress.TryParse(normalized, out var address) && IsLocalAddress(address)); + } + + // isScript is true for script and worker requests, which may only ever come from the plugin's own files. + public static bool IsAllowed(Uri uri, PluginManifest manifest, PluginTrust trust, bool isScript = false) + { + if (!uri.IsAbsoluteUri) + { + return false; + } + + if (IsOwnOrigin(uri, manifest.Id)) + { + return true; + } + + if (IsPluginHost(uri.IdnHost)) + { + return false; + } + + if (isScript || uri.Scheme != Uri.UriSchemeHttps || uri.UserInfo.Length > 0 || IsLocalHost(uri.IdnHost)) + { + return false; + } + + return AllowsAnySite(manifest, trust) || + manifest.Sites.Any(site => + site.Port == uri.Port && site.IdnHost.Equals(uri.IdnHost.TrimEnd('.'), StringComparison.OrdinalIgnoreCase)); + } + + public static string BuildContentSecurityPolicy(PluginManifest manifest, PluginTrust trust) + { + var allowsAnySite = AllowsAnySite(manifest, trust); + var wssSites = string.Join(' ', manifest.Sites.Select(site => + site.IsDefaultPort ? $"wss://{site.IdnHost}" : $"wss://{site.IdnHost}:{site.Port}")); + + string images; + string connectHttps; + + if (allowsAnySite) + { + images = "https:"; + connectHttps = "https:"; + } + else + { + var originParts = manifest.Sites.Select(site => + site.IsDefaultPort ? $"https://{site.IdnHost}" : $"https://{site.IdnHost}:{site.Port}").ToArray(); + images = string.Join(' ', originParts); + connectHttps = string.Join(' ', originParts); + } + + var connect = Prefix(connectHttps) + Prefix(wssSites); + return "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; " + + $"img-src 'self' data:{Prefix(images)}; connect-src 'self'{connect}; " + + "frame-src 'none'; worker-src 'none'; webrtc 'block'; object-src 'none'; base-uri 'none'; form-action 'none'"; + + static string Prefix(string value) => value.Length == 0 ? string.Empty : " " + value; + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs b/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs new file mode 100644 index 0000000..7b0410e --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginPaths.cs @@ -0,0 +1,37 @@ +namespace FourFoldAccountManager.Core.Plugins; + +public static class PluginPaths +{ + // Resolves relativePath inside folder. False when the path is rooted, empty, or escapes the folder, so a plugin + // can never name a file outside its own folder. + public static bool TryResolveInside(string folder, string relativePath, out string fullPath) + { + fullPath = string.Empty; + if (string.IsNullOrWhiteSpace(folder) || string.IsNullOrWhiteSpace(relativePath) || + relativePath.Contains('\0') || Path.IsPathRooted(relativePath)) + { + return false; + } + + string root; + string candidate; + try + { + root = Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + + Path.DirectorySeparatorChar; + candidate = Path.GetFullPath(Path.Combine(root, relativePath)); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + + if (!candidate.StartsWith(root, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + fullPath = candidate; + return true; + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs b/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs new file mode 100644 index 0000000..4d2a035 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginStorage.cs @@ -0,0 +1,115 @@ +using System.Text.Json; +using FourFoldAccountManager.Core.Data; + +namespace FourFoldAccountManager.Core.Plugins; + +// One plugin's private key-value store: a small JSON file, saved atomically. A missing or corrupt file loads as +// empty; a file that is locked or unreadable at the moment rejects the call and is never overwritten. +public sealed class PluginStorage(string filePath) +{ + public const int MaximumBytes = 256 * 1024; + + public const int MaximumKeyLength = 64; + + private readonly SemaphoreSlim _gate = new(1, 1); + private Dictionary? _values; + + public async Task GetAsync(string key) + { + ValidateKey(key); + await _gate.WaitAsync(); + try + { + return (await LoadAsync()).TryGetValue(key, out var value) ? value : null; + } + finally + { + _gate.Release(); + } + } + + public async Task SetAsync(string key, JsonElement value) + { + ValidateKey(key); + await _gate.WaitAsync(); + try + { + var values = await LoadAsync(); + var next = new Dictionary(values, StringComparer.Ordinal) { [key] = value.Clone() }; + if (JsonSerializer.SerializeToUtf8Bytes(next, AtomicJsonFile.Options).Length > MaximumBytes) + { + throw new PluginApiException("limit-exceeded", "Plugin storage is limited to 256 KB."); + } + + await AtomicJsonFile.WriteAsync(filePath, next, CancellationToken.None); + _values = next; + } + finally + { + _gate.Release(); + } + } + + public async Task RemoveAsync(string key) + { + ValidateKey(key); + await _gate.WaitAsync(); + try + { + var values = await LoadAsync(); + if (!values.ContainsKey(key)) + { + return; + } + + var next = new Dictionary(values, StringComparer.Ordinal); + next.Remove(key); + await AtomicJsonFile.WriteAsync(filePath, next, CancellationToken.None); + _values = next; + } + finally + { + _gate.Release(); + } + } + + private static void ValidateKey(string key) + { + if (string.IsNullOrEmpty(key) || key.Length > MaximumKeyLength) + { + throw new PluginApiException("invalid-argument", "A storage key must be 1 to 64 characters."); + } + } + + private async Task> LoadAsync() + { + if (_values is not null) + { + return _values; + } + + try + { + await using var stream = File.OpenRead(filePath); + _values = await JsonSerializer.DeserializeAsync>(stream) ?? []; + } + catch (FileNotFoundException) + { + _values = []; + } + catch (DirectoryNotFoundException) + { + _values = []; + } + catch (JsonException) + { + _values = []; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + throw new PluginApiException("unavailable", "Plugin storage couldn't be read right now."); + } + + return _values; + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginText.cs b/src/FourFoldAccountManager.Core/Plugins/PluginText.cs new file mode 100644 index 0000000..5b233c4 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginText.cs @@ -0,0 +1,19 @@ +using System.Globalization; +using System.Text; + +namespace FourFoldAccountManager.Core.Plugins; + +public static class PluginText +{ + // Text a plugin supplies is drawn by FourFold, so it can't carry anything that rearranges or hides the text around + // it: control characters (a line break, a bell), direction overrides, zero-width spaces and the line and paragraph + // separators. The zero-width joiner and non-joiner (U+200D, U+200C) are allowed: emoji and several scripts + // (Persian, for one) need them. + public static bool HasUnsafeCharacter(string text) => + text.EnumerateRunes().Any(rune => Rune.IsControl(rune) || Rune.GetUnicodeCategory(rune) switch + { + UnicodeCategory.Format => rune.Value is not (0x200C or 0x200D), + UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator => true, + _ => false + }); +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs b/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs new file mode 100644 index 0000000..0544d79 --- /dev/null +++ b/src/FourFoldAccountManager.Core/Plugins/PluginTrust.cs @@ -0,0 +1,13 @@ +namespace FourFoldAccountManager.Core.Plugins; + +public enum PluginTrust +{ + // 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, + + // 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 new file mode 100644 index 0000000..068e2c0 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs @@ -0,0 +1,294 @@ +using System.Collections.Concurrent; +using System.IO; +using System.Text.Json; +using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Core.Overlay; +using FourFoldAccountManager.Core.Plugins; +using FourFoldAccountManager.Desktop.Plugins.Web; +using Xunit; + +namespace FourFoldAccountManager.Desktop.Tests.Plugins; + +public sealed class PluginApiTests : IDisposable +{ + private const string PluginId = "cody.goal-tracker"; + + private static readonly Guid KnownAccount = Guid.Parse("6b1d7c3e-2f4a-4c58-9e0b-1a2b3c4d5e6f"); + + private readonly string _folder = Path.Combine(Path.GetTempPath(), "fourfold-plugin-api-" + Guid.NewGuid().ToString("N")); + private readonly FakeHost _host = new(); + private readonly ManualTimeProvider _clock = new(); + private readonly PluginCardStore _cards = new(); + private readonly PluginManifest _manifest; + private readonly PluginHttpFetcher _http; + private readonly PluginApi _api; + + public PluginApiTests() + { + _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, PluginTrust.Standard, _host, new PluginStorage(Path.Combine(_folder, "storage.json")), _http, + _cards, _clock); + } + + public void Dispose() + { + _http.Dispose(); + if (Directory.Exists(_folder)) + { + Directory.Delete(_folder, recursive: true); + } + } + + [Fact] + public async Task OpenExternalOnlyOpensPublicHttpsLinksOnDeclaredSites() + { + _host.PanelShowing = true; + + foreach (var url in new[] + { + "file:///C:/Windows/System32/calc.exe", "javascript:alert(1)", "http://example.com/", + "https://localhost/", "https://192.168.1.1/", "https://printer.local/", + "https://user@example.com/", "ms-settings:", + "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" }); + + Assert.Null(ErrorCode(opened)); + 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() + { + var link = new { url = "https://example.com/" }; + + Assert.Equal("unavailable", ErrorCode(await Call("openExternal", link))); + Assert.Empty(_host.Opened); + + _host.PanelShowing = true; + Assert.Null(ErrorCode(await Call("openExternal", link))); + Assert.Single(_host.Opened); + + Assert.Equal("limit-exceeded", ErrorCode(await Call("openExternal", link))); + Assert.Single(_host.Opened); + + _clock.Advance(TimeSpan.FromSeconds(2)); + Assert.Null(ErrorCode(await Call("openExternal", link))); + Assert.Equal(2, _host.Opened.Count); + } + + [Fact] + public async Task ACardCanOnlyBeSetForADeclaredCardAndAKnownAccount() + { + Assert.Equal( + "not-declared", ErrorCode(await Call("cards.set", new { cardId = "other", accountId = KnownAccount }))); + Assert.Equal( + "invalid-argument", ErrorCode(await Call("cards.set", new { cardId = "goal", accountId = Guid.NewGuid() }))); + + // A right-to-left override (U+202E) in a label would reverse the text drawn after it. + Assert.Equal( + "invalid-argument", + ErrorCode(await Call("cards.set", new + { + cardId = "goal", + accountId = KnownAccount, + rows = new[] { new { label = "Done\u202E", value = "3" } } + }))); + + var key = new OverlayCardKey(OverlayAddOnKind.Plugin, KnownAccount, "cody.goal-tracker/goal"); + Assert.Null(_cards.Get(key)); + + var reply = await Call("cards.set", new + { + cardId = "goal", + accountId = KnownAccount, + summary = "3 of 5", + rows = new[] { new { label = "Done", value = "3", progress = 0.6 } } + }); + + Assert.Null(ErrorCode(reply)); + var content = Assert.IsType(_cards.Get(key)); + Assert.Equal("3 of 5", content.Summary); + var row = Assert.Single(content.Rows); + Assert.Equal(("Done", "3", 0.6), (row.Label, row.Value, row.Progress)); + } + + [Fact] + public async Task HostileMessagesNeverThrow() + { + var messages = new[] + { + "not json", + "[]", + "{}", + """{"id":"x"}""", + """{"id":1}""", + """{"id":1,"method":5}""", + """{"id":1,"method":"xp.get","params":[]}""", + """{"id":1,"method":"cards.set","params":{"cardId":"goal","rows":"x"}}""", + """{"id":1,"method":"cards.set","params":{"cardId":"summary","rows":[5,null,{"progress":"x"}]}}""" + }; + + foreach (var message in messages) + { + var reply = await _api.HandleAsync(message); + + if (reply is null) + { + continue; + } + + using var document = JsonDocument.Parse(reply); + Assert.True( + document.RootElement.TryGetProperty("result", out _) || document.RootElement.TryGetProperty("error", out _), + $"The reply to {message[..Math.Min(message.Length, 60)]} had neither a result nor an error."); + } + + var tooLong = "{\"id\":1,\"method\":\"storage.set\",\"params\":{\"key\":\"k\",\"value\":\"" + + new string('x', PluginApi.MaximumMessageLength) + "\"}}"; + Assert.Null(await _api.HandleAsync(tooLong)); + } + + [Fact] + public void CallsBeyondTheInFlightLimitAreRefusedNotQueued() + { + // Resumed work waits in a queue until the test runs it, so the calls stay in flight the way a slow disk keeps + // them (the app resumes them on the UI thread one at a time). + var context = new QueuedContext(); + var previous = SynchronizationContext.Current; + SynchronizationContext.SetSynchronizationContext(context); + try + { + var calls = Enumerable.Range(1, 100) + .Select(id => _api.HandleAsync(JsonSerializer.Serialize( + new { id, method = "storage.set", @params = new { key = "k" + id, value = "v" } }))) + .ToList(); + context.RunUntil(Task.WhenAll(calls)); + + var codes = calls.Select(call => ErrorCode(JsonDocument.Parse(call.Result!).RootElement)).ToList(); + Assert.Contains("limit-exceeded", codes); + Assert.True(codes.Count(code => code is null) <= PluginApi.MaximumCallsInFlight); + } + finally + { + SynchronizationContext.SetSynchronizationContext(previous); + } + } + + [Fact] + public async Task StorageWritesAreRateLimited() + { + for (var write = 0; write < PluginApi.MaximumStorageWritesPerMinute; write++) + { + var reply = write % 2 == 0 + ? await Call("storage.set", new { key = "k", value = write }) + : await Call("storage.remove", new { key = "k" }); + Assert.Null(ErrorCode(reply)); + } + + Assert.Equal("limit-exceeded", ErrorCode(await Call("storage.set", new { key = "k", value = 0 }))); + + _clock.Advance(TimeSpan.FromSeconds(60)); + Assert.Null(ErrorCode(await Call("storage.set", new { key = "k", value = 1 }))); + } + + private 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 })); + Assert.NotNull(reply); + return JsonDocument.Parse(reply).RootElement; + } + + private static string? ErrorCode(JsonElement reply) => + reply.TryGetProperty("error", out var error) ? error.GetProperty("code").GetString() : null; + + private sealed class QueuedContext : SynchronizationContext + { + private readonly BlockingCollection<(SendOrPostCallback Callback, object? State)> _queue = []; + + public override void Post(SendOrPostCallback callback, object? state) => _queue.Add((callback, state)); + + public void RunUntil(Task task) + { + var deadline = DateTime.UtcNow.AddSeconds(30); + while (!task.IsCompleted) + { + Assert.True(DateTime.UtcNow < deadline, "The calls never finished."); + if (_queue.TryTake(out var item, 50)) + { + item.Callback(item.State); + } + } + } + } + + private sealed class FakeHost : IPluginHostData + { + public IReadOnlyList Accounts { get; set; } = []; + + public bool PanelShowing { get; set; } + + public List Opened { get; } = []; + + public IReadOnlyList GetAccounts() => Accounts; + + public PluginXpInfo? GetXp(Guid accountId) => null; + + public PluginStatsInfo? GetStats(Guid accountId) => null; + + public PluginTimerInfo GetTimer() => new("stopped", 0, []); + + public bool IsPanelShowing(string pluginId) => PanelShowing; + + public void OpenInBrowser(Uri uri) => Opened.Add(uri); + } +} diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs new file mode 100644 index 0000000..467d231 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginHostDataTests.cs @@ -0,0 +1,17 @@ +using Xunit; + +namespace FourFoldAccountManager.Desktop.Tests.Plugins; + +public sealed class PluginHostDataTests +{ + [Fact] + public void ABlankRankingNameNeverExposesTheProfileName() + { + // With no ranking name the profile was looked up by the saved login, so its name is the login. + Assert.Null(MainWindow.PublicInGameName(null, "MyLogin")); + Assert.Null(MainWindow.PublicInGameName("", "MyLogin")); + Assert.Null(MainWindow.PublicInGameName(" ", "MyLogin")); + Assert.Equal("HERO", MainWindow.PublicInGameName("Hero", "HERO")); + Assert.Equal("Hero", MainWindow.PublicInGameName("Hero", null)); + } +} diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs new file mode 100644 index 0000000..5cb60e0 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs @@ -0,0 +1,285 @@ +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; + +namespace FourFoldAccountManager.Desktop; + +// Community plugins: loading, the data they may read, and the events they are sent. +public partial class MainWindow : IPluginHostData +{ + private readonly PluginCardStore _pluginCards = new(); + private readonly Dictionary + _postedXpUpdates = []; + private CommunityPluginManager _communityPlugins = null!; + private PluginHub _pluginHub = null!; + private string _postedAccounts = string.Empty; + private System.Windows.Threading.DispatcherTimer? _pluginCardRefreshTimer; + + // Built-in plugins first, then community plugins: the one list the strip, the plugin list and the layout policy use. + private IReadOnlyList AllPlugins => [.. _plugins.All, .. _communityPlugins.Plugins]; + + private IReadOnlyList AllPluginDescriptors => + AllPlugins.Select(plugin => plugin.Descriptor).ToArray(); + + private void InitializeCommunityPlugins(LocalDataPaths paths) + { + _communityPlugins = new CommunityPluginManager(paths, this, PluginParkingHost, _pluginCards); + _communityPlugins.Changed += () => + { + RefreshPluginSidebar(); + RefreshTrackerRows(); + }; + _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 => + _ = ApplyPluginChangeAsync( + settings => settings.PluginDeveloperMode == on ? settings : settings with { PluginDeveloperMode = on }, + refreshEffects: true); + PluginSidebar.PanelOpenRequested += () => + _ = ApplyPluginChangeAsync( + settings => settings.PluginsSidebarExpanded ? settings : settings with { PluginsSidebarExpanded = true }, + refreshEffects: false); + PluginSidebar.OpenDevFolderRequested += () => + { + try + { + Directory.CreateDirectory(paths.DevPluginsRoot); + Process.Start(new ProcessStartInfo(paths.DevPluginsRoot) { UseShellExecute = true }); + } + catch (Exception) + { + GlobalStatusText.Text = "The dev plugins folder couldn't be opened."; + } + }; + } + + // 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); + PluginSidebar.SetCommunityState(_communityPlugins.Rejected, _communityPlugins.StartupError); + } + + // A plugin can set its cards many times a second; they are redrawn at most four times a second. + private void QueuePluginCardRefresh() + { + if (_shutdownStarted) + { + return; + } + + if (_pluginCardRefreshTimer is null) + { + _pluginCardRefreshTimer = new System.Windows.Threading.DispatcherTimer + { + Interval = TimeSpan.FromMilliseconds(250) + }; + _pluginCardRefreshTimer.Tick += (_, _) => + { + // A click that straddles a rebuild of the switches is lost, so wait for the button to come up; the + // timer keeps running and tries again 250 ms later. + if (Mouse.LeftButton == MouseButtonState.Pressed || Mouse.RightButton == MouseButtonState.Pressed) + { + return; + } + + _pluginCardRefreshTimer.Stop(); + RefreshTrackerRows(); + }; + } + + if (!_pluginCardRefreshTimer.IsEnabled) + { + _pluginCardRefreshTimer.Start(); + } + } + + // Adds every switched-on community plugin's cards of this scope: global cards once, account cards per open account. + private void AddPluginCards( + OverlayAddOnScope scope, + Guid? accountId, + string accountLabel, + bool showOverGame, + List switches, + OverlayCardBuild build) + { + foreach (var plugin in _communityPlugins.Plugins.Where( + plugin => PluginLayoutPolicy.IsEnabled(_panelSettings, plugin.Descriptor.Id))) + { + foreach (var card in plugin.Descriptor.Cards.Where(card => card.Scope == scope)) + { + var key = new OverlayCardKey( + OverlayAddOnKind.Plugin, accountId, PluginCardId.Create(plugin.Descriptor.Id, card.Id)); + var content = _pluginCards.Get(key); + var data = new PluginCardData( + card.Name, + accountLabel, + IsStale: !plugin.IsRunning, + content?.Rows.Select(row => new PluginCardRowData(row.Label, row.Value, row.Progress)).ToArray() ?? [], + content?.Summary ?? "No data yet"); + // The short label says whose card it is: two plugins can both declare "Goals", and a card named "Timer" + // must not pass for FourFold's own in the Overlays panel and the floating checklist. + AddOverlayCard( + new OverlayAddOnDefinition( + OverlayAddOnKind.Plugin, scope, $"{card.Name} ({plugin.Descriptor.ShortLabel})", 220, 120, 150, 44), + key, accountLabel, data, showOverGame, switches, build); + } + } + } + + // Tells running plugins what changed since the last refresh: the account list, and anything in an account's XP + // that xp.get would return differently. + private void NotifyPluginsOfDataChanges() + { + var accounts = string.Join('|', _accounts.Select( + account => $"{account.Id}:{account.Label}:{_openAccountIds.Contains(account.Id)}")); + if (accounts != _postedAccounts) + { + _postedAccounts = accounts; + _communityPlugins.PostEvent("accounts.changed", null); + } + + foreach (var state in _xpTracker.GetStates()) + { + var current = (state.LastUpdated, state.IsStale, state.RatePerHour, state.SessionGain); + // Equals, not ==, so a NaN rate counts as unchanged instead of posting on every refresh. + if (!_postedXpUpdates.TryGetValue(state.AccountId, out var posted) || !posted.Equals(current)) + { + _postedXpUpdates[state.AccountId] = current; + _communityPlugins.PostEvent("xp.updated", new { accountId = state.AccountId }); + } + } + } + + // A NaN or infinite number can't be written as JSON, so it goes to plugins as null. + private static double? Finite(double? value) => value is { } number && double.IsFinite(number) ? number : null; + + // The name plugins may see. With no ranking name saved, the profile is looked up by the saved login, so the + // name read from it is the login and stays private. + internal static string? PublicInGameName(string? rankingUsername, string? profileUsername) => + string.IsNullOrWhiteSpace(rankingUsername) ? null : profileUsername ?? rankingUsername; + + IReadOnlyList IPluginHostData.GetAccounts() => + _accounts.Select(account => new PluginAccountInfo( + account.Id, + account.Label, + PublicInGameName(account.RankingUsername, _xpTracker.GetLatestSnapshot(account.Id)?.Username), + _openAccountIds.Contains(account.Id))).ToArray(); + + PluginXpInfo? IPluginHostData.GetXp(Guid accountId) + { + if (_accounts.All(account => account.Id != accountId)) + { + return null; + } + + var state = _xpTracker.GetStates().FirstOrDefault(candidate => candidate.AccountId == accountId); + var snapshot = _xpTracker.GetLatestSnapshot(accountId); + var active = snapshot?.ActiveClassName is { } className && snapshot.Classes.TryGetValue(className, out var found) + ? found + : null; + return new PluginXpInfo( + state?.ActiveClass ?? snapshot?.ActiveClassName, + active?.Level, + active?.CurrentXp, + active?.NextLevelXp, + state?.XpUntilNextLevel, + Finite(state?.HoursUntilNextLevel), + Finite(state?.RatePerHour), + state?.SessionGain ?? 0, + snapshot?.Classes + .Select(entry => new PluginClassInfo( + entry.Key, entry.Value.Level, entry.Value.CurrentXp, entry.Value.NextLevelXp)) + .ToArray() ?? [], + state?.LastUpdated, + // No XP data yet reads as stale, for an open account as for a closed one. + state is null || state.IsStale || state.LastUpdated is null); + } + + PluginStatsInfo? IPluginHostData.GetStats(Guid accountId) + { + var snapshot = _xpTracker.GetLatestSnapshot(accountId); + return snapshot?.ActiveClassName is { } className && snapshot.Classes.TryGetValue(className, out var active) + ? new PluginStatsInfo(className, active.Level, active.Hp, active.Sp, active.Attack, active.Magic, + active.Skill, active.Speed, active.Luck, active.Defense, active.Resistance) + : null; + } + + PluginTimerInfo IPluginHostData.GetTimer() + { + var snapshot = _timer.Snapshot(); + return new PluginTimerInfo( + snapshot.State switch + { + SpeedrunTimerState.Running => "running", + SpeedrunTimerState.Finished => "finished", + _ => "ready" + }, + (long)snapshot.Total.TotalMilliseconds, + snapshot.Laps.Select(lap => new PluginLapInfo( + lap.Number, (long)lap.LapTime.TotalMilliseconds, (long)lap.SplitTotal.TotalMilliseconds)).ToArray()); + } + + bool IPluginHostData.IsPanelShowing(string pluginId) => PluginSidebar.IsShowing(pluginId); + + // The shell gets AbsoluteUri, never ToString(), which un-escapes %22 into a quote and could add an argument. + void IPluginHostData.OpenInBrowser(Uri uri) + { + if (uri.Scheme != Uri.UriSchemeHttps) + { + return; + } + + try + { + Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true }); + } + catch (Exception) + { + GlobalStatusText.Text = "The link couldn't be opened."; + } + } +} diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml b/src/FourFoldAccountManager.Desktop/MainWindow.xaml index e3769a5..56016cc 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml @@ -193,8 +193,8 @@ ToolTip="Starts missing or failed assigned sessions; healthy open sessions stay open." /> @@ -226,6 +226,9 @@ + +