Cache plugin package hashes, add a content security policy, and limit browser windows
Plugin runtime cost: - Remove the timed plugin scan. Windows scan at start, on focus, on Refresh, and on plugins-changed. - Keep one package check for each plugin folder. Read and hash the files again only when the entry names, sizes, or modification times change. Enable and load always read all files. An asset read checks the SHA-256 hash of its file. - A changed package still stops and needs a new enable decision. Add tests for the cache, for changes that keep the metadata, and for the enable decision. - Replace the 50 ms wait loops of update and removal with a condition variable. The limit stays at 10 seconds. Command names, arguments, and results do not change. Content security policy: - Set app.security.csp in tauri.conf.json. Keep Tauri from adding nonces to style-src. - Add CSP mode to the smoke tests (pnpm smoke --csp). The dev server sends the same policy with each HTML page, and the harness fails a test on a policy violation. - Decode data URLs without fetch in the background frame test. Capabilities: - Give browser windows their own capability. They load no installed plugin. Add a unit test and a browser window smoke test for the command set. Document the scans, the hash cache, the policy, and the window capabilities.
This commit is contained in:
+18
-1
@@ -36,7 +36,7 @@ Do not start a separate `pnpm dev` for this workflow.
|
|||||||
| Rust code in `src-tauri/src/` | Cargo rebuilds the changed code, and Tauri restarts the app. |
|
| Rust code in `src-tauri/src/` | Cargo rebuilds the changed code, and Tauri restarts the app. |
|
||||||
| Rust dependencies or build settings | Cargo compiles the affected crates. This can take several minutes. |
|
| Rust dependencies or build settings | Cargo compiles the affected crates. This can take several minutes. |
|
||||||
| JavaScript dependencies, after a pull | Stop the session, run `pnpm install --frozen-lockfile`, and start it again. |
|
| JavaScript dependencies, after a pull | Stop the session, run `pnpm install --frozen-lockfile`, and start it again. |
|
||||||
| Tauri configuration, capabilities, or Vite configuration | Restart `pnpm tauri dev`. |
|
| Tauri configuration, capabilities, or Vite configuration | Restart `pnpm tauri dev`. The content security policy applies only to a built app, not to `pnpm tauri dev`. See [Content security policy](plugin-host.md#content-security-policy). |
|
||||||
| A plugin in a sibling repository | Build and package that plugin, then install the new ZIP through Settings. See [Build examples](plugin-development.md#build-examples). |
|
| A plugin in a sibling repository | Build and package that plugin, then install the new ZIP through Settings. See [Build examples](plugin-development.md#build-examples). |
|
||||||
| Installer or release behavior | Use the [build guide](builds.md). |
|
| Installer or release behavior | Use the [build guide](builds.md). |
|
||||||
|
|
||||||
@@ -74,6 +74,7 @@ Windows is the primary platform. macOS and Linux builds are experimental.
|
|||||||
|
|
||||||
The interface calls Rust commands through Tauri `invoke`. Most calls go through the wrappers in `src/lib/workspace/api.ts`.
|
The interface calls Rust commands through Tauri `invoke`. Most calls go through the wrappers in `src/lib/workspace/api.ts`.
|
||||||
A new command needs an entry in `generate_handler!` in `lib.rs`, in the command list in `src-tauri/build.rs`, and in the capability files in `src-tauri/capabilities/`.
|
A new command needs an entry in `generate_handler!` in `lib.rs`, in the command list in `src-tauri/build.rs`, and in the capability files in `src-tauri/capabilities/`.
|
||||||
|
`default.json` must list every command. `settings.json` and `browser.json` list subsets. See [Window capabilities](plugin-host.md#window-capabilities).
|
||||||
|
|
||||||
### Interface: `src/lib/`
|
### Interface: `src/lib/`
|
||||||
|
|
||||||
@@ -193,6 +194,7 @@ They do not replace tests in the native app. Real folder access, file writes, an
|
|||||||
| `pnpm smoke` | All smoke tests, four at a time |
|
| `pnpm smoke` | All smoke tests, four at a time |
|
||||||
| `pnpm smoke tabs tables/drag` | The tests whose path contains one of the filters |
|
| `pnpm smoke tabs tables/drag` | The tests whose path contains one of the filters |
|
||||||
| `pnpm smoke --list` | Nothing. It lists each test, its requirements, and why a test would skip. |
|
| `pnpm smoke --list` | Nothing. It lists each test, its requirements, and why a test would skip. |
|
||||||
|
| `pnpm smoke --csp` | All smoke tests under the content security policy of the app. A test fails on any policy violation. |
|
||||||
|
|
||||||
The runner starts the Vite server when nothing serves `SMOKE_URL`, and stops it at the end.
|
The runner starts the Vite server when nothing serves `SMOKE_URL`, and stops it at the end.
|
||||||
Use `--no-serve` to require a running server, `--jobs <n>` to change the number of parallel tests, and `--timeout <seconds>` to change the limit for each test (default 180).
|
Use `--no-serve` to require a running server, `--jobs <n>` to change the number of parallel tests, and `--timeout <seconds>` to change the limit for each test (default 180).
|
||||||
@@ -216,6 +218,7 @@ A test states what it needs near its top. The runner skips the test, with the re
|
|||||||
| `SMOKE_URL` | The frontend address. The default is `http://127.0.0.1:1420`. When the runner starts Vite, it uses the port of this address, so two checkouts can run tests at the same time. |
|
| `SMOKE_URL` | The frontend address. The default is `http://127.0.0.1:1420`. When the runner starts Vite, it uses the port of this address, so two checkouts can run tests at the same time. |
|
||||||
| `RUNESTONE_PLUGIN_REPOS` | The folder of the sibling plugin checkouts. The default is the parent folder of this repository. |
|
| `RUNESTONE_PLUGIN_REPOS` | The folder of the sibling plugin checkouts. The default is the parent folder of this repository. |
|
||||||
| `RUNESTONE_TERMINAL_DIST` | The compiled Terminal plugin. The default is `RuneStone_Terminal/dist` in that folder. |
|
| `RUNESTONE_TERMINAL_DIST` | The compiled Terminal plugin. The default is `RuneStone_Terminal/dist` in that folder. |
|
||||||
|
| `RUNESTONE_CSP` | `1` sends and checks the content security policy. `--csp` sets it. |
|
||||||
| `CHROME_PATH` | A Chromium browser for Playwright |
|
| `CHROME_PATH` | A Chromium browser for Playwright |
|
||||||
| `PLAYWRIGHT_MODULE` | A different Playwright package |
|
| `PLAYWRIGHT_MODULE` | A different Playwright package |
|
||||||
|
|
||||||
@@ -227,6 +230,20 @@ To read or change a section later, use `window.__TEST__.settings(section)` and `
|
|||||||
A failed test saves `failure.png` in its output folder and prints the page console errors and warnings.
|
A failed test saves `failure.png` in its output folder and prints the page console errors and warnings.
|
||||||
You can also run one test file directly while `pnpm dev` runs, for example `node tests/smoke/tabs/order.smoke.mjs`.
|
You can also run one test file directly while `pnpm dev` runs, for example `node tests/smoke/tabs/order.smoke.mjs`.
|
||||||
|
|
||||||
|
### CSP mode
|
||||||
|
|
||||||
|
`--csp` sets `RUNESTONE_CSP=1`. With this variable, `vite.config.js` sends the policy from `src-tauri/tauri.conf.json` as a `Content-Security-Policy` header with each HTML page, as the installed app does.
|
||||||
|
It adds only what the dev server needs:
|
||||||
|
|
||||||
|
| Directive | Addition | Reason |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `script-src` | The SHA-256 hash of each inline script in the page | Tauri adds the same hashes in the installed app. The SvelteKit start script is inline. |
|
||||||
|
| `connect-src` | `ws://<address of the page>` | The Vite hot-reload WebSocket |
|
||||||
|
|
||||||
|
The harness records the `securitypolicyviolation` events of each page and frame, and fails the test when there is one. Violations inside workers do not reach the harness.
|
||||||
|
The runner refuses to use a server at `SMOKE_URL` that does not send the policy. Stop that server, or set `SMOKE_URL` to a free port.
|
||||||
|
The smoke tests do not replace a check in the installed app. The page there is the Tauri web view, and some plugins are not in the smoke tests. See [Content security policy](plugin-host.md#content-security-policy).
|
||||||
|
|
||||||
The tests in `tests/native/` attach to a running desktop app through the WebView2 remote-debugging port, and `pnpm smoke` does not run them.
|
The tests in `tests/native/` attach to a running desktop app through the WebView2 remote-debugging port, and `pnpm smoke` does not run them.
|
||||||
Set `NATIVE_CDP_URL` to the debugging address, for example `http://127.0.0.1:9224`.
|
Set `NATIVE_CDP_URL` to the debugging address, for example `http://127.0.0.1:9224`.
|
||||||
Before you start the app, set `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=<port>`. Each file states its port and variables at the top.
|
Before you start the app, set `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=<port>`. Each file states its port and variables at the top.
|
||||||
|
|||||||
+75
-3
@@ -6,6 +6,8 @@ This reference describes how RuneStone stores, installs, downloads, and removes
|
|||||||
|
|
||||||
- [Storage and recovery](#storage-and-recovery)
|
- [Storage and recovery](#storage-and-recovery)
|
||||||
- [Gitea downloads](#gitea-downloads)
|
- [Gitea downloads](#gitea-downloads)
|
||||||
|
- [Content security policy](#content-security-policy)
|
||||||
|
- [Window capabilities](#window-capabilities)
|
||||||
- [Modules and checks](#modules-and-checks)
|
- [Modules and checks](#modules-and-checks)
|
||||||
|
|
||||||
## Storage and recovery
|
## Storage and recovery
|
||||||
@@ -37,17 +39,37 @@ Each window asks for a new snapshot at these times:
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Window start | `startExternalPlugins` in `src/lib/plugins/external.ts` |
|
| Window start | `startExternalPlugins` in `src/lib/plugins/external.ts` |
|
||||||
| Window focus | The same function |
|
| Window focus | The same function |
|
||||||
| Every 5 seconds | The same function. It finds changes from a file manager. |
|
|
||||||
| **Refresh** in Settings → Plug-ins | `PluginManager.svelte` |
|
| **Refresh** in Settings → Plug-ins | `PluginManager.svelte` |
|
||||||
| `plugins-changed` event | Any change from another window |
|
| `plugins-changed` event | Any change from another window |
|
||||||
|
|
||||||
A scan reads files and hashes only. It does not run code, install dependencies, or run scripts.
|
There is no timed scan. A change from a file manager appears at the next focus or **Refresh**. RuneStone does not support packages that users copy into the folder.
|
||||||
|
|
||||||
|
A scan reads file metadata, and reads and hashes files only when necessary. It does not run code, install dependencies, or run scripts.
|
||||||
|
|
||||||
- A package with a changed hash gets an error and becomes disabled. The user must review it and enable it again.
|
- A package with a changed hash gets an error and becomes disabled. The user must review it and enable it again.
|
||||||
- When a package folder is missing, the service removes its catalog entry. It never restores a missing package.
|
- When a package folder is missing, the service removes its catalog entry. It never restores a missing package.
|
||||||
- A valid package that someone copies directly into `plugins/` appears as disabled, with an unknown install time.
|
- A valid package that someone copies directly into `plugins/` appears as disabled, with an unknown install time.
|
||||||
- The service never scans `plugin-staging/`.
|
- The service never scans `plugin-staging/`.
|
||||||
|
|
||||||
|
### Package hashes
|
||||||
|
|
||||||
|
The package hash is a SHA-256 hash of all file names and contents. To avoid a full read of each package at each scan, the service keeps a cache in memory:
|
||||||
|
|
||||||
|
| Step | Reads |
|
||||||
|
| --- | --- |
|
||||||
|
| Scan (`plugins_snapshot`), `plugins_data`, and the row checks of other commands | The metadata of the package folder: entry names, file sizes, and modification times. The service reads and hashes the files again only when this metadata changed. |
|
||||||
|
| Enable (`plugins_set_enabled`) and load (`plugins_load`) | All files. The hash must agree with the hash that the user saw (enable) or the installed hash (load). The cache cannot approve code. |
|
||||||
|
| Asset (`plugins_asset`) | The metadata, then the one file. The file must have the SHA-256 hash from the last full read. |
|
||||||
|
| Install, update, and removal | All files, as before. These steps also clear the cache entry of the package. |
|
||||||
|
|
||||||
|
The cache keeps the metadata from before each read. A file that changes during a read thus causes a new read at the next check.
|
||||||
|
An edit that keeps the file size and the modification time stays hidden from a scan. The next load or asset read finds it, and the plugin then becomes disabled at the next scan.
|
||||||
|
|
||||||
|
### Waits for other windows
|
||||||
|
|
||||||
|
An update and a removal disable the plugin, then wait until no window holds a lease, at most 10 seconds.
|
||||||
|
The wait uses a condition variable that `plugins_release` and window close signal. It does not keep the plugin lock while it waits.
|
||||||
|
|
||||||
### Install and update
|
### Install and update
|
||||||
|
|
||||||
1. The ZIP picker accepts at most 100 `.zip` files. Folders and loose manifests are not installation inputs.
|
1. The ZIP picker accepts at most 100 `.zip` files. Folders and loose manifests are not installation inputs.
|
||||||
@@ -124,6 +146,55 @@ The review shows the repository, the tag, and the attachment link without its qu
|
|||||||
A change to the remote release after review does not change the pending installation.
|
A change to the remote release after review does not change the pending installation.
|
||||||
The same ID, enable, update, and removal rules apply to local and remote packages.
|
The same ID, enable, update, and removal rules apply to local and remote packages.
|
||||||
|
|
||||||
|
## Content security policy
|
||||||
|
|
||||||
|
`app.security.csp` in `src-tauri/tauri.conf.json` holds the policy. It limits what a page can load. It does not isolate plugins: a plugin module runs in the app window with the same access as the app.
|
||||||
|
The policy stops a script that comes in through rendered content, for example a `<script>` element or an event attribute in a Markdown document.
|
||||||
|
|
||||||
|
| Directive | Sources | Reason |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `default-src` | `'self'` | All other types come only from the app. |
|
||||||
|
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: the PDF Viewer decodes JPEG 2000 and JBIG2 images and color profiles with WebAssembly in its worker. It does not permit `eval`. |
|
||||||
|
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of Monaco, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF Viewer, Background Slideshow). |
|
||||||
|
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
|
||||||
|
| `font-src` | `'self' data:` | The Monaco icon font, and fonts that the PDF Viewer embeds. |
|
||||||
|
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the Background Slideshow worker reads its image from a Blob URL. |
|
||||||
|
| `worker-src` | `'self' blob:` | `'self'`: Monaco workers. `blob:`: the PDF Viewer and Background Slideshow workers. |
|
||||||
|
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
|
||||||
|
| `base-uri` | `'self'` | |
|
||||||
|
| `form-action` | `'none'` | No form sends data to an address. |
|
||||||
|
| `frame-ancestors` | `'none'` | |
|
||||||
|
|
||||||
|
No source permits `'unsafe-eval'`. The app, Monaco, Mermaid, and the current plugins do not use `eval` or `new Function`.
|
||||||
|
`style-src` needs `'unsafe-inline'`, because style attributes and generated `<style>` elements have no nonce.
|
||||||
|
|
||||||
|
Tauri sends the policy as a header with each HTML page of the installed app. It adds the SHA-256 hash of the inline start script of SvelteKit to `script-src`.
|
||||||
|
`dangerousDisableAssetCspModification: ["style-src"]` stops Tauri from adding nonces to `style-src`, because a nonce disables `'unsafe-inline'`. Tauri still adds the script hashes.
|
||||||
|
`pnpm tauri dev` loads the page from the Vite server. Tauri does not apply the policy there. Use the [CSP mode](development.md#csp-mode) of the smoke tests, or an installed build.
|
||||||
|
|
||||||
|
Workers that the app loads from its own files get no policy. Workers from Blob URLs get the policy of the page.
|
||||||
|
|
||||||
|
## Window capabilities
|
||||||
|
|
||||||
|
`src-tauri/capabilities/` gives commands to window labels. A plugin can call every command that its window allows.
|
||||||
|
|
||||||
|
| Capability | Windows | Plugins | Commands |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app commands |
|
||||||
|
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, backgrounds, completion, browser |
|
||||||
|
| `browser.json` | `browser-*` | Only the built-in browser (`src/routes/+page.svelte`) | Browser, `plugins_snapshot`, settings, spelling, and window controls |
|
||||||
|
|
||||||
|
A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this.
|
||||||
|
|
||||||
|
The other windows load every enabled plugin. A smaller command set for them would limit only the app code, not the plugins. That split belongs to the plugin isolation work. Findings for that work:
|
||||||
|
|
||||||
|
- Terminal windows use the plugin host commands, `pty_*` through the Terminal plugin, and `core:window:allow-destroy`. Other plugins in the same window expect the full host API.
|
||||||
|
- Settings windows use no `workspace_*`, `git_*`, or `pty_*` commands, but plugin settings views run there.
|
||||||
|
- Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace.
|
||||||
|
- `pty_write`, `pty_resize`, and `pty_close` do not check the window that opened the terminal.
|
||||||
|
- `backgrounds_*`, and `browser_request` without a browser session token, need a plugin lease of the calling window.
|
||||||
|
- A new command for plugins goes in `default.json` and, if settings views need it, in `settings.json`. Add it to `browser.json` only when the built-in browser needs it.
|
||||||
|
|
||||||
## Modules and checks
|
## Modules and checks
|
||||||
|
|
||||||
| Module | Owns |
|
| Module | Owns |
|
||||||
@@ -154,7 +225,7 @@ To make it without a release ZIP, run `node scripts/build.mjs --no-package` in t
|
|||||||
Unit tests:
|
Unit tests:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
node --experimental-strip-types --test tests/unit/plugins/plugins.spec.ts tests/unit/plugins/externalPlugins.spec.ts tests/unit/plugins/pluginPackaging.spec.ts tests/unit/plugins/pluginHostExtensions.spec.ts tests/unit/plugins/pluginDocuments.spec.ts tests/unit/plugins/pluginAccess.spec.ts tests/unit/plugins/completion.spec.ts tests/unit/theme/backgrounds.spec.ts
|
node --experimental-strip-types --test tests/unit/plugins/plugins.spec.ts tests/unit/plugins/externalPlugins.spec.ts tests/unit/plugins/pluginPackaging.spec.ts tests/unit/plugins/pluginHostExtensions.spec.ts tests/unit/plugins/pluginDocuments.spec.ts tests/unit/plugins/pluginAccess.spec.ts tests/unit/plugins/completion.spec.ts tests/unit/plugins/windowCapabilities.spec.ts tests/unit/theme/backgrounds.spec.ts
|
||||||
```
|
```
|
||||||
|
|
||||||
Native tests use real temporary files and archives:
|
Native tests use real temporary files and archives:
|
||||||
@@ -173,6 +244,7 @@ node tests/smoke/plugins/choiceMenus.smoke.mjs
|
|||||||
node tests/smoke/find/pluginViews.smoke.mjs
|
node tests/smoke/find/pluginViews.smoke.mjs
|
||||||
node tests/smoke/tabs/lastTabAndSiteIcons.smoke.mjs
|
node tests/smoke/tabs/lastTabAndSiteIcons.smoke.mjs
|
||||||
node tests/smoke/settings/general.smoke.mjs
|
node tests/smoke/settings/general.smoke.mjs
|
||||||
|
node tests/smoke/browser/window.smoke.mjs
|
||||||
```
|
```
|
||||||
|
|
||||||
`pluginInstall.smoke.mjs` covers the link form, download errors, token clearing, cancel, focus, and disabled installation.
|
`pluginInstall.smoke.mjs` covers the link form, download errors, token clearing, cancel, focus, and disabled installation.
|
||||||
|
|||||||
+21
-3
@@ -1,6 +1,6 @@
|
|||||||
// Run the browser smoke tests in tests/smoke/. See docs/development.md#browser-smoke-tests.
|
// Run the browser smoke tests in tests/smoke/. See docs/development.md#browser-smoke-tests.
|
||||||
//
|
//
|
||||||
// pnpm smoke [filter...] [--list] [--jobs N] [--timeout seconds] [--retries N] [--no-serve]
|
// pnpm smoke [filter...] [--list] [--jobs N] [--timeout seconds] [--retries N] [--no-serve] [--csp]
|
||||||
//
|
//
|
||||||
// A filter selects the tests whose path contains it, for example `tabs` or `tables/drag`.
|
// A filter selects the tests whose path contains it, for example `tabs` or `tables/drag`.
|
||||||
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
|
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
// A test that fails because of a known app defect states it near the top:
|
// A test that fails because of a known app defect states it near the top:
|
||||||
// // @known-issue <the defect>
|
// // @known-issue <the defect>
|
||||||
// It still runs. A failure counts as "known". A pass counts as a failure, so remove the stale line.
|
// It still runs. A failure counts as "known". A pass counts as a failure, so remove the stale line.
|
||||||
|
// --csp runs the tests under the app's content security policy (RUNESTONE_CSP=1). A test fails on any violation.
|
||||||
import { spawn } from "node:child_process";
|
import { spawn } from "node:child_process";
|
||||||
import { createWriteStream, existsSync } from "node:fs";
|
import { createWriteStream, existsSync } from "node:fs";
|
||||||
import { mkdir, readdir, readFile } from "node:fs/promises";
|
import { mkdir, readdir, readFile } from "node:fs/promises";
|
||||||
@@ -39,9 +40,11 @@ const serve = !flag("--no-serve");
|
|||||||
const jobs = Math.max(1, Number(option("--jobs", "4")));
|
const jobs = Math.max(1, Number(option("--jobs", "4")));
|
||||||
const timeoutMs = Math.max(10, Number(option("--timeout", "180"))) * 1000;
|
const timeoutMs = Math.max(10, Number(option("--timeout", "180"))) * 1000;
|
||||||
const retries = Math.max(0, Number(option("--retries", "1")));
|
const retries = Math.max(0, Number(option("--retries", "1")));
|
||||||
|
const csp = flag("--csp");
|
||||||
const filters = args;
|
const filters = args;
|
||||||
|
|
||||||
const env = { ...process.env, SMOKE_URL: process.env.SMOKE_URL || "http://127.0.0.1:1420" };
|
const env = { ...process.env, SMOKE_URL: process.env.SMOKE_URL || "http://127.0.0.1:1420" };
|
||||||
|
if (csp) env.RUNESTONE_CSP = "1";
|
||||||
const pluginRepos = env.RUNESTONE_PLUGIN_REPOS || path.join(root, "..");
|
const pluginRepos = env.RUNESTONE_PLUGIN_REPOS || path.join(root, "..");
|
||||||
|
|
||||||
async function findTests(dir) {
|
async function findTests(dir) {
|
||||||
@@ -109,11 +112,21 @@ async function reachable(url) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** True when the server sends the content security policy with the app page (see vite.config.js). */
|
||||||
|
async function sendsPolicy(url) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, { headers: { accept: "text/html" }, signal: AbortSignal.timeout(10000) });
|
||||||
|
return response.headers.has("content-security-policy");
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function startServer() {
|
async function startServer() {
|
||||||
const vite = path.join(root, "node_modules", "vite", "bin", "vite.js");
|
const vite = path.join(root, "node_modules", "vite", "bin", "vite.js");
|
||||||
// Serve on the port in SMOKE_URL, so that two checkouts can run their tests at the same time.
|
// Serve on the port in SMOKE_URL, so that two checkouts can run their tests at the same time.
|
||||||
const port = new URL(env.SMOKE_URL).port || "1420";
|
const port = new URL(env.SMOKE_URL).port || "1420";
|
||||||
const server = spawn(process.execPath, [vite, "dev", "--port", port, "--strictPort"], { cwd: root, stdio: "ignore", windowsHide: true });
|
const server = spawn(process.execPath, [vite, "dev", "--port", port, "--strictPort"], { cwd: root, env, stdio: "ignore", windowsHide: true });
|
||||||
for (let waited = 0; waited < 60000; waited += 500) {
|
for (let waited = 0; waited < 60000; waited += 500) {
|
||||||
if (await reachable(env.SMOKE_URL)) return server;
|
if (await reachable(env.SMOKE_URL)) return server;
|
||||||
await new Promise(resolve => setTimeout(resolve, 500));
|
await new Promise(resolve => setTimeout(resolve, 500));
|
||||||
@@ -175,9 +188,14 @@ if (!(await reachable(env.SMOKE_URL))) {
|
|||||||
console.error(`Nothing serves ${env.SMOKE_URL}. Start pnpm dev, or run without --no-serve.`);
|
console.error(`Nothing serves ${env.SMOKE_URL}. Start pnpm dev, or run without --no-serve.`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
console.log(`Starting the dev server at ${env.SMOKE_URL}...`);
|
console.log(`Starting the dev server at ${env.SMOKE_URL}${csp ? " in CSP mode" : ""}...`);
|
||||||
server = await startServer();
|
server = await startServer();
|
||||||
}
|
}
|
||||||
|
if (csp && !(await sendsPolicy(env.SMOKE_URL))) {
|
||||||
|
server?.kill();
|
||||||
|
console.error(`The server at ${env.SMOKE_URL} does not send a content security policy. Stop it, or set SMOKE_URL to a free port, so that --csp can start a server with RUNESTONE_CSP=1.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
const results = [];
|
const results = [];
|
||||||
const queue = plan.filter(item => !item.reasons.length);
|
const queue = plan.filter(item => !item.reasons.length);
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
|
"identifier": "browser",
|
||||||
|
"description": "Browser windows. They run only the built-in browser and never load installed plugins.",
|
||||||
|
"windows": [
|
||||||
|
"browser-*"
|
||||||
|
],
|
||||||
|
"permissions": [
|
||||||
|
"allow-browser-request",
|
||||||
|
"allow-browser-connect",
|
||||||
|
"allow-browser-stop",
|
||||||
|
"allow-plugins-snapshot",
|
||||||
|
"allow-settings-read",
|
||||||
|
"allow-settings-write",
|
||||||
|
"allow-settings-migrate",
|
||||||
|
"allow-spelling-menu-install",
|
||||||
|
"allow-spelling-menu-uninstall",
|
||||||
|
"allow-spelling-menu-select",
|
||||||
|
"allow-spelling-suggestions",
|
||||||
|
"core:default",
|
||||||
|
"core:window:allow-destroy",
|
||||||
|
"core:window:allow-close",
|
||||||
|
"core:window:allow-minimize",
|
||||||
|
"core:window:allow-toggle-maximize",
|
||||||
|
"core:window:allow-start-dragging"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -5,8 +5,7 @@
|
|||||||
"windows": [
|
"windows": [
|
||||||
"main",
|
"main",
|
||||||
"workspace-*",
|
"workspace-*",
|
||||||
"terminal-*",
|
"terminal-*"
|
||||||
"browser-*"
|
|
||||||
],
|
],
|
||||||
"permissions": [
|
"permissions": [
|
||||||
"allow-spelling-menu-install",
|
"allow-spelling-menu-install",
|
||||||
|
|||||||
+301
-109
@@ -5,7 +5,7 @@ use std::{
|
|||||||
fs,
|
fs,
|
||||||
io::Read,
|
io::Read,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
sync::Mutex,
|
sync::{Arc, Condvar, Mutex},
|
||||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||||
};
|
};
|
||||||
use tauri::{AppHandle, Emitter, Manager};
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
@@ -19,6 +19,8 @@ use crate::fsutil;
|
|||||||
const MAX_FILES: usize = 5000;
|
const MAX_FILES: usize = 5000;
|
||||||
const MAX_FILE: u64 = 25 * 1024 * 1024;
|
const MAX_FILE: u64 = 25 * 1024 * 1024;
|
||||||
const MAX_TOTAL: usize = 100 * 1024 * 1024;
|
const MAX_TOTAL: usize = 100 * 1024 * 1024;
|
||||||
|
/// The longest time that an update or a removal waits for other windows to stop a plugin.
|
||||||
|
const LEASE_WAIT: Duration = Duration::from_secs(10);
|
||||||
fn uid() -> String {
|
fn uid() -> String {
|
||||||
Uuid::new_v4().to_string()
|
Uuid::new_v4().to_string()
|
||||||
}
|
}
|
||||||
@@ -115,9 +117,29 @@ struct Package {
|
|||||||
files: BTreeMap<String, Vec<u8>>,
|
files: BTreeMap<String, Vec<u8>>,
|
||||||
hash: String,
|
hash: String,
|
||||||
}
|
}
|
||||||
|
/// The names, sizes, and modification times of the entries in a package folder. It contains no file data.
|
||||||
|
#[derive(PartialEq, Eq)]
|
||||||
|
struct Stamp(Vec<(String, u64, Option<SystemTime>)>);
|
||||||
|
/// The result of a full package read: the manifest, the package hash, and the SHA-256 hash of each file.
|
||||||
|
struct Checked {
|
||||||
|
manifest: Manifest,
|
||||||
|
hash: String,
|
||||||
|
digests: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
impl From<&Package> for Checked {
|
||||||
|
fn from(package: &Package) -> Self {
|
||||||
|
Self {
|
||||||
|
manifest: package.manifest.clone(),
|
||||||
|
hash: package.hash.clone(),
|
||||||
|
digests: package.files.iter().map(|(name, bytes)| (name.clone(), digest(bytes))).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
struct Service {
|
struct Service {
|
||||||
root: PathBuf,
|
root: PathBuf,
|
||||||
catalog: Catalog,
|
catalog: Catalog,
|
||||||
|
/// Package checks by folder. An entry is valid while the folder has the same stamp.
|
||||||
|
checked: BTreeMap<PathBuf, (Stamp, Arc<Checked>)>,
|
||||||
candidates: BTreeMap<String, Candidate>,
|
candidates: BTreeMap<String, Candidate>,
|
||||||
plans: BTreeMap<String, Plan>,
|
plans: BTreeMap<String, Plan>,
|
||||||
leases: BTreeMap<String, BTreeSet<String>>,
|
leases: BTreeMap<String, BTreeSet<String>>,
|
||||||
@@ -127,6 +149,8 @@ struct Service {
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct PluginState {
|
pub struct PluginState {
|
||||||
inner: Mutex<Option<Service>>,
|
inner: Mutex<Option<Service>>,
|
||||||
|
/// Signals that a window released one or more plugin leases.
|
||||||
|
released: Condvar,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn normal_component(name: &str) -> bool {
|
fn normal_component(name: &str) -> bool {
|
||||||
@@ -233,6 +257,38 @@ fn directory_files(path: &Path) -> Result<BTreeMap<String, Vec<u8>>> {
|
|||||||
fn tree_hash(path: &Path) -> Result<String> {
|
fn tree_hash(path: &Path) -> Result<String> {
|
||||||
Ok(fingerprint(&directory_files(path)?))
|
Ok(fingerprint(&directory_files(path)?))
|
||||||
}
|
}
|
||||||
|
fn digest(bytes: &[u8]) -> String {
|
||||||
|
format!("{:x}", Sha256::digest(bytes))
|
||||||
|
}
|
||||||
|
/// Read the metadata of every entry in a package folder. Links and junctions are errors, as in `walk`.
|
||||||
|
fn stamp(root: &Path) -> Result<Stamp> {
|
||||||
|
fn visit(
|
||||||
|
root: &Path,
|
||||||
|
directory: &Path,
|
||||||
|
entries: &mut Vec<(String, u64, Option<SystemTime>)>,
|
||||||
|
) -> Result<()> {
|
||||||
|
plain(directory)?;
|
||||||
|
for entry in fs::read_dir(directory)? {
|
||||||
|
let path = entry?.path();
|
||||||
|
if entries.len() >= MAX_FILES {
|
||||||
|
return Err("The package contains too many entries.".into());
|
||||||
|
}
|
||||||
|
let name = path.strip_prefix(root)?.to_string_lossy().replace('\\', "/");
|
||||||
|
let meta = plain(&path)?;
|
||||||
|
if meta.is_dir() {
|
||||||
|
entries.push((name + "/", 0, None));
|
||||||
|
visit(root, &path, entries)?;
|
||||||
|
} else {
|
||||||
|
entries.push((name, meta.len(), meta.modified().ok()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
visit(root, root, &mut entries)?;
|
||||||
|
entries.sort();
|
||||||
|
Ok(Stamp(entries))
|
||||||
|
}
|
||||||
fn valid_version(version: &str) -> bool {
|
fn valid_version(version: &str) -> bool {
|
||||||
let parts: Vec<_> = version.split('.').collect();
|
let parts: Vec<_> = version.split('.').collect();
|
||||||
if parts.len() != 3 || parts[..2].iter().any(|part| {
|
if parts.len() != 3 || parts[..2].iter().any(|part| {
|
||||||
@@ -408,6 +464,7 @@ impl Service {
|
|||||||
let mut service = Self {
|
let mut service = Self {
|
||||||
root,
|
root,
|
||||||
catalog,
|
catalog,
|
||||||
|
checked: BTreeMap::new(),
|
||||||
candidates: BTreeMap::new(),
|
candidates: BTreeMap::new(),
|
||||||
plans: BTreeMap::new(),
|
plans: BTreeMap::new(),
|
||||||
leases: BTreeMap::new(),
|
leases: BTreeMap::new(),
|
||||||
@@ -489,18 +546,58 @@ impl Service {
|
|||||||
let data = serde_json::to_vec_pretty(&self.catalog)?;
|
let data = serde_json::to_vec_pretty(&self.catalog)?;
|
||||||
Ok(fsutil::replace_file(&path, &temp, &data)?)
|
Ok(fsutil::replace_file(&path, &temp, &data)?)
|
||||||
}
|
}
|
||||||
fn row(&self, id: &str) -> Result<PluginRow> {
|
/// Return the package check from the cache while the folder metadata stays the same.
|
||||||
let record = self
|
/// Otherwise read and hash the package again. Enable and load use `verify`, which always reads the files.
|
||||||
|
fn check(&mut self, path: &Path) -> Result<Arc<Checked>> {
|
||||||
|
let Ok(stamp) = stamp(path) else {
|
||||||
|
self.checked.remove(path);
|
||||||
|
return package(path).map(|current| Arc::new(Checked::from(¤t)));
|
||||||
|
};
|
||||||
|
if let Some((cached, checked)) = self.checked.get(path) {
|
||||||
|
if *cached == stamp {
|
||||||
|
return Ok(checked.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.remember(path, stamp, package(path)).map(|(_, checked)| checked)
|
||||||
|
}
|
||||||
|
/// Read and hash the package files, and replace the cached check.
|
||||||
|
fn verify(&mut self, path: &Path) -> Result<Package> {
|
||||||
|
let Ok(stamp) = stamp(path) else {
|
||||||
|
self.checked.remove(path);
|
||||||
|
return package(path);
|
||||||
|
};
|
||||||
|
self.remember(path, stamp, package(path)).map(|(current, _)| current)
|
||||||
|
}
|
||||||
|
/// Keep a successful check with the stamp from before the read. A file that changes during the read changes the next stamp.
|
||||||
|
fn remember(&mut self, path: &Path, stamp: Stamp, current: Result<Package>) -> Result<(Package, Arc<Checked>)> {
|
||||||
|
match current {
|
||||||
|
Ok(current) => {
|
||||||
|
let checked = Arc::new(Checked::from(¤t));
|
||||||
|
self.checked.insert(path.to_owned(), (stamp, checked.clone()));
|
||||||
|
Ok((current, checked))
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
self.checked.remove(path);
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn row(&mut self, id: &str) -> Result<PluginRow> {
|
||||||
|
let removal = self
|
||||||
.catalog
|
.catalog
|
||||||
.plugins
|
.plugins
|
||||||
.get(id)
|
.get(id)
|
||||||
.ok_or("The plugin is not installed.")?;
|
.ok_or("The plugin is not installed.")?
|
||||||
let path = self.directory("plugins")?.join(id);
|
.removal
|
||||||
let checked = if record.removal.is_some() {
|
.is_some();
|
||||||
|
let parent = self.directory("plugins")?;
|
||||||
|
let path = parent.join(id);
|
||||||
|
let checked = if removal {
|
||||||
Err("Removal incomplete. Retry file cleanup.".into())
|
Err("Removal incomplete. Retry file cleanup.".into())
|
||||||
} else {
|
} else {
|
||||||
safe_child(&self.directory("plugins")?, &path).and_then(|_| package(&path))
|
safe_child(&parent, &path).and_then(|_| self.check(&path))
|
||||||
};
|
};
|
||||||
|
let record = &self.catalog.plugins[id];
|
||||||
let mut manifest = record.manifest.clone();
|
let mut manifest = record.manifest.clone();
|
||||||
if let Ok(current) = &checked {
|
if let Ok(current) = &checked {
|
||||||
if current.manifest.id == id {
|
if current.manifest.id == id {
|
||||||
@@ -509,14 +606,14 @@ impl Service {
|
|||||||
}
|
}
|
||||||
let (hash, error) = match checked {
|
let (hash, error) = match checked {
|
||||||
Ok(current) if current.manifest.id != id => (
|
Ok(current) if current.manifest.id != id => (
|
||||||
current.hash,
|
current.hash.clone(),
|
||||||
Some("The installed plugin ID changed.".into()),
|
Some("The installed plugin ID changed.".into()),
|
||||||
),
|
),
|
||||||
Ok(current) if current.hash != record.hash => (
|
Ok(current) if current.hash != record.hash => (
|
||||||
current.hash,
|
current.hash.clone(),
|
||||||
Some("Plugin files changed. Review them before enabling this plugin.".into()),
|
Some("Plugin files changed. Review them before enabling this plugin.".into()),
|
||||||
),
|
),
|
||||||
Ok(current) => (current.hash, self.cleanup_errors.get(id).cloned()),
|
Ok(current) => (current.hash.clone(), self.cleanup_errors.get(id).cloned()),
|
||||||
Err(error) => (record.hash.clone(), Some(error.to_string())),
|
Err(error) => (record.hash.clone(), Some(error.to_string())),
|
||||||
};
|
};
|
||||||
Ok(PluginRow {
|
Ok(PluginRow {
|
||||||
@@ -542,13 +639,13 @@ impl Service {
|
|||||||
if !valid_id(&id) || self.catalog.plugins.contains_key(&id) {
|
if !valid_id(&id) || self.catalog.plugins.contains_key(&id) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if let Ok(current) = safe_child(&directory, &path).and_then(|_| package(&path)) {
|
if let Ok(current) = safe_child(&directory, &path).and_then(|_| self.check(&path)) {
|
||||||
if current.manifest.id == id {
|
if current.manifest.id == id {
|
||||||
self.catalog.plugins.insert(
|
self.catalog.plugins.insert(
|
||||||
id,
|
id,
|
||||||
Installed {
|
Installed {
|
||||||
manifest: current.manifest,
|
manifest: current.manifest.clone(),
|
||||||
hash: current.hash,
|
hash: current.hash.clone(),
|
||||||
enabled: false,
|
enabled: false,
|
||||||
installed_at: None,
|
installed_at: None,
|
||||||
removal: None,
|
removal: None,
|
||||||
@@ -559,6 +656,8 @@ impl Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Forget the checks of folders that no longer exist.
|
||||||
|
self.checked.retain(|path, _| path.exists());
|
||||||
let mut plugins = Vec::new();
|
let mut plugins = Vec::new();
|
||||||
for id in self.catalog.plugins.keys().cloned().collect::<Vec<_>>() {
|
for id in self.catalog.plugins.keys().cloned().collect::<Vec<_>>() {
|
||||||
if !directory.join(&id).exists() && self.catalog.plugins[&id].removal.is_none() {
|
if !directory.join(&id).exists() && self.catalog.plugins[&id].removal.is_none() {
|
||||||
@@ -713,6 +812,7 @@ impl Service {
|
|||||||
return Err(error);
|
return Err(error);
|
||||||
}
|
}
|
||||||
let candidate = self.candidates.remove(token).unwrap();
|
let candidate = self.candidates.remove(token).unwrap();
|
||||||
|
self.checked.remove(&target);
|
||||||
if let Err(error) = fs::rename(&candidate.directory, &target) {
|
if let Err(error) = fs::rename(&candidate.directory, &target) {
|
||||||
self.catalog.plugins.remove(&id);
|
self.catalog.plugins.remove(&id);
|
||||||
let _ = self.persist();
|
let _ = self.persist();
|
||||||
@@ -758,7 +858,7 @@ impl Service {
|
|||||||
if self.removing.get(&id) != Some(&previous.hash) {
|
if self.removing.get(&id) != Some(&previous.hash) {
|
||||||
return Err("Start the plugin update again.".into());
|
return Err("Start the plugin update again.".into());
|
||||||
}
|
}
|
||||||
if self.leases.get(&id).is_some_and(|windows| !windows.is_empty()) || self.cleanup_errors.contains_key(&id) {
|
if self.leased(&id) || self.cleanup_errors.contains_key(&id) {
|
||||||
return Err("Plugin cleanup did not finish. Close other RuneStone windows and retry the update.".into());
|
return Err("Plugin cleanup did not finish. Close other RuneStone windows and retry the update.".into());
|
||||||
}
|
}
|
||||||
if candidate.source.as_ref().map(|source| package(source)).transpose()?.is_some_and(|source| source.hash != candidate.hash)
|
if candidate.source.as_ref().map(|source| package(source)).transpose()?.is_some_and(|source| source.hash != candidate.hash)
|
||||||
@@ -779,6 +879,7 @@ impl Service {
|
|||||||
backup: backup.file_name().unwrap().to_string_lossy().into_owned(),
|
backup: backup.file_name().unwrap().to_string_lossy().into_owned(),
|
||||||
staged: candidate.directory.file_name().unwrap().to_string_lossy().into_owned() };
|
staged: candidate.directory.file_name().unwrap().to_string_lossy().into_owned() };
|
||||||
fs::write(&journal_path, serde_json::to_vec(&journal)?)?;
|
fs::write(&journal_path, serde_json::to_vec(&journal)?)?;
|
||||||
|
self.checked.remove(&target);
|
||||||
fs::rename(&target, &backup)?;
|
fs::rename(&target, &backup)?;
|
||||||
if let Err(error) = fs::rename(&candidate.directory, &target) {
|
if let Err(error) = fs::rename(&candidate.directory, &target) {
|
||||||
fs::rename(&backup, &target)?;
|
fs::rename(&backup, &target)?;
|
||||||
@@ -857,11 +958,7 @@ impl Service {
|
|||||||
Ok(plan.id)
|
Ok(plan.id)
|
||||||
}
|
}
|
||||||
fn finish_remove(&mut self, id: &str) -> Result<()> {
|
fn finish_remove(&mut self, id: &str) -> Result<()> {
|
||||||
if self
|
if self.leased(id) {
|
||||||
.leases
|
|
||||||
.get(id)
|
|
||||||
.is_some_and(|windows| !windows.is_empty())
|
|
||||||
{
|
|
||||||
return Err("Removal blocked. Close other RuneStone windows and try again.".into());
|
return Err("Removal blocked. Close other RuneStone windows and try again.".into());
|
||||||
}
|
}
|
||||||
if let Some(error) = self.cleanup_errors.get(id) {
|
if let Some(error) = self.cleanup_errors.get(id) {
|
||||||
@@ -887,9 +984,10 @@ impl Service {
|
|||||||
record.removal = Some(token.clone());
|
record.removal = Some(token.clone());
|
||||||
record.removal_files = current_files
|
record.removal_files = current_files
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(name, bytes)| (name.clone(), format!("{:x}", Sha256::digest(bytes))))
|
.map(|(name, bytes)| (name.clone(), digest(bytes)))
|
||||||
.collect();
|
.collect();
|
||||||
self.persist()?;
|
self.persist()?;
|
||||||
|
self.checked.remove(&target);
|
||||||
let destination = self.directory("plugin-removals")?.join(token);
|
let destination = self.directory("plugin-removals")?.join(token);
|
||||||
if let Err(error) = fs::rename(&target, &destination) {
|
if let Err(error) = fs::rename(&target, &destination) {
|
||||||
self.catalog.plugins.get_mut(id).unwrap().removal = None;
|
self.catalog.plugins.get_mut(id).unwrap().removal = None;
|
||||||
@@ -920,7 +1018,7 @@ impl Service {
|
|||||||
safe_child(&parent, &target)?;
|
safe_child(&parent, &target)?;
|
||||||
let expected = &self.catalog.plugins[id].removal_files;
|
let expected = &self.catalog.plugins[id].removal_files;
|
||||||
for (name, bytes) in directory_files(&target)? {
|
for (name, bytes) in directory_files(&target)? {
|
||||||
if expected.get(&name) != Some(&format!("{:x}", Sha256::digest(bytes))) {
|
if expected.get(&name) != Some(&digest(&bytes)) {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"Removal files changed. Inspect {} before retrying.",
|
"Removal files changed. Inspect {} before retrying.",
|
||||||
target.display()
|
target.display()
|
||||||
@@ -938,6 +1036,73 @@ impl Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Service {
|
impl Service {
|
||||||
|
/// Return true when a window holds a lease for the plugin.
|
||||||
|
fn leased(&self, id: &str) -> bool {
|
||||||
|
self.leases.get(id).is_some_and(|windows| !windows.is_empty())
|
||||||
|
}
|
||||||
|
fn set_enabled(&mut self, id: &str, enabled: bool, hash: Option<&str>) -> Result<()> {
|
||||||
|
if self.removing.contains_key(id) {
|
||||||
|
return Err("Wait for plugin removal to finish.".into());
|
||||||
|
}
|
||||||
|
let row = self.row(id)?;
|
||||||
|
if row.removal {
|
||||||
|
return Err("Finish the confirmed removal first.".into());
|
||||||
|
}
|
||||||
|
let old = self.catalog.plugins[id].clone();
|
||||||
|
if enabled {
|
||||||
|
if self.cleanup_errors.contains_key(id) {
|
||||||
|
return Err("Restart RuneStone after the cleanup failure.".into());
|
||||||
|
}
|
||||||
|
// Enable reads every file. The cache alone cannot approve code.
|
||||||
|
let current = self.verify(&self.directory("plugins")?.join(id))?;
|
||||||
|
if current.manifest.id != id || hash != Some(current.hash.as_str()) {
|
||||||
|
return Err("Plugin files changed. Refresh and review them again.".into());
|
||||||
|
}
|
||||||
|
let record = self.catalog.plugins.get_mut(id).unwrap();
|
||||||
|
record.hash = current.hash;
|
||||||
|
record.manifest = current.manifest;
|
||||||
|
}
|
||||||
|
self.catalog.plugins.get_mut(id).unwrap().enabled = enabled;
|
||||||
|
if let Err(error) = self.persist() {
|
||||||
|
self.catalog.plugins.insert(id.into(), old);
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
/// Return the entry module and record a lease for the window `owner`. Load reads every file.
|
||||||
|
fn load(&mut self, owner: &str, id: &str, hash: &str) -> Result<String> {
|
||||||
|
let row = self.row(id)?;
|
||||||
|
if !row.enabled || row.hash != hash {
|
||||||
|
return Err("The plugin is disabled or changed.".into());
|
||||||
|
}
|
||||||
|
let mut current = self.verify(&self.directory("plugins")?.join(id))?;
|
||||||
|
if current.hash != hash {
|
||||||
|
return Err("The plugin changed during loading.".into());
|
||||||
|
}
|
||||||
|
self.leases.entry(id.into()).or_default().insert(owner.into());
|
||||||
|
let entry = current.files.remove(¤t.manifest.entry).unwrap_or_default();
|
||||||
|
String::from_utf8(entry).map_err(Error::from)
|
||||||
|
}
|
||||||
|
/// Read one file of an enabled plugin. The file must have the hash from the last full package read.
|
||||||
|
fn asset(&mut self, id: &str, path: &str) -> Result<Vec<u8>> {
|
||||||
|
if !self.row(id)?.enabled {
|
||||||
|
return Err("The plugin is disabled.".into());
|
||||||
|
}
|
||||||
|
let name = relative(path)?;
|
||||||
|
let folder = self.directory("plugins")?.join(id);
|
||||||
|
let current = self.check(&folder)?;
|
||||||
|
if current.hash != self.catalog.plugins[id].hash {
|
||||||
|
return Err("Plugin assets changed. Review the package again.".into());
|
||||||
|
}
|
||||||
|
let expected = current.digests.get(path).ok_or("The plugin asset is missing.")?;
|
||||||
|
let bytes = bounded(&folder.join(name), MAX_FILE)?;
|
||||||
|
if digest(&bytes) != *expected {
|
||||||
|
// The next check reads the package again and reports the change.
|
||||||
|
self.checked.remove(&folder);
|
||||||
|
return Err("Plugin assets changed. Review the package again.".into());
|
||||||
|
}
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
/// Accept only a plugin that is enabled and loaded in the window `owner`.
|
/// Accept only a plugin that is enabled and loaded in the window `owner`.
|
||||||
fn require_lease(&self, owner: &str, id: &str) -> Result<()> {
|
fn require_lease(&self, owner: &str, id: &str) -> Result<()> {
|
||||||
let record = self.catalog.plugins.get(id);
|
let record = self.catalog.plugins.get(id);
|
||||||
@@ -1010,10 +1175,31 @@ impl PluginState {
|
|||||||
let app = app.clone();
|
let app = app.clone();
|
||||||
tauri::async_runtime::spawn_blocking(move || app.state::<PluginState>().with(&app, action)).await?
|
tauri::async_runtime::spawn_blocking(move || app.state::<PluginState>().with(&app, action)).await?
|
||||||
}
|
}
|
||||||
|
/// Wait until no window holds a lease for `id`, or until `limit` ends. Return true when no lease remains.
|
||||||
|
/// The plugin lock is open while this function waits.
|
||||||
|
fn wait_for_release(&self, id: &str, limit: Duration) -> Result<bool> {
|
||||||
|
let deadline = Instant::now() + limit;
|
||||||
|
let mut guard = self.inner.lock()?;
|
||||||
|
loop {
|
||||||
|
if !guard.as_ref().is_some_and(|service| service.leased(id)) {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
let left = deadline.saturating_duration_since(Instant::now());
|
||||||
|
if left.is_zero() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
guard = self.released.wait_timeout(guard, left)?.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
/// Release the window without waiting. Return `None` when another command holds the plugin lock.
|
/// Release the window without waiting. Return `None` when another command holds the plugin lock.
|
||||||
pub fn try_release_window(&self, owner: &str) -> Option<StagingCleanup> {
|
pub fn try_release_window(&self, owner: &str) -> Option<StagingCleanup> {
|
||||||
match self.inner.try_lock() {
|
match self.inner.try_lock() {
|
||||||
Ok(mut guard) => Some(StagingCleanup(guard.as_mut().map(|service| service.release_window(owner)))),
|
Ok(mut guard) => {
|
||||||
|
let cleanup = StagingCleanup(guard.as_mut().map(|service| service.release_window(owner)));
|
||||||
|
drop(guard);
|
||||||
|
self.released.notify_all();
|
||||||
|
Some(cleanup)
|
||||||
|
}
|
||||||
Err(std::sync::TryLockError::WouldBlock) => None,
|
Err(std::sync::TryLockError::WouldBlock) => None,
|
||||||
Err(std::sync::TryLockError::Poisoned(_)) => Some(StagingCleanup(None)),
|
Err(std::sync::TryLockError::Poisoned(_)) => Some(StagingCleanup(None)),
|
||||||
}
|
}
|
||||||
@@ -1024,6 +1210,7 @@ impl PluginState {
|
|||||||
Ok(mut guard) => StagingCleanup(guard.as_mut().map(|service| service.release_window(owner))),
|
Ok(mut guard) => StagingCleanup(guard.as_mut().map(|service| service.release_window(owner))),
|
||||||
Err(_) => return,
|
Err(_) => return,
|
||||||
};
|
};
|
||||||
|
self.released.notify_all();
|
||||||
cleanup.erase();
|
cleanup.erase();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1143,14 +1330,11 @@ pub async fn plugins_install(
|
|||||||
Ok(id) => {
|
Ok(id) => {
|
||||||
if let Some(id) = &id {
|
if let Some(id) = &id {
|
||||||
changed(&app);
|
changed(&app);
|
||||||
let start = Instant::now();
|
let (wait_app, wait_id) = (app.clone(), id.clone());
|
||||||
while PluginState::run(&app, {
|
// `install` checks the leases again and reports a window that did not stop the plugin.
|
||||||
let id = id.clone();
|
let _ = tauri::async_runtime::spawn_blocking(move || {
|
||||||
move |service| Ok(service.leases.get(&id).is_some_and(|windows| !windows.is_empty()))
|
wait_app.state::<PluginState>().wait_for_release(&wait_id, LEASE_WAIT)
|
||||||
}).await?
|
}).await;
|
||||||
&& start.elapsed() < Duration::from_secs(10) {
|
|
||||||
tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
let owner = owner.clone();
|
let owner = owner.clone();
|
||||||
let installed = PluginState::run(&app, move |service| {
|
let installed = PluginState::run(&app, move |service| {
|
||||||
@@ -1182,34 +1366,7 @@ pub async fn plugins_set_enabled(
|
|||||||
hash: Option<String>,
|
hash: Option<String>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let stop_browser = id == "runestone.browser" && !enabled;
|
let stop_browser = id == "runestone.browser" && !enabled;
|
||||||
PluginState::run(&app, move |service| {
|
PluginState::run(&app, move |service| service.set_enabled(&id, enabled, hash.as_deref())).await?;
|
||||||
if service.removing.contains_key(&id) {
|
|
||||||
return Err("Wait for plugin removal to finish.".into());
|
|
||||||
}
|
|
||||||
let row = service.row(&id)?;
|
|
||||||
if row.removal {
|
|
||||||
return Err("Finish the confirmed removal first.".into());
|
|
||||||
}
|
|
||||||
let old = service.catalog.plugins[&id].clone();
|
|
||||||
if enabled {
|
|
||||||
if service.cleanup_errors.contains_key(&id) {
|
|
||||||
return Err("Restart RuneStone after the cleanup failure.".into());
|
|
||||||
}
|
|
||||||
let current = package(&service.directory("plugins")?.join(&id))?;
|
|
||||||
if current.manifest.id != id || hash.as_deref() != Some(¤t.hash) {
|
|
||||||
return Err("Plugin files changed. Refresh and review them again.".into());
|
|
||||||
}
|
|
||||||
let record = service.catalog.plugins.get_mut(&id).unwrap();
|
|
||||||
record.hash = current.hash;
|
|
||||||
record.manifest = current.manifest;
|
|
||||||
}
|
|
||||||
service.catalog.plugins.get_mut(&id).unwrap().enabled = enabled;
|
|
||||||
if let Err(error) = service.persist() {
|
|
||||||
service.catalog.plugins.insert(id, old);
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}).await?;
|
|
||||||
if stop_browser {
|
if stop_browser {
|
||||||
// Stopping the browser engine waits for its reply.
|
// Stopping the browser engine waits for its reply.
|
||||||
let browser_app = app.clone();
|
let browser_app = app.clone();
|
||||||
@@ -1226,23 +1383,7 @@ pub async fn plugins_load(
|
|||||||
hash: String,
|
hash: String,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
let owner = window.label().to_owned();
|
let owner = window.label().to_owned();
|
||||||
PluginState::run(&app, move |service| {
|
PluginState::run(&app, move |service| service.load(&owner, &id, &hash)).await
|
||||||
let row = service.row(&id)?;
|
|
||||||
if !row.enabled || row.hash != hash {
|
|
||||||
return Err("The plugin is disabled or changed.".into());
|
|
||||||
}
|
|
||||||
let current = package(&service.directory("plugins")?.join(&id))?;
|
|
||||||
if current.hash != hash {
|
|
||||||
return Err("The plugin changed during loading.".into());
|
|
||||||
}
|
|
||||||
service
|
|
||||||
.leases
|
|
||||||
.entry(id)
|
|
||||||
.or_default()
|
|
||||||
.insert(owner);
|
|
||||||
String::from_utf8(current.files[¤t.manifest.entry].clone()).map_err(Error::from)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn plugins_release(
|
pub async fn plugins_release(
|
||||||
@@ -1252,7 +1393,7 @@ pub async fn plugins_release(
|
|||||||
error: Option<String>,
|
error: Option<String>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let owner = window.label().to_owned();
|
let owner = window.label().to_owned();
|
||||||
PluginState::run(&app, move |service| {
|
let result = PluginState::run(&app, move |service| {
|
||||||
if let Some(error) = error {
|
if let Some(error) = error {
|
||||||
service.cleanup_errors.insert(id.clone(), error);
|
service.cleanup_errors.insert(id.clone(), error);
|
||||||
}
|
}
|
||||||
@@ -1261,7 +1402,9 @@ pub async fn plugins_release(
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.await
|
.await;
|
||||||
|
app.state::<PluginState>().released.notify_all();
|
||||||
|
result
|
||||||
}
|
}
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn plugins_prepare_remove(
|
pub async fn plugins_prepare_remove(
|
||||||
@@ -1279,23 +1422,10 @@ pub async fn plugins_remove(app: AppHandle, window: tauri::Window, token: String
|
|||||||
changed(&app);
|
changed(&app);
|
||||||
let worker_app = app.clone();
|
let worker_app = app.clone();
|
||||||
let result = tauri::async_runtime::spawn_blocking(move || {
|
let result = tauri::async_runtime::spawn_blocking(move || {
|
||||||
let start = Instant::now();
|
let state = worker_app.state::<PluginState>();
|
||||||
loop {
|
// `finish_remove` checks the leases again and reports a window that did not stop the plugin.
|
||||||
let leased = worker_app
|
let _ = state.wait_for_release(&id, LEASE_WAIT);
|
||||||
.state::<PluginState>()
|
state
|
||||||
.with(&worker_app, |service| {
|
|
||||||
Ok(service
|
|
||||||
.leases
|
|
||||||
.get(&id)
|
|
||||||
.is_some_and(|windows| !windows.is_empty()))
|
|
||||||
})?;
|
|
||||||
if !leased || start.elapsed() > Duration::from_secs(10) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
std::thread::sleep(Duration::from_millis(50));
|
|
||||||
}
|
|
||||||
worker_app
|
|
||||||
.state::<PluginState>()
|
|
||||||
.with(&worker_app, |service| {
|
.with(&worker_app, |service| {
|
||||||
let result = service.finish_remove(&id);
|
let result = service.finish_remove(&id);
|
||||||
service.removing.remove(&id);
|
service.removing.remove(&id);
|
||||||
@@ -1392,19 +1522,7 @@ pub async fn plugins_asset(
|
|||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
PluginState::run(&app, move |service| {
|
PluginState::run(&app, move |service| {
|
||||||
if !service.row(&id)?.enabled {
|
Ok(base64::engine::general_purpose::STANDARD.encode(service.asset(&id, &path)?))
|
||||||
return Err("The plugin is disabled.".into());
|
|
||||||
}
|
|
||||||
relative(&path)?;
|
|
||||||
let current = package(&service.directory("plugins")?.join(&id))?;
|
|
||||||
if current.hash != service.catalog.plugins[&id].hash {
|
|
||||||
return Err("Plugin assets changed. Review the package again.".into());
|
|
||||||
}
|
|
||||||
let bytes = current
|
|
||||||
.files
|
|
||||||
.get(&path)
|
|
||||||
.ok_or("The plugin asset is missing.")?;
|
|
||||||
Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@@ -1645,7 +1763,7 @@ mod tests {
|
|||||||
record.enabled = true;
|
record.enabled = true;
|
||||||
f.service.persist().unwrap();
|
f.service.persist().unwrap();
|
||||||
}
|
}
|
||||||
let recovered = Service::open(f.root.join("app")).unwrap();
|
let mut recovered = Service::open(f.root.join("app")).unwrap();
|
||||||
let row = recovered.row(&id).unwrap();
|
let row = recovered.row(&id).unwrap();
|
||||||
assert!(row.error.is_none());
|
assert!(row.error.is_none());
|
||||||
assert_eq!(row.manifest.version, if phase == 3 { "1.0.1" } else { "1.0.0" });
|
assert_eq!(row.manifest.version, if phase == 3 { "1.0.1" } else { "1.0.0" });
|
||||||
@@ -1976,7 +2094,7 @@ mod tests {
|
|||||||
record.enabled = false;
|
record.enabled = false;
|
||||||
record.removal = Some(uid());
|
record.removal = Some(uid());
|
||||||
f.service.persist().unwrap();
|
f.service.persist().unwrap();
|
||||||
let recovered = Service::open(f.service.root.clone()).unwrap();
|
let mut recovered = Service::open(f.service.root.clone()).unwrap();
|
||||||
assert!(recovered.catalog.plugins[&id].removal.is_none());
|
assert!(recovered.catalog.plugins[&id].removal.is_none());
|
||||||
assert!(!recovered.row(&id).unwrap().enabled);
|
assert!(!recovered.row(&id).unwrap().enabled);
|
||||||
}
|
}
|
||||||
@@ -2013,4 +2131,78 @@ mod tests {
|
|||||||
assert!(Service::open(f.service.root.clone()).is_err());
|
assert!(Service::open(f.service.root.clone()).is_err());
|
||||||
assert!(safe_child(&f.service.directory("plugins").unwrap(), &f.source).is_err());
|
assert!(safe_child(&f.service.directory("plugins").unwrap(), &f.source).is_err());
|
||||||
}
|
}
|
||||||
|
#[test]
|
||||||
|
fn package_checks_are_cached_until_file_metadata_changes() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let id = f.install(true);
|
||||||
|
let folder = f.service.directory("plugins").unwrap().join(&id);
|
||||||
|
let first = f.service.check(&folder).unwrap();
|
||||||
|
f.service.snapshot().unwrap();
|
||||||
|
assert!(Arc::ptr_eq(&first, &f.service.check(&folder).unwrap()), "A scan without file changes reuses the hash.");
|
||||||
|
fs::create_dir(folder.join("empty")).unwrap();
|
||||||
|
assert!(!Arc::ptr_eq(&first, &f.service.check(&folder).unwrap()), "A new entry starts a new read.");
|
||||||
|
fs::write(folder.join("main.js"), "export function activate() { /* edited */ }").unwrap();
|
||||||
|
let row = f.service.row(&id).unwrap();
|
||||||
|
assert_eq!(row.error.as_deref(), Some("Plugin files changed. Review them before enabling this plugin."));
|
||||||
|
assert!(!row.enabled);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn changed_packages_stop_and_need_a_new_enable_decision() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let id = f.install(true);
|
||||||
|
let reviewed = f.service.row(&id).unwrap().hash;
|
||||||
|
let entry = f.service.directory("plugins").unwrap().join(&id).join("main.js");
|
||||||
|
assert_eq!(f.service.load("main", &id, &reviewed).unwrap(), "export function activate() {}");
|
||||||
|
assert_eq!(f.service.asset(&id, "main.js").unwrap(), b"export function activate() {}");
|
||||||
|
assert!(f.service.asset(&id, "missing.js").unwrap_err().to_string().contains("missing"));
|
||||||
|
f.service.leases.clear();
|
||||||
|
// The same size and modification time hide the edit from the cache, but not from a file read.
|
||||||
|
let modified = fs::metadata(&entry).unwrap().modified().unwrap();
|
||||||
|
fs::write(&entry, "export function activatE() {}").unwrap();
|
||||||
|
fs::File::options().write(true).open(&entry).unwrap().set_modified(modified).unwrap();
|
||||||
|
assert!(f.service.row(&id).unwrap().enabled);
|
||||||
|
assert!(f.service.asset(&id, "main.js").unwrap_err().to_string().contains("changed"));
|
||||||
|
assert!(f.service.load("main", &id, &reviewed).is_err());
|
||||||
|
assert!(!f.service.leased(&id));
|
||||||
|
let row = f.service.row(&id).unwrap();
|
||||||
|
assert!(row.error.is_some() && !row.enabled);
|
||||||
|
// A scan stops the plugin in every window: the snapshot reports it as disabled and saves that state.
|
||||||
|
let snapshot = f.service.snapshot().unwrap();
|
||||||
|
assert!(!snapshot.plugins[0].enabled);
|
||||||
|
assert!(!Service::open(f.root.join("app")).unwrap().catalog.plugins[&id].enabled);
|
||||||
|
// Enable needs the hash that the user saw for the current files.
|
||||||
|
assert!(f.service.set_enabled(&id, true, Some(&reviewed)).is_err());
|
||||||
|
assert!(f.service.set_enabled(&id, true, None).is_err());
|
||||||
|
f.service.set_enabled(&id, true, Some(&row.hash)).unwrap();
|
||||||
|
assert!(f.service.row(&id).unwrap().enabled);
|
||||||
|
assert_eq!(f.service.load("main", &id, &row.hash).unwrap(), "export function activatE() {}");
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn lease_wait_ends_when_the_last_window_releases_its_lease() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let id = f.install(true);
|
||||||
|
f.service.leases.entry(id.clone()).or_default().extend(["main".to_owned(), "other".to_owned()]);
|
||||||
|
let reopened = Service::open(f.root.join("app")).unwrap();
|
||||||
|
let state = Arc::new(PluginState::default());
|
||||||
|
*state.inner.lock().unwrap() = Some(std::mem::replace(&mut f.service, reopened));
|
||||||
|
let start = Instant::now();
|
||||||
|
assert!(!state.wait_for_release(&id, Duration::from_millis(100)).unwrap());
|
||||||
|
assert!(start.elapsed() >= Duration::from_millis(100));
|
||||||
|
let waiter = {
|
||||||
|
let (state, id) = (state.clone(), id.clone());
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let start = Instant::now();
|
||||||
|
(state.wait_for_release(&id, LEASE_WAIT).unwrap(), start.elapsed())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
state.close_window("main");
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
assert!(!waiter.is_finished(), "One window still holds a lease.");
|
||||||
|
state.close_window("other");
|
||||||
|
let (released, elapsed) = waiter.join().unwrap();
|
||||||
|
assert!(released);
|
||||||
|
assert!(elapsed < Duration::from_secs(5), "The wait ends without the full time limit.");
|
||||||
|
assert!(state.wait_for_release("org.test.missing", LEASE_WAIT).unwrap());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,20 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"security": {
|
"security": {
|
||||||
"csp": null
|
"csp": {
|
||||||
|
"default-src": "'self'",
|
||||||
|
"script-src": "'self' blob: 'wasm-unsafe-eval'",
|
||||||
|
"style-src": "'self' 'unsafe-inline'",
|
||||||
|
"img-src": "'self' data: blob: https: http:",
|
||||||
|
"font-src": "'self' data:",
|
||||||
|
"connect-src": "'self' ipc: http://ipc.localhost blob:",
|
||||||
|
"worker-src": "'self' blob:",
|
||||||
|
"object-src": "'none'",
|
||||||
|
"base-uri": "'self'",
|
||||||
|
"form-action": "'none'",
|
||||||
|
"frame-ancestors": "'none'"
|
||||||
|
},
|
||||||
|
"dangerousDisableAssetCspModification": ["style-src"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"bundle": {
|
"bundle": {
|
||||||
|
|||||||
@@ -375,12 +375,11 @@ export function startExternalPlugins(allowed?: string[]): () => void {
|
|||||||
await activate({ manifest: { schemaVersion: 1, id: "runestone.browser", name: "Browser", author: "RuneStone", description: "Built-in browser", version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module);
|
await activate({ manifest: { schemaVersion: 1, id: "runestone.browser", name: "Browser", author: "RuneStone", description: "Built-in browser", version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module);
|
||||||
}).catch(reason => report("runestone.browser", reason));
|
}).catch(reason => report("runestone.browser", reason));
|
||||||
void refreshPlugins();
|
void refreshPlugins();
|
||||||
|
// Scans run at start, on window focus, on Refresh, and on `plugins-changed`. There is no timed scan.
|
||||||
const focus = () => { void refreshPlugins(); };
|
const focus = () => { void refreshPlugins(); };
|
||||||
window.addEventListener("focus", focus);
|
window.addEventListener("focus", focus);
|
||||||
// Also detects changes made in a file manager while this window stays open.
|
|
||||||
const timer = setInterval(focus, 5000);
|
|
||||||
return () => {
|
return () => {
|
||||||
disposed = true; started = false; generation++; off?.(); clearInterval(timer); window.removeEventListener("focus", focus);
|
disposed = true; started = false; generation++; off?.(); window.removeEventListener("focus", focus);
|
||||||
for (const id of [...sessions.keys()]) void stop(id).catch(reason => report(id, reason));
|
for (const id of [...sessions.keys()]) void stop(id).catch(reason => report(id, reason));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,10 +18,35 @@ export function playwright() {
|
|||||||
return createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
|
return createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Start headless Chromium. CHROME_PATH selects an installed browser. */
|
/** True in CSP mode (`pnpm smoke --csp`). The dev server then sends the app's content security policy. */
|
||||||
export function launchBrowser(options = {}) {
|
export const cspMode = process.env.RUNESTONE_CSP === "1";
|
||||||
|
/** The content security policy violations of all pages in CSP mode. `runSmoke` fails when this list is not empty. */
|
||||||
|
export const cspViolations = [];
|
||||||
|
const CSP_PREFIX = "[csp-violation] ";
|
||||||
|
// This function runs in each page and frame. Violations inside workers do not reach it.
|
||||||
|
function reportCspViolations(prefix) {
|
||||||
|
addEventListener("securitypolicyviolation", event => {
|
||||||
|
console.error(prefix + JSON.stringify({ directive: event.effectiveDirective, blocked: event.blockedURI, source: event.sourceFile, line: event.lineNumber, sample: event.sample, page: location.href }));
|
||||||
|
}, true);
|
||||||
|
}
|
||||||
|
/** Record the violations of a browser context or a page. */
|
||||||
|
async function watchCsp(target) {
|
||||||
|
await target.addInitScript(reportCspViolations, CSP_PREFIX);
|
||||||
|
target.on("console", message => {
|
||||||
|
if (message.text().startsWith(CSP_PREFIX)) cspViolations.push(message.text().slice(CSP_PREFIX.length));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Start headless Chromium. CHROME_PATH selects an installed browser. In CSP mode, each new context and page records violations. */
|
||||||
|
export async function launchBrowser(options = {}) {
|
||||||
const executablePath = process.env.CHROME_PATH;
|
const executablePath = process.env.CHROME_PATH;
|
||||||
return playwright().chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}), ...options });
|
const browser = await playwright().chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}), ...options });
|
||||||
|
if (cspMode) {
|
||||||
|
const { newContext, newPage } = { newContext: browser.newContext.bind(browser), newPage: browser.newPage.bind(browser) };
|
||||||
|
browser.newContext = async (...args) => { const context = await newContext(...args); await watchCsp(context); return context; };
|
||||||
|
browser.newPage = async (...args) => { const page = await newPage(...args); await watchCsp(page); return page; };
|
||||||
|
}
|
||||||
|
return browser;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -267,10 +292,14 @@ export async function runSmoke(name, body, { viewport, timeout, allowPageErrors
|
|||||||
page = await openPage(browser, { viewport, timeout });
|
page = await openPage(browser, { viewport, timeout });
|
||||||
await body({ browser, page });
|
await body({ browser, page });
|
||||||
if (!allowPageErrors && page.errors.length) throw new Error(`Page errors:\n${page.errors.join("\n")}`);
|
if (!allowPageErrors && page.errors.length) throw new Error(`Page errors:\n${page.errors.join("\n")}`);
|
||||||
|
if (cspViolations.length) throw new Error(`Content security policy violations:\n${[...new Set(cspViolations)].join("\n")}`);
|
||||||
console.log(`PASS ${name}`);
|
console.log(`PASS ${name}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`FAIL ${name}`);
|
console.error(`FAIL ${name}`);
|
||||||
console.error(error);
|
console.error(error);
|
||||||
|
if (cspViolations.length && !String(error?.message).startsWith("Content security policy violations")) {
|
||||||
|
console.error(`Content security policy violations:\n${[...new Set(cspViolations)].join("\n")}`);
|
||||||
|
}
|
||||||
if (page) {
|
if (page) {
|
||||||
if (page.console.length) console.error(`Console:\n${page.console.join("\n")}`);
|
if (page.console.length) console.error(`Console:\n${page.console.join("\n")}`);
|
||||||
const file = path.join(await outputDir(name), "failure.png");
|
const file = path.join(await outputDir(name), "failure.png");
|
||||||
|
|||||||
@@ -38,7 +38,9 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
|
|||||||
};
|
};
|
||||||
const saved = make('#bd486c', '#438f67');
|
const saved = make('#bd486c', '#438f67');
|
||||||
saveAppearance({ theme: 'default', mode: theme, newTabBackground: { image: saved, overlay: 0.15, position: 'center', size: 'cover' } });
|
saveAppearance({ theme: 'default', mode: theme, newTabBackground: { image: saved, overlay: 0.15, position: 'center', size: 'cover' } });
|
||||||
const urls = await Promise.all([make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(async url => URL.createObjectURL(await (await fetch(url)).blob())));
|
// Decode the data URLs without fetch: the content security policy does not permit `data:` in connect-src.
|
||||||
|
const blob = url => new Blob([Uint8Array.from(atob(url.split(',')[1]), character => character.charCodeAt(0))], { type: 'image/png' });
|
||||||
|
const urls = [make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(url => URL.createObjectURL(blob(url)));
|
||||||
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
|
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
|
||||||
}, theme);
|
}, theme);
|
||||||
const background = page.locator('.workarea-background');
|
const background = page.locator('.workarea-background');
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
// A browser window (`?browserWindow=true`): it adopts the moved tab, starts no installed plugin,
|
||||||
|
// and calls only the commands that src-tauri/capabilities/browser.json grants.
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { mockTauri, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
|
||||||
|
|
||||||
|
await runSmoke('browser/window', async ({ page }) => {
|
||||||
|
await mockTauri(page, {
|
||||||
|
label: 'browser-smoke',
|
||||||
|
commands: test => {
|
||||||
|
const snapshot = { profiles: [{ id: 'user', name: 'User' }], tabs: [{ id: 'moved', profileId: 'user', url: 'https://example.com', title: 'Example', loading: false, blocked: 0, canBack: false, canForward: false, transferToken: 'token' }], bookmarks: [], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
|
||||||
|
let next = 0;
|
||||||
|
return {
|
||||||
|
browser_connect: () => 'window-session',
|
||||||
|
browser_stop: () => null,
|
||||||
|
browser_request: ({ session, command, args }) => {
|
||||||
|
if (session !== 'window-session') throw Error('Missing browser session');
|
||||||
|
if (command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
|
||||||
|
if (command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
|
||||||
|
if (command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.tabId); tab.url = args.input; }
|
||||||
|
return structuredClone(snapshot);
|
||||||
|
},
|
||||||
|
// An installed plugin that a browser window must not load.
|
||||||
|
plugins_snapshot: () => ({ root: 'test', plugins: [{ manifest: { schemaVersion: 1, id: 'org.test.tasks', name: 'Tasks', author: 'Test', description: '', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'tasks', enabled: true, installedAt: 1, path: '', error: null, removal: false }] }),
|
||||||
|
spelling_menu_install: () => null,
|
||||||
|
spelling_menu_uninstall: () => null,
|
||||||
|
'plugin:window|is_maximized': () => false,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await page.goto(smokeUrl + '/?browserWindow=true&browserTab=moved');
|
||||||
|
await page.getByRole('application', { name: 'RuneStone browser' }).waitFor();
|
||||||
|
await page.locator('[data-browser-state="ready"]').waitFor();
|
||||||
|
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.org');
|
||||||
|
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
|
||||||
|
await page.keyboard.press('Control+t');
|
||||||
|
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'browser_request' && call.args.command === 'newTab'));
|
||||||
|
|
||||||
|
const capability = JSON.parse(await readFile(path.join(repoRoot, 'src-tauri/capabilities/browser.json'), 'utf8'));
|
||||||
|
const granted = new Set(capability.permissions);
|
||||||
|
const calls = await page.evaluate(() => [...new Set(window.__TEST__.calls.map(call => call.command))]);
|
||||||
|
assert(!calls.includes('plugins_load'), 'A browser window loads no installed plugin.');
|
||||||
|
const missing = calls.filter(command => {
|
||||||
|
const plugin = /^plugin:([^|]+)\|(.+)$/.exec(command);
|
||||||
|
// core:default grants the event plugin and the read-only window commands. Window actions need their own permission.
|
||||||
|
if (plugin) return plugin[1] === 'window' && /^(destroy|close|minimize|toggle_maximize|start_dragging)$/.test(plugin[2])
|
||||||
|
? !granted.has(`core:window:allow-${plugin[2].replaceAll('_', '-')}`) : !['event', 'window', 'webview', 'app'].includes(plugin[1]);
|
||||||
|
return !granted.has(`allow-${command.replaceAll('_', '-')}`);
|
||||||
|
});
|
||||||
|
assert.deepEqual(missing, [], 'Every command of the browser window is in capabilities/browser.json.');
|
||||||
|
console.log(`Browser window commands: ${calls.join(', ')}`);
|
||||||
|
}, { viewport: { width: 1100, height: 750 } });
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
type Capability = { windows: string[]; permissions: string[] };
|
||||||
|
const read = (file: string): string => readFileSync(new URL(`../../../${file}`, import.meta.url), "utf8");
|
||||||
|
const capability = (name: string): Capability => JSON.parse(read(`src-tauri/capabilities/${name}.json`));
|
||||||
|
|
||||||
|
test("browser windows have their own capability, a subset of the main window commands", () => {
|
||||||
|
const browser = capability("browser"), main = capability("default"), settings = capability("settings");
|
||||||
|
assert.deepEqual(browser.windows, ["browser-*"]);
|
||||||
|
for (const other of [main, settings]) assert(!other.windows.some(pattern => pattern.startsWith("browser")), "Only browser.json matches browser windows.");
|
||||||
|
const extra = browser.permissions.filter(permission => !main.permissions.includes(permission));
|
||||||
|
assert.deepEqual(extra, [], "browser.json grants only permissions that default.json also grants.");
|
||||||
|
// Browser windows run no installed plugin, so they need no workspace, file, plugin package, terminal, or Git access.
|
||||||
|
const denied = browser.permissions.filter(permission => /^allow-(workspace|git|pty|backgrounds|tab-transfer|completion|theme|settings-open)-|^allow-plugins-(?!snapshot$)|^(opener|dialog):/.test(permission));
|
||||||
|
assert.deepEqual(denied, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("browser windows start only the built-in browser", () => {
|
||||||
|
// The capability split depends on this: a browser window never loads an installed plugin.
|
||||||
|
assert.match(read("src/routes/+page.svelte"), /startExternalPlugins\(browserWindow \? \["runestone\.browser"\] : undefined\)/);
|
||||||
|
assert.match(read("src-tauri/src/browser.rs"), /let label = format!\("browser-\{\}", uuid::Uuid::new_v4\(\)\);/);
|
||||||
|
});
|
||||||
+68
-1
@@ -1,6 +1,7 @@
|
|||||||
import { defineConfig } from "vite";
|
import { defineConfig } from "vite";
|
||||||
import { sveltekit } from "@sveltejs/kit/vite";
|
import { sveltekit } from "@sveltejs/kit/vite";
|
||||||
import process from "node:process";
|
import process from "node:process";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
// The installer build sets RUNESTONE_VERSION. It writes package.json only after the build completes.
|
// The installer build sets RUNESTONE_VERSION. It writes package.json only after the build completes.
|
||||||
@@ -10,9 +11,75 @@ const appVersion = process.env.RUNESTONE_VERSION || packageVersion;
|
|||||||
const host = process.env.TAURI_DEV_HOST;
|
const host = process.env.TAURI_DEV_HOST;
|
||||||
const monacoCss = `${process.cwd().replaceAll("\\", "/")}/node_modules/monaco-editor/min/vs/editor/editor.main.css`;
|
const monacoCss = `${process.cwd().replaceAll("\\", "/")}/node_modules/monaco-editor/min/vs/editor/editor.main.css`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CSP mode for the smoke tests (`RUNESTONE_CSP=1`, or `pnpm smoke --csp`).
|
||||||
|
* The dev server sends the policy of `src-tauri/tauri.conf.json` with each HTML page, as the installed app does.
|
||||||
|
* It adds only what the dev server needs:
|
||||||
|
* - script-src: the SHA-256 hash of each inline script in the page. Tauri adds the same hashes to the installed app.
|
||||||
|
* - connect-src: the Vite HMR WebSocket on the address of the page.
|
||||||
|
*/
|
||||||
|
/** @returns {import("vite").Plugin} */
|
||||||
|
function contentSecurityPolicy() {
|
||||||
|
const config = JSON.parse(readFileSync(new URL("./src-tauri/tauri.conf.json", import.meta.url), "utf8"));
|
||||||
|
/** @type {Record<string, string>} */
|
||||||
|
const policy = config.app.security.csp;
|
||||||
|
/** @param {string} html @param {string | undefined} address */
|
||||||
|
const policyFor = (html, address) => {
|
||||||
|
const directives = { ...policy };
|
||||||
|
const hashes = [...html.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)]
|
||||||
|
.map(([, code]) => `'sha256-${createHash("sha256").update(code).digest("base64")}'`);
|
||||||
|
directives["script-src"] = [directives["script-src"], ...hashes].join(" ");
|
||||||
|
directives["connect-src"] = `${directives["connect-src"]} ws://${address}`;
|
||||||
|
return Object.entries(directives).map(([name, sources]) => `${name} ${sources}`).join("; ");
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
name: "runestone-csp",
|
||||||
|
configureServer(server) {
|
||||||
|
// Buffer each HTML response, then send it with the policy header. Other responses pass unchanged,
|
||||||
|
// because Tauri sends the policy only with HTML pages.
|
||||||
|
server.middlewares.use((request, original, next) => {
|
||||||
|
if (request.method !== "GET" || !request.headers.accept?.includes("text/html")) return next();
|
||||||
|
/** @type {any} The response methods have overloads. The replacements accept all their forms. */
|
||||||
|
const response = original;
|
||||||
|
/** @type {Buffer[]} */
|
||||||
|
const chunks = [];
|
||||||
|
const send = { writeHead: response.writeHead.bind(response), end: response.end.bind(response) };
|
||||||
|
/** @type {any[] | undefined} */
|
||||||
|
let head;
|
||||||
|
/** @param {unknown} chunk @param {unknown} encoding */
|
||||||
|
const add = (chunk, encoding) => {
|
||||||
|
if (typeof chunk === "string") chunks.push(Buffer.from(chunk, /** @type {BufferEncoding} */ (typeof encoding === "string" ? encoding : "utf8")));
|
||||||
|
else if (chunk instanceof Uint8Array) chunks.push(Buffer.from(chunk));
|
||||||
|
};
|
||||||
|
/** @param {any[]} args */
|
||||||
|
response.writeHead = (...args) => { head = args; return response; };
|
||||||
|
/** @param {unknown} chunk @param {unknown} encoding @param {unknown} callback */
|
||||||
|
response.write = (chunk, encoding, callback) => {
|
||||||
|
add(chunk, encoding);
|
||||||
|
const done = typeof encoding === "function" ? encoding : callback;
|
||||||
|
if (typeof done === "function") done();
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
/** @param {unknown} chunk @param {unknown} encoding @param {unknown} callback */
|
||||||
|
response.end = (chunk, encoding, callback) => {
|
||||||
|
add(chunk, encoding);
|
||||||
|
const body = Buffer.concat(chunks);
|
||||||
|
/** @type {Record<string, unknown>} */
|
||||||
|
const headers = head?.find(item => item && typeof item === "object") ?? {};
|
||||||
|
const type = String(Object.entries(headers).find(([name]) => name.toLowerCase() === "content-type")?.[1] ?? response.getHeader("content-type") ?? "");
|
||||||
|
if (type.includes("text/html")) response.setHeader("Content-Security-Policy", policyFor(body.toString("utf8"), request.headers.host));
|
||||||
|
if (head) send.writeHead(...head);
|
||||||
|
return send.end(body, [chunk, encoding, callback].find(item => typeof item === "function"));
|
||||||
|
};
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// https://vite.dev/config/
|
// https://vite.dev/config/
|
||||||
export default defineConfig(() => ({
|
export default defineConfig(() => ({
|
||||||
plugins: [sveltekit()],
|
plugins: [...(process.env.RUNESTONE_CSP === "1" ? [contentSecurityPolicy()] : []), sveltekit()],
|
||||||
define: {
|
define: {
|
||||||
__RUNESTONE_VERSION__: JSON.stringify(appVersion),
|
__RUNESTONE_VERSION__: JSON.stringify(appVersion),
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user