feat(skins): add component authoring workflow

This commit is contained in:
illusia committed 2026-10-10 15:53:51 +08:00
1 parent 96c29394f3
commit 0c4cc344ef
25 files changed
+2013 -58

No files matched your search

+31 -1
View File
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { createRenderer, createSSRApp, nextTick } from "vue";
import { renderToString } from "@vue/server-renderer";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { approveSkinPluginComponents } from "./skin-plugin-approval.js";
import {
parseSkinExtensionUiActionRequest,
@@ -556,3 +556,33 @@ test("skin-authored DOM nodes expose independent layout parts and retain touch b
assert.match(html, /data-ws-part="skin\.voice\.voice-toolbar\.control-part-disconnect"/);
assert.match(html, /data-ws-part="skin\.voice\.voice-toolbar\.part-caption"/);
});
test("skin nodes cannot impersonate WebSpeak page and layout hooks", async () => {
const document = parseSkinPluginDocument({
schemaVersion: 3,
components: [{
id: "hook-test",
name: "Hook test",
page: "voice",
accessibleName: "Hook test",
permissions: [],
actions: {},
root: {
tag: "section",
children: [{ tag: "div", attributes: { "data-ws-page": "admin", "data-ws-layout-hidden": true, "data-testid": "safe" } }],
},
}],
});
const html = await renderToString(createSSRApp(SkinPluginOutlet, {
skinId: "community.test",
skinVersion: "1.0.0",
document,
page: "voice",
data: {},
assets: {},
actions: {},
}));
assert.match(html, /data-testid="safe"/);
assert.doesNotMatch(html, /data-ws-page="admin"/);
assert.doesNotMatch(html, /data-ws-layout-hidden=/);
});
+37 -3
View File
@@ -375,7 +375,11 @@ test("schema version 3 accepts a schema v2 full-page surface with host widgets",
});
test("schema version 4 validates and caches isolated plugin package files without executing them", async () => {
const skin = await importSkinPack(makeSkinV4());
const defaultLayout = {
schemaVersion: 1,
pages: { voice: { desktop: { "skin.voice.runtime_plugin_root_voice-toolbar": { order: 2, visible: true } } } },
};
const skin = await importSkinPack(makeSkinV4(undefined, { layout: defaultLayout }));
const entry = "plugins/voice-toolbar/index.js";
const style = "plugins/voice-toolbar/style.css";
const icon = "plugins/voice-toolbar/assets/icon.png";
@@ -389,6 +393,7 @@ test("schema version 4 validates and caches isolated plugin package files withou
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /data-ws-runtime-plugin="voice-toolbar".*?\.toolbar/s);
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /color: teal/);
assert.match(skin.css, /position: fixed/);
assert.deepEqual(skin.layoutData?.pages.voice?.desktop?.["skin.voice.runtime_plugin_root_voice-toolbar"], { order: 2, visible: true });
await assert.rejects(
importSkinPack(makeSkinV4(undefined, { includeEntry: false })),
@@ -526,6 +531,11 @@ test("the Harbor voice skin imports a complete voice-only KOOK-inspired workspac
assert.ok(voiceSurface?.permissions.includes("session.channel.join"));
assert.ok(voiceSurface?.permissions.includes("servers.quickList.switch"));
assert.ok(voiceSurface?.permissions.includes("session.members.read"));
assert.ok(voiceSurface?.permissions.includes("chat.channel.read"));
assert.ok(voiceSurface?.permissions.includes("chat.channel.send"));
assert.ok(voiceSurface?.permissions.includes("audio.microphone.control"));
assert.ok(voiceSurface?.permissions.includes("audio.output.control"));
assert.ok(voiceSurface?.permissions.includes("voice.screenShare.control"));
function findPart(node: SkinPluginNode | undefined, part: string): SkinPluginNode | undefined {
if (!node) return undefined;
if (node.part === part) return node;
@@ -536,11 +546,34 @@ test("the Harbor voice skin imports a complete voice-only KOOK-inspired workspac
return undefined;
}
const channelRow = findPart(voiceSurface?.root, "channel-row");
assert.equal(channelRow?.events?.click, "select-channel", "single-click only selects a channel in this skin");
assert.equal(channelRow?.events?.dblclick, "join-channel", "channel switching follows TeamSpeak's double-click join behavior");
assert.equal(channelRow?.attributes?.["data-depth"], "{{channel.depth}}", "the channel hierarchy is represented without a new host API");
assert.equal(findPart(channelRow, "selected-channel-indicator")?.when?.equals, "{{channel.id}}");
const identityEntry = findPart(voiceSurface?.root, "identity-entry");
assert.equal(identityEntry?.attributes?.role, "group");
assert.equal(identityEntry?.when?.path, "session.status.userName");
assert.equal(findPart(identityEntry, "identity-name")?.children?.[0]?.text, "{{session.status.userName}}");
const channelVoiceMembers = findPart(voiceSurface?.root, "channel-voice-members");
assert.equal(channelVoiceMembers?.when?.path, "channel.current");
assert.equal(findPart(channelVoiceMembers, "channel-voice-member")?.repeat?.path, "channel.members");
assert.equal(findPart(channelVoiceMembers, "channel-member-muted")?.when?.path, "voicemember.status");
assert.equal(findPart(voiceSurface?.root, "member-away-state")?.when?.path, "member.status");
const voiceDockActions = findPart(voiceSurface?.root, "voice-dock-actions");
assert.equal(findPart(voiceDockActions, "screen-share-start")?.widget, "voice.screen-share-start");
assert.equal(findPart(voiceDockActions, "audio-controls")?.widget, "voice.audio-controls");
assert.equal(findPart(voiceDockActions, "disconnect-control")?.events?.click, "disconnect");
const chat = findPart(voiceSurface?.root, "chat");
assert.equal(findPart(chat, "chat-message")?.repeat?.path, "chat.messages");
assert.equal(findPart(chat, "chat-composer")?.events?.submit, "send-message");
assert.equal(findPart(chat, "chat-input")?.bindValue, "message");
assert.equal(findPart(chat, "chat-empty")?.when?.empty, true);
assert.equal(findPart(voiceSurface?.root, "whisper-start")?.events?.click, "whisper-on");
assert.ok(skin.css.includes("@media (max-width: 820px)"));
assert.ok(skin.css.includes('[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="1"]'));
assert.ok(skin.css.includes('[data-ws-plugin-part="harbor-workspace.identity-entry"]'));
assert.ok(skin.css.includes('data-ws-plugin-part="harbor-workspace.screen-share-start"'), "the host screen-share control uses the stable plugin part hook");
assert.ok(skin.css.includes(".accompaniment-toggle { display: none; }"));
assert.ok(!skin.css.includes("https://"), "the skin uses no remote artwork or font resources");
});
@@ -588,12 +621,13 @@ function makeSkinV4(
permissions: ["session.channels.read"],
}],
},
options: { includeEntry?: boolean; entryBytes?: Uint8Array; entryPath?: string; extra?: Record<string, Uint8Array> } = {},
options: { includeEntry?: boolean; entryBytes?: Uint8Array; entryPath?: string; layout?: unknown; extra?: Record<string, Uint8Array> } = {},
): File {
const packageFiles: Record<string, Uint8Array> = {
"manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 4, packageType: "open-skin", plugins: "plugins.json" })),
"manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 4, packageType: "open-skin", plugins: "plugins.json", ...(options.layout ? { layout: "layout.json" } : {}) })),
"skin.css": strToU8('[data-ws-part="app"] { position: fixed; color: teal; }'),
"plugins.json": strToU8(JSON.stringify(pluginDocument)),
...(options.layout ? { "layout.json": strToU8(JSON.stringify(options.layout)) } : {}),
"plugins/voice-toolbar/style.css": strToU8(".toolbar { color: teal; }"),
"plugins/voice-toolbar/assets/icon.png": new Uint8Array([1, 2, 3, 4]),
...options.extra,
@@ -0,0 +1,208 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
addSkinPluginComponent,
addSkinPluginNode,
addSkinPluginNodeSibling,
duplicateSkinPluginNode,
editableSkinPluginDocument,
getSkinPluginNode,
moveSkinPluginComponent,
moveSkinPluginNode,
removeSkinPluginComponent,
removeSkinPluginNode,
replaceSkinPluginNode,
} from "../../../src/shared/skin-plugin-editor.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import {
clearSkinPluginAuthoringDocument,
exportSkinPluginAuthoringDocument,
getSkinPluginAuthoringStorageKey,
hasSkinPluginAuthoringDocument,
importSkinPluginAuthoringDocument,
loadSkinPluginAuthoringDocument,
saveSkinPluginAuthoringDocument,
SKIN_PLUGIN_AUTHORING_STORAGE_KEY,
} from "./skin-plugin-authoring.js";
class MemoryStorage {
private readonly values = new Map<string, string>();
failWrites = false;
getItem(key: string): string | null { return this.values.get(key) ?? null; }
setItem(key: string, value: string): void {
if (this.failWrites) throw new Error("quota exceeded");
this.values.set(key, value);
}
removeItem(key: string): void { this.values.delete(key); }
}
function withLocalStorage<T>(run: (storage: MemoryStorage) => T): T {
const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
const storage = new MemoryStorage();
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });
try { return run(storage); }
finally {
if (previous) Object.defineProperty(globalThis, "localStorage", previous);
else Reflect.deleteProperty(globalThis, "localStorage");
}
}
function document(): SkinPluginDocument {
return {
schemaVersion: 3,
components: [{
id: "voice-panel",
name: "Voice panel",
page: "voice",
accessibleName: "Voice panel",
permissions: [],
actions: {},
root: { tag: "section", children: [{ tag: "p", children: [{ text: "Original" }] }, { tag: "button", attributes: { type: "button" } }] },
}],
};
}
test("component document editor supports add, update, reorder, delete, and an empty v3 document", () => {
const source = document();
const first = addSkinPluginNode(source, "voice-panel", [], { tag: "div", children: [{ text: "Added" }] });
assert.equal(getSkinPluginNode(first, "voice-panel", [2]).tag, "div");
assert.equal(source.components[0].root.children?.length, 2, "editing leaves the source tree unchanged");
const second = addSkinPluginNodeSibling(first, "voice-panel", [2], { tag: "small", children: [{ text: "Sibling" }] });
assert.equal(getSkinPluginNode(second, "voice-panel", [3]).tag, "small");
const reordered = moveSkinPluginNode(second, "voice-panel", [3], -1);
assert.equal(getSkinPluginNode(reordered, "voice-panel", [2]).tag, "small");
const updated = replaceSkinPluginNode(reordered, "voice-panel", [2, 0], { text: "Changed" });
assert.equal(getSkinPluginNode(updated, "voice-panel", [2, 0]).text, "Changed");
const withoutNode = removeSkinPluginNode(updated, "voice-panel", [2]);
assert.equal(withoutNode.components[0].root.children?.length, 3);
const withSecondComponent = addSkinPluginComponent(withoutNode, {
id: "extra-panel", name: "Extra panel", page: "voice", accessibleName: "Extra panel",
permissions: [], actions: {}, root: { tag: "aside" },
});
assert.equal(withSecondComponent.components.length, 2);
assert.equal(removeSkinPluginComponent(withSecondComponent, "voice-panel").components.length, 1);
assert.deepEqual(removeSkinPluginComponent(withSecondComponent, "voice-panel").components.map(({ id }) => id), ["extra-panel"]);
assert.deepEqual(removeSkinPluginComponent(document(), "voice-panel"), { schemaVersion: 3, components: [] });
});
test("component order is editable and stays within the selected skin document", () => {
const source = addSkinPluginComponent(document(), {
id: "second-panel", name: "Second panel", page: "voice", accessibleName: "Second panel",
permissions: [], actions: {}, root: { tag: "aside" },
});
const moved = moveSkinPluginComponent(source, "voice-panel", 1);
assert.deepEqual(moved.components.map((component) => component.id), ["second-panel", "voice-panel"]);
assert.deepEqual(moveSkinPluginComponent(moved, "voice-panel", 1), moved, "moving past the end is a no-op");
assert.deepEqual(source.components.map((component) => component.id), ["voice-panel", "second-panel"]);
});
test("duplicating a nested component node gives copied layout parts unique stable IDs", () => {
const source = document();
source.components[0].root.children![0] = {
tag: "div", part: "message", children: [{ tag: "span", part: "author", text: "Author" }],
};
const copy = duplicateSkinPluginNode(source, "voice-panel", [0]);
assert.equal(copy.part, "message-copy");
assert.equal(copy.children?.[0].part, "author-copy");
assert.throws(() => duplicateSkinPluginNode(source, "voice-panel", []), /root cannot be duplicated/i);
});
test("component editor rejects unsafe markup and invalid permission/action combinations", () => {
assert.throws(() => addSkinPluginNode(document(), "voice-panel", [], { tag: "script" }), /unsupported HTML element/i);
assert.throws(() => replaceSkinPluginNode(document(), "voice-panel", [0], {
tag: "button", events: { click: "disconnect" },
}), /refer to a declared host action/i);
assert.throws(() => addSkinPluginComponent(document(), {
id: "unsafe", name: "Unsafe", page: "voice", accessibleName: "Unsafe",
permissions: [], actions: { disconnect: { type: "voice.disconnect", args: {} } },
root: { tag: "button", events: { click: "disconnect" } },
}), /requires voice.disconnect/i);
assert.throws(() => removeSkinPluginNode(document(), "voice-panel", []), /root cannot be removed/i);
assert.throws(() => moveSkinPluginNode(document(), "voice-panel", [1.5], -1), /no longer exists/i);
});
test("older package trees upgrade to editable schema v3 without losing their component", () => {
const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument;
const editable = editableSkinPluginDocument(legacy);
assert.equal(editable.schemaVersion, 3);
assert.equal(editable.components[0].root.tag, "section");
const legacyWithWidget = structuredClone(legacy);
legacyWithWidget.components[0].permissions = [];
legacyWithWidget.components[0].root = { tag: "section", children: [{ widget: "voice.audio-controls" }] };
const migratedWidget = editableSkinPluginDocument(legacyWithWidget);
assert.deepEqual(migratedWidget.components[0].permissions, ["audio.status.read", "audio.microphone.control", "audio.output.control"]);
});
test("component authoring saves are isolated by skin version and round-trip through export/import", () => {
withLocalStorage((storage) => {
const source = addSkinPluginNode(document(), "voice-panel", [], { tag: "strong", children: [{ text: "Local edit" }] });
saveSkinPluginAuthoringDocument("community.example", "1.2.3", source);
assert.notEqual(storage.getItem(getSkinPluginAuthoringStorageKey("community.example", "1.2.3")), null);
assert.equal(storage.getItem(SKIN_PLUGIN_AUTHORING_STORAGE_KEY), null);
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.2.3"), true);
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.3")?.components[0].root.children?.length, 3);
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.4"), null);
const exported = exportSkinPluginAuthoringDocument(source);
assert.deepEqual(importSkinPluginAuthoringDocument(exported), source);
clearSkinPluginAuthoringDocument("community.example", "1.2.3");
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.3"), null);
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.2.3"), false);
const empty = removeSkinPluginComponent(source, "voice-panel");
saveSkinPluginAuthoringDocument("community.example", "1.2.3", empty);
assert.deepEqual(loadSkinPluginAuthoringDocument("community.example", "1.2.3"), { schemaVersion: 3, components: [] });
assert.deepEqual(importSkinPluginAuthoringDocument(exportSkinPluginAuthoringDocument(empty)), empty);
const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument;
saveSkinPluginAuthoringDocument("community.example", "1.2.4", legacy);
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.4")?.schemaVersion, 3);
});
});
test("invalid component files and unsafe local edits are rejected before persistence", () => {
withLocalStorage((storage) => {
assert.throws(() => importSkinPluginAuthoringDocument(JSON.stringify({
schemaVersion: 3,
components: [{
id: "broken", name: "Broken", page: "voice", accessibleName: "Broken",
permissions: [], actions: {}, root: { tag: "iframe" },
}],
})));
assert.throws(() => saveSkinPluginAuthoringDocument("community.example", "1", {
schemaVersion: 3, components: [{ ...document().components[0], root: { tag: "script" } }],
}));
const reservedHook = document();
reservedHook.components[0].root.children![0].attributes = { "data-ws-page": "admin" };
assert.throws(() => saveSkinPluginAuthoringDocument("community.example", "1", reservedHook), /owned by WebSpeak/i);
assert.equal(storage.getItem(getSkinPluginAuthoringStorageKey("community.example", "1")), null);
});
});
test("a local-storage write failure preserves the last saved component document", () => {
withLocalStorage((storage) => {
const saved = document();
saveSkinPluginAuthoringDocument("community.example", "1.2.3", saved);
const key = getSkinPluginAuthoringStorageKey("community.example", "1.2.3");
const rawBeforeFailure = storage.getItem(key);
const changed = addSkinPluginNode(saved, "voice-panel", [], { text: "not committed" });
storage.failWrites = true;
assert.throws(() => saveSkinPluginAuthoringDocument("community.example", "1.2.3", changed), /could not save/i);
assert.equal(storage.getItem(key), rawBeforeFailure);
assert.deepEqual(loadSkinPluginAuthoringDocument("community.example", "1.2.3"), editableSkinPluginDocument(saved));
});
});
test("corrupt authoring data stays isolated and can be cleared without touching another skin", () => {
withLocalStorage((storage) => {
const corruptKey = getSkinPluginAuthoringStorageKey("community.example", "1.0.0");
saveSkinPluginAuthoringDocument("community.other", "1.0.0", document());
storage.setItem(corruptKey, "not json");
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.0.0"), true);
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.0.0"), null);
clearSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.0.0"), false);
assert.equal(loadSkinPluginAuthoringDocument("community.other", "1.0.0")?.components[0].id, "voice-panel");
});
});
+78
View File
@@ -0,0 +1,78 @@
import { parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { assertSkinPluginAuthoringDocument, editableSkinPluginDocument } from "../../../src/shared/skin-plugin-editor.js";
export const SKIN_PLUGIN_AUTHORING_STORAGE_KEY = "webspeak:skin-plugin-authoring:v1";
const MAX_DOCUMENT_BYTES = 256 * 1024;
interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
function browserStorage(): StorageLike | null {
try { return typeof localStorage === "undefined" ? null : localStorage; }
catch { return null; }
}
export function getSkinPluginAuthoringStorageKey(skinId: string, skinVersion: string): string {
if (!/^[a-z0-9](?:[a-z0-9.-]{0,78}[a-z0-9])?$/.test(skinId)
|| !skinVersion || skinVersion.length > 32 || !/^[A-Za-z0-9.+_-]+$/.test(skinVersion)) {
throw new Error("Skin identity is invalid.");
}
return SKIN_PLUGIN_AUTHORING_STORAGE_KEY + ":" + skinId + "@" + skinVersion;
}
export function hasSkinPluginAuthoringDocument(skinId: string, skinVersion: string): boolean {
let key: string;
try { key = getSkinPluginAuthoringStorageKey(skinId, skinVersion); } catch { return false; }
const storage = browserStorage();
if (!storage) return false;
try { return storage.getItem(key) !== null; } catch { return false; }
}
export function loadSkinPluginAuthoringDocument(skinId: string, skinVersion: string): SkinPluginDocument | null {
let key: string;
try { key = getSkinPluginAuthoringStorageKey(skinId, skinVersion); } catch { return null; }
const storage = browserStorage();
if (!storage) return null;
let source: string | null;
try { source = storage.getItem(key); } catch { return null; }
if (!source) return null;
if (new TextEncoder().encode(source).byteLength > MAX_DOCUMENT_BYTES) return null;
try { return editableSkinPluginDocument(parseSkinPluginJson(source)); }
catch { return null; }
}
export function saveSkinPluginAuthoringDocument(skinId: string, skinVersion: string, document: unknown): SkinPluginDocument {
const key = getSkinPluginAuthoringStorageKey(skinId, skinVersion);
const validated = assertSkinPluginAuthoringDocument(document);
const serialized = JSON.stringify(validated);
if (new TextEncoder().encode(serialized).byteLength > MAX_DOCUMENT_BYTES) throw new Error("Saved component edits exceed the 256 KiB document limit.");
const storage = browserStorage();
if (!storage) throw new Error("Local browser storage is unavailable.");
try { storage.setItem(key, serialized); }
catch { throw new Error("Local browser storage could not save the component edits."); }
return validated;
}
export function clearSkinPluginAuthoringDocument(skinId: string, skinVersion: string): void {
const key = getSkinPluginAuthoringStorageKey(skinId, skinVersion);
const storage = browserStorage();
if (!storage) throw new Error("Local browser storage is unavailable.");
try { storage.removeItem(key); }
catch { throw new Error("Local browser storage could not clear the component edits."); }
}
export function importSkinPluginAuthoringDocument(source: string): SkinPluginDocument {
return assertSkinPluginAuthoringDocument(parseSkinPluginJson(source));
}
export function exportSkinPluginAuthoringDocument(document: unknown): string {
const validated = assertSkinPluginAuthoringDocument(document);
const readable = JSON.stringify(validated, null, 2);
if (new TextEncoder().encode(readable).byteLength <= MAX_DOCUMENT_BYTES) return readable;
const compact = JSON.stringify(validated);
if (new TextEncoder().encode(compact).byteLength > MAX_DOCUMENT_BYTES) throw new Error("components.json exceeds the 256 KiB document limit.");
return compact;
}