Merge PR #57: integrate host chrome theming and skin recovery

This commit is contained in:
illusia committed 2026-11-14 18:59:15 +08:00
commit 6a35d9be3d
46 files changed
+3129 -131

No files matched your search

+242
View File
@@ -0,0 +1,242 @@
import { DECORATIVE_PART_IDS, HOST_SKIN_ATTRIBUTE, SKIN_ICON_SLOT_IDS } from "./skin-visual-parts.js";
/**
* `chrome.json` is an optional, declarative companion to an open skin.
*
* It describes two host-chrome capabilities that CSS alone cannot express
* safely:
* - `visibleParts`: decorations the skin asks the host to render. This is the
* only opt-in; official and built-in skins stay clean.
* - `hiddenParts`: non-critical decorations the skin wants collapsed by
* default. Only explicitly optional parts are accepted.
* - `icons`: bitmap overrides for stable icon slots, keyed by part name.
*
* Both the browser importer and the server-side registry parse the exact same
* document, so a package accepted by one is accepted by the other.
*/
export const SKIN_CHROME_MAX_BYTES = 32 * 1024;
export const SKIN_CHROME_MAX_HIDDEN_PARTS = 32;
export const SKIN_CHROME_MAX_ICONS = 16;
export const SKIN_ICON_MAX_BYTES = 64 * 1024;
export const SKIN_ICONS_MAX_TOTAL_BYTES = 512 * 1024;
export const SKIN_ICON_DIRECTORY = "assets/icons/";
const SUPPORTED_ICON_EXTENSIONS = new Set(["png", "jpg", "jpeg", "webp", "avif", "gif"]);
/**
* Decorative host chrome that is hidden unless a skin explicitly opts in.
* Official and built-in skins ship no `chrome.json`, so they stay identical to
* production; a host-chrome pack opts in with `chrome.json#visibleParts`.
*/
export const DEFAULT_HIDDEN_HOST_PARTS: ReadonlySet<string> = new Set([
"host.watermark",
"host.hint",
"host.voice-status-decoration",
]);
export interface SkinChromeDocument {
schemaVersion: 1;
hiddenParts: string[];
/**
* Parts from `DEFAULT_HIDDEN_HOST_PARTS` (or other decorative parts) that a
* skin asks the host to render. This is the only opt-in for decorations; a
* chrome.json that omits it keeps the same clean chrome as built-in skins.
*/
visibleParts?: string[];
icons: Record<string, string>;
}
export interface SkinChromeAssetInfo {
bytes: number;
mime: string;
}
export class SkinChromeError extends Error {
constructor(message: string, readonly code: string) {
super(message);
this.name = "SkinChromeError";
}
}
function reject(message: string, code: string): never {
throw new SkinChromeError(message, code);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
/** Validate and normalize an icon asset path. Only package-local bitmaps under assets/icons/ are allowed. */
export function normalizeSkinIconPath(raw: unknown): string {
if (typeof raw !== "string" || !raw || raw.length > 160) {
return reject("An icon path must be a short, non-empty string.", "SKIN_ICON_PATH");
}
const path = raw.split(/[?#]/, 1)[0];
if (!path.startsWith(SKIN_ICON_DIRECTORY)) {
return reject(`Icon bitmaps must live in ${SKIN_ICON_DIRECTORY}.`, "SKIN_ICON_PATH");
}
const segments = path.split("/");
if (segments.length !== 3 || segments.some((segment) => !segment || segment === "." || segment === "..")) {
return reject("An icon path must be a single file inside assets/icons/.", "SKIN_ICON_PATH");
}
const filename = segments[2];
const extension = filename.split(".").pop()?.toLowerCase() ?? "";
if (!SUPPORTED_ICON_EXTENSIONS.has(extension)) {
return reject("Icon bitmaps must be PNG, JPEG, WebP, AVIF or GIF files (SVG is not allowed).", "SKIN_ICON_PATH");
}
if (/[\\:\0%\s]/.test(path) || /^[a-z]:/i.test(path) || path.startsWith("/") || path.includes("//")) {
return reject("An icon path must be a safe, package-relative path.", "SKIN_ICON_PATH");
}
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(filename)) {
return reject("An icon filename contains unsupported characters.", "SKIN_ICON_PATH");
}
return path;
}
export function parseSkinChromeDocument(source: string): SkinChromeDocument {
const bytes = new TextEncoder().encode(source).byteLength;
if (!bytes || bytes > SKIN_CHROME_MAX_BYTES) {
return reject("chrome.json must be between 1 byte and 32 KiB.", "SKIN_CHROME_SIZE");
}
let raw: unknown;
try { raw = JSON.parse(source); }
catch { return reject("chrome.json is not valid JSON.", "SKIN_CHROME_INVALID"); }
if (!isRecord(raw)) return reject("chrome.json must be an object.", "SKIN_CHROME_INVALID");
for (const key of Object.keys(raw)) {
if (key !== "schemaVersion" && key !== "hiddenParts" && key !== "visibleParts" && key !== "icons") {
return reject(`chrome.json contains an unsupported field: ${key}.`, "SKIN_CHROME_INVALID");
}
}
if (raw.schemaVersion !== 1) return reject("chrome.json must use schemaVersion 1.", "SKIN_CHROME_INVALID");
const hiddenParts: string[] = [];
if (raw.hiddenParts !== undefined) {
if (!Array.isArray(raw.hiddenParts) || raw.hiddenParts.length > SKIN_CHROME_MAX_HIDDEN_PARTS) {
return reject("hiddenParts must be an array of at most 32 part names.", "SKIN_CHROME_HIDDEN_INVALID");
}
for (const entry of raw.hiddenParts) {
if (typeof entry !== "string" || !DECORATIVE_PART_IDS.has(entry)) {
return reject(`Only explicitly optional decorative parts may be hidden: ${String(entry)}.`, "SKIN_CHROME_HIDDEN_INVALID");
}
if (!hiddenParts.includes(entry)) hiddenParts.push(entry);
}
}
let visibleParts: string[] | undefined;
if (raw.visibleParts !== undefined) {
if (!Array.isArray(raw.visibleParts) || raw.visibleParts.length > SKIN_CHROME_MAX_HIDDEN_PARTS) {
return reject("visibleParts must be an array of at most 32 part names.", "SKIN_CHROME_VISIBLE_INVALID");
}
visibleParts = [];
for (const entry of raw.visibleParts) {
if (typeof entry !== "string" || !DECORATIVE_PART_IDS.has(entry)) {
return reject(`Only explicitly optional decorative parts may be shown: ${String(entry)}.`, "SKIN_CHROME_VISIBLE_INVALID");
}
if (!visibleParts.includes(entry)) visibleParts.push(entry);
}
}
const icons: Record<string, string> = Object.create(null) as Record<string, string>;
if (raw.icons !== undefined) {
if (!isRecord(raw.icons)) return reject("icons must be an object mapping slot names to asset paths.", "SKIN_ICON_INVALID");
const entries = Object.entries(raw.icons);
if (entries.length > SKIN_CHROME_MAX_ICONS) {
return reject(`A skin may override at most ${SKIN_CHROME_MAX_ICONS} icons.`, "SKIN_ICON_INVALID");
}
for (const [slot, path] of entries) {
if (!SKIN_ICON_SLOT_IDS.has(slot)) {
return reject(`Unknown icon slot: ${slot}.`, "SKIN_ICON_INVALID");
}
icons[slot] = normalizeSkinIconPath(path);
}
}
return { schemaVersion: 1, hiddenParts, ...(visibleParts ? { visibleParts } : {}), icons };
}
/**
* Merge the instance default, the skin's explicit opt-ins and its hidden list
* into the set of optional host parts the host must not render.
*
* Decorations are hidden by default so official/built-in skins match
* production. A pack opts in with `visibleParts`; a pack that ships a
* chrome.json without that field (icons-only or hiddenParts-only) stays hidden,
* and `hiddenParts` still wins over both.
*
* The decision is intentionally independent of the generated host CSS: the
* importer appends `compileSkinChromeCss()` output after the author CSS, so
* sniffing the combined string for `data-ws-part="host.…"` would treat every
* hiddenParts entry as a declaration that the skin themes host chrome.
*/
export function resolveHiddenHostParts(
document: SkinChromeDocument | undefined,
instanceHiddenParts: readonly string[],
): ReadonlySet<string> {
const hidden = new Set<string>(instanceHiddenParts.filter((part) => DECORATIVE_PART_IDS.has(part)));
const visible = new Set<string>(document?.visibleParts ?? []);
for (const part of DEFAULT_HIDDEN_HOST_PARTS) {
if (!visible.has(part)) hidden.add(part);
}
for (const part of document?.hiddenParts ?? []) hidden.add(part);
return hidden;
}
/** Compile-time path and size validation against the actual package contents. */
export function validateSkinChromeAssets(
document: SkinChromeDocument,
lookup: (path: string) => SkinChromeAssetInfo | undefined,
): void {
let total = 0;
for (const [slot, path] of Object.entries(document.icons)) {
const asset = lookup(path);
if (!asset) return reject(`Icon bitmap is missing from the package: ${path}`, "SKIN_ICON_MISSING");
if (!asset.mime.startsWith("image/") || asset.mime === "image/svg+xml") {
return reject(`Icon bitmap is not a supported raster image: ${path}`, "SKIN_ICON_INVALID");
}
if (!asset.bytes || asset.bytes > SKIN_ICON_MAX_BYTES) {
return reject(`Icon bitmap ${path} exceeds ${SKIN_ICON_MAX_BYTES / 1024} KiB.`, "SKIN_ICON_SIZE");
}
total += asset.bytes;
if (total > SKIN_ICONS_MAX_TOTAL_BYTES) {
return reject(`All icon bitmaps together exceed ${SKIN_ICONS_MAX_TOTAL_BYTES / 1024} KiB.`, "SKIN_ICON_SIZE");
}
void slot;
}
}
/** Instance-level default: comma/space separated optional part names, or a JSON array. */
export function parseHiddenHostParts(value: unknown): string[] {
const entries = typeof value === "string"
? value.split(/[\s,]+/)
: Array.isArray(value) ? value : [];
const result: string[] = [];
for (const entry of entries) {
if (typeof entry !== "string" || !DECORATIVE_PART_IDS.has(entry)) continue;
if (!result.includes(entry) && result.length < SKIN_CHROME_MAX_HIDDEN_PARTS) result.push(entry);
}
return result;
}
function cssString(value: string): string {
return value.replace(/["\\\n\r]/g, (character) => `\\${character}`);
}
/**
* Generate host-owned CSS. It is appended to the compiled skin CSS by the
* importer, so `wskin-asset:` markers are resolved together with author CSS.
* The document-level scope reaches both the skin root and Teleported host
* chrome, while never selecting arbitrary html/body content.
*/
export function compileSkinChromeCss(document: SkinChromeDocument, skinId: string): string {
const scope = `:root[${HOST_SKIN_ATTRIBUTE}="${cssString(skinId)}"]`;
const rules: string[] = [];
for (const part of document.hiddenParts) {
rules.push(`${scope} [data-ws-part="${cssString(part)}"] { display: none !important; }`);
}
for (const [slot, path] of Object.entries(document.icons)) {
const target = `${scope} [data-ws-icon-slot="${cssString(slot)}"]`;
rules.push(`${target} { background-image: url("wskin-asset:${encodeURIComponent(path)}") !important; background-position: center !important; background-repeat: no-repeat !important; background-size: contain !important; }`);
rules.push(`${target} > * { visibility: hidden !important; }`);
}
return rules.length ? rules.join("\n") + "\n" : "";
}
+341
View File
@@ -0,0 +1,341 @@
import assert from "node:assert/strict";
import test from "node:test";
import { compileSkinCss, OPTIONAL_VISUAL_PARTS } from "./skin-css.js";
import { DECORATIVE_PART_IDS as LAYOUT_DECORATIVE, PROTECTED_PART_IDS } from "./skin-layout.js";
import { DECORATIVE_PART_IDS } from "./skin-visual-parts.js";
import {
compileSkinChromeCss,
DEFAULT_HIDDEN_HOST_PARTS,
parseHiddenHostParts,
parseSkinChromeDocument,
resolveHiddenHostParts,
SKIN_ICON_MAX_BYTES,
validateSkinChromeAssets,
} from "./skin-chrome.js";
const assets = new Set<string>();
const compile = (css: string, version: 1 | 2 | 3 | 4 = 3, id = "demo-skin") =>
compileSkinCss(css, id, assets, version);
test("the CSS hide whitelist and the layout decorative registry are one shared set", () => {
assert.deepEqual([...OPTIONAL_VISUAL_PARTS].sort(), [...DECORATIVE_PART_IDS].sort());
assert.deepEqual([...LAYOUT_DECORATIVE].sort(), [...DECORATIVE_PART_IDS].sort());
for (const part of ["host.watermark", "host.hint", "host.voice-status-decoration", "home.footer.decoration"]) {
assert.ok(OPTIONAL_VISUAL_PARTS.has(part), `${part} must be hideable`);
}
// home.footer contains the necessary "clear local data" link: only its
// decorative children may be hidden, never the container.
assert.equal(OPTIONAL_VISUAL_PARTS.has("home.footer"), false);
assert.ok(PROTECTED_PART_IDS.has("home.footer"), "the footer container must not be hidden");
assert.ok(PROTECTED_PART_IDS.has("home.footer.clear"));
// Decorative password-dialog children stay hideable: existing skins rely on it.
for (const part of ["auth.password.decoration", "auth.password.eyebrow", "auth.password.lead", "auth.password.label", "auth.password.field-icon"]) {
assert.equal(PROTECTED_PART_IDS.has(part), false, `${part} must stay hideable`);
}
for (const part of ["auth.password.dialog", "auth.password.form", "auth.password.field", "auth.password.error", "auth.password.actions"]) {
assert.ok(PROTECTED_PART_IDS.has(part), `${part} must be protected`);
}
// A screen-share exit button is a control but not part of the essential audio
// path; v3 skins may still hide it, so it is not in the protected set.
assert.equal(PROTECTED_PART_IDS.has("voice.screen-player.exit"), false);
// The load-failure banner and the library recovery entry are distinct parts.
assert.ok(PROTECTED_PART_IDS.has("app.skin-load-recovery"));
assert.ok(PROTECTED_PART_IDS.has("host.recovery"));
});
test("host chrome selectors compile into the document-level host scope", () => {
const themed = compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }');
assert.match(themed.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]/);
assert.doesNotMatch(themed.css, /\.ws-skin-root\[data-ws-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]/);
const scoped = compile('[data-ws-part="host.plugins.launcher"]:hover { color: white; }');
assert.match(scoped.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]:hover/);
const overlay = compile('[data-ws-part="host.plugins.overlay"] { border-color: red; }');
assert.match(overlay.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.overlay"\]/);
// Ordinary page parts keep the original skin-root scope.
const page = compile('[data-ws-part="home.header"] { color: teal; }');
assert.match(page.css, /\.ws-skin-root\[data-ws-skin="demo-skin"\] \[data-ws-part="home\.header"\]/);
assert.doesNotMatch(page.css, /data-ws-host-skin/);
});
test("the extended scope cannot escape to html/body or host internals", () => {
const rejected: Array<[string, RegExp]> = [
['html [data-ws-part="host.watermark"] { color: red; }', /cannot target html or body/],
['body [data-ws-part="host.watermark"] { color: red; }', /cannot target html or body/],
['[data-ws-host-skin] [data-ws-part="host.watermark"] { color: red; }', /host attribute/],
['[data-ws-route="webclient"] [data-ws-part="host.watermark"] { color: red; }', /host attribute/],
['[data-ws-part="home.header"] [data-ws-part="host.watermark"] { color: red; }', /cannot be mixed/],
['[data-ws-part="host.recovery"] { display: none; }', /Trusted or unknown host part/],
['[data-ws-part="host.permission"] { display: none; }', /Trusted or unknown host part/],
['[data-ws-part="host.unknown"] { color: red; }', /Trusted or unknown host part/],
[':root { --ws-internal-token: red; }', /--skin- prefix/],
['[data-ws-part="host.hint"] { behavior: url(x.htc); }', /Executable CSS/],
['[data-ws-part="host.hint"] { background: url("https://example.invalid/x.png"); }', /Only relative paths/],
];
for (const [css, message] of rejected) {
assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css);
}
assert.throws(() => compile('[data-ws-part="host.watermark"] { color: red; }', 1), /requires an open/);
assert.throws(() => compile('[data-ws-part="host.watermark"] { color: red; }', 2), /requires an open/);
});
test("a leading :root cannot escape the skin root through a sibling combinator", () => {
// `:root` is rewritten in place, so these become `.ws-skin-root … ~ …` and
// would select the body-level host layer in the preview/fixture topology.
for (const css of [
':root ~ [data-ws-host-layer] { display: none !important; }',
':root ~ * { display: none !important; }',
':root ~ div { pointer-events: none !important; }',
':root + [data-ws-host-layer] { display: none; }',
':root + * { visibility: hidden; }',
':root:hover ~ * { display: none !important; }',
':ROOT ~ * { display: none !important; }',
]) {
assert.throws(() => compile(css), /sibling combinator after :root/, css);
}
// Descendant scoping (the documented form) still compiles into the skin root.
const descendant = compile(':root [data-ws-part="home.header"] { color: teal; }');
assert.match(descendant.css, /\.ws-skin-root\[data-ws-skin="demo-skin"\] \[data-ws-part="home\.header"\]/);
// `>` and the descendant combinator are not sibling escapes.
assert.doesNotThrow(() => compile(':root > [data-ws-part="home.header"] { color: teal; }'));
assert.doesNotThrow(() => compile(':root { --skin-accent: #4c8f88; }'));
});
test("host-owned layer attributes are not skin hooks", () => {
for (const attribute of [
"data-ws-host-layer",
"data-ws-host-recovery",
"data-ws-host-layer-content",
"data-ws-recovery-action",
]) {
// A public hook in the same selector gets past the "must use a public hook"
// check, so the attribute-name rejection is what stops the selector.
assert.throws(() => compile(`:root [${attribute}] { display: none; }`), /host attribute/, attribute);
assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}] { color: red; }`), /host attribute/, attribute);
assert.throws(() => compile(`[data-ws-part="home.header"] [${attribute}="x"] { color: red; }`), /host attribute/, attribute);
}
// Normal descendant theming of a public part remains accepted.
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] { color: teal; }'));
});
test("trusted, permission, recovery and essential audio controls stay available even for v3 skins", () => {
for (const part of [
"voice.audio-dock",
"voice.audio-dock.microphone",
"voice.audio-dock.output",
"voice.connection-status",
"voice.audio-status",
"voice.connection-status.reconnect",
"home.security-note",
"home.footer",
"home.footer.clear",
"app.toast",
]) {
const mustNameSubject = (error: unknown) => error instanceof Error
&& error.message.includes(`"${part}"`)
&& /must remain available/.test(error.message);
assert.throws(() => compile(`[data-ws-part="${part}"] { display: none; }`), mustNameSubject, part);
assert.throws(() => compile(`[data-ws-part="${part}"] { opacity: 0; }`), mustNameSubject, part);
}
// Existing skins legitimately hide a decorative child *inside* the audio
// dock; only the dock/control subject itself is protected.
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] > div:first-child { display: none; }'));
// Hiding the screen-share exit button is a visual choice, not an essential
// audio/recovery path: v3 skins may still do it. Legacy v1/v2 skins keep the
// layout guard, so this cannot be used as a positioning attack.
assert.doesNotThrow(() => compile('[data-ws-part="voice.screen-player.exit"] { display: none; }'));
assert.throws(() => compile('[data-ws-part="voice.screen-player.exit"] { display: none; }', 1), /must not change layout/);
// Explicitly optional decorations remain hideable.
assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { display: none; }'));
assert.doesNotThrow(() => compile('[data-ws-part="home.footer.decoration"] { visibility: hidden; }'));
});
test("chrome.json declares hidden parts and icon bitmaps, with path and size validation", () => {
const valid = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
hiddenParts: ["host.watermark", "host.hint", "host.watermark"],
icons: { "language.trigger": "assets/icons/language.png", "host.plugins.launcher": "assets/icons/apps.png" },
}));
assert.deepEqual(valid.hiddenParts, ["host.watermark", "host.hint"]);
assert.equal(valid.icons["language.trigger"], "assets/icons/language.png");
assert.equal(valid.visibleParts, undefined);
const optedIn = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
visibleParts: ["host.watermark", "host.hint", "host.watermark"],
}));
assert.deepEqual(optedIn.visibleParts, ["host.watermark", "host.hint"]);
const lookup = (path: string) => path.endsWith(".png") ? { bytes: 128, mime: "image/png" } : undefined;
assert.doesNotThrow(() => validateSkinChromeAssets(valid, lookup));
const generated = compileSkinChromeCss(valid, "demo-skin");
assert.match(generated, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.watermark"\] \{ display: none !important; \}/);
assert.match(generated, /\[data-ws-icon-slot="language\.trigger"\] \{ background-image: url\("wskin-asset:assets%2Ficons%2Flanguage\.png"\)/);
assert.match(generated, /\[data-ws-icon-slot="language\.trigger"\] > \* \{ visibility: hidden/);
const invalidDocuments: Array<[unknown, RegExp]> = [
[{ schemaVersion: 2, hiddenParts: [] }, /schemaVersion 1/],
[{ schemaVersion: 1, hiddenParts: ["voice.audio-dock"] }, /explicitly optional/],
[{ schemaVersion: 1, hiddenParts: ["host.recovery"] }, /explicitly optional/],
[{ schemaVersion: 1, hiddenParts: ["home.footer"] }, /explicitly optional/],
[{ schemaVersion: 1, visibleParts: ["voice.audio-dock"] }, /explicitly optional/],
[{ schemaVersion: 1, icons: { "unknown.slot": "assets/icons/x.png" } }, /Unknown icon slot/],
[{ schemaVersion: 1, icons: { "language.trigger": "../escape.png" } }, /assets\/icons/],
[{ schemaVersion: 1, icons: { "language.trigger": "assets/icons/x.svg" } }, /SVG is not allowed/],
[{ schemaVersion: 1, icons: { "language.trigger": "https://example.invalid/x.png" } }, /assets\/icons/],
[{ schemaVersion: 1, extra: true }, /unsupported field/],
];
for (const [value, message] of invalidDocuments) {
assert.throws(() => parseSkinChromeDocument(JSON.stringify(value)), message, JSON.stringify(value));
}
assert.throws(() => validateSkinChromeAssets(valid, () => undefined), /missing from the package/);
assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: SKIN_ICON_MAX_BYTES + 1, mime: "image/png" })), /exceeds/);
assert.throws(() => validateSkinChromeAssets(valid, () => ({ bytes: 10, mime: "text/plain" })), /raster image/);
});
test("instance-level hidden parts ignore unknown and protected names", () => {
assert.deepEqual(parseHiddenHostParts("host.watermark, host.hint voice.audio-dock home.footer"), ["host.watermark", "host.hint"]);
assert.deepEqual(parseHiddenHostParts(["host.hint", "host.hint", "nope"]), ["host.hint"]);
assert.deepEqual(parseHiddenHostParts(undefined), []);
});
test("host-scope CSS cannot make the document root the subject of a hiding rule", () => {
for (const css of [
// The verified escape: the root is promoted to the host scope but still the subject.
':root:has([data-ws-part="host.watermark"]) { display: none; }',
':root:has([data-ws-part="host.hint"]) { visibility: hidden; }',
'[data-ws-part="host.watermark"] :root { display: none; }',
'*:has([data-ws-part="host.watermark"]) { display: none; }',
'html:has([data-ws-part="host.watermark"]) { display: none; }',
'body:has([data-ws-part="host.watermark"]) { display: none; }',
'[data-ws-part="host.watermark"] + body { display: none; }',
]) {
assert.throws(() => compile(css), /must start from a themeable|document root|cannot target html or body/, css);
}
// Legitimate host-part theming still compiles into the document-level scope.
const launcher = compile('[data-ws-part="host.plugins.launcher"] { color: white; }');
assert.match(launcher.css, /:root\[data-ws-host-skin="demo-skin"\] \[data-ws-part="host\.plugins\.launcher"\]/);
assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"]:has(span) { color: red; }'));
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] [data-ws-icon-slot="host.plugins.launcher"] { opacity: .5; }'));
});
test("protected controls cannot be hidden through variables or moved off-screen", () => {
assert.throws(
() => compile(':root { --skin-hide: none; } [data-ws-part="voice.audio-dock"] { display: var(--skin-hide); }'),
/cannot use indirect values/,
);
assert.throws(
() => compile('[data-ws-part="voice.audio-dock"] { position: fixed; left: -9999px; }'),
/must remain on screen/,
);
assert.throws(
() => compile('[data-ws-part="voice.audio-dock.microphone"] { transform: translateY(-9999px); }'),
/must remain on screen/,
);
assert.throws(
() => compile('[data-ws-part="voice.audio-dock"] { inset: 0 0 0 -120vw; }'),
/must remain on screen/,
);
// Large negative margins are the same escape as an inset: reject the pattern
// generically, including longhands, shorthand, relative units and calc().
for (const css of [
'[data-ws-part="voice.audio-dock"] { margin-left: -9999px; }',
'[data-ws-part="voice.audio-dock"] { margin-inline: -9999px; }',
'[data-ws-part="voice.audio-dock"] { margin-block-start: -1200px; }',
'[data-ws-part="voice.audio-dock"] { margin: 0 0 0 -999px; }',
'[data-ws-part="voice.audio-dock"] { margin-left: -100vw; }',
'[data-ws-part="voice.audio-dock"] { margin-left: calc(20px - 500px); }',
'[data-ws-part="voice.audio-dock"] { transform: matrix(1, 0, 0, 1, -4000, 0); }',
]) {
assert.throws(() => compile(css), /must remain on screen/, css);
}
assert.throws(
() => compile(':root { --skin-pull: -9999px; } [data-ws-part="voice.audio-dock"] { margin-left: var(--skin-pull); }'),
/cannot use indirect values/,
);
// Ordinary appearance tokens and optional decorations keep working.
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { background: var(--skin-panel); }'));
assert.doesNotThrow(() => compile(':root { --skin-hide: none; } [data-ws-part="host.watermark"] { display: var(--skin-hide); }'));
// A small margin on a protected control and a decorative dock child are still
// legitimate v3 theming.
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] { margin: -6px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock"] > div:first-child { display: none; }'));
// The off-screen guard only protects the subject, not decorative or
// non-protected parts.
assert.doesNotThrow(() => compile('[data-ws-part="home.header"] { margin-left: -9999px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { margin-left: -9999px; }'));
});
test("host chrome cannot be restyled into a viewport-sized overlay", () => {
assert.throws(
() => compile('[data-ws-part="host.plugins.overlay"] { position: fixed; inset: 0; z-index: 2147483647; }'),
/layout is owned by WebSpeak/,
);
assert.throws(() => compile('[data-ws-part="host.watermark"] { position: fixed; }'), /layout is owned by WebSpeak/);
assert.throws(() => compile('[data-ws-part="host.plugins.overlay"] { width: 100vw; height: 100vh; }'), /fullscreen overlay/);
// Descendant rules are the same escape: `*` can turn the library contents
// into a viewport mask even when the shell itself is frozen.
for (const css of [
'[data-ws-part="host.plugins.overlay"] * { position: fixed; inset: 0; z-index: 2147483647; }',
'[data-ws-part="host.plugins.overlay"] * { width: 100vw; height: 100vh; }',
'[data-ws-part="host.plugins.overlay"] .ws-plugin-library { position: fixed; top: 0; left: 0; }',
'[data-ws-part="host.watermark"] * { z-index: 2147483647; }',
]) {
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
}
// zoom (and any comparable scaling) must not blow the shell up either.
for (const css of [
'[data-ws-part="host.plugins.overlay"] { zoom: 10; }',
'[data-ws-part="host.plugins.overlay"] * { zoom: 10; }',
'[data-ws-part="host.plugins.overlay"] { transform: scale(10); }',
]) {
assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css);
}
// Colors, borders, radius, shadows and artwork stay available, including on
// descendants of the overlay.
const themed = compile('[data-ws-part="host.plugins.overlay"] { border: 2px solid #1d4f9c; border-radius: 4px; background: #fff; box-shadow: 0 2px 8px #0003; }');
assert.match(themed.css, /data-ws-part="host\.plugins\.overlay"/);
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.overlay"] * { color: #fff; border-color: #1d4f9c; border-radius: 6px; }'));
assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }'));
});
test("official and built-in skins hide host decorations unless the active skin opts in", () => {
const decorations = ["host.watermark", "host.hint", "host.voice-status-decoration"];
assert.deepEqual([...DEFAULT_HIDDEN_HOST_PARTS].sort(), [...decorations].sort());
// Built-in skins ship no chrome.json: decorations are hidden, launcher stays.
const builtin = resolveHiddenHostParts(undefined, []);
for (const part of decorations) assert.ok(builtin.has(part), `${part} must be hidden for built-in skins`);
assert.equal(builtin.has("host.plugins.launcher"), false);
// An explicit opt-in shows them again; hiddenParts still wins.
const optedIn = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: [], visibleParts: decorations, icons: {} }, []);
for (const part of decorations) assert.equal(optedIn.has(part), false, `${part} must be visible after opting in`);
const explicitlyHidden = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: ["host.hint"], visibleParts: decorations, icons: {} }, []);
assert.ok(explicitlyHidden.has("host.hint"));
// hiddenParts-only chrome.json is not an opt-in: decorations stay hidden.
// This is the production path that previously reported a false positive
// because the appended chrome CSS itself contained `data-ws-part="host.…"`.
const hiddenOnly = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: ["host.plugins.launcher"], icons: {} }, []);
for (const part of decorations) assert.ok(hiddenOnly.has(part), `${part} must stay hidden for a hiddenParts-only pack`);
assert.ok(hiddenOnly.has("host.plugins.launcher"));
const watermarkOnly = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: ["host.watermark"], icons: {} }, []);
for (const part of decorations) assert.ok(watermarkOnly.has(part), `${part} must stay hidden when only watermark is declared`);
// chrome.json alone (for example an icon-only override) is not an opt-in.
const iconOnly = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: [], icons: {} }, []);
for (const part of decorations) assert.ok(iconOnly.has(part), `${part} must stay hidden without visibleParts`);
// Instance defaults cannot be re-enabled by a skin.
const instanceHidden = resolveHiddenHostParts({ schemaVersion: 1, hiddenParts: [], visibleParts: decorations, icons: {} }, ["host.watermark"]);
assert.ok(instanceHidden.has("host.watermark"));
});
+290 -24
View File
@@ -1,6 +1,14 @@
import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss";
import selectorParser from "postcss-selector-parser";
import valueParser from "postcss-value-parser";
import {
DECORATIVE_PART_IDS as OPTIONAL_VISUAL_PARTS,
HOST_CHROME_PART_IDS,
HOST_SKIN_ATTRIBUTE,
PROTECTED_PART_IDS,
} from "./skin-visual-parts.js";
export { OPTIONAL_VISUAL_PARTS };
export type SkinCssSchemaVersion = 1 | 2 | 3 | 4;
export type SkinCssAssets = Readonly<Record<string, unknown>> | Map<string, unknown> | Set<string>;
@@ -36,25 +44,55 @@ const LAYOUT_AFFECTING_PROPERTIES = new Set([
"writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content",
"position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope",
]);
const OPTIONAL_VISUAL_PARTS = new Set([
"home.hero.eyebrow",
"home.gateway-status",
"home.features",
"home.feature",
"home.visitors",
"home.join-card.waveform",
"home.join-card.sonar",
"voice.activity-heading",
"voice.member.avatar",
"voice.member.live-indicator",
"voice.member-row.avatar",
"voice.screen-player.viewer-avatar",
"voice.screen-player.live",
"demo.badge",
"demo.wave",
"demo.avatar",
"demo.member-status",
"demo.note",
/**
* Properties that let a skin move a host-chrome part into a viewport-sized
* overlay or out from under the host's own layout. Appearance properties
* (colors, borders, radius, shadows, artwork) stay available.
*/
const HOST_CHROME_LOCKED_PROPERTIES = new Set([
"all", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline",
"inset-block-start", "inset-block-end", "inset-inline-start", "inset-inline-end",
"z-index", "transform", "translate", "scale", "rotate", "zoom", "float", "clear",
"clip", "clip-path", "mask", "mask-image", "perspective", "contain",
]);
/**
* The plugin library shell additionally owns its footprint: without a locked
* size a skin could still stretch it over the recovery entry even though
* `position`/`inset`/`z-index` are frozen.
*/
const HOST_OVERLAY_LOCKED_PROPERTIES = new Set([
...HOST_CHROME_LOCKED_PROPERTIES,
"width", "height", "min-width", "min-height", "max-width", "max-height",
"inline-size", "block-size", "min-inline-size", "min-block-size", "max-inline-size", "max-block-size",
"aspect-ratio", "margin", "margin-block", "margin-inline", "margin-block-start", "margin-block-end",
"margin-inline-start", "margin-inline-end",
]);
/** Properties whose indirect values could smuggle a hidden or moved control past the static checks. */
const INDIRECT_VALUE_PROPERTIES = new Set([
"all", "display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image",
"position", "top", "right", "bottom", "left", "inset",
"inset-block", "inset-inline", "inset-block-start", "inset-block-end", "inset-inline-start", "inset-inline-end",
"transform", "translate", "scale", "rotate", "zoom",
// Margins move a subject just like insets do; a variable could resolve to a
// viewport-sized negative value, so protected controls may not use them.
"margin", "margin-top", "margin-right", "margin-bottom", "margin-left",
"margin-block", "margin-block-start", "margin-block-end",
"margin-inline", "margin-inline-start", "margin-inline-end",
]);
/** Attributes a skin author must never use to reach outside the public hooks. */
const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
HOST_SKIN_ATTRIBUTE,
"data-ws-skin",
"data-ws-route",
"data-theme",
"data-ws-hidden-host-parts",
// Host-owned recovery layer internals. They are deliberately not skin hooks,
// and naming them keeps `:root [data-ws-host-layer]` / mixed selectors from
// opting into the element by attribute.
"data-ws-host-layer",
"data-ws-host-recovery",
"data-ws-host-layer-content",
"data-ws-recovery-action",
]);
export function compileSkinCss(source: string, id: string, assets: SkinCssAssets, schemaVersion: SkinCssSchemaVersion, pluginId?: string): { css: string; warnings: string[] } {
const size = new TextEncoder().encode(source).byteLength;
@@ -67,6 +105,12 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
const scope = pluginId
? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]`
: skinScope;
// Host chrome is Teleported outside `.ws-skin-root`. Rules that target only
// registered host parts use a second, document-level scope anchored to an
// attribute the host sets while this exact skin is active. Author CSS never
// names html/body: the host generates the scope itself.
const hostSkinScope = `:root[${HOST_SKIN_ATTRIBUTE}="${id}"]`;
const hostScopeNodes = selectorParser().astSync(hostSkinScope).first!.nodes.map((node) => node.clone());
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`;
const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone());
const warnings = new Set<string>();
@@ -117,12 +161,15 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
const text = selector.toString().trim();
if (!text) throw new SkinCssValidationError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinCssValidationError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR");
const hostScope = assertHostChromeSelector(text, schemaVersion, Boolean(pluginId));
const activeScope = hostScope ? hostSkinScope : scope;
const activeNodes = hostScope ? hostScopeNodes : scopeNodes;
if (/^:root\b/.test(text)) {
selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone());
selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, activeScope)).first!.clone());
return;
}
selector.prepend(selectorParser.combinator({ value: " " }));
for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone());
for (let index = activeNodes.length - 1; index >= 0; index -= 1) selector.prepend(activeNodes[index].clone());
});
}).processSync(rule.selector);
} catch (error) {
@@ -157,6 +204,7 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
root.walkDecls((declaration: Declaration) => {
const property = decodeCssEscapes(declaration.prop).toLowerCase();
const unprefixedProperty = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
const value = declaration.value.trim();
const decodedValue = decodeCssEscapes(value);
const owningRule = findOwningRule(declaration);
@@ -164,6 +212,16 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
// Trusted UI and essential audio/recovery controls stay available even for
// open skins. The host also draws authorization and recovery UI outside the
// skin root, so a container-level hide cannot remove them either.
const protectedTarget = owningRule && !keyframesRule ? selectorSubjectProtectedPart(owningRule.selector) : null;
// Every themeable host part referenced anywhere in the selector. A rule may
// target a descendant of the overlay (for example with `*`), so the subject
// alone is not enough to decide whether host chrome layout is at stake.
const hostChromeParts = owningRule && !keyframesRule ? selectorHostChromeParts(owningRule.selector) : [];
const inHostChromeScope = hostChromeParts.length > 0;
const inOverlayScope = hostChromeParts.includes("host.plugins.overlay");
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
throw declaration.error(pluginId
@@ -173,13 +231,26 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
if (schemaVersion < 3 && isLayoutAffectingProperty(property)) {
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
}
// Host chrome lives outside the skin root and owns its own placement. A
// skin may repaint it (colors, borders, radius, artwork) but must not turn
// it — or any of its descendants — into a viewport-sized overlay above
// authorization/recovery UI.
if (inHostChromeScope && HOST_CHROME_LOCKED_PROPERTIES.has(unprefixedProperty)) {
throw declaration.error("Host chrome layout is owned by WebSpeak; skins may theme colors, borders, radius and artwork but must not reposition or restack host controls.");
}
if (inOverlayScope && HOST_OVERLAY_LOCKED_PROPERTIES.has(unprefixedProperty)) {
throw declaration.error("The application library shell cannot be resized into a fullscreen overlay; theme its colors, borders, radius and artwork instead.");
}
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) {
throw declaration.error("Executable CSS values are not allowed.");
}
const compactValue = decodeCssEscapes(valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("")).toLowerCase();
if (schemaVersion < 3 && ["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
if (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
if (protectedTarget) {
throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`);
}
if (!canHideTarget && schemaVersion < 3) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
}
const removesVisual = property === "all"
|| (property === "display" && compactValue === "none")
@@ -188,16 +259,25 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
|| (property === "pointer-events" && compactValue === "none")
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
if (removesVisual && protectedTarget) {
throw declaration.error(`The required control "${protectedTarget}" must remain available; permission, recovery and essential audio paths cannot be hidden.`);
}
if (removesVisual && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
}
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue))
|| (property === "clip-path" && /inset\(\s*50%/i.test(decodedValue))
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue));
if (visuallyRemoves && protectedTarget) {
throw declaration.error(`The required control "${protectedTarget}" must remain visible.`);
}
if (visuallyRemoves && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
}
if (schemaVersion >= 3 && removesVisual) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
if (protectedTarget && valueMovesOffscreen(unprefixedProperty, decodedValue)) {
throw declaration.error(`The required control "${protectedTarget}" must remain on screen and reachable.`);
}
if (schemaVersion >= 3 && removesVisual && !protectedTarget) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${decodedValue}`) || (property === "position" && decodedValue === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile.");
const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames);
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
@@ -250,6 +330,136 @@ function selectorUsesPublicHook(selector: string, allowCustomClasses = false): b
}
}
/**
* A leading `:root` is rewritten in place to `.ws-skin-root[data-ws-skin=…]`.
* With a sibling combinator (`+` / `~`) that would select siblings of the
* skin root — for example the host-owned layer, which is a body child and a
* sibling of the skin root in the preview fixture. Skin scope must only apply
* to the root's own subtree, so reject that shape structurally. A leading
* `:root` followed by a descendant combinator (`:root [data-ws-part="…"]`)
* remains valid.
*/
function assertNoRootSiblingEscape(parsed: selectorParser.Root): void {
for (const item of parsed.nodes) {
const first = item.nodes[0];
if (!first || first.type !== "pseudo" || first.value.toLowerCase() !== ":root") continue;
const combinator = item.nodes.find((node) => node.type === "combinator");
if (combinator && (combinator.value === "+" || combinator.value === "~")) {
throw new SkinCssValidationError(
"Skin selectors cannot use a sibling combinator after :root; the scope must stay inside the skin root.",
"SKIN_CSS_SELECTOR",
);
}
}
}
/**
* Decide whether one selector of an author rule targets host chrome, and
* enforce the boundary around the extended document-level scope.
*
* Returns true when the compiled rule must use `:root[data-ws-host-skin=…]`.
* Author CSS can never name html/body or the host marker attribute itself; the
* host generates that anchor. Host parts are only available to open (v3/v4)
* skins and may not be mixed with page parts in the same selector.
*/
function assertHostChromeSelector(selector: string, schemaVersion: SkinCssSchemaVersion, isPluginStyle: boolean): boolean {
let parsed: selectorParser.Root;
try { parsed = selectorParser().astSync(selector); }
catch { throw new SkinCssValidationError("A CSS selector is invalid.", "SKIN_CSS_SELECTOR"); }
assertNoRootSiblingEscape(parsed);
const partNames: string[] = [];
parsed.walk((node) => {
if (node.type === "tag" && ["html", "body"].includes(node.value.toLowerCase())) {
throw new SkinCssValidationError("Skin selectors cannot target html or body elements.", "SKIN_CSS_SELECTOR");
}
if (node.type === "attribute" && FORBIDDEN_SCOPE_ATTRIBUTES.has(node.attribute.toLowerCase())) {
throw new SkinCssValidationError(`Skin selectors cannot reference the host attribute ${node.attribute}.`, "SKIN_CSS_SELECTOR");
}
if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) {
partNames.push(node.value.replace(/^['"]|['"]$/g, ""));
}
});
const hostParts = partNames.filter((part) => HOST_CHROME_PART_IDS.has(part));
const unknownHostParts = partNames.filter((part) => part.startsWith("host.") && !HOST_CHROME_PART_IDS.has(part));
if (unknownHostParts.length) {
throw new SkinCssValidationError(`Trusted or unknown host part cannot be styled: ${unknownHostParts[0]}.`, "SKIN_CSS_SELECTOR");
}
if (!hostParts.length) return false;
if (hostParts.length !== partNames.length) {
throw new SkinCssValidationError("Host chrome parts cannot be mixed with page parts in one selector.", "SKIN_CSS_SELECTOR");
}
if (isPluginStyle) throw new SkinCssValidationError("Plugin styles cannot target host chrome parts.", "SKIN_CSS_SELECTOR");
if (schemaVersion < 3) throw new SkinCssValidationError("Host chrome theming requires an open (schemaVersion 3 or 4) skin.", "SKIN_CSS_SELECTOR");
assertHostChromeSubject(parsed);
return true;
}
/**
* A host-scope rule is promoted to the document root. To keep that promotion
* from turning the root/html/body (or an arbitrary ancestor) into the rule's
* subject, every host-scope selector must be anchored on a themeable host part
* in its first compound and must never end in `:root`.
*/
function assertHostChromeSubject(parsed: selectorParser.Root): void {
for (const item of parsed.nodes) {
if (!item.nodes.length) continue;
const firstCombinator = item.nodes.findIndex((node) => node.type === "combinator");
if (firstCombinator === 0) {
throw new SkinCssValidationError("Host chrome rules must start from a themeable host part.", "SKIN_CSS_SELECTOR");
}
const firstCompound = firstCombinator === -1 ? item.nodes : item.nodes.slice(0, firstCombinator);
const anchored = firstCompound.some((node) => node.type === "attribute"
&& node.attribute.toLowerCase() === "data-ws-part"
&& HOST_CHROME_PART_IDS.has((node.value ?? "").replace(/^['"]|['"]$/g, "")));
if (!anchored) {
throw new SkinCssValidationError("Host chrome rules must start from a themeable [data-ws-part=\"host.…\"] selector; the document root cannot be themed or hidden.", "SKIN_CSS_SELECTOR");
}
let subjectStart = 0;
for (let index = item.nodes.length - 1; index >= 0; index -= 1) {
if (item.nodes[index].type === "combinator") { subjectStart = index + 1; break; }
}
for (let index = subjectStart; index < item.nodes.length; index += 1) {
const node = item.nodes[index];
if (node.type === "pseudo" && node.value.toLowerCase() === ":root") {
throw new SkinCssValidationError("Host chrome rules cannot make the document root the subject of a rule.", "SKIN_CSS_SELECTOR");
}
}
}
}
/** Find a protected part in the subject (last compound) of any selector in a rule. */
function selectorSubjectProtectedPart(selector: string): string | null {
try {
const parsed = selectorParser().astSync(selector);
for (const item of parsed.nodes) {
let start = 0;
for (let index = item.nodes.length - 1; index >= 0; index -= 1) {
if (item.nodes[index].type === "combinator") { start = index + 1; break; }
}
for (let index = start; index < item.nodes.length; index += 1) {
const node = item.nodes[index];
if (node.type !== "attribute" || node.attribute.toLowerCase() !== "data-ws-part" || !node.value) continue;
const part = node.value.replace(/^['"]|['"]$/g, "");
if (PROTECTED_PART_IDS.has(part)) return part;
}
}
} catch { /* A malformed selector is rejected elsewhere. */ }
return null;
}
/** Find every themeable host part referenced by a selector, in any compound. */
function selectorHostChromeParts(selector: string): string[] {
const parts: string[] = [];
try {
selectorParser().astSync(selector).walk((node) => {
if (node.type !== "attribute" || node.attribute.toLowerCase() !== "data-ws-part" || !node.value) return;
const part = node.value.replace(/^['"]|['"]$/g, "");
if (HOST_CHROME_PART_IDS.has(part) && !parts.includes(part)) parts.push(part);
});
} catch { /* A malformed selector is rejected elsewhere. */ }
return parts;
}
function isLayoutAffectingProperty(property: string): boolean {
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
@@ -259,6 +469,62 @@ function isLayoutAffectingProperty(property: string): boolean {
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
}
/**
* True when a positioning/margin/transform value can push a protected control
* off-screen. Thresholds are deliberately low: a protected control has a
* minimum 44 px hit target, so an offset of a hundred pixels is already enough
* to make it unreachable. Percentages and viewport units are compared against a
* full viewport/containing block.
*/
const OFFSET_PROPERTY_PATTERN = /^(?:margin|inset|left|right|top|bottom|translate|transform|scale|rotate)(?:-|$)/;
const ABSOLUTE_OFFSET_LIMIT_PX = 100;
const RELATIVE_OFFSET_LIMIT = 100;
function absoluteLengthToPixels(magnitude: number, unit: string): number | null {
switch (unit) {
case "px": return magnitude;
case "rem": case "em": return magnitude * 16;
case "ex": case "rex": case "ch": return magnitude * 8;
case "cm": return magnitude * 37.8;
case "mm": return magnitude * 3.78;
case "q": return magnitude * 0.945;
case "in": return magnitude * 96;
case "pt": return magnitude * 1.333;
case "pc": return magnitude * 16;
default: return null;
}
}
function valueMovesOffscreen(property: string, value: string): boolean {
if (!OFFSET_PROPERTY_PATTERN.test(property)) return false;
let offscreen = false;
valueParser(value).walk((node) => {
if (node.type !== "word") return;
const match = /^(-?(?:\d+|\d*\.\d+))(px|rem|em|r?ex|ch|%|cm|mm|q|in|pt|pc|(?:s|l|d)?v(?:w|h|min|max)|cq(?:w|h|min|max|i|b))$/i.exec(node.value);
if (!match) return;
const magnitude = Math.abs(Number(match[1]));
const unit = match[2].toLowerCase();
if (unit === "%" || /^(?:s|l|d)?v(?:w|h|min|max)$/.test(unit) || /^cq(?:w|h|min|max|i|b)$/.test(unit)) {
if (magnitude >= RELATIVE_OFFSET_LIMIT) offscreen = true;
return;
}
const pixels = absoluteLengthToPixels(magnitude, unit);
if (pixels !== null && pixels >= ABSOLUTE_OFFSET_LIMIT_PX) offscreen = true;
});
// A matrix transform can smuggle a large translation in unitless numbers.
if (property === "transform") {
valueParser(value).walk((node) => {
if (node.type !== "function") return;
const name = node.value.toLowerCase();
if (name !== "matrix" && name !== "matrix3d") return;
const numbers = valueParser.stringify(node.nodes).split(",").map((item) => Number(item.trim()));
const translations = name === "matrix" ? [numbers[4], numbers[5]] : [numbers[12], numbers[13]];
if (translations.some((translation) => Number.isFinite(translation) && Math.abs(translation) >= ABSOLUTE_OFFSET_LIMIT_PX)) offscreen = true;
});
}
return offscreen;
}
function findOwningRule(node: Node): Rule | null {
let parent = node.parent;
while (parent && parent.type !== "root") {
+31 -15
View File
@@ -8,7 +8,11 @@ import {
SKIN_LAYOUT_COMPONENTS,
validateSkinLayout,
canEditSkinLayoutComponent,
DECORATIVE_PART_IDS,
HOST_PART_IDS,
} from "./skin-layout.js";
import { HOST_TRUSTED_PART_IDS } from "./skin-visual-parts.js";
import { OPTIONAL_VISUAL_PARTS } from "./skin-css.js";
async function vueSources(directory: URL): Promise<string[]> {
const files = (await readdir(directory, { recursive: true })).filter((file) => file.endsWith(".vue"));
@@ -16,16 +20,20 @@ async function vueSources(directory: URL): Promise<string[]> {
}
test("the stable layout registry covers public skin hooks and excludes the admin console", async () => {
const [webClient, demo, sharedComponents, skinSwitcher, languageSwitcher, admin, adminComponents] = await Promise.all([
const [webClient, demo, sharedComponents, skinSwitcher, languageSwitcher, hostChrome, pluginPanel, authorization, recoveryNotice, admin, adminComponents] = await Promise.all([
readFile(new URL("../../web/src/views/WebClient.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/views/DemoView.vue", import.meta.url), "utf8"),
vueSources(new URL("../../web/src/components/web-client/", import.meta.url)),
readFile(new URL("../../web/src/components/SkinSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/components/LanguageSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/components/HostChrome.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/components/PluginPanel.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/components/InstanceAuthorization.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/components/SkinLoadRecoveryNotice.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/views/AdminView.vue", import.meta.url), "utf8"),
vueSources(new URL("../../web/src/components/admin/", import.meta.url)),
]);
const publicSource = [webClient, demo, ...sharedComponents, skinSwitcher, languageSwitcher].join("\n");
const publicSource = [webClient, demo, ...sharedComponents, skinSwitcher, languageSwitcher, hostChrome, pluginPanel, authorization, recoveryNotice].join("\n");
const publicParts = new Set([...publicSource.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
const interactiveParts = new Set<string>();
for (const match of publicSource.matchAll(/<[A-Za-z][\w.-]*\b[^>]*>/gs)) {
@@ -35,17 +43,25 @@ test("the stable layout registry covers public skin hooks and excludes the admin
const isNativeControl = /^<(?:button|a|input|select|textarea)\b/i.test(attributes);
const hasButtonRole = /\brole="button"/.test(attributes);
const keyboardAction = /@keydown\.(?:enter|space)\b/.test(attributes);
// Native HTML drag gestures are desktop-only and do not make a row a 44px touch control.
if (isNativeControl || hasButtonRole || keyboardAction) interactiveParts.add(part);
// Native HTML drag gestures are desktop-only and do not make a row a 44px touch control.
if (isNativeControl || hasButtonRole || keyboardAction) interactiveParts.add(part);
}
const registered = new Set(SKIN_LAYOUT_COMPONENTS.map((component) => component.selectorPart));
for (const part of publicParts) assert.ok(registered.has(part), "Unregistered public layout hook: " + part);
const micStatus = getSkinLayoutComponent("voice.member.mic-status", "voice");
assert.equal(micStatus?.category, "core");
assert.equal(micStatus?.editable, true);
assert.ok(micStatus?.layoutModes.includes("visibility"));
assert.equal(getSkinLayoutComponent("voice.server-banner", "voice")?.editable, true);
for (const part of interactiveParts) {
const registered = new Set(SKIN_LAYOUT_COMPONENTS.map((component) => component.selectorPart));
for (const part of publicParts) assert.ok(registered.has(part), "Unregistered public layout hook: " + part);
for (const part of HOST_PART_IDS) assert.ok(registered.has(part), "Unregistered host chrome hook: " + part);
// The layout registry and the CSS hiding whitelist must never drift apart.
assert.deepEqual([...DECORATIVE_PART_IDS].sort(), [...OPTIONAL_VISUAL_PARTS].sort());
for (const part of HOST_TRUSTED_PART_IDS) {
const component = getSkinLayoutComponent(part, "voice");
assert.equal(component?.category, "trusted-chrome", "Trusted host entry must not be layout-editable: " + part);
assert.equal(component?.editable, false);
}
const micStatus = getSkinLayoutComponent("voice.member.mic-status", "voice");
assert.equal(micStatus?.category, "core");
assert.equal(micStatus?.editable, true);
assert.ok(micStatus?.layoutModes.includes("visibility"));
assert.equal(getSkinLayoutComponent("voice.server-banner", "voice")?.editable, true);
for (const part of interactiveParts) {
const component = SKIN_LAYOUT_COMPONENTS.find((entry) => entry.id === part);
assert.ok(component, "Interactive public hook must have its own component metadata: " + part);
assert.ok(component.minTouchTarget >= 44, "Interactive public hook needs a 44px touch target: " + part);
@@ -174,9 +190,9 @@ test("registered components carry accessibility, responsive, purpose, and data-s
assert.ok(component.narrowScreenBehavior.length > 0);
assert.ok(component.dataSensitivity.length > 0);
}
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.connect")?.minTouchTarget, 44);
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.range")?.minTouchTarget, 44);
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.checkbox")?.minTouchTarget, 44);
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.connect")?.minTouchTarget, 44);
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.range")?.minTouchTarget, 44);
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.checkbox")?.minTouchTarget, 44);
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.feature")?.category, "optional");
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.security-note")?.category, "trusted-chrome");
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.identity-import.security")?.dataSensitivity, "identity");
+26 -33
View File
@@ -1,3 +1,13 @@
import {
AUTH_PASSWORD_PART_IDS,
DECORATIVE_PART_IDS,
HOST_PART_IDS,
PROTECTED_PART_IDS,
TRUSTED_PART_IDS,
} from "./skin-visual-parts.js";
export { AUTH_PASSWORD_PART_IDS, DECORATIVE_PART_IDS, TRUSTED_PART_IDS, PROTECTED_PART_IDS, HOST_PART_IDS };
export type SkinLayoutPage = "home" | "voice" | "demo";
export type SkinLayoutProfile = "desktop" | "tablet" | "mobile";
@@ -46,24 +56,10 @@ export interface SkinLayoutComponent {
editable: boolean;
}
const AUTH_PASSWORD_PART_IDS = [
"auth.password.backdrop",
"auth.password.dialog",
"auth.password.decoration",
"auth.password.eyebrow",
"auth.password.title",
"auth.password.lead",
"auth.password.form",
"auth.password.label",
"auth.password.field",
"auth.password.field-icon",
"auth.password.error",
"auth.password.actions",
] as const;
const PUBLIC_PART_IDS = new Set<string>([
"app",
"app.toast",
"app.skin-load-recovery",
...AUTH_PASSWORD_PART_IDS,
"control",
"demo.action.poke",
@@ -336,25 +332,16 @@ const PUBLIC_PART_IDS = new Set<string>([
"voice.shell",
"voice.whisper-strip",
"voice.workspace",
// Host chrome is rendered outside the skin root. It stays in the public
// part registry so contract tests and the layout catalogue describe it,
// even though the layout editor only moves elements inside the root.
...HOST_PART_IDS,
"home.footer.decoration",
"home.footer.clear",
"skin.library",
]);
const CONTROL_KINDS = ["button", "link", "input", "checkbox", "range", "select", "textarea", "menuitem", "draggable"] as const;
const TRUSTED_PART_IDS = new Set([
...AUTH_PASSWORD_PART_IDS,
"app",
"app.toast",
"home.security-note",
"home.identity-import.security",
"voice.connection-status",
"voice.screen-share-error",
]);
const DECORATIVE_PART_IDS = new Set([
"demo.avatar", "demo.badge", "demo.note", "demo.poke-notification", "demo.wave",
"home.feature", "home.features", "home.footer", "home.hero.eyebrow", "home.join-card.sonar",
"home.join-card.waveform", "home.visitors", "voice.activity.artwork", "voice.member.avatar-wrap",
"voice.member.live-indicator", "voice.performance.metrics", "voice.performance.webrtc-stats",
"voice.screen-player.viewer-avatar",
]);
const SHELL_PART_IDS = new Set([
"app", "home", "home.content", "home.form", "home.header", "voice.shell", "voice.workspace",
"voice.content", "demo.layout", "demo.main",
@@ -379,6 +366,7 @@ const ACTION_PART_IDS = new Set([
"voice.favorite-servers.strip.server", "demo.voice-card", "home.identity-import.drop-zone",
"voice.channel-group", "voice.member-row", "voice.server-switcher.trigger", "voice.server-switcher.item",
"voice.channel-tree.expander", "voice.channel-tree.row", "demo.skin-switcher", "demo.language-switcher",
"skin.library", "home.footer.clear", "host.plugins.launcher",
]);
const INTERACTIVE_PART_IDS = new Set([
"voice.invite.create", "voice.invite.copy",
@@ -399,6 +387,7 @@ const INTERACTIVE_PART_IDS = new Set([
"voice.screen-player.exit", "voice.screen-player.fullscreen", "demo.voice-card",
"home.identity-import.drop-zone", "voice.channel-group", "voice.member-row", "demo.skin-switcher",
"demo.language-switcher",
"skin.library", "home.footer.clear", "host.plugins.launcher",
]);
const IDENTITY_PART_IDS = new Set([
"home.identity", "home.identity-actions", "home.identity-export.button", "home.identity-import-dialog",
@@ -409,8 +398,9 @@ const IDENTITY_PART_IDS = new Set([
]);
const COMMON_PART_IDS = new Set([
...AUTH_PASSWORD_PART_IDS,
"app", "app.toast", "control", "skin.trigger", "skin.menu", "skin.option",
"language.trigger", "language.menu", "language.option",
...HOST_PART_IDS,
"app", "app.toast", "app.skin-load-recovery", "control", "skin.trigger", "skin.menu", "skin.option",
"skin.library", "language.trigger", "language.menu", "language.option",
]);
function pageOfPart(id: string): SkinLayoutPage | "common" | null {
@@ -451,6 +441,9 @@ const COMPONENT_NAME_PARTS: Record<string, string> = {
user: "User", video: "Video", viewer: "Viewer", viewers: "Viewers", visitors: "Visitors", voice: "Voice",
volume: "Volume", wave: "Wave", waveform: "Waveform", webrtc: "WebRTC", whisper: "Whisper", workspace: "Workspace",
wrap: "Wrapper", zone: "Drop zone",
host: "Host", plugins: "Plugins", launcher: "Launcher", overlay: "Overlay", watermark: "Watermark",
decoration: "Decoration", recovery: "Recovery", permission: "Permission", library: "Library",
clear: "Clear",
};
function componentName(id: string): string {
+155
View File
@@ -0,0 +1,155 @@
/**
* Single source of truth for the public skin part policy.
*
* `skin-css.ts` (CSS hiding whitelist), `skin-layout.ts` (layout editor
* metadata) and `skin-chrome.ts` (declarative host chrome document) all read
* these sets so a part can never be "hideable" in one layer and protected in
* another. Adding a part here is the only way to make it explicitly optional.
*/
/** Password dialog parts are trusted in both the CSS and layout layers. */
export const AUTH_PASSWORD_PART_IDS = [
"auth.password.backdrop",
"auth.password.dialog",
"auth.password.decoration",
"auth.password.eyebrow",
"auth.password.title",
"auth.password.lead",
"auth.password.form",
"auth.password.label",
"auth.password.field",
"auth.password.field-icon",
"auth.password.error",
"auth.password.actions",
] as const;
/**
* Host chrome is drawn by WebSpeak outside `.ws-skin-root` (Teleport to body)
* or is painted by the host with fixed artwork. A skin may theme these parts,
* but only through the dedicated document-level host scope, never with a
* global `html` / `body` selector.
*/
export const HOST_CHROME_PART_IDS: ReadonlySet<string> = new Set([
"host.plugins.launcher",
"host.plugins.overlay",
"host.watermark",
"host.hint",
"host.voice-status-decoration",
]);
/** Host parts that must stay reachable and can never be hidden or themed. */
export const HOST_TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
"host.recovery",
"host.permission",
]);
/** All host-owned parts (used by the part registry and documentation). */
export const HOST_PART_IDS: ReadonlySet<string> = new Set([
...HOST_CHROME_PART_IDS,
...HOST_TRUSTED_PART_IDS,
]);
/**
* Explicitly optional (decorative) visual parts. Both `OPTIONAL_VISUAL_PARTS`
* in the CSS compiler and `DECORATIVE_PART_IDS` in the layout registry are
* aliases of this set.
*
* `home.footer` is deliberately absent: the footer contains the necessary
* "clear local data" recovery link. The purely decorative text is split into
* `home.footer.decoration`, which is the part that may be hidden.
*/
export const DECORATIVE_PART_IDS: ReadonlySet<string> = new Set([
"demo.avatar", "demo.badge", "demo.note", "demo.poke-notification", "demo.wave",
"demo.member-status",
"home.feature", "home.features", "home.footer.decoration", "home.hero.eyebrow",
"home.gateway-status", "home.join-card.sonar", "home.join-card.waveform", "home.visitors",
"voice.activity.artwork", "voice.activity-heading", "voice.member.avatar",
"voice.member.avatar-wrap", "voice.member.live-indicator", "voice.member-row.avatar",
"voice.performance.metrics", "voice.performance.webrtc-stats",
"voice.screen-player.viewer-avatar", "voice.screen-player.live",
"host.watermark", "host.hint", "host.voice-status-decoration", "host.plugins.launcher",
]);
/** Trusted host UI: authorization, connection status, identity and recovery. */
export const TRUSTED_PART_IDS: ReadonlySet<string> = new Set([
...AUTH_PASSWORD_PART_IDS,
...HOST_TRUSTED_PART_IDS,
"app",
"app.toast",
"app.skin-load-recovery",
"home.security-note",
"home.identity-import.security",
"voice.connection-status",
"voice.screen-share-error",
]);
/**
* Parts that even an open (v3/v4) skin must never visually remove: the
* permission/recovery entries and the essential audio operation path.
*
* This is deliberately narrower than `TRUSTED_PART_IDS`: trusted metadata also
* covers decorative children of the password dialog (`auth.password.decoration`,
* `auth.password.eyebrow`, `auth.password.lead`, `auth.password.label`,
* `auth.password.field-icon`), which existing skins legitimately hide. Only the
* dialog shell, form, field, error and action row are protected.
*/
export const PROTECTED_PART_IDS: ReadonlySet<string> = new Set([
"app",
"app.toast",
"app.skin-load-recovery",
"home.security-note",
"home.identity-import.security",
// The footer container holds the necessary "clear local data" recovery
// link; only its decorative children may be hidden.
"home.footer",
"home.footer.clear",
"voice.connection-status",
"voice.connection-status.reconnect",
"voice.connection-status.nickname.input",
"voice.audio-status",
"voice.audio-dock",
"voice.audio-dock.microphone",
"voice.audio-dock.output",
"voice.audio-dock.microphone-panel",
"voice.audio-dock.output-panel",
"voice.audio-settings",
"voice.screen-share-error",
"voice.mobile-nav",
"voice.mobile-more",
"demo.reconnect.restore",
"auth.password.dialog",
"auth.password.form",
"auth.password.field",
"auth.password.error",
"auth.password.actions",
"host.recovery",
"host.permission",
]);
/** Stable icon bitmap slots. `chrome.json` may only reference these names. */
export const SKIN_ICON_SLOT_IDS: ReadonlySet<string> = new Set([
"host.plugins.launcher",
"language.trigger",
"skin.trigger",
"voice.performance",
"home.toolbar.settings",
]);
export function isHostChromePart(part: string): boolean {
return HOST_CHROME_PART_IDS.has(part);
}
export function isHostPart(part: string): boolean {
return HOST_PART_IDS.has(part) || part.startsWith("host.");
}
export function isDecorativePart(part: string): boolean {
return DECORATIVE_PART_IDS.has(part);
}
export function isProtectedPart(part: string): boolean {
return PROTECTED_PART_IDS.has(part);
}
/** Document-level marker set by the host while a custom skin is active. */
export const HOST_SKIN_ATTRIBUTE = "data-ws-host-skin";