Files
RuneStone/vite.config.js
T
Knotty Wyvern e83bf46268 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.
2026-10-28 02:01:50 -07:00

120 lines
5.4 KiB
JavaScript

import { defineConfig } from "vite";
import { sveltekit } from "@sveltejs/kit/vite";
import process from "node:process";
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
// The installer build sets RUNESTONE_VERSION. It writes package.json only after the build completes.
const packageVersion = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version;
const appVersion = process.env.RUNESTONE_VERSION || packageVersion;
const host = process.env.TAURI_DEV_HOST;
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/
export default defineConfig(() => ({
plugins: [...(process.env.RUNESTONE_CSP === "1" ? [contentSecurityPolicy()] : []), sveltekit()],
define: {
__RUNESTONE_VERSION__: JSON.stringify(appVersion),
},
resolve: {
alias: {
"monaco-editor-css": monacoCss,
},
},
optimizeDeps: {
include: ["monaco-editor"],
},
worker: {
format: /** @type {"es"} */ ("es"),
},
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent Vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
host: host || "127.0.0.1",
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
// 3. tell Vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**", "**/fixtures/**", "**/.runestone/**", "**/.audit/**", "**/output/**", "**/browser-runtime/dist/**", "**/browser-runtime/output/**"],
},
},
}));