feat(skin): bridge trusted plugin actions

This commit is contained in:
illusia committed 2026-10-10 15:53:50 +08:00
1 parent 1aa29158ef
commit 35cb6ad6df
13 files changed
+276 -45

No files matched your search

+20 -3
View File
@@ -3,7 +3,7 @@ import type { SkinExtensionSessionStatus } from "../../../src/shared/skin-extens
import { computeSkinRuntimePluginDigest, createSkinRuntimePluginApproval, isSkinRuntimePluginApproved, type SkinRuntimePluginApproval } from "../../../src/shared/skin-runtime-plugin-approval.js";
import type { SkinRuntimePlugin, SkinRuntimePluginDocument, SkinRuntimePluginPage } from "../../../src/shared/skin-runtime-plugins.js";
import { parseSkinExtensionUiInput, type SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { SKIN_PLUGIN_ACTION_PERMISSIONS, skinPluginActionPermission, type SkinPluginAction, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS } from "../../../src/shared/skin-runtime-plugin-context.js";
import SkinPluginOutlet from "./SkinPluginOutlet.js";
import { approveSkinRuntimePlugin, getSkinRuntimePluginApproval, revokeSkinRuntimePluginApprovals } from "../services/skin-runtime-plugin-approval.js";
@@ -13,7 +13,12 @@ import type { SkinExtensionWasmSandboxHandle } from "../services/skin-extension-
import { resolveSkinCssAssets } from "../services/skin-pack.js";
const EMPTY_DOCUMENT: SkinPluginDocument = { schemaVersion: 3, components: [] };
const SUPPORTED_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS, "ui.surface.replace"]);
const SUPPORTED_PERMISSIONS = new Set([
...SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS,
...SKIN_PLUGIN_ACTION_PERMISSIONS,
"ui.surface.replace",
]);
type HostActionHandler = (args: Record<string, string | number | boolean>) => void | Promise<void>;
type Session = ReturnType<typeof createSkinRuntimePluginSession>;
type RunHandle = { result: Promise<{ uiOutput: string | null }>; close(reason?: string): void };
@@ -85,6 +90,7 @@ export default defineComponent({
assets: { type: Object as PropType<Record<string, Blob>>, default: () => ({}) },
page: { type: String as PropType<SkinRuntimePluginPage>, required: true },
context: { type: Object as PropType<Record<string, unknown>>, default: () => ({}) },
actions: { type: Object as PropType<Partial<Record<SkinPluginAction, HostActionHandler>>>, default: () => ({}) },
readSessionStatus: { type: Function as PropType<(signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>>, required: true },
},
emits: {
@@ -196,6 +202,17 @@ export default defineComponent({
const session = createSkinRuntimePluginSession({
plugin,
createRun: (input) => createRun(props.skinId, props.skinVersion, plugin, grant, props.files, props.context, props.readSessionStatus, input),
onAction: async (action) => {
const permission = skinPluginActionPermission(action.type);
const currentGrant = approved(plugin);
if (!permission || !plugin.permissions.includes(permission) || !currentGrant
|| sessions.get(plugin.id) !== session || disposed) {
throw new Error("The plugin action is no longer approved.");
}
const handler = props.actions[action.type];
if (!handler) throw new Error("The host does not provide this action.");
await handler(action.args);
},
onOutput: () => {
installStyle(plugin);
outputs.value = { ...outputs.value, [plugin.id]: session.output };
@@ -383,7 +400,7 @@ export default defineComponent({
]),
]);
}),
h("p", { class: "ws-plugin-consent-note" }, "当前开发原型支持 Wasm、安全的公开数据读取与 ui.surface.replace;TeamSpeak 写操作仍未接入此运行时。数据字段只按清单中的读取权限投影,授权绑定到此皮肤版本、插件清单和所有插件文件的 SHA-256。/ This development prototype supports Wasm, safe public data reads, and ui.surface.replace; TeamSpeak write actions are not connected to this runtime. Data is projected by the read permissions in the descriptor, and approval is bound to this skin version, descriptor, and every plugin file by SHA-256."),
h("p", { class: "ws-plugin-consent-note" }, "当前开发原型支持 Wasm、权限化公开数据和 ui.surface.replace;已批准的宿主动作只能由可信的明确用户操作触发,并仍由 WebSpeak 校验会话和参数。数据字段只按清单中的读取权限投影,授权绑定到此皮肤版本、插件清单和所有插件文件的 SHA-256。/ This development prototype supports Wasm, permission-filtered public data, and ui.surface.replace. Approved host actions require a trusted explicit user event and are still validated by WebSpeak against the current session and arguments. Data is projected by the read permissions in the descriptor, and approval is bound to this skin version, descriptor, and every plugin file by SHA-256."),
h("div", { class: "ws-plugin-consent-actions" }, showApproval
? [
h("button", { type: "button", class: "secondary", onClick: keepDisabled }, "暂不启用 / Keep disabled"),
@@ -5,6 +5,7 @@ import { renderToString } from "@vue/server-renderer";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { approveSkinPluginComponents } from "./skin-plugin-approval.js";
import {
parseSkinExtensionUiActionRequest,
parseSkinExtensionUiOutput,
SKIN_EXTENSION_UI_OUTPUT_LIMIT_BYTES,
SkinExtensionUiOutputError,
@@ -107,6 +108,35 @@ test("generated UI schema 5 carries bounded state and named callbacks for a trus
assert.equal(component.root.children?.[0].events?.click, "select-server");
});
test("generated UI schema 6 validates one host action against plugin permissions", () => {
const source = JSON.stringify({
schemaVersion: 6,
components: [{
id: "voice-channels",
name: "Voice channels",
page: "voice",
accessibleName: "Voice channels",
state: {},
root: { tag: "button", events: { dblclick: "join" }, children: [{ text: "Join" }] },
}],
request: { type: "voice.joinChannel", args: { channelId: "channel-1" } },
});
const document = parseSkinExtensionUiOutput(source);
assert.equal(document.components[0].runtimeCallbacks, true);
const action = parseSkinExtensionUiActionRequest(source, ["session.channel.join"]);
assert.deepEqual(action && { type: action.type, args: { ...action.args } }, {
type: "voice.joinChannel",
args: { channelId: "channel-1" },
});
assert.throws(() => parseSkinExtensionUiActionRequest(source, []), (error: unknown) =>
error instanceof SkinExtensionUiOutputError && error.code === "SKIN_EXTENSION_UI_ACTION_INVALID");
expectOutputError(JSON.stringify({
schemaVersion: 6,
components: [{ id: "voice-channels", name: "Voice channels", page: "voice", accessibleName: "Voice channels", root: { tag: "main" } }],
request: { type: "voice.joinChannel", args: { channelId: "channel-1", address: "private.example" } },
}), "SKIN_EXTENSION_UI_ACTION_INVALID");
});
test("generated UI callbacks reject unsupported events, malformed IDs, and password inputs", () => {
const schema5 = (root: Record<string, unknown>) => JSON.stringify({
schemaVersion: 5,
@@ -16,7 +16,7 @@ export interface SkinExtensionWasmUiLoopRunHandle {
export interface SkinExtensionWasmUiLoopOptions {
/** Creates one bounded, disposable Wasm job for the supplied UI input. */
createRun(input: SkinExtensionUiInput): SkinExtensionWasmUiLoopRunHandle;
onOutput?(output: string, document: SkinPluginDocument): void | Promise<void>;
onOutput?(output: string, document: SkinPluginDocument, input: SkinExtensionUiInput): void | Promise<void>;
onError?(error: Error): void;
}
@@ -77,7 +77,7 @@ export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWas
const nextDocument = parseSkinExtensionUiOutput(result.uiOutput);
output = result.uiOutput;
document = nextDocument;
await options.onOutput?.(output, nextDocument);
await options.onOutput?.(output, nextDocument, input);
}
return true;
} catch (error) {
@@ -19,6 +19,22 @@ const plugin = parseSkinRuntimePluginDocument({
}],
}).plugins[0];
const joinPlugin = parseSkinRuntimePluginDocument({
schemaVersion: 1,
plugins: [{
id: "voice-join",
name: "Voice join",
version: "1.0.0",
apiVersion: 1,
runtime: "wasm",
page: "voice",
mode: "surface",
entry: "plugins/voice-join/index.wasm",
assets: [],
permissions: ["ui.surface.replace", "session.channel.join"],
}],
}).plugins[0];
function output(page = "voice", count = 1): string {
return JSON.stringify({
schemaVersion: 5,
@@ -33,6 +49,21 @@ function output(page = "voice", count = 1): string {
});
}
function joinOutput(request = false, eventName: "dblclick" | "input" = "dblclick"): string {
return JSON.stringify({
schemaVersion: 6,
components: [{
id: "voice-ui",
name: "Voice UI",
page: "voice",
accessibleName: "Voice workspace",
state: {},
root: { tag: "button", events: { [eventName]: "join" }, children: [{ text: "Join" }] },
}],
...(request ? { request: { type: "voice.joinChannel", args: { channelId: "channel-1" } } } : {}),
});
}
function sessionWithOutput(value: string, onError: (error: Error) => void = () => undefined) {
return createSkinRuntimePluginSession({
plugin,
@@ -67,3 +98,51 @@ test("runtime surface plugins cannot emit competing roots", async () => {
assert.equal((errors[0] as SkinRuntimePluginSessionError).code, "SKIN_RUNTIME_PLUGIN_SURFACE_OUTPUT_INVALID");
assert.equal(session.output, null);
});
test("runtime host actions require an approved permission and a trusted explicit event", async () => {
const actions: Array<{ type: string; args: Record<string, string | number | boolean> }> = [];
const session = createSkinRuntimePluginSession({
plugin: joinPlugin,
createRun: (input) => ({ result: Promise.resolve({ uiOutput: joinOutput(Boolean(input.event)) }), close: () => undefined }),
onAction: (action) => { actions.push({ type: action.type, args: { ...action.args } }); },
});
assert.equal(await session.start(), true);
assert.equal(await session.dispatch({
schemaVersion: 1,
state: {},
event: { componentId: "voice-ui", handlerId: "join", eventName: "dblclick" },
}), true);
assert.deepEqual(actions, [{ type: "voice.joinChannel", args: { channelId: "channel-1" } }]);
session.close();
});
test("runtime host actions reject initial effects, typing events, and permissions absent from the manifest", async () => {
const initialActions: unknown[] = [];
const initial = createSkinRuntimePluginSession({
plugin: joinPlugin,
createRun: () => ({ result: Promise.resolve({ uiOutput: joinOutput(true) }), close: () => undefined }),
onAction: (action) => { initialActions.push(action); },
});
assert.equal(await initial.start(), false);
assert.deepEqual(initialActions, []);
const noJoinPermission = parseSkinRuntimePluginDocument({
schemaVersion: 1,
plugins: [{ ...joinPlugin, id: "voice-readonly", entry: "plugins/voice-readonly/index.wasm", permissions: ["ui.surface.replace"] }],
}).plugins[0];
const deniedActions: unknown[] = [];
const denied = createSkinRuntimePluginSession({
plugin: noJoinPermission,
createRun: (input) => ({ result: Promise.resolve({ uiOutput: joinOutput(Boolean(input.event), "dblclick") }), close: () => undefined }),
onAction: (action) => { deniedActions.push(action); },
});
assert.equal(await denied.start(), true);
assert.equal(await denied.dispatch({
schemaVersion: 1,
state: {},
event: { componentId: "voice-ui", handlerId: "join", eventName: "dblclick" },
}), false);
assert.deepEqual(deniedActions, []);
denied.close();
});
@@ -1,6 +1,7 @@
import type { SkinRuntimePlugin } from "../../../src/shared/skin-runtime-plugins.js";
import type { SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { parseSkinExtensionUiActionRequest } from "../../../src/shared/skin-extension-ui.js";
import type { SkinExtensionUiInput, SkinExtensionUiEventInput } from "../../../src/shared/skin-extension-ui-input.js";
import type { SkinPluginActionDefinition, SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import {
createSkinExtensionWasmUiLoopPrototype,
type SkinExtensionWasmUiLoopRunHandle,
@@ -13,10 +14,22 @@ export class SkinRuntimePluginSessionError extends Error {
}
}
const HOST_ACTION_EVENT_NAMES = new Set(["click", "dblclick", "submit", "keydown", "keyup", "contextmenu", "pointerdown", "pointerup", "drop"]);
function assertExplicitUserActivation(event: SkinExtensionUiEventInput): void {
if (!HOST_ACTION_EVENT_NAMES.has(event.eventName)) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_ACTION_EVENT_INVALID", "Host actions require an explicit user activation event.");
}
if ((event.eventName === "keydown" || event.eventName === "keyup") && !["Enter", " ", "Escape"].includes(event.key ?? "")) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_ACTION_KEY_INVALID", "Host actions may only use Enter, Space, or Escape key events.");
}
}
export interface SkinRuntimePluginSessionOptions {
plugin: SkinRuntimePlugin;
createRun(input: SkinExtensionUiInput): SkinExtensionWasmUiLoopRunHandle;
onOutput?(output: string, document: SkinPluginDocument): void | Promise<void>;
onAction?(action: SkinPluginActionDefinition, event: SkinExtensionUiEventInput): void | Promise<void>;
onError?(error: Error): void;
}
@@ -25,13 +38,24 @@ export function createSkinRuntimePluginSession(options: SkinRuntimePluginSession
let output: string | null = null;
const loop = createSkinExtensionWasmUiLoopPrototype({
createRun: options.createRun,
onOutput: async (nextOutput, document) => {
onOutput: async (nextOutput, document, input) => {
if (document.components.some((component) => component.page !== options.plugin.page)) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_PAGE_MISMATCH", "Generated UI must stay on the page declared by its plugin.");
}
if (options.plugin.mode === "surface" && document.components.length !== 1) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_SURFACE_OUTPUT_INVALID", "A surface plugin must generate exactly one root component.");
}
const action = parseSkinExtensionUiActionRequest(nextOutput, options.plugin.permissions);
if (action) {
if (!input.event) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_ACTION_WITHOUT_EVENT", "A host action can only follow a trusted UI event.");
}
assertExplicitUserActivation(input.event);
if (!options.onAction) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_ACTION_UNAVAILABLE", "The host action bridge is unavailable.");
}
await options.onAction(action, input.event);
}
output = nextOutput;
await options.onOutput?.(nextOutput, document);
},
@@ -48,7 +48,7 @@ test("Wasm plugin startup rechecks the exact digest approval before creating a W
}), (error: unknown) => error instanceof SkinRuntimePluginWasmError && error.code === "SKIN_EXTENSION_WASM_APPROVAL_INVALID");
});
test("Wasm prototype refuses write permissions that have no host action bridge", async () => {
test("Wasm prototype accepts a host-mediated channel join permission", async () => {
const writePlugin = parseSkinRuntimePluginDocument({
schemaVersion: 1,
plugins: [{ ...plugin, permissions: ["session.channel.join"] }],
@@ -56,16 +56,41 @@ test("Wasm prototype refuses write permissions that have no host action bridge",
const files = { [writePlugin.entry]: new Blob([createSkinExtensionWasmPrefixByteImmediateProbe()]) };
const digest = await computeSkinRuntimePluginDigest(writePlugin, files);
const approval = createSkinRuntimePluginApproval("community.sample", "2.0.0", writePlugin, digest);
await assert.rejects(createSkinRuntimePluginWasmSandboxPrototype({
skinId: "community.sample",
skinVersion: "2.0.0",
plugin: writePlugin,
approval,
files,
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
prototypeOnly: true,
}), (error: unknown) => error instanceof SkinRuntimePluginWasmError
&& error.code === "SKIN_EXTENSION_WASM_PERMISSION_UNSUPPORTED");
const previousWorker = Object.getOwnPropertyDescriptor(globalThis, "Worker");
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
class FakeWorker {
onmessage: ((event: MessageEvent<unknown>) => void) | null = null;
onmessageerror: (() => void) | null = null;
onerror: (() => void) | null = null;
postMessage(): void {
queueMicrotask(() => {
this.onmessage?.({ data: { type: "running" } } as MessageEvent<unknown>);
this.onmessage?.({ data: {
type: "complete", result: 1, linearMemoryBytes: 65_536, statusReadCount: 0, uiInputReadCount: 0, uiOutput: null,
} } as MessageEvent<unknown>);
});
}
terminate(): void { /* The test worker has no external resources. */ }
}
Object.defineProperty(globalThis, "Worker", { configurable: true, value: FakeWorker });
Object.defineProperty(globalThis, "window", { configurable: true, value: { setTimeout, clearTimeout } });
try {
const handle = await createSkinRuntimePluginWasmSandboxPrototype({
skinId: "community.sample",
skinVersion: "2.0.0",
plugin: writePlugin,
approval,
files,
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
prototypeOnly: true,
});
assert.equal((await handle.result).uiOutput, null);
} finally {
if (previousWorker) Object.defineProperty(globalThis, "Worker", previousWorker);
else Reflect.deleteProperty(globalThis, "Worker");
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
}
});
test("approved read permissions project only their public fields into each Wasm job", async () => {
+2 -1
View File
@@ -10,6 +10,7 @@ import {
type SkinRuntimePluginApproval,
} from "../../../src/shared/skin-runtime-plugin-approval.js";
import { parseSkinRuntimePluginDocument, type SkinRuntimePlugin } from "../../../src/shared/skin-runtime-plugins.js";
import { SKIN_PLUGIN_ACTION_PERMISSIONS } from "../../../src/shared/skin-plugin.js";
import { projectSkinRuntimePluginContext, SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS } from "../../../src/shared/skin-runtime-plugin-context.js";
import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
import {
@@ -37,7 +38,7 @@ export interface SkinRuntimePluginWasmOptions {
prototypeOnly: true;
}
const WASM_PROTOTYPE_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS, "ui.surface.replace"]);
const WASM_PROTOTYPE_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS, ...SKIN_PLUGIN_ACTION_PERMISSIONS, "ui.surface.replace"]);
/** Starts a Wasm entry only after rechecking the exact package digest and local approval. */
export async function createSkinRuntimePluginWasmSandboxPrototype(
+1
View File
@@ -34,6 +34,7 @@
:assets="activeSkin.assets"
:page="showVoiceShell ? 'voice' : 'home'"
:context="skinPluginContext"
:actions="skinPluginActions"
:read-session-status="readSkinRuntimeSessionStatus"
@surface-change="skinRuntimePluginSurfaceActive = $event"
@restore-skin="switchToBuiltIn"