Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(plugins): accept package-local theme assets

vastsaad3932468e9b
diff --git a/apps/desktop/electron/main/plugin-asset-protocol.ts b/apps/desktop/electron/main/plugin-asset-protocol.ts
index 5cbc64236..882932c48 100644
--- a/apps/desktop/electron/main/plugin-asset-protocol.ts
+++ b/apps/desktop/electron/main/plugin-asset-protocol.ts
@@ -1,5 +1,4 @@
import { protocol } from "electron";
-import { readFileSync } from "node:fs";
import { THEME_ASSET_SCHEME } from "@pi-desktop/plugin-sdk";
/**
@@ -11,12 +10,12 @@ import { THEME_ASSET_SCHEME } from "@pi-desktop/plugin-sdk";
* `url()` references to `plugin-asset://<pluginId>/<path>`, and this handler
* hands back the bytes (ADR 0248).
*
- * The allowlist is not computed here. `resolve` answers only for paths a loaded
- * plugin actually declared, already resolved inside that plugin's package, so a
- * path that was never declared — or that escapes the package — has no URL to
- * begin with. Nothing on disk outside a plugin package is reachable.
+ * The resolver returns bytes only for an asset the loaded plugin declared.
+ * Package-relative assets are realpath-confined to the plugin root; explicitly
+ * declared absolute assets retain their existing support. No file path reaches
+ * the renderer.
*/
-export type PluginAssetResolver = (pluginId: string, assetPath: string) => string | null;
+export type PluginAssetResolver = (pluginId: string, assetPath: string) => Uint8Array | null;
const MIME_TYPES: Record<string, string> = {
png: "image/png",
@@ -84,22 +83,19 @@ export function installPluginAssetProtocol(resolve: PluginAssetResolver): void {
if (!pluginId || !assetPath) return notFound();
const mime = mimeTypeFor(assetPath);
if (!mime) return notFound();
- const absolute = resolve(pluginId, assetPath);
- if (!absolute) return notFound();
- let body: Buffer;
+ let body: Uint8Array | null;
try {
- body = readFileSync(absolute);
+ body = resolve(pluginId, assetPath);
} catch {
return notFound();
}
- // Copy into a plain view: `Buffer` is a `Uint8Array` subtype that the DOM
- // `BodyInit` union does not accept, and this tsconfig loads both libs.
+ if (!body) return notFound();
const bytes = new Uint8Array(body);
return new Response(bytes, {
status: 200,
headers: {
"content-type": mime,
- "content-length": String(body.byteLength),
+ "content-length": String(bytes.byteLength),
// A theme asset is replaced when the plugin changes, so caching it
// would outlive the plugin that owns it.
"cache-control": "no-store",
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index b29694153..7d57eba12 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -78,6 +78,12 @@ import {
resolveWithinRoot,
} from "@pi-desktop/host-runtime";
import { pluginChildEnv } from "./child-process-env";
+import {
+ readThemeAssetBytes,
+ resolveAbsoluteThemeAssetPath,
+ resolvePackageThemeAssetPath,
+ themeAssetGroupWithinBudget,
+} from "./plugin-theme-assets.js";
import { desktopDataDir } from "./data-paths";
import { McpServerClient, type McpServerClientOptions } from "./plugin-mcp";
import { PluginToolInvocations, type PluginToolInvocation } from "./plugin-tool-invocations";
@@ -1129,10 +1135,9 @@ export function resolveInsidePlugin(pluginPath: string, relative: string): strin
/**
* Resolve one theme's declared assets to files inside the plugin package.
*
- * The manifest validator already checked the shape; here each entry has to
- * exist, stay out of the dependency directory, and fit the declared total. A
- * theme that asks for more than the budget gets none of its assets, so a sheet
- * referencing one is refused instead of served from a half-honoured list.
+ * Package-relative assets are canonicalized after the plugin's `onLoad` hook
+ * and rechecked by `resolveThemeAsset` before every host-scheme read. Absolute
+ * assets retain their existing behavior.
*/
function resolveThemeAssets(
pluginPath: string,
@@ -1144,13 +1149,13 @@ function resolveThemeAssets(
let dropped = 0;
for (const asset of declared) {
const normalized = normalizeThemeAssetPath(asset);
- if (!normalized || normalized.split("/").includes("node_modules")) {
+ if (!normalized || normalized.split("/").some((segment) => segment.toLowerCase() === "node_modules")) {
dropped += 1;
continue;
}
const absolute = isExternalThemeAssetPath(normalized)
- ? normalized
- : resolveInsidePlugin(pluginPath, normalized);
+ ? resolveAbsoluteThemeAssetPath(normalized)
+ : resolvePackageThemeAssetPath(pluginPath, normalized);
if (!absolute || !existsSync(absolute)) {
dropped += 1;
continue;
@@ -1280,6 +1285,7 @@ export class PluginRuntime {
* so a path nobody declared has no URL at all (ADR 0248).
*/
private themeAssets = new Map<string, Map<string, string>>();
+ private themeAssetGroups = new Map<string, Map<string, ReadonlyMap<string, string>>>();
private mcpClients = new Map<string, McpServerClient[]>();
private serviceStates = new Map<string, PluginServiceStatus>();
private restarts = new Map<string, RestartRecord>();
@@ -1448,9 +1454,11 @@ export class PluginRuntime {
private externalThemeAsset(loaded: LoadedPlugin, target: string): string | null {
const key = normalizeThemeAssetPath(target);
if (!key || !isExternalThemeAssetPath(key)) return null;
+ const absolute = resolveAbsoluteThemeAssetPath(key);
+ if (!absolute) return null;
let stats: Stats;
try {
- stats = statSync(key);
+ stats = statSync(absolute);
} catch {
return null;
}
@@ -1460,14 +1468,25 @@ export class PluginRuntime {
registry = new Map();
this.themeAssets.set(loaded.manifest.id, registry);
}
- registry.set(key, key);
+ registry.set(key, absolute);
return themeAssetUrl(loaded.manifest.id, key);
}
- resolveThemeAsset(pluginId: string, assetPath: string): string | null {
+ resolveThemeAsset(pluginId: string, assetPath: string): Uint8Array | null {
const normalized = normalizeThemeAssetPath(assetPath);
if (!normalized) return null;
- return this.themeAssets.get(pluginId)?.get(normalized) ?? null;
+ const registered = this.themeAssets.get(pluginId)?.get(normalized);
+ if (!registered) return null;
+ const loaded = this.loaded.get(pluginId);
+ if (!loaded) return null;
+ const current = isExternalThemeAssetPath(normalized)
+ ? resolveAbsoluteThemeAssetPath(normalized)
+ : resolvePackageThemeAssetPath(loaded.path, normalized);
+ if (current !== registered) return null;
+ const groups = this.themeAssetGroups.get(pluginId);
+ const owners = groups ? [...groups.values()].filter((group) => group.has(normalized)) : [];
+ if (owners.some((group) => !themeAssetGroupWithinBudget(loaded.path, group))) return null;
+ return readThemeAssetBytes(registered);
}
/** Supervision state of every resident service, ordered for a stable list. */
@@ -3062,6 +3081,7 @@ export class PluginRuntime {
// A gone plugin must stop serving its assets; the handler resolves through
// this map only, so clearing it revokes every `plugin-asset:` URL at once.
this.themeAssets.delete(pluginId);
+ this.themeAssetGroups.delete(pluginId);
// Closing the client kills the stdio child / drops the HTTP session, so a
// disabled plugin leaves no process behind.
for (const client of this.mcpClients.get(pluginId) ?? []) {
@@ -3340,6 +3360,12 @@ export class PluginRuntime {
this.themeAssets.set(pluginId, registry);
}
for (const [assetPath, absolute] of assets.files) registry.set(assetPath, absolute);
+ let assetGroups = this.themeAssetGroups.get(pluginId);
+ if (!assetGroups) {
+ assetGroups = new Map();
+ this.themeAssetGroups.set(pluginId, assetGroups);
+ }
+ assetGroups.set(themeId, new Map(assets.files));
this.themes.set(id, {
id,
pluginId,
diff --git a/apps/desktop/electron/main/plugin-theme-assets.ts b/apps/desktop/electron/main/plugin-theme-assets.ts
new file mode 100644
index 000000000..58c48e924
--- /dev/null
+++ b/apps/desktop/electron/main/plugin-theme-assets.ts
@@ -0,0 +1,137 @@
+import {
+ closeSync,
+ constants,
+ fstatSync,
+ openSync,
+ readSync,
+ realpathSync,
+ statSync,
+} from "node:fs";
+import { isAbsolute, relative, resolve, sep } from "node:path";
+import {
+ THEME_ASSET_MAX_BYTES,
+ isExternalThemeAssetPath,
+ normalizeThemeAssetPath,
+} from "@pi-desktop/plugin-sdk";
+
+/** Resolve one package-relative theme asset to a real file under the plugin root. */
+export function resolvePackageThemeAssetPath(pluginPath: string, assetPath: string): string | null {
+ const normalized = normalizeThemeAssetPath(assetPath);
+ if (
+ !normalized ||
+ isExternalThemeAssetPath(normalized) ||
+ normalized.split("/").some((segment) => segment.toLowerCase() === "node_modules")
+ ) {
+ return null;
+ }
+
+ const root = resolve(pluginPath);
+ const target = resolve(root, normalized);
+ if (isOutsideRoot(root, target)) return null;
+
+ try {
+ const canonicalRoot = realpathSync(root);
+ const canonicalTarget = realpathSync(target);
+ if (isOutsideRoot(canonicalRoot, canonicalTarget) || !statSync(canonicalTarget).isFile()) {
+ return null;
+ }
+ return canonicalTarget;
+ } catch {
+ return null;
+ }
+}
+
+/** Resolve an explicitly declared absolute theme asset, preserving legacy support. */
+export function resolveAbsoluteThemeAssetPath(assetPath: string): string | null {
+ const normalized = normalizeThemeAssetPath(assetPath);
+ if (!normalized || !isExternalThemeAssetPath(normalized)) return null;
+ try {
+ const canonicalPath = realpathSync(normalized);
+ return statSync(canonicalPath).isFile() ? canonicalPath : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Recheck the summed asset budget for a theme after plugin code has run. */
+export function themeAssetGroupWithinBudget(
+ pluginPath: string,
+ assets: ReadonlyMap<string, string>,
+): boolean {
+ let total = 0;
+ for (const [assetPath, registeredPath] of assets) {
+ const current = isExternalThemeAssetPath(assetPath)
+ ? resolveAbsoluteThemeAssetPath(assetPath)
+ : resolvePackageThemeAssetPath(pluginPath, assetPath);
+ if (!current || current !== registeredPath) return false;
+ try {
+ const size = statSync(current).size;
+ if (!Number.isSafeInteger(size) || size < 0) return false;
+ total += size;
+ if (total > THEME_ASSET_MAX_BYTES) return false;
+ } catch {
+ return false;
+ }
+ }
+ return true;
+}
+
+/**
+ * Read a canonical theme asset through a stable descriptor and a fixed byte
+ * bound. Inode verification prevents a plugin from swapping in a symlink after
+ * path validation; the extra byte detects growth beyond the per-file limit.
+ */
+export function readThemeAssetBytes(assetPath: string): Uint8Array | null {
+ let descriptor: number | undefined;
+ try {
+ const canonicalPath = realpathSync(assetPath);
+ if (canonicalPath !== assetPath) return null;
+ const before = statSync(canonicalPath, { bigint: true });
+ const maxBytes = BigInt(THEME_ASSET_MAX_BYTES);
+ if (!before.isFile() || before.size > maxBytes) return null;
+ if (realpathSync(canonicalPath) !== canonicalPath) return null;
+
+ descriptor = openSync(canonicalPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
+ const opened = fstatSync(descriptor, { bigint: true });
+ if (
+ !opened.isFile() ||
+ opened.dev !== before.dev ||
+ opened.ino !== before.ino ||
+ opened.size > maxBytes
+ ) {
+ return null;
+ }
+
+ const buffer = Buffer.alloc(THEME_ASSET_MAX_BYTES + 1);
+ let total = 0;
+ while (total < buffer.length) {
+ const count = readSync(descriptor, buffer, total, buffer.length - total, total);
+ if (count === 0) break;
+ total += count;
+ }
+ const after = fstatSync(descriptor, { bigint: true });
+ if (
+ total > THEME_ASSET_MAX_BYTES ||
+ after.dev !== opened.dev ||
+ after.ino !== opened.ino ||
+ after.size > maxBytes
+ ) {
+ return null;
+ }
+ return buffer.subarray(0, total);
+ } catch {
+ return null;
+ } finally {
+ if (descriptor !== undefined) closeSync(descriptor);
+ }
+}
+
+function isOutsideRoot(root: string, target: string): boolean {
+ const relativeTarget = relative(root, target);
+ return (
+ relativeTarget.length === 0 ||
+ isAbsolute(relativeTarget) ||
+ relativeTarget === ".." ||
+ relativeTarget.startsWith(`..${sep}`)
+ );
+}
diff --git a/apps/desktop/test/plugin-themes.test.mjs b/apps/desktop/test/plugin-themes.test.mjs
index 691605bcf..450ca019c 100644
--- a/apps/desktop/test/plugin-themes.test.mjs
+++ b/apps/desktop/test/plugin-themes.test.mjs
@@ -2,9 +2,16 @@ import { readAppSourceSync, readSettingsSourceSync, readStoreSourceSync, readMai
import { sanitizeThemeCss } from "@pi-desktop/plugin-sdk";
import assert from "node:assert/strict";
import test from "node:test";
-import { readFileSync } from "node:fs";
+import { readFileSync, realpathSync } from "node:fs";
+import { mkdtemp, mkdir, rm, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
+import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
+import {
+ readThemeAssetBytes,
+ resolvePackageThemeAssetPath,
+ themeAssetGroupWithinBudget,
+} from "../electron/main/plugin-theme-assets.ts";
const here = dirname(fileURLToPath(import.meta.url));
const desktopRoot = join(here, "..");
@@ -240,3 +247,58 @@ test("the shipped example theme survives sanitation", () => {
assert.match(css, /@import/);
assert.equal(sanitizeThemeCss(css).ok, true);
});
+
+test("package-relative theme assets stay canonicalized inside their plugin", async () => {
+ const parent = await mkdtemp(join(tmpdir(), "pi-plugin-theme-assets-"));
+ const plugin = join(parent, "plugin");
+ const asset = join(plugin, "art/bg.png");
+ const secondAsset = join(plugin, "art/second.png");
+ try {
+ await mkdir(dirname(asset), { recursive: true });
+ await writeFile(asset, "image");
+ await writeFile(secondAsset, "image");
+ const registered = resolvePackageThemeAssetPath(plugin, "art/bg.png");
+ const secondRegistered = resolvePackageThemeAssetPath(plugin, "art/second.png");
+ assert.ok(registered);
+ assert.ok(secondRegistered);
+ assert.equal(registered, realpathSync(asset));
+ const initialBytes = readThemeAssetBytes(registered);
+ assert.equal(Buffer.from(initialBytes ?? []).toString("utf8"), "image");
+ assert.equal(
+ resolvePackageThemeAssetPath(plugin, "../outside.png"),
+ null,
+ );
+
+ const group = new Map([
+ ["art/bg.png", registered],
+ ["art/second.png", secondRegistered],
+ ]);
+ assert.equal(themeAssetGroupWithinBudget(plugin, group), true);
+ const twoMiBPlusOne = Buffer.alloc(2 * 1024 * 1024 + 1);
+ await writeFile(asset, twoMiBPlusOne);
+ await writeFile(secondAsset, twoMiBPlusOne);
+ assert.equal(themeAssetGroupWithinBudget(plugin, group), false);
+
+ await writeFile(asset, Buffer.alloc(4 * 1024 * 1024 + 1));
+ assert.equal(readThemeAssetBytes(registered), null);
+ await writeFile(asset, "image");
+
+ if (process.platform !== "win32") {
+ const outside = join(parent, "outside.png");
+ await writeFile(outside, "outside");
+ await rm(asset);
+ await symlink(outside, asset);
+ assert.equal(resolvePackageThemeAssetPath(plugin, "art/bg.png"), null);
+ assert.equal(readThemeAssetBytes(registered), null);
+ }
+
+ assert.match(runtimeSrc, /resolvePackageThemeAssetPath\(pluginPath,\s*normalized\)/);
+ assert.match(runtimeSrc, /resolvePackageThemeAssetPath\(loaded\.path,\s*normalized\)/);
+ assert.match(runtimeSrc, /themeAssetGroupWithinBudget\(loaded\.path, group\)/);
+ const assetProtocolSrc = readFileSync(join(desktopRoot, "electron/main/plugin-asset-protocol.ts"), "utf8");
+ assert.match(assetProtocolSrc, /PluginAssetResolver = .*Uint8Array \| null/);
+ assert.doesNotMatch(assetProtocolSrc, /readFileSync/);
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
diff --git a/crates/host-core/src/plugins/tests.rs b/crates/host-core/src/plugins/tests.rs
index 5f6f74c00..db926bc0a 100644
--- a/crates/host-core/src/plugins/tests.rs
+++ b/crates/host-core/src/plugins/tests.rs
@@ -839,80 +839,244 @@ fn theme_contributions_require_permission_and_css() {
}
#[test]
-fn theme_assets_are_absolute_paths_on_the_whitelist() {
+fn theme_assets_accept_package_relative_and_absolute_whitelisted_paths() {
let dir = tempdir().unwrap();
- // A theme asset is an absolute path, so the files live outside the plugin package.
- let art = dir.path().join("shared/art");
- std::fs::create_dir_all(&art).unwrap();
- std::fs::write(art.join("bg.png"), "png").unwrap();
- let font_dir = dir.path().join("shared/font");
- std::fs::create_dir_all(&font_dir).unwrap();
- std::fs::write(font_dir.join("ui.woff2"), "woff").unwrap();
- let bg = art.join("bg.png").to_string_lossy().replace('\\', "/");
- let font = font_dir
- .join("ui.woff2")
+ let package = dir.path().join("package");
+ write_plugin(
+ &package,
+ capability_manifest(
+ json!({ "themes": [{
+ "id": "a", "label": "A", "path": "themes/a.css",
+ "assets": ["art/bg.png", "fonts/ui.woff2"]
+ }] }),
+ json!(["ui.theme"]),
+ ),
+ &[
+ ("themes/a.css", ":root {}"),
+ ("art/bg.png", "png"),
+ ("fonts/ui.woff2", "woff"),
+ ],
+ );
+ assert!(PluginManager::read_manifest(&package).is_ok());
+
+ // Prefix and separator normalization produce one package-relative key.
+ let duplicate = dir.path().join("duplicate");
+ write_plugin(
+ &duplicate,
+ capability_manifest(
+ json!({ "themes": [{
+ "id": "a", "label": "A", "path": "themes/a.css",
+ "assets": ["art/bg.png", ".\\art\\bg.png"]
+ }] }),
+ json!(["ui.theme"]),
+ ),
+ &[("themes/a.css", ":root {}"), ("art/bg.png", "png")],
+ );
+ assert!(read_manifest_err(&duplicate).contains("twice"));
+
+ // Absolute filesystem paths and their legacy file: spellings remain valid.
+ let shared = dir.path().join("shared");
+ fs::create_dir_all(&shared).unwrap();
+ fs::write(shared.join("outside.png"), "png").unwrap();
+ fs::write(shared.join("font.woff2"), "woff").unwrap();
+ let image = shared
+ .join("outside.png")
.to_string_lossy()
.replace('\\', "/");
-
- // No longer assets: package-relative spellings, escapes, a wrong extension.
- for (name, asset) in [
- ("relative", "art/bg.png".to_string()),
- ("dot-relative", "./art/bg.png".to_string()),
- ("escape", "../bg.png".to_string()),
- ("traversal", format!("{bg}/../bg.png")),
- ("wrong-ext", bg.replace(".png", ".gif")),
+ let font = shared
+ .join("font.woff2")
+ .to_string_lossy()
+ .replace('\\', "/");
+ let spaced_font = shared.join("font folder/ui font.woff2");
+ fs::create_dir_all(spaced_font.parent().unwrap()).unwrap();
+ fs::write(&spaced_font, "woff").unwrap();
+ let encoded_font_url = format!(
+ "FILE://{}",
+ spaced_font
+ .to_string_lossy()
+ .replace('\\', "/")
+ .replace(' ', "%20")
+ );
+ let absolute = dir.path().join("absolute");
+ write_plugin(
+ &absolute,
+ capability_manifest(
+ json!({ "themes": [{
+ "id": "a", "label": "A", "path": "themes/a.css",
+ "assets": [image, format!("file://{font}"), encoded_font_url]
+ }] }),
+ json!(["ui.theme"]),
+ ),
+ &[("themes/a.css", ":root {}")],
+ );
+ assert!(PluginManager::read_manifest(&absolute).is_ok());
+
+ for (name, asset, expected_error) in [
+ ("missing", "art/missing.png".to_string(), "asset missing"),
+ (
+ "escape",
+ "../outside.png".to_string(),
+ "package-relative or absolute image or font path on the whitelist",
+ ),
+ (
+ "traversal",
+ "art/../outside.png".to_string(),
+ "package-relative or absolute image or font path on the whitelist",
+ ),
+ (
+ "absolute-traversal",
+ format!("{image}/../outside.png"),
+ "package-relative or absolute image or font path on the whitelist",
+ ),
+ (
+ "node-modules",
+ "node_modules/pkg/image.png".to_string(),
+ "package-relative or absolute image or font path on the whitelist",
+ ),
+ (
+ "empty-segment",
+ "art//bg.png".to_string(),
+ "package-relative or absolute image or font path on the whitelist",
+ ),
+ (
+ "dot-segment",
+ "art/./bg.png".to_string(),
+ "package-relative or absolute image or font path on the whitelist",
+ ),
+ (
+ "scheme",
+ "https://example.test/image.png".to_string(),
+ "package-relative or absolute image or font path on the whitelist",
+ ),
+ (
+ "colon",
+ "art:image.png".to_string(),
+ "package-relative or absolute image or font path on the whitelist",
+ ),
+ (
+ "wrong-ext",
+ "art/bg.gif".to_string(),
+ "package-relative or absolute image or font path on the whitelist",
+ ),
] {
let root = dir.path().join(name);
write_plugin(
&root,
capability_manifest(
- json!({ "themes": [{ "id": "a", "label": "A", "path": "themes/a.css", "assets": [asset] }] }),
+ json!({ "themes": [{
+ "id": "a", "label": "A", "path": "themes/a.css", "assets": [asset]
+ }] }),
json!(["ui.theme"]),
),
&[("themes/a.css", ":root {}")],
);
- assert!(
- read_manifest_err(&root).contains("absolute image or font path"),
- "{name} was accepted"
- );
+ let error = read_manifest_err(&root);
+ assert!(error.contains(expected_error), "{name}: {error}");
}
+}
- // An absolute path that is simply not there.
- let missing = dir.path().join("missing");
+#[test]
+fn package_relative_theme_asset_budget_is_enforced_across_files() {
+ let dir = tempdir().unwrap();
+ let root = dir.path().join("budget");
write_plugin(
- &missing,
+ &root,
capability_manifest(
- json!({ "themes": [{ "id": "a", "label": "A", "path": "themes/a.css", "assets": [format!("{bg}.gone.png")] }] }),
+ json!({ "themes": [{
+ "id": "a", "label": "A", "path": "themes/a.css",
+ "assets": ["art/first.webp", "art/second.webp"]
+ }] }),
json!(["ui.theme"]),
),
&[("themes/a.css", ":root {}")],
);
- assert!(read_manifest_err(&missing).contains("asset missing"));
+ fs::create_dir_all(root.join("art")).unwrap();
+ let first = root.join("art/first.webp");
+ let second = root.join("art/second.webp");
+ fs::write(&first, vec![b'x'; 2 * 1024 * 1024]).unwrap();
+ fs::write(&second, vec![b'x'; 2 * 1024 * 1024]).unwrap();
+ assert!(PluginManager::read_manifest(&root).is_ok());
+
+ fs::write(&second, vec![b'x'; 2 * 1024 * 1024 + 1]).unwrap();
+ assert!(read_manifest_err(&root).contains("assets exceed 4194304 bytes"));
+}
- // Two spellings of one file are one asset.
- let duplicated = dir.path().join("duplicated");
+#[cfg(unix)]
+#[test]
+fn package_relative_theme_assets_cannot_escape_through_symlinks() {
+ let dir = tempdir().unwrap();
+ let root = dir.path().join("plugin");
write_plugin(
- &duplicated,
+ &root,
capability_manifest(
- json!({ "themes": [{ "id": "a", "label": "A", "path": "themes/a.css", "assets": [bg.clone(), format!("file://{bg}")] }] }),
+ json!({ "themes": [{
+ "id": "a", "label": "A", "path": "themes/a.css", "assets": ["art/escape.webp"]
+ }] }),
json!(["ui.theme"]),
),
&[("themes/a.css", ":root {}")],
);
- assert!(read_manifest_err(&duplicated).contains("twice"));
+ let art = root.join("art");
+ fs::create_dir_all(&art).unwrap();
+ let outside = dir.path().join("outside.webp");
+ fs::write(&outside, "image").unwrap();
+ std::os::unix::fs::symlink(&outside, art.join("escape.webp")).unwrap();
- // Absolute paths, including the file: spelling, are accepted.
- let ok = dir.path().join("ok");
- write_plugin(
- &ok,
- capability_manifest(
- json!({ "themes": [{ "id": "a", "label": "A", "path": "themes/a.css", "assets": [bg.clone(), format!("file://{font}")] }] }),
- json!(["ui.theme"]),
- ),
- &[("themes/a.css", ":root {}")],
- );
- assert!(PluginManager::read_manifest(&ok).is_ok());
+ assert!(read_manifest_err(&root).contains("resolves outside the plugin package"));
+}
+
+#[test]
+fn install_from_package_accepts_a_package_relative_theme_asset() {
+ with_local_market(|| {
+ let dir = tempdir().unwrap();
+ let manifest = json!({
+ "schemaVersion": 1,
+ "id": "demo.theme-pack",
+ "name": "Theme Pack",
+ "version": "0.1.0",
+ "main": "main.js",
+ "contributes": {
+ "themes": [{
+ "id": "sunset",
+ "label": "Sunset",
+ "path": "themes/sunset.css",
+ "assets": ["art/preview.png"]
+ }]
+ },
+ "permissions": ["ui.theme"]
+ });
+ let package = make_zip(&[
+ (
+ "theme-pack/manifest.json",
+ &serde_json::to_vec(&manifest).unwrap(),
+ ),
+ ("theme-pack/main.js", b"export function onLoad() {}"),
+ ("theme-pack/themes/sunset.css", b":root {}"),
+ ("theme-pack/art/preview.png", b"png"),
+ ]);
+ let package_path = dir.path().join("theme-pack.piplug");
+ fs::write(&package_path, package).unwrap();
+
+ let mut manager = PluginManager::new(dir.path(), MarketChannel::Official, None);
+ let installed = manager
+ .install_from_package(
+ package_path.to_str().unwrap(),
+ InstallOptions {
+ source: "installed".into(),
+ enable: true,
+ marketplace: None,
+ expected_shasum: None,
+ auto_update: false,
+ granted_permissions: None,
+ },
+ )
+ .unwrap();
+
+ assert_eq!(installed.plugin.id, "demo.theme-pack");
+ let install_root = Path::new(installed.plugin.path.as_deref().unwrap());
+ assert!(install_root.join("art/preview.png").is_file());
+ });
}
#[test]
diff --git a/crates/host-core/src/plugins/validation.rs b/crates/host-core/src/plugins/validation.rs
index ccdc041a5..8866ffc74 100644
--- a/crates/host-core/src/plugins/validation.rs
+++ b/crates/host-core/src/plugins/validation.rs
@@ -379,15 +379,27 @@ pub(crate) fn validate_contributions(root: &Path, manifest: &PluginManifest) ->
})?;
let normalized = normalize_theme_asset_path(raw).ok_or_else(|| {
anyhow!(
- "PLUGIN_INVALID: theme {id} asset {raw} must be an absolute image or font path"
+ "PLUGIN_INVALID: theme {id} asset {raw} must be a package-relative or absolute image or font path on the whitelist"
)
})?;
if seen_assets.contains(&normalized) {
bail!("PLUGIN_INVALID: theme {id} declares asset {raw} twice");
}
- // A theme asset is an absolute path: the plugin names the file and the
- // host serves it, so there is nothing to resolve against the package root.
- let resolved = std::path::Path::new(&normalized);
+ let resolved = if is_absolute_theme_asset_path(&normalized) {
+ std::path::PathBuf::from(&normalized)
+ } else {
+ let joined = safe_join(root, &normalized)?;
+ let package_root = root.canonicalize().map_err(|_| {
+ anyhow!("PLUGIN_INVALID: plugin package root cannot be resolved")
+ })?;
+ let asset_path = joined.canonicalize().map_err(|_| {
+ anyhow!("PLUGIN_INVALID: theme {id} asset missing: {raw}")
+ })?;
+ if !asset_path.starts_with(&package_root) {
+ bail!("PLUGIN_INVALID: theme {id} asset {raw} resolves outside the plugin package");
+ }
+ asset_path
+ };
let metadata = resolved
.metadata()
.map_err(|_| anyhow!("PLUGIN_INVALID: theme {id} asset missing: {raw}"))?;
@@ -694,33 +706,55 @@ fn require_permission(manifest: &PluginManifest, permission: &str, what: &str) -
bail!("PLUGIN_INVALID: {what} require the {permission} permission")
}
-/// Extensions a theme may reference out of its own package (ADR 0247).
+/// Extensions a theme may reference from its own package or an absolute path (ADR 0288).
const THEME_ASSET_EXTENSIONS: [&str; 7] = ["png", "jpg", "jpeg", "webp", "avif", "svg", "woff2"];
/// Declared assets of one theme, summed.
const THEME_ASSET_MAX_BYTES: u64 = 4 * 1024 * 1024;
-/// Mirrors `normalizeThemeAssetPath` in the plugin SDK: a forward-slash
-/// **absolute** path on the extension whitelist, or `None`.
+/// Mirrors `normalizeThemeAssetPath` in the plugin SDK: a normalized package-relative
+/// or absolute path on the extension whitelist, or `None`.
///
-/// A theme asset always names a file by absolute path (`C:/art/bg.png`,
-/// `/art/bg.png`, or either spelled as a `file:` URL). Relative references are
-/// rejected: the host serves theme bytes straight from the filesystem.
+/// Absolute paths and `file:` spellings keep their existing handling. Relative
+/// paths are resolved under the plugin root by the caller.
fn normalize_theme_asset_path(value: &str) -> Option<String> {
let raw = value.trim();
- let without_scheme = match raw.strip_prefix("file://") {
- Some(rest) => rest,
- None => raw.strip_prefix("file:").unwrap_or(raw),
+ let file_url_path = if raw
+ .get(..7)
+ .is_some_and(|scheme| scheme.eq_ignore_ascii_case("file://"))
+ {
+ Some(&raw[7..])
+ } else if raw
+ .get(..5)
+ .is_some_and(|scheme| scheme.eq_ignore_ascii_case("file:"))
+ {
+ Some(&raw[5..])
+ } else {
+ None
+ };
+ let without_scheme = match file_url_path {
+ Some(path) => decode_theme_file_url_path(path)?,
+ None => raw.to_string(),
};
let normalized = without_scheme.replace('\\', "/");
// `file:///C:/art/bg.png` and `file:///art/bg.png` both lose the extra slash
// the authority marker leaves behind; a drive letter is written without it.
- let path = match normalized.strip_prefix('/') {
+ let mut path = match normalized.strip_prefix('/') {
Some(rest) if is_windows_drive_path(rest) => rest.to_string(),
_ => normalized,
};
if !is_absolute_theme_asset_path(&path) {
- return None;
+ path = path.strip_prefix("./").unwrap_or(&path).to_string();
+ if path.contains(':')
+ || path.split('/').any(|segment| {
+ segment.is_empty()
+ || segment == "."
+ || segment == ".."
+ || segment.eq_ignore_ascii_case("node_modules")
+ })
+ {
+ return None;
+ }
}
if path
.split('/')
@@ -735,6 +769,33 @@ fn normalize_theme_asset_path(value: &str) -> Option<String> {
Some(path)
}
+fn decode_theme_file_url_path(value: &str) -> Option<String> {
+ let bytes = value.as_bytes();
+ let mut decoded = Vec::with_capacity(bytes.len());
+ let mut index = 0;
+ while index < bytes.len() {
+ if bytes[index] == b'%' {
+ let high = theme_asset_hex_value(*bytes.get(index + 1)?)?;
+ let low = theme_asset_hex_value(*bytes.get(index + 2)?)?;
+ decoded.push((high << 4) | low);
+ index += 3;
+ } else {
+ decoded.push(bytes[index]);
+ index += 1;
+ }
+ }
+ String::from_utf8(decoded).ok()
+}
+
+fn theme_asset_hex_value(byte: u8) -> Option<u8> {
+ match byte {
+ b'0'..=b'9' => Some(byte - b'0'),
+ b'a'..=b'f' => Some(byte - b'a' + 10),
+ b'A'..=b'F' => Some(byte - b'A' + 10),
+ _ => None,
+ }
+}
+
/// `C:/…` — a Windows drive path after forward-slash normalization.
fn is_windows_drive_path(value: &str) -> bool {
let bytes = value.as_bytes();
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 05a488d4a..a04ae2541 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2731,12 +2731,12 @@ identify the platform validation still needed.
#### E2E-024J: Plugin theme applies and falls back when withdrawn
-- **Preconditions**: `examples/plugins/hello` enabled with `ui.theme` granted; a plugin whose CSS uses `@import` or a remote `url()` available for the rejection case, plus a variant of it that only names those tokens inside a comment; a third variant whose theme declares an image asset and a `windowAppearance` background, with and without `ui.window.appearance`.
-- **Steps**: 1) Open Settings → General → Theme and pick `Hello Midnight`. 2) Restart the app. 3) Disable the providing plugin. 4) Re-enable it, then uninstall it. 5) Load the plugin with unsafe CSS. 6) Load the comment-only variant. 7) Select the asset variant's theme on Windows/Linux and on macOS, and check the panel opened from that plugin. 8) Deselect its theme after removing `ui.window.appearance`.
-- **Expected**: The plugin theme appears in the picker alongside the built-ins and applies immediately; the choice survives restart as `plugin:demo.hello:midnight`; disabling or uninstalling the provider falls back to `system` instead of an unstyled shell; unsafe CSS is refused at load with the reason logged and no `<style>` element injected; the comment-only sheet loads and contributes its theme, because the sanitizer only inspects CSS the browser would apply; the declared asset paints through `plugin-asset:` in the shell and in the plugin's own panel, an undeclared reference is refused with the reason logged, the declared background colours the native window on Windows/Linux and is never sent on macOS, and deselecting the theme or dropping the grant returns the window to the host background; the whole shell follows the theme, including the work-panel column, its header, and the browser/file viewer strips, all of which read `--ds-bg-dock` / `--ds-bg-dock-raised` rather than a literal.
-- **Specs linked**: `07-plugins/04-plugin-security.md` §3.1, `04-ux/07-ui-design-system.md`, D175
+- **Preconditions**: A marketplace/package-installable `examples/plugins/hello` variant (`demo.hello`) whose `midnight` theme CSS references a declared package-relative image at `art/preview.png`; a plugin with CSS using `@import` or remote `url()` for rejection plus a comment-only variant; an asset theme with `windowAppearance` variants with and without `ui.window.appearance`.
+- **Steps**: 1) Install the packaged Hello variant from Marketplace or its `.piplug` package and select `Hello Midnight` in Settings → General → Theme. 2) Restart the app. 3) Disable the providing plugin. 4) Re-enable it, then uninstall it. 5) Load the plugin with unsafe CSS. 6) Load the comment-only variant. 7) Select the asset variant's theme on Windows/Linux and on macOS, verify the package-relative image renders through `plugin-asset:` in the shell and the plugin's panel, and load a sheet with an undeclared package-relative `url()` to verify it is refused. 8) Deselect its theme after removing `ui.window.appearance`.
+- **Expected**: The packaged plugin installs successfully with its relative image resolved inside the plugin root; its theme appears in the picker alongside the built-ins and applies immediately, with the image served through `plugin-asset:`; the choice survives restart as `plugin:demo.hello:midnight`; disabling or uninstalling the provider falls back to `system` instead of an unstyled shell; unsafe CSS is refused at load with the reason logged and no `<style>` element injected; the comment-only sheet loads and contributes its theme, because the sanitizer only inspects CSS the browser would apply; the declared asset paints through `plugin-asset:` in the shell and in the plugin's own panel, an undeclared reference is refused with the reason logged, the declared background colours the native window on Windows/Linux and is never sent on macOS, and deselecting the theme or dropping the grant returns the window to the host background; the whole shell follows the theme, including the work-panel column, its header, and the browser/file viewer strips, all of which read `--ds-bg-dock` / `--ds-bg-dock-raised` rather than a literal.
+- **Specs linked**: `07-plugins/02-plugin-manifest-schema.md`, `07-plugins/04-plugin-security.md` §3.1, `04-ux/07-ui-design-system.md`, D175
- **Acceptance**: G (theme contribution) + Security
-- **Status**: Unit-covered (`plugin-themes.test.mjs`, `theme-css` SDK tests); visual scenario Draft
+- **Status**: Unit-covered (`plugin-themes.test.mjs`, `theme-css` SDK tests, host-core package-relative asset/install tests); visual scenario Draft
#### E2E-PLUGIN-runtime-theme-apis
diff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.md
index aef30b3d5..a57370705 100644
--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md
+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md
@@ -215,7 +215,8 @@ type PluginThemeContrib = {
label: string;
path: string; // relative `.css` file
base?: "light" | "dark"; // palette the overrides layer on, default `dark`
- assets?: string[]; // absolute png/jpg/jpeg/webp/avif/svg/woff2, 4 MB summed;
+ assets?: string[]; // package-relative or absolute png/jpg/jpeg/webp/avif/svg/woff2, 4 MB summed;
+ // relative paths resolve inside plugin root; traversal/node_modules are rejected;
// each matching `url()` is rewritten to `plugin-asset://`
};
diff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.md
index 254122ee9..f9ca2221a 100644
--- a/docs/spec/07-plugins/04-plugin-security.md
+++ b/docs/spec/07-plugins/04-plugin-security.md
@@ -98,17 +98,19 @@ before it is ever sent to the UI:
points at the source, and each `url(...)` argument is kept verbatim and judged
by its target. A sheet that merely *mentions* a banned token in a comment or a
string is therefore accepted
-- Rejected: `@import`, any `url()` target that is not a `data:` URI, a `url(`
- the parser cannot resolve, `javascript:`, `expression(`, and markup sequences
- (`<style`, `</style`, `<!--`); an empty sheet is refused too
+- Rejected: `@import`, any `url()` target that is neither a `data:` URI nor a
+ declared theme asset, a `url(` the parser cannot resolve, `javascript:`,
+ `expression(`, and markup sequences (`<style`, `</style`, `<!--`); an empty
+ sheet is refused too
- Capped at 256KB per file, 8 themes per plugin
-- A theme may declare `assets` (absolute paths, whitelisted image and font
- extensions, 4MB summed). Each matching `url()` is rewritten to
- `plugin-asset://<pluginId>/<path>` and served by a host handler that resolves
- only through the loaded plugin's own registered list: read-only, `nosniff`,
- and revoked when the plugin unloads. `pi.themes.upsert` registers the same
- kind of path at runtime. An unregistered reference is still refused, and the
- raw path never reaches the renderer
+- A theme may declare `assets` using whitelisted image/font extensions: either
+ package-relative paths (resolved inside the plugin root; traversal and `node_modules`
+ references are rejected) or absolute paths. The total is capped at 4MB.
+ Each matching `url()` is rewritten to `plugin-asset://<pluginId>/<path>`
+ and served read-only through the loaded plugin's registered list with `nosniff`;
+ the registration is revoked when the plugin unloads. `pi.themes.upsert` may
+ register the same kind of path at runtime. An unregistered reference is refused,
+ and the raw path never reaches the renderer
- `contributes.windowAppearance` (`#rrggbb` / `#rrggbbaa`) requires
`ui.window.appearance` and applies only while one of that plugin's themes is
the selected one; leaving the theme restores the host background, because the
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 2953c5522..194cd60cb 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -1376,12 +1376,12 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备
#### E2E-024J:插件主题适用并在撤回时回退
-- **先决条件**:在授予 `ui.theme` 的情况下启用 `examples/plugins/hello`; CSS 使用 `@import` 或远程 `url()` 可用于拒绝情况的插件,以及只在注释里提到这些关键字的同一插件变体;第三个变体的主题声明了图片资源与 `windowAppearance` 背景,并提供有/无 `ui.window.appearance` 两种版本。
-- **步骤**: 1) 打开设置 → 常规 → 主题并选择 `Hello Midnight`。 2)重新启动应用程序。 3) 禁用提供的插件。 4)重新启用它,然后卸载它。 5) 使用不安全的 CSS 加载插件。 6) 加载只在注释里提到关键字的变体。 7) 在 Windows/Linux 与 macOS 上分别选中资源变体的主题,并检查该插件打开的面板。 8) 去掉 `ui.window.appearance` 后取消选中该主题。
-- **预期**:插件主题与内置插件一起出现在选择器中并立即应用;该选择在重新启动后仍保留为 `plugin:demo.hello:midnight`;禁用或卸载提供程序会退回到 `system` 而不是无样式的 shell;不安全的 CSS 在加载时被拒绝,并记录了原因,并且没有注入 `<style>` 元素;只在注释里提到关键字的样式表正常加载并提供其主题,因为消毒器只检查浏览器实际生效的 CSS;声明的资源在宿主外壳与该插件自己的面板中都经 `plugin-asset:` 渲染,未声明的引用被拒绝并记录原因,声明的背景在 Windows/Linux 上给原生窗口着色、在 macOS 上不下发,取消选中该主题或收回该权限后窗口回到宿主背景;整个外壳都跟随主题,包括工作面板列、其标题栏以及浏览器/文件查看器条目栏 —— 它们的表面色读 `--ds-bg-dock` / `--ds-bg-dock-raised`,而不是字面量。
-- **链接规格**:`07-plugins/04-plugin-security.md` §3.1、`04-ux/07-ui-design-system.md`、D175
+- **先决条件**:可从市场或 `.piplug` 包安装的 `examples/plugins/hello` 变体(`demo.hello`),其 `midnight` 主题 CSS 引用已声明的包内相对图片 `art/preview.png`;CSS 使用 `@import` 或远程 `url()` 的拒绝用插件及仅在注释中出现这些关键字的变体;另有声明图片资源和 `windowAppearance` 背景、分别带/不带 `ui.window.appearance` 权限的主题变体。
+- **步骤**:1) 从市场安装 Hello 包变体或导入其 `.piplug` 包,在设置 → 常规 → 主题中选择 `Hello Midnight`。2) 重启应用。3) 禁用提供主题的插件。4) 重新启用后卸载。5) 加载不安全 CSS 插件。6) 加载仅在注释中提到关键字的变体。7) 在 Windows/Linux 与 macOS 上选中资源变体主题,验证包内相对图片通过 `plugin-asset:` 在外壳和插件面板中渲染,并加载引用未声明相对资源的样式表以验证其被拒绝。8) 去掉 `ui.window.appearance` 后取消选中该主题。
+- **预期**:带包内相对图片的插件包成功安装,图片在插件根目录内解析;插件主题出现在选择器中并立即应用,图片通过 `plugin-asset:` 提供;选择在重启后仍保留为 `plugin:demo.hello:midnight`;禁用或卸载提供程序会退回到 `system` 而不是无样式的 shell;不安全 CSS 在加载时被拒绝并记录原因,且不注入 `<style>` 元素;仅在注释中提到关键字的样式表正常加载并提供主题,因为消毒器只检查浏览器实际生效的 CSS;声明的资源在宿主外壳与插件自己的面板中都经 `plugin-asset:` 渲染,未声明引用被拒绝并记录原因,声明的背景在 Windows/Linux 上给原生窗口着色、在 macOS 上不下发;取消选中主题或收回权限后窗口回到宿主背景;整个外壳都跟随主题,包括工作面板列、标题栏以及浏览器/文件查看器条目栏,其表面色读取 `--ds-bg-dock` / `--ds-bg-dock-raised` 而不是字面量。
+- **链接规格**:`07-plugins/02-plugin-manifest-schema.md`、`07-plugins/04-plugin-security.md` §3.1、`04-ux/07-ui-design-system.md`、D175
- **接受**:G(主题贡献)+安全
-- **状态**:单位覆盖(`plugin-themes.test.mjs`、`theme-css` SDK 测试);视觉场景草稿
+- **状态**:单元覆盖(`plugin-themes.test.mjs`、`theme-css` SDK 测试、host-core 包内相对资源/安装测试);视觉场景草稿
#### E2E-024K:插件 MCP 服务器工具到达代理
diff --git a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md
index 79abb088c..37251cee1 100644
--- a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md
+++ b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md
@@ -183,8 +183,9 @@ type PluginThemeContrib = {
label: string;
path: string; // relative `.css` file
base?: "light" | "dark"; // palette the overrides layer on, default `dark`
- assets?: string[]; // 绝对路径的 png/jpg/jpeg/webp/avif/svg/woff2,总和上限 4 MB;
- // 命中的 `url()` 会被改写为 `plugin-asset://`
+ assets?: string[]; // 插件包内相对路径或绝对路径;png/jpg/jpeg/webp/avif/svg/woff2 白名单,总和上限 4 MB;
+ // 相对路径在插件根目录内解析,拒绝路径穿越和 `node_modules`;
+ // 命中的 `url()` 改写为 `plugin-asset://`
};
type PluginWindowAppearanceContrib = {
diff --git a/docs/zh-CN/spec/07-plugins/04-plugin-security.md b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
index b137d01a6..ed83393f6 100644
--- a/docs/zh-CN/spec/07-plugins/04-plugin-security.md
+++ b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
@@ -56,14 +56,15 @@
- 只检查浏览器实际生效的 CSS:先按等长空白遮蔽注释体与字符串字面量
(每个被遮蔽字符对应一个空格,偏移仍指向原文),`url(...)` 参数按原样保留
并按目标判定。因此仅在注释或字符串里*提到*被禁关键字的样式表会被接受
-- 拒绝:`@import`、任何不是 `data:` 的 `url()` 目标 URI、`url(`
- 解析器无法解析 `javascript:`、`expression(` 和标记序列
- (`<style`、`</style`、`<!--`);空纸也会被拒绝
+- 拒绝:`@import`、既非 `data:` URI 也非已声明主题资源的 `url()` 目标、
+ 解析器无法解析的 `url(`、`javascript:`、`expression(` 和标记序列
+ (`<style`、`</style`、`<!--`);空样式表也会被拒绝
- 每个文件上限为 256KB,每个插件 8 个主题
-- 主题可声明 `assets`(绝对路径、扩展名白名单、总量上限 4MB)。命中的 `url()`
- 会被改写为 `plugin-asset://<pluginId>/<path>`,由宿主的处理器提供;该处理器
+- 主题可声明 `assets`,使用白名单图片/字体扩展名:插件包内相对路径(在插件根目录内解析,拒绝
+ 路径穿越和 `node_modules`)或绝对路径;所有资源总量上限为 4MB。命中的 `url()`
+ 会被改写为 `plugin-asset://<pluginId>/<path>`,由宿主处理器提供;该处理器
只按已加载插件自己登记的清单解析,只读、带 `nosniff`,并在插件卸载时一并撤销。
- `pi.themes.upsert` 也能在运行时登记同样的路径。未登记的引用仍被拒绝,
+ `pi.themes.upsert` 也可在运行时登记同类路径。未登记的引用仍会被拒绝,
原始路径不会到达渲染器
- `contributes.windowAppearance`(`#rrggbb` / `#rrggbbaa`)需要
`ui.window.appearance`,且只在该插件的某个主题被选中时生效;离开该主题即恢复
diff --git a/packages/plugin-sdk/src/theme-css.test.ts b/packages/plugin-sdk/src/theme-css.test.ts
index 383680097..1eae363b5 100644
--- a/packages/plugin-sdk/src/theme-css.test.ts
+++ b/packages/plugin-sdk/src/theme-css.test.ts
@@ -240,10 +240,14 @@ describe("theme assets", () => {
}
});
- it("builds host urls for package-relative and absolute paths", () => {
+ it("builds host URLs for package-relative and absolute paths", () => {
expect(themeAssetUrl("demo.hello", ASSET)).toBe(
`plugin-asset://demo.hello/${ASSET}`,
);
+ const special = "assets/bg#night?.png";
+ const url = themeAssetUrl("demo.hello", special);
+ expect(url).toBe("plugin-asset://demo.hello/assets/bg%23night%3F.png");
+ expect(decodeURIComponent(new URL(url).pathname.slice(1))).toBe(special);
expect(themeAssetUrl("demo.hello", "C:/art/bg.png")).toBe(
`plugin-asset://demo.hello/${encodeURIComponent("C:/art/bg.png")}`,
);
diff --git a/packages/plugin-sdk/src/theme-css.ts b/packages/plugin-sdk/src/theme-css.ts
index fad722f57..60ba4b510 100644
--- a/packages/plugin-sdk/src/theme-css.ts
+++ b/packages/plugin-sdk/src/theme-css.ts
@@ -44,12 +44,16 @@ const THEME_ASSET_EXTENSION_PATTERN = new RegExp(
/**
* `plugin-asset://<pluginId>/<assetPath>` — how a theme reaches its bytes.
*
- * Package-relative keys are written directly. Absolute filesystem keys are
- * percent-encoded so drive colons and URL delimiters cannot change the lookup.
+ * Package-relative path segments are encoded independently so `/` stays a
+ * separator and URL delimiters such as `?` and `#` remain part of the filename.
+ * Absolute filesystem keys are encoded as a whole so drive colons cannot alter
+ * lookup.
*/
export function themeAssetUrl(pluginId: string, assetPath: string): string {
const normalized = normalizeThemeAssetPath(assetPath);
- const key = isExternalThemeAssetPath(normalized) ? encodeURIComponent(normalized) : normalized;
+ const key = isExternalThemeAssetPath(normalized)
+ ? encodeURIComponent(normalized)
+ : normalized.split("/").map(encodeURIComponent).join("/");
return `${THEME_ASSET_SCHEME}://${pluginId}/${key}`;
}