From a4ae4de82fe19a5ca656c8f056a95c2caf31bb58 Mon Sep 17 00:00:00 2001 From: OddTurtleHead <355182507+OddTurtleHead@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:09:42 +0800 Subject: [PATCH 01/12] fix: close keyframe bypasses on protected controls without policing skin layout Hold @keyframes to the same hide/yeet checks as regular declarations, including escaped and namespaced animation names. Loosen decorative host-chrome layout locks so open skins can restyle layout freely. Listen for the recovery shortcut in the capture phase, move the load-failure banner into the host-owned layer, and fix recovery aria-labels. --- docs/SKIN_DEVELOPMENT.md | 12 +- src/shared/skin-css.test.ts | 114 ++++++++++++- src/shared/skin-css.ts | 150 ++++++++++++++---- web/src/components/HostChrome.vue | 9 +- web/src/components/SkinLoadRecoveryNotice.vue | 20 ++- web/src/i18n/host-chrome.ts | 10 +- web/src/services/host-owned-layer.ts | 2 +- web/test/fixtures/host-chrome-recovery.html | 2 + web/test/host-chrome-recovery.test.mjs | 24 ++- 9 files changed, 286 insertions(+), 57 deletions(-) diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index 875fdd1..e0564b2 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -435,7 +435,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 - 皮肤激活时,宿主在 `documentElement` 上设置 `data-ws-host-skin="<皮肤 ID>"`;停用或回退到内置皮肤时立即移除。 - 编译 `skin.css` 时,**只**命中下列宿主部件的单个选择器会被限定到 `:root[data-ws-host-skin="<皮肤 ID>"] …`,其余规则仍限定到 `.ws-skin-root[data-ws-skin="…"]`。宿主部件的选择器必须**以可主题化的 `[data-ws-part="host.…"]` 开头**,不能把 `:root`、`html`、`body` 或 `*:has(…)` 作为规则主体;`:root:has([data-ws-part="host.watermark"])` 一类写法会被拒绝。皮肤作者不能自己写 `html`、`body`、`data-ws-host-skin`、`data-ws-route`、`data-theme` 或 `data-ws-skin` 选择器,也不能在同一选择器里混用宿主部件与页面部件;宿主部件只对 schema v3/v4 开放皮肤生效。 -- 宿主外壳的布局与层级由 WebSpeak 拥有:皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform` 等把 `host.plugins.overlay` 之类控件变成全屏遮罩。 +- 宿主外壳的布局与层级:应用库外壳 `host.plugins.overlay` 仍由 WebSpeak 拥有——皮肤可改颜色、边框、圆角、阴影和素材,但不能用 `position`、`inset`、`z-index`、`transform`、尺寸等把它或其子元素变成全屏遮罩。装饰性宿主部件(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)可以被重定位、改变尺寸和动画化;恢复路径不依赖它们。 - 自定义变量仍必须使用 `--skin-` 前缀(不能覆盖宿主内部令牌),`@import`、脚本、`expression()`、`javascript:` 等仍被拒绝。 - 皮肤根作用域只在根内部向下生效。编译器会拒绝任何以 `:root` 开头、紧跟兄弟组合符(`+` / `~`)的选择器,例如 `:root ~ *`、`:root ~ [data-ws-host-layer]` 或 `:root:hover + div`;这类规则会被改写为皮肤根的兄弟选择器,从而够到 body 上的宿主层。`:root [data-ws-part="home.header"]`、`:root > [data-ws-part=…]` 这类后代/子代写法仍然可用。 - 宿主自有层的属性 `data-ws-host-layer`、`data-ws-host-recovery`、`data-ws-host-layer-content` 与 `data-ws-recovery-action` **不是皮肤钩子**:它们不在公开部件表中,编译器会按名称拒绝引用它们的皮肤选择器(包括 `:root [data-ws-host-layer]` 这类带公开钩子的混合写法)。 @@ -461,9 +461,9 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 **显示规则**:只要当前是第三方(非内置/非官方)皮肤,恢复入口就作为小型常驻胶囊显示在左下角;它不是水印或装饰条,官方 Day、Night、ILLUSIA 与 KAAK 皮肤不会自动出现它。对内置/官方皮肤,它只在 `host.plugins.launcher` 被实例配置或 `chrome.json` 声明隐藏、或宿主在已连接状态下检测到启动器被 CSS 隐藏/移出视口/不可点击时作为兜底出现。 -**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。 +**键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。 -`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不再对应可被皮肤命中的 DOM 钩子**。皮肤加载失败的横幅使用独立部件 `app.skin-load-recovery`(「切换到内置皮肤」),与恢复胶囊不是同一个钩子。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。 +`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不再对应可被皮肤命中的 DOM 钩子**。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),但它和恢复胶囊一样运行在闭合 Shadow DOM 宿主层中,编译后的皮肤 CSS 无法命中或改写它。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。 恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。 @@ -618,9 +618,11 @@ v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显 [data-ws-part="host.plugins.launcher"] ``` -上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。 +上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。 -皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。 +关键帧与普通声明遵循同一套受保护控件检查:如果关键帧被受保护控件(例如 `voice.audio-dock`)引用,则其中的 `display: none`、`opacity: 0`、把控件移出视口的 `transform`/`inset`/`margin`,以及 `filter: opacity(0)` / `brightness(0)` 等视觉移除写法都会被拒绝;受保护控件上的 `animation` / `animation-name` 也不能用 `var()` / `attr()` 间接指定动画名。只被可选/装饰部件引用的关键帧仍可隐藏它们,v3 对非受保护部件的隐藏只给出警告。`clip`、`clip-path` 和 `mask` 并非一律禁止:它们仅在受保护控件主体上(以及作为 `host.plugins.overlay` 的既有锁定属性)被拒绝;官方示例皮肤(harbor、kaak)已经使用 `clip-path`。校验器是恢复路径的最后一道安全网,不是布局或视觉质量检查;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。 + +皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。装饰性宿主外壳(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)和普通页面部件不受布局锁限制,可以自由使用 flex/grid、重定位、自定义尺寸、大背景和动画;固定定位或极端 `z-index` 只会给出提示。开放皮肤(v3/v4)的布局与视觉质量由官方库的人工审核保证,编译器不会阻止一般性的布局回归。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。 CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。 diff --git a/src/shared/skin-css.test.ts b/src/shared/skin-css.test.ts index 3cb73db..c5ca71b 100644 --- a/src/shared/skin-css.test.ts +++ b/src/shared/skin-css.test.ts @@ -277,7 +277,6 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => { () => 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 @@ -286,7 +285,6 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => { '[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); } @@ -299,6 +297,19 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => { assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css); } + // Decorative host chrome is not on the recovery path: it may be repositioned, + // resized, restacked and animated, at most with a warning. + for (const css of [ + '[data-ws-part="host.watermark"] { position: fixed; }', + '[data-ws-part="host.watermark"] * { z-index: 2147483647; }', + '[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; }', + '[data-ws-part="host.plugins.launcher"] { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; }', + '[data-ws-part="host.hint"] { position: absolute; transform: translateX(-10px); }', + '[data-ws-part="host.voice-status-decoration"] { position: fixed; inset: 0; pointer-events: none; }', + ]) { + assert.doesNotThrow(() => compile(css), 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; }'); @@ -307,6 +318,105 @@ test("host chrome cannot be restyled into a viewport-sized overlay", () => { assert.doesNotThrow(() => compile('[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; width: 120px; }')); }); +test("keyframes follow the same protected-control rules as regular declarations", () => { + const rejected: Array<[string, RegExp]> = [ + ['@keyframes k { to { display: none; opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/], + ['@keyframes k { to { visibility: hidden; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain available/], + ['@keyframes k { to { transform: translateX(-9999px); } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/], + ['@keyframes k { to { inset: 0 0 0 -120vw; } } [data-ws-part="voice.audio-dock"] { animation: k 1s forwards; }', /must remain on screen/], + ['@keyframes k { to { filter: opacity(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain visible/], + ['@keyframes k { to { filter: brightness(0); } } [data-ws-part="voice.audio-dock"] { animation-name: k; }', /must remain visible/], + // A variable animation name must not hide the name from the walk. + [':root { --skin-anim: k; } @keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation: var(--skin-anim) 1s forwards; }', /cannot use indirect values/], + ['@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { --skin-anim: k; } [data-ws-part="voice.audio-dock"] { animation-name: var(--skin-anim); }', /cannot use indirect values/], + ]; + for (const [css, message] of rejected) { + assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css); + } + // A keyframe shared by a protected and a non-protected part is judged by the + // protected reference. + assert.throws( + () => compile('@keyframes k { to { opacity: 0; } } [data-ws-part="home.title"] { animation: k 1s; } [data-ws-part="voice.audio-dock"] { animation: k 1s; }'), + /must remain available/, + ); + + // Harmless fades, color tweens and gentle motion on non-protected parts, and + // visual / motion keyframes on decorative host parts, still compile. + for (const css of [ + '@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { animation: fade 2s ease; }', + '@keyframes tint { from { color: #fff; } to { color: #1d4f9c; } } [data-ws-part="home.header"] { animation: tint 1.2s; }', + '@keyframes drift { from { transform: translateY(0); } to { transform: translateY(-6px); } } [data-ws-part="home.hero.eyebrow"] { animation: drift 3s infinite alternate; }', + '@keyframes wm { from { opacity: .1; color: #8ab9cf; transform: translateX(0); } to { opacity: .3; color: #2b6d8a; transform: translateX(20px); } } [data-ws-part="host.watermark"] { animation: wm 4s infinite alternate; }', + '@keyframes big { to { width: 100vw; height: 100vh; opacity: .2; } } [data-ws-part="host.watermark"] { animation: big 1s forwards; }', + '@keyframes hide { to { display: none; } } [data-ws-part="host.hint"] { animation: hide 1s forwards; }', + ]) { + assert.doesNotThrow(() => compile(css), css); + } +}); + +test("escaped, namespaced and :is()/:where() animation names cannot bypass the protected-control locks", () => { + const rejected: Array<[string, RegExp]> = [ + // Escaped property name used to skip the keyframe mapping walk. + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { anim\\61 tion: k 1s forwards; }', /must remain available/], + // A pack can predict the namespace and reference the already-renamed keyframe. + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-k 1s forwards; }', /must remain available/], + // The protected subject can be wrapped in a functional pseudo-class. + [':is([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/], + [':where([data-ws-part="voice.audio-dock"]) { display: none; }', /must remain available/], + ['@keyframes k { to { opacity: 0; } } :is([data-ws-part="voice.audio-dock"]) { animation: k 1s forwards; }', /must remain available/], + // -webkit-* animation longhands participate in the same walks. + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation: k 1s forwards; }', /must remain available/], + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { -webkit-animation-name: k; }', /must remain available/], + ['[data-ws-part="voice.audio-dock"] { -webkit-animation: var(--skin-a); }', /cannot use indirect values/], + // Escaped *values* used to bail out of the mapping walk on a backslash and + // still resolve to the renamed keyframe in the browser. + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\6b 1s forwards; }', /must remain available/], + ['@keyframes k { to { display: none; } } [data-ws-part="voice.audio-dock"] { animation: ws-demo-skin-\\00006b 1s forwards; }', /must remain available/], + ['@keyframes k { to { opacity: 0; } } [data-ws-part="voice.audio-dock"] { animation-name: \\6b; }', /must remain available/], + // Prefixed visual-removal properties must use the same checks as the unprefixed form. + ['[data-ws-part="voice.audio-dock"] { -webkit-filter: opacity(0); }', /must remain visible/], + ['[data-ws-part="voice.audio-dock"] { -webkit-transform: scale(0); }', /must remain visible/], + ]; + for (const [css, message] of rejected) { + assert.throws(() => compile(css), (error: unknown) => error instanceof Error && message.test(error.message), css); + } + + // `:not()` does not make the protected part the subject; only a v3 warning. + assert.doesNotThrow(() => compile(':not([data-ws-part="voice.audio-dock"]) { display: none; }')); + + // A harmless -webkit-animation on a non-protected part still compiles and its + // keyframe name is rewritten into the skin namespace. + const webkit = compile('@keyframes fade { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="home.title"] { -webkit-animation: fade 2s ease; }'); + assert.match(webkit.css, /@keyframes ws-demo-skin-fade/); + assert.match(webkit.css, /-webkit-animation: ws-demo-skin-fade 2s ease/); +}); + +test("keyframes cannot turn the plugin overlay into a fullscreen layer", () => { + for (const css of [ + '@keyframes k { to { position: fixed; inset: 0; z-index: 2147483647; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }', + '@keyframes k { to { width: 100vw; height: 100vh; } } [data-ws-part="host.plugins.overlay"] * { animation: k 1s forwards; }', + '@keyframes k { to { zoom: 10; } } [data-ws-part="host.plugins.overlay"] { animation: k 1s forwards; }', + '@keyframes k { to { transform: scale(10); } } [data-ws-part="host.plugins.overlay"] { animation-name: k; }', + ]) { + assert.throws(() => compile(css), /layout is owned by WebSpeak|fullscreen overlay/, css); + } + // The same animation is harmless on decorative host chrome. + assert.doesNotThrow(() => compile('@keyframes k { to { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; opacity: .2; } } [data-ws-part="host.watermark"] { animation: k 1s forwards; }')); +}); + +test("large layout restyles of non-protected parts and decorative host chrome compile", () => { + for (const css of [ + '[data-ws-part="home.header"] { display: grid; grid-template-columns: 1fr 2fr; gap: 16px; position: relative; width: 80vw; height: 50vh; }', + '[data-ws-part="home.header"] { display: flex; flex-direction: column; align-items: stretch; translate: 24px 0; }', + '[data-ws-part="voice.audio-dock"] > div:first-child { position: absolute; width: 100vw; height: 100vh; }', + // Official example skins (harbor, kaak) clip their own artwork. + '[data-ws-part="home.header"] { clip-path: polygon(0 0, 100% 0, 100% 82%, 0 100%); }', + '[data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; transform: rotate(-8deg); }', + ]) { + assert.doesNotThrow(() => compile(css), css); + } +}); + 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()); diff --git a/src/shared/skin-css.ts b/src/shared/skin-css.ts index 543d340..48e9e73 100644 --- a/src/shared/skin-css.ts +++ b/src/shared/skin-css.ts @@ -1,5 +1,5 @@ import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss"; -import selectorParser from "postcss-selector-parser"; +import selectorParser, { type Node as SelectorNode } from "postcss-selector-parser"; import valueParser from "postcss-value-parser"; import { DECORATIVE_PART_IDS as OPTIONAL_VISUAL_PARTS, @@ -180,21 +180,47 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets const referencedKeyframes = new Set(); const nonOptionalKeyframes = new Set(); + // Keyframes referenced by a protected control must obey the same + // visibility/positioning rules as a declaration on that control. Keyframe + // params are already namespaced at this point, so the maps use scoped names. + const protectedKeyframeParts = new Map(); + // Keyframes referenced by non-decorative host chrome (the plugin overlay + // shell) keep the host layout locks; decorative host parts are free to move. + const lockedHostKeyframeParts = new Map>(); root.walkRules((rule: Rule) => { if (hasKeyframesAncestor(rule)) return; const optionalTarget = hideableRules.has(rule); rule.walkDecls((declaration: Declaration) => { - const property = declaration.prop.toLowerCase(); + // Match the enforcement walk: decode the property so an escaped + // `anim\61 tion` cannot skip the keyframe mapping, and treat + // `-webkit-animation` as `animation`. + const property = decodeCssEscapes(declaration.prop).toLowerCase().replace(/^-(?:webkit|moz|ms|o)-/, ""); if (property !== "animation" && property !== "animation-name") return; - const value = declaration.value; - if (/\b(?:var|attr)\s*\(|\\/i.test(value)) { + // Decode first so an escaped identifier (`\6b`, `ws-…-\00006b`) is + // matched against the original and namespaced names. `var()`/`attr()` + // still cannot be resolved statically; only those bail out. A bare + // backslash is no longer a reason to skip protected mapping. + const decodedValue = decodeCssEscapes(declaration.value); + if (/\b(?:var|attr)\s*\(/i.test(decodedValue)) { keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name)); return; } - for (const name of keyframeNames.keys()) { - if (!referencesCssIdentifier(value, name)) continue; + // The value may already use the namespaced name (a pack can name its own + // id), so match both the original and the rewritten identifier. + const protectedTarget = selectorSubjectProtectedPart(rule.selector); + const lockedHostParts = selectorLockedHostParts(rule.selector); + for (const [name, scopedName] of keyframeNames) { + if (!referencesCssIdentifier(decodedValue, name) && !referencesCssIdentifier(decodedValue, scopedName)) continue; referencedKeyframes.add(name); if (!optionalTarget) nonOptionalKeyframes.add(name); + if (protectedTarget && !protectedKeyframeParts.has(scopedName)) { + protectedKeyframeParts.set(scopedName, protectedTarget); + } + if (lockedHostParts.length) { + const parts = lockedHostKeyframeParts.get(scopedName) ?? new Set(); + for (const part of lockedHostParts) parts.add(part); + lockedHostKeyframeParts.set(scopedName, parts); + } } }); }); @@ -209,17 +235,30 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets const decodedValue = decodeCssEscapes(value); const owningRule = findOwningRule(declaration); const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null; + const keyframeScope = keyframesRule?.params.trim() ?? null; 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; + // skin root, so a container-level hide cannot remove them either. A + // keyframe inherits the protected status of the rules that reference it. + const protectedTarget = owningRule + ? keyframesRule + ? (keyframeScope ? protectedKeyframeParts.get(keyframeScope) ?? null : null) + : 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) : []; + // Decorative host chrome (watermark, hint, status strip, plugin launcher) + // is free to be repositioned; only non-decorative host chrome keeps its + // layout locks. + const hostChromeParts = owningRule + ? keyframesRule + ? (keyframeScope ? [...(lockedHostKeyframeParts.get(keyframeScope) ?? [])] : []) + : selectorLockedHostParts(owningRule.selector) + : []; const inHostChromeScope = hostChromeParts.length > 0; const inOverlayScope = hostChromeParts.includes("host.plugins.overlay"); if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property) @@ -231,10 +270,11 @@ 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. + // Non-decorative 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. Decorative host parts skip this + // lock so they can be repositioned and resized freely. 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."); } @@ -252,22 +292,29 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets } 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") - || (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue)) - || (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue)) - || (property === "pointer-events" && compactValue === "none") - || (property === "clip-path" && /inset\(\s*50%/.test(compactValue)) - || (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue)); + // An indirect animation name could resolve to a keyframe that hides or + // moves the subject; check it at the declaration site instead of treating + // every keyframe in the file as protected. + if (!keyframesRule && protectedTarget && (unprefixedProperty === "animation" || unprefixedProperty === "animation-name") + && /\b(?:var|attr)\s*\(/i.test(decodedValue)) { + throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`); + } + const removesVisual = unprefixedProperty === "all" + || (unprefixedProperty === "display" && compactValue === "none") + || (unprefixedProperty === "visibility" && /^(?:hidden|collapse)$/.test(compactValue)) + || (unprefixedProperty === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue)) + || (unprefixedProperty === "pointer-events" && compactValue === "none") + || (unprefixedProperty === "clip-path" && /inset\(\s*50%/.test(compactValue)) + || (unprefixedProperty === "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)); + const visuallyRemoves = (unprefixedProperty === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue)) + || (unprefixedProperty === "clip-path" && /inset\(\s*50%/i.test(decodedValue)) + || (unprefixedProperty === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue)); if (visuallyRemoves && protectedTarget) { throw declaration.error(`The required control "${protectedTarget}" must remain visible.`); } @@ -279,7 +326,7 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets } 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); + const withScopedNames = rewriteScopedNames(value, unprefixedProperty, keyframeNames, fontFamilyNames); declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => { if (!hasSkinCssAsset(assets, assetPath)) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`); return `wskin-asset:${encodeURIComponent(assetPath)}`; @@ -427,21 +474,46 @@ function assertHostChromeSubject(parsed: selectorParser.Root): void { } } +/** Functional pseudo-classes whose arguments keep the subject role. */ +const SUBJECT_PSEUDO_CLASSES = new Set([":is", ":where", ":matches", ":-webkit-any", ":-moz-any"]); + +/** The nodes after the last combinator, i.e. the subject compound. */ +function lastCompound(nodes: SelectorNode[]): SelectorNode[] { + let start = 0; + for (let index = nodes.length - 1; index >= 0; index -= 1) { + if (nodes[index].type === "combinator") { start = index + 1; break; } + } + return nodes.slice(start); +} + +/** + * Find a protected part in one compound. The subject may be wrapped in + * `:is()`/`:where()`, so descend into those arguments. `:not(...)` is + * deliberately skipped: a protected part inside `:not()` is not the subject. + */ +function compoundProtectedPart(nodes: SelectorNode[]): string | null { + for (const node of nodes) { + if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) { + const part = node.value.replace(/^['"]|['"]$/g, ""); + if (PROTECTED_PART_IDS.has(part)) return part; + } + if (node.type === "pseudo" && node.nodes && SUBJECT_PSEUDO_CLASSES.has(node.value.toLowerCase())) { + for (const nested of node.nodes) { + const part = compoundProtectedPart(lastCompound(nested.nodes)); + if (part) return part; + } + } + } + return null; +} + /** 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; - } + const part = compoundProtectedPart(lastCompound(item.nodes)); + if (part) return part; } } catch { /* A malformed selector is rejected elsewhere. */ } return null; @@ -460,6 +532,16 @@ function selectorHostChromeParts(selector: string): string[] { return parts; } +/** + * Host parts whose layout stays owned by WebSpeak. Decorative host chrome (the + * watermark, hint, voice-status strip and plugin launcher) is deliberately + * excluded: skins may reposition, resize and animate it because recovery does + * not depend on it. + */ +function selectorLockedHostParts(selector: string): string[] { + return selectorHostChromeParts(selector).filter((part) => !OPTIONAL_VISUAL_PARTS.has(part)); +} + function isLayoutAffectingProperty(property: string): boolean { const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, ""); if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true; diff --git a/web/src/components/HostChrome.vue b/web/src/components/HostChrome.vue index 09d81d7..eea4ac2 100644 --- a/web/src/components/HostChrome.vue +++ b/web/src/components/HostChrome.vue @@ -162,13 +162,16 @@ function openLibrary() { } function onKeydown(event: KeyboardEvent) { - if (event.defaultPrevented || event.repeat || !thirdPartyAllowed.value) return; + if (event.repeat || !thirdPartyAllowed.value) return; + // The recovery chord must survive a capture-phase preventDefault() from a + // skin or plugin, so it runs before the defaultPrevented check below. if (isRecoveryShortcut(event)) { event.preventDefault(); shortcutOpen.value = true; void nextTick(() => recoveryPopover.value?.querySelector("button")?.focus()); return; } + if (event.defaultPrevented) return; if (event.key === "Escape" && shortcutOpen.value) shortcutOpen.value = false; } @@ -184,13 +187,13 @@ onMounted(() => { refreshLauncherReachability(); reachabilityTimer = setInterval(refreshLauncherReachability, 1000); window.addEventListener("resize", refreshLauncherReachability); - window.addEventListener("keydown", onKeydown); + window.addEventListener("keydown", onKeydown, true); void nextTick(syncPopover); }); onBeforeUnmount(() => { if (reachabilityTimer) clearInterval(reachabilityTimer); window.removeEventListener("resize", refreshLauncherReachability); - window.removeEventListener("keydown", onKeydown); + window.removeEventListener("keydown", onKeydown, true); layer?.dispose(); }); diff --git a/web/src/components/SkinLoadRecoveryNotice.vue b/web/src/components/SkinLoadRecoveryNotice.vue index dbff921..308b66e 100644 --- a/web/src/components/SkinLoadRecoveryNotice.vue +++ b/web/src/components/SkinLoadRecoveryNotice.vue @@ -1,5 +1,5 @@ - +`; + +const layer: HostOwnedLayer | null = createHostOwnedLayer("skin-load", SKIN_LOAD_LAYER_CSS); + +onBeforeUnmount(() => layer?.dispose()); + diff --git a/web/src/i18n/host-chrome.ts b/web/src/i18n/host-chrome.ts index 5ccaade..7f1b75d 100644 --- a/web/src/i18n/host-chrome.ts +++ b/web/src/i18n/host-chrome.ts @@ -4,7 +4,7 @@ import type { SiteLanguage } from "../../../src/site-copy.js"; const en = { hint: "Audio controls remain available in the toolbar and voice workspace.", library: "Application library", - recovery: "Restore application library", + recovery: "Restore built-in skin", useBuiltIn: "Use built-in skin", shortcut: "Restore the built-in skin (Ctrl+Alt+Shift+R, or ⌘+⌥+⇧+R on macOS)", }; @@ -13,28 +13,28 @@ export const hostChromeCopy: Record = { zh: { hint: "音频控制始终保留在工具栏和语音工作区中。", library: "应用库", - recovery: "恢复应用库", + recovery: "恢复内置皮肤", useBuiltIn: "使用内置皮肤", shortcut: "恢复内置皮肤(Ctrl+Alt+Shift+R,macOS 为 ⌘+⌥+⇧+R)", }, de: { hint: "Audiosteuerung bleibt in der Werkzeugleiste und im Sprachbereich verfügbar.", library: "Anwendungsbibliothek", - recovery: "Anwendungsbibliothek wiederherstellen", + recovery: "Integrierten Skin wiederherstellen", useBuiltIn: "Integrierten Skin verwenden", shortcut: "Integrierten Skin wiederherstellen (Strg+Alt+Umschalt+R, unter macOS ⌘+⌥+⇧+R)", }, ru: { hint: "Управление звуком остаётся доступным на панели инструментов и в голосовой области.", library: "Библиотека приложений", - recovery: "Восстановить библиотеку приложений", + recovery: "Восстановить встроенную тему", useBuiltIn: "Использовать встроенную тему", shortcut: "Восстановить встроенную тему (Ctrl+Alt+Shift+R, в macOS ⌘+⌥+⇧+R)", }, ja: { hint: "音声コントロールはツールバーと音声ワークスペースで常に利用できます。", library: "アプリライブラリ", - recovery: "アプリライブラリを復元", + recovery: "組み込みスキンを復元", useBuiltIn: "組み込みスキンを使用", shortcut: "組み込みスキンを復元(Ctrl+Alt+Shift+R、macOS は ⌘+⌥+⇧+R)", }, diff --git a/web/src/services/host-owned-layer.ts b/web/src/services/host-owned-layer.ts index 04a96d9..6a1d742 100644 --- a/web/src/services/host-owned-layer.ts +++ b/web/src/services/host-owned-layer.ts @@ -17,7 +17,7 @@ * without the Popover API still shows the UI above ordinary content. */ -export type HostOwnedLayerName = "recovery" | "authorization"; +export type HostOwnedLayerName = "recovery" | "authorization" | "skin-load"; /** * The CSS 32-bit maximum stacking value. A compiled skin may legitimately use diff --git a/web/test/fixtures/host-chrome-recovery.html b/web/test/fixtures/host-chrome-recovery.html index 99b6f0b..8f6a386 100644 --- a/web/test/fixtures/host-chrome-recovery.html +++ b/web/test/fixtures/host-chrome-recovery.html @@ -26,6 +26,8 @@
Application library
+ +
pending
diff --git a/web/test/host-chrome-recovery.test.mjs b/web/test/host-chrome-recovery.test.mjs index 79469c7..c38716b 100644 --- a/web/test/host-chrome-recovery.test.mjs +++ b/web/test/host-chrome-recovery.test.mjs @@ -42,15 +42,26 @@ const scenarios = [ name: "pointer-events-none", css: compileHostile('[data-ws-part="host.plugins.launcher"], [data-ws-part="host.plugins.overlay"] { pointer-events: none !important; }'), }, + { + // Decorative host chrome may legitimately be a fixed, viewport-sized, + // max-stacking decoration. Recovery lives in a closed-shadow top layer and + // must still win the hit test. + name: "decorative-watermark-overlay", + css: compileHostile(` + @keyframes drift { from { transform: translateX(0); } to { transform: translateX(12px); } } + [data-ws-part="host.watermark"] { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 2147483647; background: #123; animation: drift 3s ease-in-out infinite alternate; } + `), + }, ]; test("host chrome renders recovery and authorization in a closed-shadow top layer", async () => { - const [hostChrome, authorization, ownedLayer, hostChromeService, publicSkin] = await Promise.all([ + const [hostChrome, authorization, ownedLayer, hostChromeService, publicSkin, recoveryNotice] = await Promise.all([ read("../src/components/HostChrome.vue"), read("../src/components/InstanceAuthorization.vue"), read("../src/services/host-owned-layer.ts"), read("../src/services/host-chrome.ts"), read("../src/composables/usePublicSkin.ts"), + read("../src/components/SkinLoadRecoveryNotice.vue"), ]); // Recovery: closed shadow root + manual popover + no skin hook. @@ -59,6 +70,11 @@ test("host chrome renders recovery and authorization in a closed-shadow top laye assert.match(hostChrome, /data-ws-recovery-action="built-in"/); assert.match(hostChrome, /requestBuiltInSkin/); assert.match(hostChrome, /isThirdPartySkinActive/); + // The shortcut runs in the capture phase so a plugin/skin capture listener + // cannot swallow it with preventDefault(). + assert.match(hostChrome, /addEventListener\("keydown", onKeydown, true\)/); + assert.match(hostChrome, /removeEventListener\("keydown", onKeydown, true\)/); + assert.doesNotMatch(hostChrome, /event\.defaultPrevented \|\| event\.repeat/); assert.doesNotMatch(hostChrome, /data-ws-part="host\.recovery"/); assert.doesNotMatch(hostChrome, /ws-host-recovery-layer/); @@ -67,6 +83,12 @@ test("host chrome renders recovery and authorization in a closed-shadow top laye assert.match(authorization, /showModal\(\)/); assert.doesNotMatch(authorization, /data-ws-part="host\.permission"/); + // The load-failure banner is trusted UI too: closed shadow layer, stylesheet + // inside the boundary, no document-level scoped stylesheet to override. + assert.match(recoveryNotice, /createHostOwnedLayer\("skin-load"/); + assert.match(recoveryNotice, /data-ws-part="app\.skin-load-recovery"/); + assert.doesNotMatch(recoveryNotice, / + + + +
+
+
+ +
+
+
pending
+ + + diff --git a/web/test/host-chrome-recovery.test.mjs b/web/test/host-chrome-recovery.test.mjs index b32a622..1a05e2c 100644 --- a/web/test/host-chrome-recovery.test.mjs +++ b/web/test/host-chrome-recovery.test.mjs @@ -76,7 +76,8 @@ test("host chrome renders recovery and authorization in a closed-shadow top laye assert.match(hostChrome, /addEventListener\("keydown", onKeydown, true\)/); assert.match(hostChrome, /removeEventListener\("keydown", onKeydown, true\)/); // Escape closes the popover from inside its closed shadow root. - assert.match(hostChrome, /@keydown\.escape="shortcutOpen = false"/); + assert.match(hostChrome, /@keydown\.escape="onRecoveryEscape"/); + assert.match(hostChrome, /function onRecoveryEscape\(\) \{\s*shortcutOpen\.value = false;/); assert.doesNotMatch(hostChrome, /event\.defaultPrevented \|\| event\.repeat/); assert.doesNotMatch(hostChrome, /data-ws-part="host\.recovery"/); assert.doesNotMatch(hostChrome, /ws-host-recovery-layer/); @@ -237,3 +238,59 @@ test("recovery stays visible and clickable under hostile compiled skins", { skip assert.equal(result.layerOutsideSkinRoot, true, `${result.name}: recovery was rendered inside .ws-skin-root`); } }); + +test("a declared slot docks the capsule and falls back at runtime", { skip: !CHROME && "google-chrome is not installed" }, async (t) => { + const server = await createServer({ + root: webRoot, + configFile: path.join(webRoot, "vite.config.ts"), + logLevel: "silent", + server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false }, + }); + t.after(() => server.close()); + await server.listen(); + const address = server.httpServer?.address(); + const port = address && typeof address === "object" ? address.port : 0; + assert.ok(port, "Vite did not expose a listening port"); + + const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-slot-placement.html`); + const match = dom.match(/
]*>([\s\S]*?)<\/pre>/);
+  assert.ok(match, "the fixture did not emit a result block");
+  const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
+  assert.equal(payload.error, undefined, payload.error);
+  const byName = Object.fromEntries(payload.results.map((result) => [result.name, result]));
+
+  const initial = byName.initial;
+  assert.equal(initial.mode, "slotted", JSON.stringify(payload));
+  assert.equal(initial.insideAnchor, true, "the capsule is not placed over the anchor");
+  assert.equal(initial.hitIsLayerHost, true, "the docked capsule is not the hit-test target");
+  assert.equal(initial.background, "rgb(16, 32, 48)", "skin background token was not applied");
+  assert.equal(initial.color, "rgb(255, 255, 255)", "skin foreground token was not applied");
+  assert.ok(initial.buttonHeight >= 36, "the large size tier minimum was not enforced");
+
+  assert.equal(byName["anchor-hidden"].mode, "floating");
+  assert.equal(byName["anchor-hidden"].reason, "anchor-missing");
+  assert.equal(byName["anchor-hidden"].inlineLeft, "");
+  assert.equal(byName["anchor-hidden"].atDefaultCorner, true);
+
+  // Anti-flap: one good check after a fallback is not enough to re-dock.
+  assert.equal(byName["restored-once"].mode, "floating");
+  assert.equal(byName["restored-twice"].mode, "slotted");
+  assert.equal(byName["restored-twice"].insideAnchor, true);
+
+  assert.equal(byName["covers-mic"].mode, "floating");
+  assert.equal(byName["covers-mic"].reason, "covers-protected");
+  assert.equal(byName["covers-mic"].atDefaultCorner, true);
+
+  assert.equal(byName["anchor-offscreen"].mode, "floating");
+  // An invisible/off-screen element is never resolved as the anchor at all.
+  assert.equal(byName["anchor-offscreen"].reason, "anchor-missing");
+  assert.equal(byName["anchor-offscreen"].atDefaultCorner, true);
+
+  // Foreground equal to background: the whole colour group reverts.
+  assert.equal(byName["unreadable-tokens"].background, "rgb(255, 255, 255)");
+  assert.equal(byName["unreadable-tokens"].color, "rgb(49, 82, 79)");
+
+  assert.equal(byName.disposed.inlineLeft, "");
+  assert.equal(byName.disposed.atDefaultCorner, true);
+  assert.equal(byName.disposed.leftoverAccent, "");
+});

From c1187d12d267a6aa018dedd067dea495c3f5135a Mon Sep 17 00:00:00 2001
From: OddTurtleHead <355182507+OddTurtleHead@users.noreply.github.com>
Date: Sun, 15 Nov 2026 17:03:07 +0800
Subject: [PATCH 05/12] feat: let skins theme every protected control through
 skin.css and shared host tokens

App-DOM protected parts keep only hide/off-screen/disable guards; host-owned recovery capsule, skin-load banner and authorization dialog read one sanitized --skin-host-* token set with per-part overrides (--skin-recovery-*, --skin-load-recovery-*, --skin-permission-*) via the new host-control-tokens module.
---
 docs/SKIN_DEVELOPMENT.md                      |  75 ++-
 docs/examples/host-chrome-demo.wskin          | Bin 2778 -> 3188 bytes
 docs/examples/host-chrome-demo/manifest.json  |   2 +-
 docs/examples/host-chrome-demo/skin.css       |  57 ++
 docs/examples/host-chrome-themed.wskin        | Bin 2685 -> 3095 bytes
 package.json                                  |   2 +-
 src/shared/skin-css.test.ts                   |  51 ++
 src/shared/skin-css.ts                        |   7 +-
 web/public/host-chrome-demo.wskin             | Bin 2778 -> 3188 bytes
 web/public/host-chrome-themed.wskin           | Bin 2685 -> 3095 bytes
 web/src/components/HostChrome.vue             |  57 +-
 web/src/components/InstanceAuthorization.vue  |  25 +-
 web/src/components/SkinLoadRecoveryNotice.vue |  49 +-
 web/src/services/host-control-tokens.test.ts  | 250 +++++++++
 web/src/services/host-control-tokens.ts       | 522 ++++++++++++++++++
 web/src/services/host-slot-placement.test.ts  | 108 +---
 web/src/services/host-slot-placement.ts       | 296 +---------
 web/test/fixtures/host-slot-placement.html    |   8 +-
 web/test/host-chrome-recovery.test.mjs        |   7 +
 19 files changed, 1094 insertions(+), 422 deletions(-)
 create mode 100644 web/src/services/host-control-tokens.test.ts
 create mode 100644 web/src/services/host-control-tokens.ts

diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md
index c841748..4a3d937 100644
--- a/docs/SKIN_DEVELOPMENT.md
+++ b/docs/SKIN_DEVELOPMENT.md
@@ -406,7 +406,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 | 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
 | 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
 | `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
-| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 停靠到皮肤布局,但仍无 CSS 钩子)/ `host.permission` / `app.skin-load-recovery` 仅为宿主内部标识(闭合 Shadow DOM,恢复入口与授权对话框还在顶层;无 CSS 钩子,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
+| 宿主外壳(皮肤根之外 / 宿主固定绘制) | 可主题化:`host.plugins.launcher`、`host.plugins.overlay`、`host.watermark`、`host.hint`、`host.voice-status-decoration`;`host.recovery`(可经 `chrome.json#slots` 停靠,并可用 `--skin-recovery-*` / `--skin-host-*` 令牌换肤)/ `host.permission` 与 `app.skin-load-recovery`(无 CSS 钩子;分别用 `--skin-permission-*` / `--skin-load-recovery-*` 令牌换肤,见下文);`skin.library` 是皮肤菜单里的应用库入口 |
 | 首页页脚拆分 | `home.footer`(容器,不可隐藏)、`home.footer.decoration`(装饰文案,可隐藏)、`home.footer.clear`(必要链接,受保护) |
 
 `voice.member.avatar` 是语音活动区头像;`voice.member.mic-status` 在成员麦克风静音时显示,状态值为 `muted`;`voice.member.action-trigger` 是打开宿主成员操作菜单的按钮,由成员卡片小组件的 `options.memberActions` 控制;`voice.member-row.avatar` 是右侧成员树头像。语音成员列表的动态项提供 `.ws-voice-member-enter-active`、`.ws-voice-member-leave-active`、`.ws-voice-member-enter-from`、`.ws-voice-member-leave-to` 和 `.ws-voice-member-move` 动效钩子,可分别设置加入、离开和排序变化的过渡。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
@@ -453,7 +453,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 
 ### 恢复入口与授权对话框:结构上不可被皮肤触及
 
-`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接主题化的 CSS 钩子(`host.recovery` 只能通过下文的 `chrome.json#slots` 声明锚点和受限的 `--skin-recovery-*` 令牌间接参与布局):当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们:
+`host.recovery`(恢复入口)与 `host.permission`(授权对话框)是可信宿主控件。它们**不是**可供皮肤选择或直接改写的 CSS 钩子;当前客户端把两者渲染在 `Teleport` 到 `body` 的宿主层里,该层满足下面三条,编译后的皮肤 CSS 无法命中、遮挡或禁用它们。皮肤可以通过下文「受保护控件的主题化」中的受控令牌让它们融入外观,`host.recovery` 还可以通过 `chrome.json#slots` 停靠到皮肤布局:
 
 1. **闭合 Shadow DOM**:内容位于 `attachShadow({ mode: "closed" })` 的根内。作者 CSS(无论影子根开或闭)不能跨越 shadow 边界;宿主层元素本身也不带任何 `data-ws-part`,因此连文档级宿主作用域(`:root[data-ws-host-skin="…"] [data-ws-part="host.…"]`)也匹配不到。
 2. **顶层(top layer)**:恢复入口是 `popover="manual"`,授权对话框是 `` + `showModal()`。顶层绘制高于所有普通层叠上下文,包括皮肤把某个公开部件写成 `position: fixed; inset: 0; z-index: 2147483647` 的全屏层。
@@ -463,7 +463,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 
 **键盘快捷键**:第三方皮肤被允许时,`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)随时把同一宿主层恢复入口召唤到顶层并聚焦第一个按钮;它不与 WebSpeak 现有快捷键或浏览器常用快捷键冲突。监听器运行在捕获阶段,皮肤或插件脚本提前调用 `preventDefault()` 不会吞掉该组合键。
 
-`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不再对应可被皮肤命中的 DOM 钩子**。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),但它和恢复胶囊一样运行在闭合 Shadow DOM 宿主层中,编译后的皮肤 CSS 无法命中或改写它。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
+`host.recovery` 与 `host.permission` 这两个名称仅保留为文档/布局元数据中的概念标识,**不对应可被皮肤命中的 DOM 钩子**。当前客户端没有渲染 `host.permission` 元素;授权界面由宿主自己的 `InstanceAuthorization` 对话框绘制,它和恢复胶囊一样位于闭合 Shadow DOM 的顶层。皮肤加载失败的横幅保留 `app.skin-load-recovery` 部件标识(「切换到内置皮肤」),它同样运行在闭合 Shadow DOM 宿主层中。三者都只能通过受保护控件令牌间接换肤,编译后的皮肤 CSS 无法命中或改写它们。`skin.library` 是皮肤菜单里的应用库快捷入口,可作辅助路径,但**不是**兜底。
 
 恢复入口的宿主层与授权对话框的宿主层各自独立;两者都不与装饰同父,因此 `[data-ws-part="host.watermark"] ~ *` 一类兄弟选择器也碰不到它们。
 
@@ -492,13 +492,14 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 
 **这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
 
-**样式令牌**:皮肤可在锚点或它的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。令牌只对声明了 `slots` 的皮肤生效(没有插槽的皮肤里写了也不会读取,胶囊保持默认外观)。锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
+**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
 
 | 令牌 | 规则 |
 | --- | --- |
 | `--skin-recovery-accent` | 强调色,用于紧凑模式焦点框和「使用内置皮肤」按钮的边框。与背景的对比度必须 ≥ 3,否则整组颜色回退。该按钮自身固定为浅色底 `#fff7ed`,如果强调色在这块浅底上对比度不足 3,只有这个按钮的边框改用宿主默认 `#b45309`,其余位置仍用皮肤强调色。 |
-| `--skin-recovery-background` | 胶囊背景。宿主强制不透明(alpha 视为 1)。 |
+| `--skin-recovery-background` | 胶囊和按钮背景。宿主强制不透明(alpha 视为 1)。 |
 | `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 |
+| `--skin-recovery-border` | 胶囊和普通按钮的边框色。与背景的对比度必须 ≥ 3,否则使用宿主默认边框;不影响固定浅色底的「使用内置皮肤」按钮。 |
 | `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 |
 | `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;其他值使用宿主默认字体。 |
 | `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 |
@@ -509,6 +510,70 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 
 **键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
 
+#### 受保护控件的主题化
+
+28 个受保护部件里,`host.recovery`、`app.skin-load-recovery` 和授权对话框由宿主在闭合 Shadow DOM 中绘制,`host.permission` 目前没有渲染点;其余 25 个都渲染在 `.ws-skin-root` 内(服务器/频道密码弹窗也在根内,不是 `Teleport`)。开放皮肤(schemaVersion 3/4)可以直接用 `skin.css` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。
+
+**应用 DOM 内的受保护控件。** 颜色、`var()` 颜色、纯色/渐变/包内位图背景、边框、圆角、`font-family`/`font-size`、内边距、宽高、`box-shadow`、`text-shadow`、`filter`、`outline` 等纯视觉属性都可以写:
+
+```css
+[data-ws-part="voice.audio-dock.microphone"],
+[data-ws-part="auth.password.dialog"],
+[data-ws-part="home.footer.clear"] {
+  color: var(--skin-ink);
+  background: linear-gradient(135deg, #0f172a, #1e3a5f);
+  border: 2px solid var(--skin-accent);
+  border-radius: 16px;
+  font: 600 14px/1.4 Tahoma, "Segoe UI", sans-serif;
+  padding: 10px 16px;
+  min-width: 56px;
+  min-height: 56px;
+  box-shadow: 0 8px 24px #0006;
+}
+```
+
+以下规则仍会被拒绝,因为它们会隐藏、禁用或把控件移出视口:`display:none`、`visibility:hidden/collapse`、`opacity:0`、`pointer-events:none`、使 `clip`/`clip-path`/`mask` 完全裁掉内容、`transform`/`scale` 缩到 0、`inset`/`top`/`left`/`margin` 等把控件推到视口外,以及在这些隐藏/移动属性上使用 `var()`/`attr()`。`margin` 仍算移动属性,所以 `margin: var(--skin-gap)` 会被拒绝;普通的小 `margin` 数值可以写。自定义变量仍然只能使用 `--skin-` 前缀。
+
+个别受保护部件的子元素(例如音频面板和音频设置里的 ``)由 Vue 写入内联 `style`;要给滑轨本身换肤,用视觉属性的 `!important` 覆盖即可,受保护的外壳不受影响。
+
+**宿主自有的受保护控件。** `host.recovery`、`app.skin-load-recovery` 横幅和授权对话框在闭合 Shadow DOM 内,皮肤 CSS 不能命中。宿主提供一组统一的令牌;皮肤把变量写在活动皮肤根(`:root`,编译后就是皮肤根)上即可,恢复胶囊也接受写在锚点或其祖先上的值:
+
+| 控件 | 每部件前缀 | 说明 |
+| --- | --- | --- |
+| `host.recovery` | `--skin-recovery-*` | 兼容原有令牌;写到锚点、锚点祖先或皮肤根上都有效 |
+| `app.skin-load-recovery` | `--skin-load-recovery-*` | 皮肤加载失败时出现的顶部横幅;只换肤,不参与停靠 |
+| 授权对话框(`host.permission` 概念) | `--skin-permission-*` | `host.permission` 没有 DOM 渲染点;令牌作用于宿主自己的授权对话框 |
+
+每个每部件令牌都有全局回退:`--skin-host-accent`、`--skin-host-background`、`--skin-host-foreground`、`--skin-host-border`、`--skin-host-radius`、`--skin-host-font`、`--skin-host-size`。每部件值优先于全局值。例如:
+
+```css
+:root {
+  --skin-host-accent: #47dcc4;
+  --skin-host-background: #0b1418;
+  --skin-host-foreground: #edf8f5;
+  --skin-host-border: #2a5a54;
+  --skin-host-radius: 10px;
+  --skin-host-font: Tahoma, "Segoe UI", sans-serif;
+  --skin-host-size: medium;
+
+  /* 只覆盖恢复胶囊,其他宿主控件继续使用全局值 */
+  --skin-recovery-background: #102030;
+}
+```
+
+宿主从计算样式读取这些变量,通过影子根内的探针解析颜色,再写入控件自己的 `--ws-control-*` 变量;皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
+
+- 背景强制不透明(alpha 视为 1)。
+- 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。
+- 边框与背景对比度 ≥ 3,否则使用宿主默认边框。
+- 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。
+- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符。
+- `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。
+- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白,保证可读。
+- 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。
+
+`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)和「使用内置皮肤」的重置路径完全不受令牌影响。旧皮肤继续写 `--skin-recovery-*` 也能工作;新皮肤建议优先使用全局 `--skin-host-*`,只在需要区分具体控件时写每部件覆盖。
+
 `host.watermark`、`host.hint` 与 `host.voice-status-decoration` 属于默认隐藏的装饰:官方/内置皮肤(Day、Night、ILLUSIA、KAAK)不会渲染它们,外观与生产版一致。主题化宿主外壳的皮肤需在 `chrome.json` 中用 `visibleParts` 明确开启;`chrome.json` 的 `hiddenParts` 仍然优先。
 
 示例(v3 `skin.css`):
diff --git a/docs/examples/host-chrome-demo.wskin b/docs/examples/host-chrome-demo.wskin
index eaebaaaa353c5a1f35cbf6d3071d34b0160cb0f2..45f89392899d425ea79e3919d4dc1befee6608aa 100644
GIT binary patch
delta 1811
zcmZ8idpHw%AD`PUBE?z~M=mq5EqR6M=#Wbo&L**u=C(2BIuzcT)lj0&8aYrRdHZi`LV#-8yIrt=O>OW%O_hpY=`Gc#w=qV7nao(
zFs&>Z3oFz3v~an9Tk>X_tW~_urYn@TeW}j$>ImiPhZxLQoH#SB5a}`q
z^|Hf6H|}u@SIy;wZR_fY)C1bp0>P}y2sKx3#y&%Mu-U?ItnP#mirPUp%%*=-8s&Vfh4?f%c6kv^rU)SXdNfn!*zY|wsB7u@%hzXR)
zR_rT~1^_?`VoCu3dN4Hof4M~-xIH^j2~$)a3pZWvG8yKF4L6-Kg57fTLnmBU
z9sQWe7>$r6q)2vNL5?tbw6k8m3p;u6nv7%Vm;_*JL3ia}%J;2(@m6FOGvBtdZvhl=
z+vcEB1`RdGbh~0QAlm#oHw4~Qwd|8Xm4Hm^Iweh}j^rBpt
zXg5#<+}3%(CZ!T?U2R5>`gR6PYsNNu9wur)QF+@+$RZs5K9vC{)*uMwW9{|a+NrMz
zFcrS$5EM#z_{L>z1@){s$dv*ifC>6%kJ_~FJ(SNsLAQ`}!aC!MSA6(^jTRm!`e157RqKbuE8fRH%va`!mhQ9uUmH)w@){CR`k}+H+-HP=F*N5kg)he
zy8aDXOM+Qp6tssjJZG>~JMu?$Jf@QaQBRgo%!s6()ymFU@BUyE&h$YSpD_$xg<@OWL|^
zkcwB7i1yTXxGGb#d{pBq
z@PO&K73l>kp6{x*c=Y7rMLEV+iTROMlV1NzgUr>H-*P7{Pen&%GpeX{vlOG5B)_qd
z{!(wtuf67D$Cc)C7g<6_cb<`mK4GlC+F+7sr3qY68yQW^ZQD%3XJdK?r$u@}ALZ15
zxBXEiVKF?H{jWS<+aHi$5m|AsX4pLh@-W8)G)KFoIE5uIKG^xWy;ryqUGdMme_#Vv
zLp$bw)^->vRf^iw4Rlb+BmHQB2=bBZ!lLbKkZFIWuPF=*h3lSeyJAILdo!KLwuVYX
z4p6rca?Xs!6(nx`^mlO!^LnW++~%Z#4scpzu1LaJ96MmP7(M`bVn_z%h(RBmBmaLE
z!WjUg#SK}As+q}-pZEnvhJ}#7I|&XeAqfTi&vyQ)nmfYzpP+EOA^XKwVj-%Mh9FKR
z1R<`PcB;1^jtHW4Nc`t3ed+>jXCr(k_x*SEJH~)H8nRko@zAFWJt`aq1SYu;!ts~=
VekM&;Rk9YsDU>}7^pq9P{{&KlX}-mI4DK1H(cf<^_u8Cgx?Pr52ayWfkY=xlTBk
zb=W|_1VeOn;uP5v_5bpL}W>_Db+q=`?XsDmr5kLQXQg7T$
zw%v-D`RT9j$qz9p6+2H~k6u+VVecF5u;~_&^I!7I*~_kyWIw@c>9StwBWF?hja|+@$31eU>r@5aEO4EX
zamMbbvW%wG(}pdnmK#>?TP~uOtylCV+wY8GPj+?xYk_Nrh1op%=^W4E&spuxns+&L
zU8&H-{`bdX*q4iXz00WK7ytdt-6-qyybt}qlfq7K*0gbMHI(QzczXQxqRLn2Hp_1=UT{EQd2ep`vDTGS*FHXJv23gE
ztE$NSh*#-FiyJoIJR5U&-%X)7|C4)^mrRV3-mdjvTJo<(OC#r>uQ)Hy5i2OJocT`Y
z*a=BzgzAook1I>>RSf~
zGJH4qV0dBs@#CehKD&HVKUsV2()Y_|I#U!SRr!?OuX*|A)f2hf)2?)SiSpk#sg!+0
z%)736vF+OU;MdWmTwYF`rNq{HcIvLysp{*sVSen{Q&=~ngZh(wDcXAzys-#UJucR;Xu1
z&P$W+*cUN{*G_)KJ`Y4Sam)o#ikx7tsW2b&&I-
zxMi4Z*d|wSD}#7*fxJ6xlXpXS4}iRC_Q{5v(vu~5coaYmQO)N61T#_`#YlOM$*w$_
KYzIMQ2Lk}R7FiGg

diff --git a/docs/examples/host-chrome-demo/manifest.json b/docs/examples/host-chrome-demo/manifest.json
index ccac039..06f0305 100644
--- a/docs/examples/host-chrome-demo/manifest.json
+++ b/docs/examples/host-chrome-demo/manifest.json
@@ -6,7 +6,7 @@
   "version": "1.0.0",
   "author": "WebSpeak Project",
   "license": "AGPL-3.0-only",
-  "description": "Minimal open skin demonstrating host chrome theming, declarative hiding and bitmap icon overrides.",
+  "description": "Minimal open skin demonstrating host chrome theming, protected-control theming, declarative hiding and bitmap icon overrides.",
   "entry": "skin.css",
   "chrome": "chrome.json",
   "minAppVersion": "0.3.2"
diff --git a/docs/examples/host-chrome-demo/skin.css b/docs/examples/host-chrome-demo/skin.css
index e2b9289..57ee104 100644
--- a/docs/examples/host-chrome-demo/skin.css
+++ b/docs/examples/host-chrome-demo/skin.css
@@ -7,6 +7,26 @@
   --skin-panel: #ffffff;
   --skin-border: #c9c9c9;
   --skin-text: #141414;
+
+  /* Host-owned protected controls: one global set, per-part overrides below. */
+  --skin-host-accent: #1d4f9c;
+  --skin-host-background: #ffffff;
+  --skin-host-foreground: #141414;
+  --skin-host-border: #9db6b2;
+  --skin-host-radius: 10px;
+  --skin-host-font: Tahoma, "Segoe UI", sans-serif;
+  --skin-host-size: medium;
+  --skin-recovery-accent: #1d4f9c;
+  --skin-recovery-background: #ffffff;
+  --skin-recovery-foreground: #141414;
+  --skin-recovery-border: #9db6b2;
+  --skin-recovery-radius: 999px;
+  --skin-load-recovery-accent: #b45309;
+  --skin-load-recovery-background: #fff7ed;
+  --skin-load-recovery-foreground: #7c2d12;
+  --skin-permission-accent: #1d4f9c;
+  --skin-permission-background: #ffffff;
+  --skin-permission-foreground: #141414;
 }
 
 [data-ws-page] {
@@ -34,6 +54,43 @@
   --skin-recovery-size: small;
 }
 
+/* --- Protected app-DOM controls: purely visual theming is allowed --- */
+[data-ws-part="voice.audio-dock.microphone"] button,
+[data-ws-part="voice.audio-dock.output"] button,
+[data-ws-part="voice.connection-status.reconnect"],
+[data-ws-part="home.footer.clear"] {
+  color: #141414;
+  background: linear-gradient(180deg, #ffffff, #eef3fa);
+  border: 1px solid var(--skin-accent);
+  border-radius: 8px;
+  font-family: Tahoma, "Segoe UI", sans-serif;
+  font-size: 12px;
+  padding: 8px 12px;
+  min-height: 44px;
+  box-shadow: 0 2px 6px #1d4f9c22;
+}
+
+[data-ws-part="voice.audio-dock.microphone"] button:hover,
+[data-ws-part="voice.audio-dock.output"] button:hover,
+[data-ws-part="voice.connection-status.reconnect"]:hover,
+[data-ws-part="home.footer.clear"]:hover {
+  background: #e7eefb;
+}
+
+[data-ws-part="auth.password.dialog"],
+[data-ws-part="voice.audio-settings"] {
+  background: #ffffff;
+  border: 2px solid var(--skin-accent);
+  border-radius: 18px;
+  box-shadow: 0 18px 48px #1d4f9c33;
+}
+
+[data-ws-part="auth.password.dialog"] h2,
+[data-ws-part="voice.audio-settings"] h2 {
+  color: var(--skin-accent);
+  letter-spacing: .01em;
+}
+
 /* --- Host chrome (outside .ws-skin-root) --- */
 [data-ws-part="host.plugins.launcher"] {
   background: #1d4f9c;
diff --git a/docs/examples/host-chrome-themed.wskin b/docs/examples/host-chrome-themed.wskin
index 8843ac733843a07962d1b48e9b605d66e1974d8c..927d40dbc81b6eda13e9357984fc9ca4d3786f4a 100644
GIT binary patch
delta 1831
zcmZvdc{JPU8pp$sMX5n1C~9jg5h<=MS{-UBf+lJSs|0_7IGYT4K9u?`6)NbMM?U?>X=JocFxX^L^j*{p0%_!ZW29c-&V4
za1aOt1tFQC9%9_BoG-^G79R*Ca?D__5VD^yEdmor3k|VIHKlZD3A4T=u3@#u?k-g<
zSIg#fuHNO<-m_g-w*1U$O06CXF#>+fn}mttF4yX%
zr|#>B<@Dq6FLB9|PnsE{1e=w^$4GCIo?u*mbyDz(o$;NfC~6~pgq{@jbDW%GSf-JU
zGgl@h4>l#RkM`ekdY*MLob1&ya!7BhF*|?p{3ikQrE8^>4-jn&12bior4U~swPeg`
zRzla7sGaXs`oXlvp&o3;V^JRMdI@gTQd(S?X_u3zvNKkC&4vO+n+kh?ZK78OIFdp5
z!8tfu9aRy$LVR}LSQ5FCyufqVYpa)D?!1&U{q6sH1)%t*7$=tT<%*9y5deW8q9-PT
zKr{+D1mi=ay>{sfnbZIJ#lAYYAL(lD_9a-BUi0+G^K*4TY@J}D62z?tt^d$cp~R3(
z@RTojHvpMXT}(~)9e=buUxyHvnxz_U_8CkMgiil*MHi87>w}3&lI1RCGPq$v#6vBj2kBWn=vCeS@
z)q?Ws1()auI{P`*DN}cK$qib`D6ytwNaH=Guz#g-SqJ=261LUX%Y_iD|zp*
zv!(g6J{j<=dy`~F{E!rs$N#NGt4am
zqTp$1j0EKTcdZLAvk?g$bGzpK72S)i?zKZryw-m$OlJpa6VV8|g4)ei<&ELxsR;O>
z-}I{1LDS6h20FGEfXUzI6VC`IUsuj8*zNyamm2G(8u3LK4Cz}QN1L*YHcCw*ox<6!
zABPCaHm;aqnt@q-o^Qc>&p-^57j&J@-!F%q@mkhCbU$kJnqhNcwr-O18%WK
z)0i(u7xEZ;ve3J(WK-Z1Av;l*t<~#W1GbjHr6ms`KE`-nxVC0^TLkZ?EC17WSz>_W
z*4O%@%nVHpddOFT?hO1+WyS;F2Avw*Xqya2er4Sb7@UL~*~24EI$n3&qLXWPQYeTt
z`)deYoM_Km;H1<#rw?8j8=J?9u67LUXWNV
zTxU+%y0CRQw0V7v?N$SpnG$$SZidS$?Anhf=7CETEC1E-6qnnzQp|{u$l0EM4
ztffV^IA+=3XIPbh*;u{dAX}@AyP_K&15o={)*e({n)t6jKF9fQhrH!oJ!dmhB@wZ&
z7GQIxh;-3JHPB1A4~MaCL_hfT;g0C^)YPtf*QqE@wzZK;cvowkY5`cS40gkanLW%p
z_)E5hdc2XJIs&vH(ttHg7;u890FMO;{75FSB$#`GBry8~C`iEx`XL1(e;FP?G!%1k
zQ2~|ZLjgU|GlqW`l*d{5p9SOpZ*1ameEe|GpA!j?g~{>{g8?I$s=|rJHwkAKgO9tY
z$NQT<+y7t`1c-$x|54PVL0${`+ahTw@Cv4U^0mcd-9{*21d%!Ye=lkY$?{)^0ro=b
K;3L?H^uGc9Gbf$^

delta 1419
zcmbO(@mHiiz?+#xgn@y9gF&b`KQ^Es*7Y-xm&M4yzzd{v6Z10DQj1IUvWoNbY$qJd
zI&2`|QlEP9rdVF>Y27autEkBs{Of(}(Iw`F#NPXet#3GrmamBcm42>;w9y6$~x~Qt4
z&$DR9%#zcuREo~(tnS-d_u4x!b9IjRPWv}YHT=@I)X%^4-|=jM`|q5({|w0CGue#s
zZapZNirUr-NH8-ntYilT90Nmfc4nSla&d8Q=-E7JbAf%YHQ7G7^7$Oy6k~l$VfiB0
zq8BG~8y9_OR7&5vX6GE%lVAP2nJPPMoaJ=`DHer)=?Fo_s8Px
z>g4YGKfL<-qQ>t7^>ac}7Ekb6*v&fU?3dD=0r}?B+^n|bXnf8;y+LLD#m%m|mu_xy
zsX4cD-R1g9>tFRIx3cv`!%|LmpAi;IIJ>G#)74Y2E9ly>eIg%ruURoo++g2fQN=$W
z6VLpwH$D}-!01r?CtIm~T$fk{FU;oAPv>|Rf6i)m*1XH1>q>s>|-
zzxeNG?nYUs=Y7y$S`|^5HP`Qjte1XRT-IR|zqEWk({*|?>bIm?{b3h>IY-?*m}S{v-`1y?
z9^q2_W#$q##oaY>tC!irtv5V%DpOb{2pm{4yY;1gV8*B?Buf@6j3tO9=e{1KzmDj(sAD!>E$>!c3UKtN*j%j;1wtSOd(&x^tuu-a?
z=XK5gPfhvs?FaZ@)f5=VxGgcVw-QeB4f*1uFaD5svO+y8N>+NvwunincycTIJP@VI
zF&9J~;Q$L}a4zCSDUBwJbLmBbMCQuN{@Di1a6!QGi5o~GfE-XHIin~)Hx*n~1$Z+u
zi7+4vHuM~e(D;{e@;ojv1(4|{Wa

diff --git a/package.json b/package.json
index ca63c7a..c6a147d 100644
--- a/package.json
+++ b/package.json
@@ -11,7 +11,7 @@
   "scripts": {
     "dev": "tsx src/index.ts",
     "build": "tsc",
-    "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/test/host-chrome-recovery.test.mjs",
+    "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/test/host-chrome-recovery.test.mjs",
     "verify": "npm test && npm run build && npm run web:build",
     "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
     "skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
diff --git a/src/shared/skin-css.test.ts b/src/shared/skin-css.test.ts
index 3b03c72..0c5d251 100644
--- a/src/shared/skin-css.test.ts
+++ b/src/shared/skin-css.test.ts
@@ -340,6 +340,57 @@ test("protected controls cannot be hidden through variables or moved off-screen"
   assert.doesNotThrow(() => compile('[data-ws-part="host.watermark"] { margin-left: -9999px; }'));
 });
 
+test("protected controls accept every purely visual property", () => {
+  const themed = compileSkinCss(`
+    :root {
+      --skin-ink: #f8fafc;
+      --skin-card: #0f172a;
+      --skin-line: #38bdf8;
+      --skin-pad: 14px;
+      --skin-size: 56px;
+      --skin-shadow: 0 10px 30px #0006;
+    }
+    [data-ws-part="voice.audio-dock.microphone"],
+    [data-ws-part="voice.connection-status.reconnect"],
+    [data-ws-part="home.footer.clear"],
+    [data-ws-part="auth.password.dialog"] {
+      color: var(--skin-ink);
+      background-color: var(--skin-card);
+      background-image: linear-gradient(135deg, #123456, #654321), url("assets/protected-pattern.png");
+      border: 2px solid var(--skin-line);
+      border-radius: 18px;
+      font-family: var(--skin-font, Tahoma, "Segoe UI", sans-serif);
+      font-size: 15px;
+      padding: var(--skin-pad);
+      width: var(--skin-size);
+      height: var(--skin-size);
+      box-shadow: var(--skin-shadow);
+      text-shadow: 0 1px 2px #0008;
+    }
+    [data-ws-part="voice.audio-dock.microphone-panel"]::before,
+    [data-ws-part="auth.password.actions"] > button {
+      background: var(--skin-line);
+      border-color: var(--skin-line);
+      border-radius: 12px;
+    }
+  `, "demo-skin", new Set(["assets/protected-pattern.png"]), 3);
+
+  assert.match(themed.css, /\[data-ws-part="voice\.audio-dock\.microphone"\]/);
+  assert.match(themed.css, /wskin-asset:assets%2Fprotected-pattern\.png/);
+  // The hide/move guarantees are unchanged.
+  for (const css of [
+    '[data-ws-part="voice.audio-dock.microphone"] { display: none; }',
+    '[data-ws-part="voice.audio-dock.microphone"] { visibility: hidden; }',
+    '[data-ws-part="voice.audio-dock.microphone"] { opacity: 0; }',
+    '[data-ws-part="voice.audio-dock.microphone"] { pointer-events: none; }',
+    '[data-ws-part="voice.audio-dock.microphone"] { clip-path: inset(100%); }',
+    '[data-ws-part="voice.audio-dock.microphone"] { transform: translateY(-9999px); }',
+    ':root { --skin-pull: -9999px; } [data-ws-part="voice.audio-dock.microphone"] { margin-left: var(--skin-pull); }',
+  ]) {
+    assert.throws(() => compile(css), /must remain available|must remain on screen|cannot use indirect values/, css);
+  }
+});
+
 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; }'),
diff --git a/src/shared/skin-css.ts b/src/shared/skin-css.ts
index c35e820..363fc9e 100644
--- a/src/shared/skin-css.ts
+++ b/src/shared/skin-css.ts
@@ -67,7 +67,12 @@ const HOST_OVERLAY_LOCKED_PROPERTIES = new Set([
   "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. */
+/**
+ * Properties whose indirect values could smuggle a hidden or moved control past
+ * the static checks. Purely visual properties (colour, background, border,
+ * radius, font, shadow, padding, width/height) are deliberately absent: a
+ * protected control may theme them with `var()`.
+ */
 const INDIRECT_VALUE_PROPERTIES = new Set([
   "all", "display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image",
   "position", "top", "right", "bottom", "left", "inset",
diff --git a/web/public/host-chrome-demo.wskin b/web/public/host-chrome-demo.wskin
index eaebaaaa353c5a1f35cbf6d3071d34b0160cb0f2..45f89392899d425ea79e3919d4dc1befee6608aa 100644
GIT binary patch
delta 1811
zcmZ8idpHw%AD`PUBE?z~M=mq5EqR6M=#Wbo&L**u=C(2BIuzcT)lj0&8aYrRdHZi`LV#-8yIrt=O>OW%O_hpY=`Gc#w=qV7nao(
zFs&>Z3oFz3v~an9Tk>X_tW~_urYn@TeW}j$>ImiPhZxLQoH#SB5a}`q
z^|Hf6H|}u@SIy;wZR_fY)C1bp0>P}y2sKx3#y&%Mu-U?ItnP#mirPUp%%*=-8s&Vfh4?f%c6kv^rU)SXdNfn!*zY|wsB7u@%hzXR)
zR_rT~1^_?`VoCu3dN4Hof4M~-xIH^j2~$)a3pZWvG8yKF4L6-Kg57fTLnmBU
z9sQWe7>$r6q)2vNL5?tbw6k8m3p;u6nv7%Vm;_*JL3ia}%J;2(@m6FOGvBtdZvhl=
z+vcEB1`RdGbh~0QAlm#oHw4~Qwd|8Xm4Hm^Iweh}j^rBpt
zXg5#<+}3%(CZ!T?U2R5>`gR6PYsNNu9wur)QF+@+$RZs5K9vC{)*uMwW9{|a+NrMz
zFcrS$5EM#z_{L>z1@){s$dv*ifC>6%kJ_~FJ(SNsLAQ`}!aC!MSA6(^jTRm!`e157RqKbuE8fRH%va`!mhQ9uUmH)w@){CR`k}+H+-HP=F*N5kg)he
zy8aDXOM+Qp6tssjJZG>~JMu?$Jf@QaQBRgo%!s6()ymFU@BUyE&h$YSpD_$xg<@OWL|^
zkcwB7i1yTXxGGb#d{pBq
z@PO&K73l>kp6{x*c=Y7rMLEV+iTROMlV1NzgUr>H-*P7{Pen&%GpeX{vlOG5B)_qd
z{!(wtuf67D$Cc)C7g<6_cb<`mK4GlC+F+7sr3qY68yQW^ZQD%3XJdK?r$u@}ALZ15
zxBXEiVKF?H{jWS<+aHi$5m|AsX4pLh@-W8)G)KFoIE5uIKG^xWy;ryqUGdMme_#Vv
zLp$bw)^->vRf^iw4Rlb+BmHQB2=bBZ!lLbKkZFIWuPF=*h3lSeyJAILdo!KLwuVYX
z4p6rca?Xs!6(nx`^mlO!^LnW++~%Z#4scpzu1LaJ96MmP7(M`bVn_z%h(RBmBmaLE
z!WjUg#SK}As+q}-pZEnvhJ}#7I|&XeAqfTi&vyQ)nmfYzpP+EOA^XKwVj-%Mh9FKR
z1R<`PcB;1^jtHW4Nc`t3ed+>jXCr(k_x*SEJH~)H8nRko@zAFWJt`aq1SYu;!ts~=
VekM&;Rk9YsDU>}7^pq9P{{&KlX}-mI4DK1H(cf<^_u8Cgx?Pr52ayWfkY=xlTBk
zb=W|_1VeOn;uP5v_5bpL}W>_Db+q=`?XsDmr5kLQXQg7T$
zw%v-D`RT9j$qz9p6+2H~k6u+VVecF5u;~_&^I!7I*~_kyWIw@c>9StwBWF?hja|+@$31eU>r@5aEO4EX
zamMbbvW%wG(}pdnmK#>?TP~uOtylCV+wY8GPj+?xYk_Nrh1op%=^W4E&spuxns+&L
zU8&H-{`bdX*q4iXz00WK7ytdt-6-qyybt}qlfq7K*0gbMHI(QzczXQxqRLn2Hp_1=UT{EQd2ep`vDTGS*FHXJv23gE
ztE$NSh*#-FiyJoIJR5U&-%X)7|C4)^mrRV3-mdjvTJo<(OC#r>uQ)Hy5i2OJocT`Y
z*a=BzgzAook1I>>RSf~
zGJH4qV0dBs@#CehKD&HVKUsV2()Y_|I#U!SRr!?OuX*|A)f2hf)2?)SiSpk#sg!+0
z%)736vF+OU;MdWmTwYF`rNq{HcIvLysp{*sVSen{Q&=~ngZh(wDcXAzys-#UJucR;Xu1
z&P$W+*cUN{*G_)KJ`Y4Sam)o#ikx7tsW2b&&I-
zxMi4Z*d|wSD}#7*fxJ6xlXpXS4}iRC_Q{5v(vu~5coaYmQO)N61T#_`#YlOM$*w$_
KYzIMQ2Lk}R7FiGg

diff --git a/web/public/host-chrome-themed.wskin b/web/public/host-chrome-themed.wskin
index 8843ac733843a07962d1b48e9b605d66e1974d8c..927d40dbc81b6eda13e9357984fc9ca4d3786f4a 100644
GIT binary patch
delta 1831
zcmZvdc{JPU8pp$sMX5n1C~9jg5h<=MS{-UBf+lJSs|0_7IGYT4K9u?`6)NbMM?U?>X=JocFxX^L^j*{p0%_!ZW29c-&V4
za1aOt1tFQC9%9_BoG-^G79R*Ca?D__5VD^yEdmor3k|VIHKlZD3A4T=u3@#u?k-g<
zSIg#fuHNO<-m_g-w*1U$O06CXF#>+fn}mttF4yX%
zr|#>B<@Dq6FLB9|PnsE{1e=w^$4GCIo?u*mbyDz(o$;NfC~6~pgq{@jbDW%GSf-JU
zGgl@h4>l#RkM`ekdY*MLob1&ya!7BhF*|?p{3ikQrE8^>4-jn&12bior4U~swPeg`
zRzla7sGaXs`oXlvp&o3;V^JRMdI@gTQd(S?X_u3zvNKkC&4vO+n+kh?ZK78OIFdp5
z!8tfu9aRy$LVR}LSQ5FCyufqVYpa)D?!1&U{q6sH1)%t*7$=tT<%*9y5deW8q9-PT
zKr{+D1mi=ay>{sfnbZIJ#lAYYAL(lD_9a-BUi0+G^K*4TY@J}D62z?tt^d$cp~R3(
z@RTojHvpMXT}(~)9e=buUxyHvnxz_U_8CkMgiil*MHi87>w}3&lI1RCGPq$v#6vBj2kBWn=vCeS@
z)q?Ws1()auI{P`*DN}cK$qib`D6ytwNaH=Guz#g-SqJ=261LUX%Y_iD|zp*
zv!(g6J{j<=dy`~F{E!rs$N#NGt4am
zqTp$1j0EKTcdZLAvk?g$bGzpK72S)i?zKZryw-m$OlJpa6VV8|g4)ei<&ELxsR;O>
z-}I{1LDS6h20FGEfXUzI6VC`IUsuj8*zNyamm2G(8u3LK4Cz}QN1L*YHcCw*ox<6!
zABPCaHm;aqnt@q-o^Qc>&p-^57j&J@-!F%q@mkhCbU$kJnqhNcwr-O18%WK
z)0i(u7xEZ;ve3J(WK-Z1Av;l*t<~#W1GbjHr6ms`KE`-nxVC0^TLkZ?EC17WSz>_W
z*4O%@%nVHpddOFT?hO1+WyS;F2Avw*Xqya2er4Sb7@UL~*~24EI$n3&qLXWPQYeTt
z`)deYoM_Km;H1<#rw?8j8=J?9u67LUXWNV
zTxU+%y0CRQw0V7v?N$SpnG$$SZidS$?Anhf=7CETEC1E-6qnnzQp|{u$l0EM4
ztffV^IA+=3XIPbh*;u{dAX}@AyP_K&15o={)*e({n)t6jKF9fQhrH!oJ!dmhB@wZ&
z7GQIxh;-3JHPB1A4~MaCL_hfT;g0C^)YPtf*QqE@wzZK;cvowkY5`cS40gkanLW%p
z_)E5hdc2XJIs&vH(ttHg7;u890FMO;{75FSB$#`GBry8~C`iEx`XL1(e;FP?G!%1k
zQ2~|ZLjgU|GlqW`l*d{5p9SOpZ*1ameEe|GpA!j?g~{>{g8?I$s=|rJHwkAKgO9tY
z$NQT<+y7t`1c-$x|54PVL0${`+ahTw@Cv4U^0mcd-9{*21d%!Ye=lkY$?{)^0ro=b
K;3L?H^uGc9Gbf$^

delta 1419
zcmbO(@mHiiz?+#xgn@y9gF&b`KQ^Es*7Y-xm&M4yzzd{v6Z10DQj1IUvWoNbY$qJd
zI&2`|QlEP9rdVF>Y27autEkBs{Of(}(Iw`F#NPXet#3GrmamBcm42>;w9y6$~x~Qt4
z&$DR9%#zcuREo~(tnS-d_u4x!b9IjRPWv}YHT=@I)X%^4-|=jM`|q5({|w0CGue#s
zZapZNirUr-NH8-ntYilT90Nmfc4nSla&d8Q=-E7JbAf%YHQ7G7^7$Oy6k~l$VfiB0
zq8BG~8y9_OR7&5vX6GE%lVAP2nJPPMoaJ=`DHer)=?Fo_s8Px
z>g4YGKfL<-qQ>t7^>ac}7Ekb6*v&fU?3dD=0r}?B+^n|bXnf8;y+LLD#m%m|mu_xy
zsX4cD-R1g9>tFRIx3cv`!%|LmpAi;IIJ>G#)74Y2E9ly>eIg%ruURoo++g2fQN=$W
z6VLpwH$D}-!01r?CtIm~T$fk{FU;oAPv>|Rf6i)m*1XH1>q>s>|-
zzxeNG?nYUs=Y7y$S`|^5HP`Qjte1XRT-IR|zqEWk({*|?>bIm?{b3h>IY-?*m}S{v-`1y?
z9^q2_W#$q##oaY>tC!irtv5V%DpOb{2pm{4yY;1gV8*B?Buf@6j3tO9=e{1KzmDj(sAD!>E$>!c3UKtN*j%j;1wtSOd(&x^tuu-a?
z=XK5gPfhvs?FaZ@)f5=VxGgcVw-QeB4f*1uFaD5svO+y8N>+NvwunincycTIJP@VI
zF&9J~;Q$L}a4zCSDUBwJbLmBbMCQuN{@Di1a6!QGi5o~GfE-XHIin~)Hx*n~1$Z+u
zi7+4vHuM~e(D;{e@;ojv1(4|{Wa

diff --git a/web/src/components/HostChrome.vue b/web/src/components/HostChrome.vue
index b7fb2fa..bf4ed35 100644
--- a/web/src/components/HostChrome.vue
+++ b/web/src/components/HostChrome.vue
@@ -85,6 +85,11 @@ import {
 import { bindHostSlot, type HostSlotBinding } from "../services/host-slot-placement.js";
 import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
 import { thirdPartyAllowed } from "../services/instance-authorization.js";
+import {
+  RECOVERY_CONTROL_DEFAULTS,
+  bindHostControlTheme,
+  findSkinRoot,
+} from "../services/host-control-tokens.js";
 
 const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean; pluginLibraryAvailable?: boolean }>(), { connected: false });
 const copy = computed(() => hostChromeCopy[props.language] ?? hostChromeCopy.en);
@@ -102,12 +107,12 @@ const RECOVERY_LAYER_CSS = `
   gap: 4px;
   max-width: calc(100vw - 24px);
   padding: 4px 5px 4px 9px;
-  border: 1px solid #9db6b2;
-  border-radius: var(--ws-recovery-radius, 999px);
-  background: var(--ws-recovery-background, color-mix(in srgb, #ffffff 92%, transparent));
-  color: var(--ws-recovery-foreground, #31524f);
-  font-family: var(--ws-recovery-font, ui-sans-serif, system-ui, sans-serif);
-  font-size: var(--ws-recovery-font-size, 11px);
+  border: 1px solid var(--ws-control-border, #9db6b2);
+  border-radius: var(--ws-control-radius, 999px);
+  background: var(--ws-control-background, color-mix(in srgb, #ffffff 92%, transparent));
+  color: var(--ws-control-foreground, #31524f);
+  font-family: var(--ws-control-font, ui-sans-serif, system-ui, sans-serif);
+  font-size: var(--ws-control-font-size, 11px);
   box-shadow: 0 6px 18px #0f2a2626;
   pointer-events: auto;
 }
@@ -122,18 +127,18 @@ const RECOVERY_LAYER_CSS = `
 .ws-host-recovery button {
   display: inline-flex;
   align-items: center;
-  min-height: var(--ws-recovery-hit, 28px);
+  min-height: var(--ws-control-hit, 28px);
   padding: 4px 9px;
-  border: 1px solid #9db6b2;
-  border-radius: var(--ws-recovery-radius, 999px);
-  background: var(--ws-recovery-background, #fff);
-  color: var(--ws-recovery-foreground, #31524f);
+  border: 1px solid var(--ws-control-border, #9db6b2);
+  border-radius: var(--ws-control-radius, 999px);
+  background: var(--ws-control-background, #fff);
+  color: var(--ws-control-foreground, #31524f);
   font: inherit;
   cursor: pointer;
   white-space: nowrap;
 }
 .ws-host-recovery button[data-ws-recovery-action="built-in"] {
-  border-color: var(--ws-recovery-builtin-border, #b45309);
+  border-color: var(--ws-control-builtin-border, #b45309);
   background: #fff7ed;
   color: #7c2d12;
 }
@@ -142,10 +147,10 @@ const RECOVERY_LAYER_CSS = `
 .ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) { gap: 0; padding: 4px; }
 .ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-action { display: none; }
 .ws-host-recovery.ws-host-recovery-compact:not(:hover):not(:focus-within) .ws-host-recovery-mark {
-  min-width: var(--ws-recovery-hit, 28px);
-  min-height: var(--ws-recovery-hit, 28px);
+  min-width: var(--ws-control-hit, 28px);
+  min-height: var(--ws-control-hit, 28px);
 }
-.ws-host-recovery.ws-host-recovery-compact:focus-visible { outline: 2px solid var(--ws-recovery-accent, #4c8f88); outline-offset: 2px; }
+.ws-host-recovery.ws-host-recovery-compact:focus-visible { outline: 2px solid var(--ws-control-accent, #4c8f88); outline-offset: 2px; }
 @media (prefers-reduced-motion: reduce) {
   .ws-host-recovery, .ws-host-recovery button { transition: none !important; }
 }
@@ -172,6 +177,21 @@ const showRecovery = computed(() => shouldShowRecovery({
 // already reset). It never renders decoration on its own.
 const shortcutOpen = ref(false);
 const recoveryPopover = ref(null);
+
+/**
+ * Theme the capsule even when the skin does not declare a slot. `bindHostSlot`
+ * still reads the anchor first when a slot exists; this root-level pass covers
+ * the floating capsule and is overwritten by the anchor values on the next
+ * revalidation.
+ */
+const recoveryTheme = layer ? bindHostControlTheme({
+  layer,
+  control: () => recoveryPopover.value,
+  part: "host.recovery",
+  defaults: RECOVERY_CONTROL_DEFAULTS,
+  source: () => findSkinRoot(hostChromeActiveSkinId.value),
+}) : null;
+
 const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
 
 /**
@@ -238,6 +258,9 @@ let slotBinding: HostSlotBinding | undefined;
 function syncSlotBinding() {
   slotBinding?.dispose();
   slotBinding = undefined;
+  // Disposing a slot clears its inline tokens; restore the root-level theme
+  // before deciding whether a new anchor should override it.
+  recoveryTheme?.apply();
   // A fresh binding starts floating and reports its first successful dock.
   slotMode.value = "floating";
   const control = recoveryPopover.value;
@@ -294,6 +317,9 @@ watch([recoveryVisible, recoveryPopover], () => {
     slotBinding?.revalidate();
   });
 }, { flush: "post" });
+watch([recoveryPopover, hostChromeActiveSkinId], () => {
+  void nextTick(() => recoveryTheme?.apply());
+}, { flush: "post", immediate: true });
 watch([slotConfig, hostChromeActiveSkinId], () => {
   void nextTick(() => {
     syncPopover();
@@ -317,6 +343,7 @@ onBeforeUnmount(() => {
   if (reachabilityTimer) clearInterval(reachabilityTimer);
   if (compactHoldTimer) clearTimeout(compactHoldTimer);
   slotBinding?.dispose();
+  recoveryTheme?.dispose();
   window.removeEventListener("resize", refreshLauncherReachability);
   window.removeEventListener("keydown", onKeydown, true);
   window.removeEventListener("pointerdown", onDocumentPointerDown, true);
diff --git a/web/src/components/InstanceAuthorization.vue b/web/src/components/InstanceAuthorization.vue
index f0c83c9..5676b90 100644
--- a/web/src/components/InstanceAuthorization.vue
+++ b/web/src/components/InstanceAuthorization.vue
@@ -25,13 +25,19 @@ import type { SiteLanguage } from '../../../src/site-copy.js';
 import { authorizationDecision, authorizationLanguage, authorizationRequested, setInstanceAuthorization } from '../services/instance-authorization.js';
 import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
 import { createHostOwnedLayer, type HostOwnedLayer } from '../services/host-owned-layer.js';
+import { hostChromeActiveSkinId } from '../services/host-chrome.js';
+import {
+  PERMISSION_CONTROL_DEFAULTS,
+  bindHostControlTheme,
+  findSkinRoot,
+} from '../services/host-control-tokens.js';
 
 const AUTHORIZATION_LAYER_CSS = `
 :host { font: 14px/1.75 system-ui, -apple-system, "Segoe UI", sans-serif; }
-.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:inherit;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
+.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid var(--ws-control-border,#dbe3f1);border-radius:var(--ws-control-radius,20px);background:var(--ws-control-background,#fff);color:var(--ws-control-foreground,#25324b);font-family:var(--ws-control-font,system-ui,-apple-system,"Segoe UI",sans-serif);font-size:var(--ws-control-font-size,14px);line-height:1.75;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
 .ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
-.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
-.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
+.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:var(--ws-control-foreground,#202e49)}.ws-instance-authorization p{margin:12px 0;color:color-mix(in srgb,var(--ws-control-foreground,#25324b) 76%,transparent)}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:color-mix(in srgb,var(--ws-control-accent,#5265df) 14%,var(--ws-control-background,#fff));color:var(--ws-control-accent,#5265df);font-size:28px}
+.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));border:1px solid var(--ws-control-border,#dce3f3);border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:var(--ws-control-hit,42px);padding:9px 16px;border:1px solid var(--ws-control-border,#d9e1ef);border-radius:var(--ws-control-radius,10px);background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));color:var(--ws-control-foreground,#43516d);font:600 var(--ws-control-font-size,14px)/1.5 var(--ws-control-font,system-ui);cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:var(--ws-control-accent,#5265df);color:var(--ws-control-on-accent,#fff);border-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid var(--ws-control-accent,#5265df);outline-offset:3px}
 @media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
 `;
 
@@ -39,6 +45,17 @@ const layer: HostOwnedLayer | null = createHostOwnedLayer('authorization', AUTHO
 const props = defineProps<{ language: SiteLanguage }>();
 const dialog = ref(null), checked = ref(false), firstVisit = ref(false);
 const copy = computed(() => instanceAuthorizationCopy[props.language]);
+
+/** The authorization dialog is host-owned; only sanitized tokens can theme it. */
+const theme = layer ? bindHostControlTheme({
+  layer,
+  control: () => dialog.value,
+  part: 'host.permission',
+  defaults: PERMISSION_CONTROL_DEFAULTS,
+  source: () => findSkinRoot(hostChromeActiveSkinId.value),
+}) : null;
+
+watch([dialog, hostChromeActiveSkinId], () => { theme?.apply(); }, { flush: 'post', immediate: true });
 watch(() => props.language, value => { authorizationLanguage.value = value; }, { immediate: true });
 watch([dialog, authorizationRequested, authorizationDecision], () => {
   if (!dialog.value || dialog.value.open || (authorizationDecision.value !== null && !authorizationRequested.value)) return;
@@ -50,5 +67,5 @@ function finish() { authorizationRequested.value = false; dialog.value?.close();
 function save() { if (firstVisit.value && !checked.value) return; setInstanceAuthorization(checked.value); finish(); }
 function decline() { setInstanceAuthorization(false); finish(); }
 function cancel() { if (firstVisit.value) decline(); else finish(); }
-onBeforeUnmount(() => { dialog.value?.close(); layer?.dispose(); });
+onBeforeUnmount(() => { dialog.value?.close(); theme?.dispose(); layer?.dispose(); });
 
diff --git a/web/src/components/SkinLoadRecoveryNotice.vue b/web/src/components/SkinLoadRecoveryNotice.vue
index 69c464c..daf5bb1 100644
--- a/web/src/components/SkinLoadRecoveryNotice.vue
+++ b/web/src/components/SkinLoadRecoveryNotice.vue
@@ -1,6 +1,6 @@
 
 
 
diff --git a/web/src/services/host-control-tokens.test.ts b/web/src/services/host-control-tokens.test.ts
new file mode 100644
index 0000000..5c89bcd
--- /dev/null
+++ b/web/src/services/host-control-tokens.test.ts
@@ -0,0 +1,250 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+  HOST_CONTROL_APPLIED_VARIABLES,
+  HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES,
+  HOST_CONTROL_MIN_ACCENT_CONTRAST,
+  HOST_CONTROL_MIN_BORDER_CONTRAST,
+  HOST_CONTROL_MIN_FONT_SIZE,
+  HOST_CONTROL_MIN_FOREGROUND_CONTRAST,
+  HOST_CONTROL_MIN_HIT_TARGET,
+  HOST_CONTROL_SIZE_METRICS,
+  PERMISSION_CONTROL_DEFAULTS,
+  RECOVERY_CONTROL_DEFAULTS,
+  SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
+  applyHostControlTokens,
+  contrastRatio,
+  hasHostControlTokens,
+  hostControlTokenKey,
+  hostControlTokenProperty,
+  parseCssColor,
+  relativeLuminance,
+  resolveHostControlTokens,
+  type HostControlRawTokens,
+} from "./host-control-tokens.js";
+
+type TokenMap = Record;
+
+const style = (tokens: TokenMap): Pick => ({
+  getPropertyValue: (name) => tokens[name] ?? "",
+});
+
+const prefixed = (prefix: string, tokens: HostControlRawTokens): TokenMap => Object.fromEntries(
+  Object.entries(tokens)
+    .filter((entry): entry is [string, string] => typeof entry[1] === "string")
+    .map(([name, value]) => [`--skin-${prefix}-${name}`, value]),
+);
+
+const resolveRecovery = (part: HostControlRawTokens = {}, global: HostControlRawTokens = {}) =>
+  resolveHostControlTokens(
+    style({ ...prefixed("host", global), ...prefixed("recovery", part) }),
+    "host.recovery",
+    raw => raw,
+    RECOVERY_CONTROL_DEFAULTS,
+  );
+
+test("host control token names are stable and keep --skin-recovery-* working", () => {
+  assert.equal(hostControlTokenKey("host.recovery"), "recovery");
+  assert.equal(hostControlTokenKey("app.skin-load-recovery"), "load-recovery");
+  assert.equal(hostControlTokenKey("host.permission"), "permission");
+  assert.equal(hostControlTokenKey("host.future"), "future");
+
+  assert.equal(hostControlTokenProperty("host.recovery", "background"), "--skin-recovery-background");
+  assert.equal(hostControlTokenProperty("app.skin-load-recovery", "size"), "--skin-load-recovery-size");
+  assert.equal(hostControlTokenProperty("host.permission", "accent"), "--skin-permission-accent");
+  assert.equal(HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES.foreground, "--skin-host-foreground");
+});
+
+test("recovery tokens default to the host palette", () => {
+  const tokens = resolveHostControlTokens(null, "host.recovery", () => undefined, RECOVERY_CONTROL_DEFAULTS);
+  assert.equal(tokens.accent, "rgb(180, 83, 9)");
+  assert.equal(tokens.builtInBorder, "rgb(180, 83, 9)");
+  assert.equal(tokens.background, "rgb(255, 255, 255)");
+  assert.equal(tokens.foreground, "rgb(49, 82, 79)");
+  assert.equal(tokens.border, "rgb(157, 182, 178)");
+  assert.equal(tokens.radius, 999);
+  assert.equal(tokens.font, "ui-sans-serif, system-ui, sans-serif");
+  assert.equal(tokens.size, "small");
+  assert.equal(tokens.hitTarget, HOST_CONTROL_MIN_HIT_TARGET);
+  assert.equal(tokens.fontSize, HOST_CONTROL_MIN_FONT_SIZE);
+  assert.ok(contrastRatio(parseCssColor(tokens.onAccent)!, parseCssColor(tokens.accent)!) >= 4.5);
+});
+
+test("a readable skin palette is kept and translucent backgrounds become opaque", () => {
+  const tokens = resolveRecovery({
+    accent: "#47dcc4",
+    background: "rgba(9, 19, 23, 0.4)",
+    foreground: "#edf8f5",
+    border: "#47dcc4",
+  });
+  assert.equal(tokens.accent, "rgb(71, 220, 196)");
+  assert.equal(tokens.background, "rgb(9, 19, 23)");
+  assert.equal(tokens.foreground, "rgb(237, 248, 245)");
+  assert.equal(tokens.border, "rgb(71, 220, 196)");
+});
+
+test("per-part tokens win over the global set and both fall back as a colour group", () => {
+  const readable = resolveRecovery(
+    { background: "#102030", foreground: "#ffffff", accent: "#47dcc4" },
+    { background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" },
+  );
+  assert.equal(readable.background, "rgb(16, 32, 48)", "the per-part background must win");
+  assert.equal(readable.foreground, "rgb(255, 255, 255)");
+  assert.equal(readable.accent, "rgb(71, 220, 196)");
+
+  // An unreadable per-part group falls back to a readable global palette.
+  const globalFallback = resolveRecovery(
+    { background: "#777777", foreground: "#888888", accent: "#47dcc4" },
+    { background: "#102030", foreground: "#ffffff", accent: "#47dcc4" },
+  );
+  assert.equal(globalFallback.background, "rgb(16, 32, 48)");
+  assert.equal(globalFallback.foreground, "rgb(255, 255, 255)");
+  assert.equal(globalFallback.accent, "rgb(71, 220, 196)");
+
+  // No readable layer: the built-in palette wins as a whole.
+  const reset = resolveRecovery(
+    { background: "#777777", foreground: "#888888", accent: "#47dcc4" },
+    { background: "#888888", foreground: "#999999", accent: "#eeeeee" },
+  );
+  assert.equal(reset.background, "rgb(255, 255, 255)");
+  assert.equal(reset.foreground, "rgb(49, 82, 79)");
+  assert.equal(reset.accent, "rgb(180, 83, 9)");
+});
+
+test("the border only uses a colour visible against the resolved background", () => {
+  assert.equal(resolveRecovery({ border: "#ffffff" }).border, "rgb(157, 182, 178)");
+  assert.equal(resolveRecovery({ border: "#000000" }).border, "rgb(0, 0, 0)");
+
+  const globalFallback = resolveRecovery({ border: "#ffffff" }, { border: "#000000" });
+  assert.equal(globalFallback.border, "rgb(0, 0, 0)");
+  assert.ok(contrastRatio(parseCssColor(globalFallback.border)!, parseCssColor(globalFallback.background)!) >= HOST_CONTROL_MIN_BORDER_CONTRAST);
+});
+
+test("radius, font and size tokens are sanitized and host minimums win", () => {
+  assert.equal(resolveRecovery({ radius: "12px" }).radius, 12);
+  assert.equal(resolveRecovery({ radius: "2000px" }).radius, 999);
+  assert.equal(resolveRecovery({ radius: "-5px" }).radius, 0);
+  assert.equal(resolveRecovery({ radius: "1em" }).radius, 999);
+  assert.equal(resolveRecovery({ radius: "12" }).radius, 999);
+
+  assert.equal(resolveRecovery({ font: 'Tahoma, "Segoe UI", sans-serif' }).font, 'Tahoma, "Segoe UI", sans-serif');
+  for (const font of ["url(https://example.invalid/a.woff2)", "Tahoma; color: red", "x".repeat(121)]) {
+    assert.equal(resolveRecovery({ font }).font, "ui-sans-serif, system-ui, sans-serif", font);
+  }
+
+  assert.equal(resolveRecovery({ size: "medium" }).hitTarget, 32);
+  assert.equal(resolveRecovery({ size: "medium" }).fontSize, 12);
+  assert.equal(resolveRecovery({ size: "large" }).hitTarget, 36);
+  assert.equal(resolveRecovery({ size: "large" }).fontSize, 13);
+  assert.equal(resolveRecovery({ size: "huge" }).size, "small");
+  for (const metrics of Object.values(HOST_CONTROL_SIZE_METRICS)) {
+    assert.ok(metrics.hitTarget >= HOST_CONTROL_MIN_HIT_TARGET);
+    assert.ok(metrics.fontSize >= HOST_CONTROL_MIN_FONT_SIZE);
+  }
+
+  // Controls with a larger built-in action never shrink below it.
+  const banner = resolveHostControlTokens(
+    style(prefixed("host", { size: "small" })),
+    "app.skin-load-recovery",
+    raw => raw,
+    SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
+  );
+  assert.equal(banner.hitTarget, 44);
+  assert.equal(banner.fontSize, 14);
+  const bannerLarge = resolveHostControlTokens(
+    style(prefixed("load-recovery", { size: "large" })),
+    "app.skin-load-recovery",
+    raw => raw,
+    SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
+  );
+  assert.equal(bannerLarge.hitTarget, 48);
+  assert.equal(bannerLarge.fontSize, 16);
+});
+
+test("the built-in button border only uses an accent visible on its fixed light background", () => {
+  const pale = resolveRecovery({ background: "#141414", foreground: "#ffffff", accent: "#fff7ec" });
+  assert.equal(pale.accent, "rgb(255, 247, 236)");
+  assert.equal(pale.builtInBorder, "rgb(180, 83, 9)");
+
+  const strong = resolveRecovery({ background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" });
+  assert.equal(strong.builtInBorder, "rgb(29, 78, 216)");
+});
+
+test("global tokens theme the banner and the authorization dialog", () => {
+  const root = style(prefixed("host", {
+    background: "#102030",
+    foreground: "#ffffff",
+    accent: "#47dcc4",
+    border: "#47dcc4",
+    radius: "18px",
+    font: "Tahoma, sans-serif",
+    size: "large",
+  }));
+  const banner = resolveHostControlTokens(root, "app.skin-load-recovery", raw => raw, SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS);
+  assert.equal(banner.background, "rgb(16, 32, 48)");
+  assert.equal(banner.foreground, "rgb(255, 255, 255)");
+  assert.equal(banner.radius, 18);
+  assert.equal(banner.font, "Tahoma, sans-serif");
+  assert.equal(banner.hitTarget, 48);
+
+  const dialog = resolveHostControlTokens(root, "host.permission", raw => raw, PERMISSION_CONTROL_DEFAULTS);
+  assert.equal(dialog.background, "rgb(16, 32, 48)");
+  assert.equal(dialog.foreground, "rgb(255, 255, 255)");
+  assert.ok(contrastRatio(parseCssColor(dialog.onAccent)!, parseCssColor(dialog.accent)!) >= 4.5);
+  assert.equal(dialog.hitTarget, 46);
+
+  const override = resolveHostControlTokens(
+    style({ ...prefixed("host", { background: "#102030", foreground: "#ffffff", accent: "#47dcc4" }), ...prefixed("load-recovery", { background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" }) }),
+    "app.skin-load-recovery",
+    raw => raw,
+    SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
+  );
+  assert.equal(override.background, "rgb(255, 255, 255)");
+});
+
+test("only a declared global or per-part token triggers host theming", () => {
+  assert.equal(hasHostControlTokens(style({}), "host.recovery"), false);
+  assert.equal(hasHostControlTokens(style({ "--skin-unrelated": "red" }), "host.recovery"), false);
+  assert.equal(hasHostControlTokens(style({ "--skin-host-background": "#102030" }), "host.recovery"), true);
+  assert.equal(hasHostControlTokens(style({ "--skin-recovery-radius": "8px" }), "host.recovery"), true);
+  assert.equal(hasHostControlTokens(style({ "--skin-load-recovery-accent": "#123456" }), "app.skin-load-recovery"), true);
+  assert.equal(hasHostControlTokens(style({ "--skin-permission-font": "Tahoma" }), "host.permission"), true);
+});
+
+test("applying and clearing tokens writes only host-owned variables", () => {
+  const values = new Map();
+  const control = {
+    style: {
+      setProperty: (name: string, value: string) => { values.set(name, value); },
+      removeProperty: (name: string) => { values.delete(name); },
+    },
+  } as unknown as HTMLElement;
+  const tokens = resolveRecovery({ background: "#102030", foreground: "#ffffff", accent: "#47dcc4", radius: "8px" });
+  applyHostControlTokens(control, tokens);
+  assert.equal(values.get(HOST_CONTROL_APPLIED_VARIABLES.background), "rgb(16, 32, 48)");
+  assert.equal(values.get(HOST_CONTROL_APPLIED_VARIABLES.radius), "8px");
+  assert.ok(values.has(HOST_CONTROL_APPLIED_VARIABLES.onAccent));
+  applyHostControlTokens(control, null);
+  assert.equal(values.size, 0);
+});
+
+test("CSS colours parse to RGB and ignore alpha for contrast", () => {
+  assert.deepEqual(parseCssColor("#1d4f9c"), { r: 29, g: 79, b: 156 });
+  assert.deepEqual(parseCssColor("#fff"), { r: 255, g: 255, b: 255 });
+  assert.deepEqual(parseCssColor("#ffff"), { r: 255, g: 255, b: 255 });
+  assert.deepEqual(parseCssColor("rgb(29, 79, 156)"), { r: 29, g: 79, b: 156 });
+  assert.deepEqual(parseCssColor("rgb(29 79 156 / 50%)"), { r: 29, g: 79, b: 156 });
+  assert.deepEqual(parseCssColor("rgba(255, 0, 0, .4)"), { r: 255, g: 0, b: 0 });
+  assert.deepEqual(parseCssColor("rgb(300, -5, 0)"), { r: 255, g: 0, b: 0 });
+  for (const invalid of ["", "red", "hsl(10, 20%, 30%)", "color(srgb 1 0 0)", "#12345", "rgb(1, 2)"]) {
+    assert.equal(parseCssColor(invalid), null, invalid);
+  }
+});
+
+test("WCAG contrast follows the relative-luminance formula", () => {
+  assert.equal(relativeLuminance({ r: 0, g: 0, b: 0 }), 0);
+  assert.equal(relativeLuminance({ r: 255, g: 255, b: 255 }), 1);
+  assert.equal(contrastRatio({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }), 21);
+  assert.equal(contrastRatio({ r: 12, g: 34, b: 56 }, { r: 12, g: 34, b: 56 }), 1);
+  assert.ok(HOST_CONTROL_MIN_FOREGROUND_CONTRAST > HOST_CONTROL_MIN_ACCENT_CONTRAST);
+});
diff --git a/web/src/services/host-control-tokens.ts b/web/src/services/host-control-tokens.ts
new file mode 100644
index 0000000..fdf3bc1
--- /dev/null
+++ b/web/src/services/host-control-tokens.ts
@@ -0,0 +1,522 @@
+/**
+ * Style tokens for host-owned protected controls.
+ *
+ * Recovery, the skin-load banner and the authorization dialog live inside
+ * closed shadow roots, so compiled skin CSS can never reach them. A skin may
+ * declare a small, sanitised token set on the active skin root instead; the
+ * host reads it, checks readability and applies the result inside the shadow
+ * root. The control still owns its structure, hit target and fallback.
+ *
+ * Token names:
+ *   --skin-host-accent | background | foreground | border | radius | font | size
+ *   --skin--                                   (per-part override)
+ *
+ * `host.recovery` keeps its historical `recovery` key so `--skin-recovery-*`
+ * continues to work; its per-part values win over the global set.
+ */
+
+import type { HostOwnedLayer } from "./host-owned-layer.js";
+
+export type HostControlSizeTier = "small" | "medium" | "large";
+export interface HostControlMetrics {
+  /** Host-enforced minimum button hit target in CSS pixels. */
+  readonly hitTarget: number;
+  /** Host-enforced minimum font size in CSS pixels. */
+  readonly fontSize: number;
+}
+
+export const HOST_CONTROL_MIN_HIT_TARGET = 28;
+export const HOST_CONTROL_MIN_FONT_SIZE = 11;
+export const HOST_CONTROL_MIN_FOREGROUND_CONTRAST = 4.5;
+export const HOST_CONTROL_MIN_ACCENT_CONTRAST = 3;
+export const HOST_CONTROL_MIN_BORDER_CONTRAST = 3;
+
+/** Host-controlled size tiers; a skin can choose a tier, never a smaller size. */
+export const HOST_CONTROL_SIZE_METRICS: Readonly> = {
+  small: { hitTarget: 28, fontSize: 11 },
+  medium: { hitTarget: 32, fontSize: 12 },
+  large: { hitTarget: 36, fontSize: 13 },
+};
+
+export const HOST_CONTROL_TOKEN_NAMES = [
+  "accent", "background", "foreground", "border", "radius", "font", "size",
+] as const;
+
+export type HostControlTokenName = (typeof HOST_CONTROL_TOKEN_NAMES)[number];
+
+/** Global token set read from the active skin root (or a slot anchor). */
+export const HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES: Readonly> = {
+  accent: "--skin-host-accent",
+  background: "--skin-host-background",
+  foreground: "--skin-host-foreground",
+  border: "--skin-host-border",
+  radius: "--skin-host-radius",
+  font: "--skin-host-font",
+  size: "--skin-host-size",
+};
+
+/**
+ * Stable per-part token keys. The last dotted segment would turn
+ * `app.skin-load-recovery` into `--skin-skin-load-recovery-*`; the explicit
+ * keys keep the public names readable.
+ */
+export const HOST_CONTROL_TOKEN_KEYS: Readonly> = {
+  "host.recovery": "recovery",
+  "app.skin-load-recovery": "load-recovery",
+  "host.permission": "permission",
+};
+
+export function hostControlTokenKey(part: string): string {
+  return HOST_CONTROL_TOKEN_KEYS[part] ?? part.split(".").pop() ?? part;
+}
+
+export function hostControlTokenProperty(part: string, token: HostControlTokenName): string {
+  return `--skin-${hostControlTokenKey(part)}-${token}`;
+}
+
+/** Host-owned variables written inside the closed shadow root. */
+export const HOST_CONTROL_APPLIED_VARIABLES = {
+  accent: "--ws-control-accent",
+  onAccent: "--ws-control-on-accent",
+  background: "--ws-control-background",
+  foreground: "--ws-control-foreground",
+  border: "--ws-control-border",
+  radius: "--ws-control-radius",
+  font: "--ws-control-font",
+  hitTarget: "--ws-control-hit",
+  fontSize: "--ws-control-font-size",
+  builtInBorder: "--ws-control-builtin-border",
+} as const;
+
+export interface HostControlRawTokens {
+  /** Computed-style colour values; unresolved values are rejected. */
+  accent?: string;
+  background?: string;
+  foreground?: string;
+  border?: string;
+  radius?: string;
+  font?: string;
+  size?: string;
+}
+
+export interface HostControlDefaults {
+  accent: RgbColor;
+  background: RgbColor;
+  foreground: RgbColor;
+  border: RgbColor;
+  radius: number;
+  maxRadius: number;
+  font: string;
+  hitTarget: number;
+  fontSize: number;
+  /** Optional per-tier metrics; defaults to HOST_CONTROL_SIZE_METRICS. */
+  sizeMetrics?: Readonly>;
+  /** A fixed light-background action that keeps its own border contrast check. */
+  builtInButton?: { background: RgbColor; border: RgbColor };
+}
+
+export interface HostControlTokens {
+  accent: string;
+  /** Text colour that stays readable on top of `accent`. */
+  onAccent: string;
+  background: string;
+  foreground: string;
+  border: string;
+  radius: number;
+  font: string;
+  size: HostControlSizeTier;
+  hitTarget: number;
+  fontSize: number;
+  builtInBorder?: string;
+}
+
+export interface RgbColor {
+  r: number;
+  g: number;
+  b: number;
+}
+
+const DEFAULT_ACCENT: RgbColor = { r: 180, g: 83, b: 9 };
+const DEFAULT_BACKGROUND: RgbColor = { r: 255, g: 255, b: 255 };
+const DEFAULT_FOREGROUND: RgbColor = { r: 49, g: 82, b: 79 };
+const DEFAULT_BORDER: RgbColor = { r: 157, g: 182, b: 178 };
+const RECOVERY_BUILT_IN_BACKGROUND: RgbColor = { r: 255, g: 247, b: 237 };
+const RECOVERY_BUILT_IN_BORDER: RgbColor = { r: 180, g: 83, b: 9 };
+const ON_ACCENT_LIGHT: RgbColor = { r: 255, g: 255, b: 255 };
+const ON_ACCENT_DARK: RgbColor = { r: 17, g: 24, b: 39 };
+const MAX_RADIUS = 999;
+const MAX_FONT_LENGTH = 120;
+const FONT_FAMILY_PATTERN = /^[A-Za-z0-9 ,'"-]{1,120}$/;
+
+/** Defaults for the recovery capsule: white surface, teal text, amber accent. */
+export const RECOVERY_CONTROL_DEFAULTS: HostControlDefaults = {
+  accent: DEFAULT_ACCENT,
+  background: DEFAULT_BACKGROUND,
+  foreground: DEFAULT_FOREGROUND,
+  border: DEFAULT_BORDER,
+  radius: 999,
+  maxRadius: MAX_RADIUS,
+  font: "ui-sans-serif, system-ui, sans-serif",
+  hitTarget: HOST_CONTROL_MIN_HIT_TARGET,
+  fontSize: HOST_CONTROL_MIN_FONT_SIZE,
+  builtInButton: { background: RECOVERY_BUILT_IN_BACKGROUND, border: RECOVERY_BUILT_IN_BORDER },
+};
+
+/** Defaults for the skin-load failure banner: amber alert, 44px action. */
+export const SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS: HostControlDefaults = {
+  accent: { r: 180, g: 83, b: 9 },
+  background: { r: 255, g: 251, b: 235 },
+  foreground: { r: 120, g: 53, b: 15 },
+  border: { r: 245, g: 158, b: 11 },
+  radius: 12,
+  maxRadius: 64,
+  font: "ui-sans-serif, system-ui, sans-serif",
+  hitTarget: 44,
+  fontSize: 14,
+  sizeMetrics: {
+    small: { hitTarget: 44, fontSize: 14 },
+    medium: { hitTarget: 46, fontSize: 15 },
+    large: { hitTarget: 48, fontSize: 16 },
+  },
+};
+
+/** Defaults for the host-owned authorization ("permission") dialog. */
+export const PERMISSION_CONTROL_DEFAULTS: HostControlDefaults = {
+  accent: { r: 82, g: 101, b: 223 },
+  background: { r: 255, g: 255, b: 255 },
+  foreground: { r: 37, g: 50, b: 75 },
+  border: { r: 219, g: 227, b: 241 },
+  radius: 20,
+  maxRadius: 64,
+  font: 'system-ui, -apple-system, "Segoe UI", sans-serif',
+  hitTarget: 42,
+  fontSize: 14,
+  sizeMetrics: {
+    small: { hitTarget: 42, fontSize: 14 },
+    medium: { hitTarget: 44, fontSize: 15 },
+    large: { hitTarget: 46, fontSize: 16 },
+  },
+};
+
+/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
+export function parseCssColor(value: string | undefined | null): RgbColor | null {
+  if (!value) return null;
+  const text = value.trim().toLowerCase();
+  const hex = /^#([0-9a-f]{3,8})$/.exec(text);
+  if (hex) {
+    const digits = hex[1];
+    if (digits.length === 3 || digits.length === 4) {
+      return {
+        r: Number.parseInt(digits[0] + digits[0], 16),
+        g: Number.parseInt(digits[1] + digits[1], 16),
+        b: Number.parseInt(digits[2] + digits[2], 16),
+      };
+    }
+    if (digits.length === 6 || digits.length === 8) {
+      return {
+        r: Number.parseInt(digits.slice(0, 2), 16),
+        g: Number.parseInt(digits.slice(2, 4), 16),
+        b: Number.parseInt(digits.slice(4, 6), 16),
+      };
+    }
+    return null;
+  }
+
+  const fn = /^rgba?\(([^()]*)\)$/.exec(text);
+  if (!fn) return null;
+  const parts = fn[1].replace(/\//g, " ").split(/[\s,]+/).filter(Boolean);
+  if (parts.length < 3 || parts.length > 4) return null;
+  const channels: number[] = [];
+  for (const part of parts.slice(0, 3)) {
+    const percent = part.endsWith("%");
+    const parsed = Number.parseFloat(part);
+    if (!Number.isFinite(parsed)) return null;
+    const channel = percent ? parsed * 2.55 : parsed;
+    channels.push(Math.round(Math.min(255, Math.max(0, channel))));
+  }
+  return { r: channels[0], g: channels[1], b: channels[2] };
+}
+
+export function formatRgb(color: RgbColor): string {
+  return `rgb(${color.r}, ${color.g}, ${color.b})`;
+}
+
+/** WCAG 2.x relative luminance, 0 (black) to 1 (white). */
+export function relativeLuminance(color: RgbColor): number {
+  const channel = (value: number): number => {
+    const normalized = Math.min(255, Math.max(0, value)) / 255;
+    return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
+  };
+  return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b);
+}
+
+export function contrastRatio(first: RgbColor, second: RgbColor): number {
+  const lighter = Math.max(relativeLuminance(first), relativeLuminance(second));
+  const darker = Math.min(relativeLuminance(first), relativeLuminance(second));
+  return (lighter + 0.05) / (darker + 0.05);
+}
+
+export function isHostControlSizeTier(value: unknown): value is HostControlSizeTier {
+  return value === "small" || value === "medium" || value === "large";
+}
+
+function sanitizeRadius(value: string | undefined, fallback: number, maxRadius: number): number {
+  if (!value) return fallback;
+  const match = /^(-?\d+(?:\.\d+)?)px$/i.exec(value.trim());
+  if (!match) return fallback;
+  const radius = Number.parseFloat(match[1]);
+  return Number.isFinite(radius) ? Math.min(maxRadius, Math.max(0, radius)) : fallback;
+}
+
+function sanitizeFont(value: string | undefined, fallback: string): string {
+  if (!value) return fallback;
+  const font = value.trim().replace(/\s+/g, " ");
+  if (!font || font.length > MAX_FONT_LENGTH || !FONT_FAMILY_PATTERN.test(font) || !/[A-Za-z0-9]/.test(font)) {
+    return fallback;
+  }
+  return font;
+}
+
+function readTokenSet(
+  style: Pick | null,
+  resolveProperty: (token: HostControlTokenName) => string,
+): HostControlRawTokens {
+  if (!style) return {};
+  const read = (token: HostControlTokenName): string | undefined => {
+    const value = style.getPropertyValue(resolveProperty(token)).trim();
+    return value || undefined;
+  };
+  return {
+    accent: read("accent"),
+    background: read("background"),
+    foreground: read("foreground"),
+    border: read("border"),
+    radius: read("radius"),
+    font: read("font"),
+    size: read("size"),
+  };
+}
+
+function mergeRawTokens(...layers: readonly HostControlRawTokens[]): HostControlRawTokens {
+  const merged: HostControlRawTokens = {};
+  for (const layer of layers) {
+    for (const token of HOST_CONTROL_TOKEN_NAMES) {
+      if (layer[token] !== undefined) merged[token] = layer[token];
+    }
+  }
+  return merged;
+}
+
+type ColorProbe = (raw: string | undefined) => string | undefined;
+
+function resolvePalette(
+  raw: HostControlRawTokens,
+  defaults: HostControlDefaults,
+  probeColor: ColorProbe,
+): { accent: RgbColor; background: RgbColor; foreground: RgbColor } {
+  return {
+    accent: parseCssColor(probeColor(raw.accent)) ?? defaults.accent,
+    background: parseCssColor(probeColor(raw.background)) ?? defaults.background,
+    foreground: parseCssColor(probeColor(raw.foreground)) ?? defaults.foreground,
+  };
+}
+
+function paletteReadable(palette: { accent: RgbColor; background: RgbColor; foreground: RgbColor }): boolean {
+  return contrastRatio(palette.foreground, palette.background) >= HOST_CONTROL_MIN_FOREGROUND_CONTRAST
+    && contrastRatio(palette.accent, palette.background) >= HOST_CONTROL_MIN_ACCENT_CONTRAST;
+}
+
+function resolveBorder(
+  raw: string | undefined,
+  background: RgbColor,
+  probeColor: ColorProbe,
+): RgbColor | undefined {
+  const color = parseCssColor(probeColor(raw));
+  return color && contrastRatio(color, background) >= HOST_CONTROL_MIN_BORDER_CONTRAST ? color : undefined;
+}
+
+function readableOnAccent(accent: RgbColor): RgbColor {
+  return contrastRatio(ON_ACCENT_LIGHT, accent) >= contrastRatio(ON_ACCENT_DARK, accent)
+    ? ON_ACCENT_LIGHT
+    : ON_ACCENT_DARK;
+}
+
+/** True when the skin root declares at least one global or per-part token. */
+export function hasHostControlTokens(
+  style: Pick | null,
+  part: string,
+): boolean {
+  if (!style) return false;
+  return HOST_CONTROL_TOKEN_NAMES.some((token) =>
+    Boolean(style.getPropertyValue(hostControlTokenProperty(part, token)).trim())
+    || Boolean(style.getPropertyValue(HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES[token]).trim())
+  );
+}
+
+/**
+ * Read and sanitize the skin token layers from one computed style.
+ *
+ * `--skin--*` wins per token; unset values fall back to
+ * `--skin-host-*`, then to the control's built-in defaults. Colours are
+ * all-or-nothing: if the combined foreground/background/accent palette is
+ * unreadable, the resolver retries the global layer and finally the built-in
+ * palette, so a skin can never make a protected control unreadable. The
+ * border is optional and must stay visible against the resolved background.
+ */
+export function resolveHostControlTokens(
+  style: Pick | null,
+  part: string,
+  probeColor: ColorProbe,
+  defaults: HostControlDefaults,
+): HostControlTokens {
+  const partTokens = readTokenSet(style, (token) => hostControlTokenProperty(part, token));
+  const globalTokens = readTokenSet(style, (token) => HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES[token]);
+  const merged = mergeRawTokens(globalTokens, partTokens);
+
+  let palette = resolvePalette(merged, defaults, probeColor);
+  if (!paletteReadable(palette)) palette = resolvePalette(globalTokens, defaults, probeColor);
+  if (!paletteReadable(palette)) palette = resolvePalette({}, defaults, probeColor);
+
+  const border = resolveBorder(merged.border, palette.background, probeColor)
+    ?? resolveBorder(globalTokens.border, palette.background, probeColor)
+    ?? defaults.border;
+
+  const sizeValue = merged.size?.trim();
+  const size = isHostControlSizeTier(sizeValue) ? sizeValue : "small";
+  const tierMetrics = (defaults.sizeMetrics ?? HOST_CONTROL_SIZE_METRICS)[size];
+  const hitTarget = Math.max(defaults.hitTarget, tierMetrics.hitTarget);
+  const fontSize = Math.max(defaults.fontSize, tierMetrics.fontSize);
+  const builtInBorder = defaults.builtInButton
+    ? contrastRatio(palette.accent, defaults.builtInButton.background) >= HOST_CONTROL_MIN_ACCENT_CONTRAST
+      ? palette.accent
+      : defaults.builtInButton.border
+    : undefined;
+
+  return {
+    accent: formatRgb(palette.accent),
+    onAccent: formatRgb(readableOnAccent(palette.accent)),
+    background: formatRgb(palette.background),
+    foreground: formatRgb(palette.foreground),
+    border: formatRgb(border),
+    radius: sanitizeRadius(merged.radius, defaults.radius, defaults.maxRadius),
+    font: sanitizeFont(merged.font, defaults.font),
+    size,
+    hitTarget,
+    fontSize,
+    ...(builtInBorder ? { builtInBorder: formatRgb(builtInBorder) } : {}),
+  };
+}
+
+/** Apply (or clear) host-owned variables on the control inside the shadow root. */
+export function applyHostControlTokens(control: HTMLElement, tokens: HostControlTokens | null): void {
+  const style = control.style;
+  for (const property of Object.values(HOST_CONTROL_APPLIED_VARIABLES)) style.removeProperty(property);
+  if (!tokens) return;
+  style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.accent, tokens.accent);
+  style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.onAccent, tokens.onAccent);
+  style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.background, tokens.background);
+  style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.foreground, tokens.foreground);
+  style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.border, tokens.border);
+  style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.radius, `${tokens.radius}px`);
+  style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.font, tokens.font);
+  style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.hitTarget, `${tokens.hitTarget}px`);
+  style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.fontSize, `${tokens.fontSize}px`);
+  if (tokens.builtInBorder) style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.builtInBorder, tokens.builtInBorder);
+}
+
+export interface HostControlThemeBindingOptions {
+  layer: HostOwnedLayer;
+  /** The host-owned element whose inline `--ws-control-*` variables are set. */
+  control: () => HTMLElement | null;
+  part: string;
+  defaults: HostControlDefaults;
+  /** The active skin root (or a slot anchor) to read token values from. */
+  source: () => Element | null;
+}
+
+export interface HostControlThemeBinding {
+  apply(): void;
+  dispose(): void;
+}
+
+/**
+ * Bind one host-owned control to the active skin's token set. The returned
+ * binding owns the hidden colour probe and never stores a token value on the
+ * skin side; callers re-apply it when the active skin or the control changes.
+ */
+export function bindHostControlTheme(options: HostControlThemeBindingOptions): HostControlThemeBinding {
+  let probe: HostControlColorProbe | null = null;
+  return {
+    apply() {
+      const control = options.control();
+      if (!control) return;
+      const source = options.source();
+      const view = source?.ownerDocument.defaultView;
+      if (!source || !view) {
+        applyHostControlTokens(control, null);
+        return;
+      }
+      const style = view.getComputedStyle(source);
+      // No token declaration keeps the control's built-in CSS fallback.
+      if (!hasHostControlTokens(style, options.part)) {
+        applyHostControlTokens(control, null);
+        return;
+      }
+      probe ??= createHostControlColorProbe(options.layer.shadow);
+      applyHostControlTokens(control, resolveHostControlTokens(style, options.part, probe.probeColor, options.defaults));
+    },
+    dispose() {
+      probe?.dispose();
+      probe = null;
+    },
+  };
+}
+
+/** The active skin root; the token source for controls without a slot anchor. */
+export function findSkinRoot(skinId: string | undefined, doc: Document = document): Element | null {
+  for (const root of doc.querySelectorAll(".ws-skin-root")) {
+    if (!skinId || root.getAttribute("data-ws-skin") === skinId) return root;
+  }
+  return null;
+}
+
+export interface HostControlColorProbe {
+  /** Resolve a CSS colour through the browser, inside the closed shadow root. */
+  probeColor(raw: string | undefined): string | undefined;
+  dispose(): void;
+}
+
+/**
+ * A hidden probe element for resolving arbitrary CSS colour syntax (for
+ * example `color-mix()` or `oklch()`) to a concrete `rgb()` value.
+ */
+export function createHostControlColorProbe(shadow: ShadowRoot): HostControlColorProbe {
+  const doc = shadow.ownerDocument;
+  const win = doc.defaultView;
+  const element = doc.createElement("span");
+  element.setAttribute("aria-hidden", "true");
+  element.style.cssText = "position:absolute;left:-9999px;top:0;width:0;height:0;visibility:hidden;pointer-events:none;";
+  shadow.append(element);
+
+  const resolveWith = (raw: string, sentinel: string): string | undefined => {
+    if (!win) return undefined;
+    // An invalid value leaves the previous colour in place. Probe against two
+    // different sentinels so a real token equal to one of them still resolves.
+    element.style.color = sentinel;
+    element.style.color = raw;
+    return win.getComputedStyle(element).color;
+  };
+
+  return {
+    probeColor(raw) {
+      if (!raw) return undefined;
+      const first = resolveWith(raw, "rgb(1, 2, 3)");
+      if (first !== "rgb(1, 2, 3)") return first;
+      const second = resolveWith(raw, "rgb(4, 5, 6)");
+      return second === "rgb(4, 5, 6)" ? undefined : second;
+    },
+    dispose() {
+      element.remove();
+    },
+  };
+}
diff --git a/web/src/services/host-slot-placement.test.ts b/web/src/services/host-slot-placement.test.ts
index 49faaad..6e2f114 100644
--- a/web/src/services/host-slot-placement.test.ts
+++ b/web/src/services/host-slot-placement.test.ts
@@ -2,22 +2,13 @@ import assert from "node:assert/strict";
 import test from "node:test";
 import {
   INITIAL_SLOT_MODE_STATE,
-  RECOVERY_BUILT_IN_BUTTON_BACKGROUND,
-  RECOVERY_MIN_ACCENT_CONTRAST,
-  RECOVERY_MIN_FONT_SIZE,
-  RECOVERY_MIN_FOREGROUND_CONTRAST,
-  RECOVERY_MIN_HIT_TARGET,
-  RECOVERY_SIZE_METRICS,
   computeSlotPlacement,
-  contrastRatio,
   evaluateSlottedControl,
   nextSlotModeState,
-  parseCssColor,
   rectsOverlap,
-  relativeLuminance,
-  resolveRecoveryTokens,
   type SlotAnchorSnapshot,
 } from "./host-slot-placement.js";
+import { HOST_CONTROL_MIN_HIT_TARGET } from "./host-control-tokens.js";
 import type { HostPartRect } from "./host-chrome-visibility.js";
 
 const rect = (left: number, top: number, width: number, height: number): HostPartRect => ({
@@ -41,7 +32,7 @@ const baseEvaluation = {
   anchor: anchor(),
   controlRect: rect(180, 105, 120, 30),
   viewport: { width: 800, height: 600 },
-  minHitTarget: RECOVERY_MIN_HIT_TARGET,
+  minHitTarget: HOST_CONTROL_MIN_HIT_TARGET,
   hitTestOk: true,
 };
 
@@ -135,90 +126,6 @@ test("control size, position and hit test are enforced", () => {
   );
 });
 
-test("CSS colours parse to RGB and ignore alpha for contrast", () => {
-  assert.deepEqual(parseCssColor("#1d4f9c"), { r: 29, g: 79, b: 156 });
-  assert.deepEqual(parseCssColor("#fff"), { r: 255, g: 255, b: 255 });
-  assert.deepEqual(parseCssColor("#ffff"), { r: 255, g: 255, b: 255 });
-  assert.deepEqual(parseCssColor("rgb(29, 79, 156)"), { r: 29, g: 79, b: 156 });
-  assert.deepEqual(parseCssColor("rgb(29 79 156 / 50%)"), { r: 29, g: 79, b: 156 });
-  assert.deepEqual(parseCssColor("rgba(255, 0, 0, .4)"), { r: 255, g: 0, b: 0 });
-  assert.deepEqual(parseCssColor("rgb(300, -5, 0)"), { r: 255, g: 0, b: 0 });
-  for (const invalid of ["", "red", "hsl(10, 20%, 30%)", "color(srgb 1 0 0)", "#12345", "rgb(1, 2)"]) {
-    assert.equal(parseCssColor(invalid), null, invalid);
-  }
-});
-
-test("WCAG contrast follows the relative-luminance formula", () => {
-  assert.equal(relativeLuminance({ r: 0, g: 0, b: 0 }), 0);
-  assert.equal(relativeLuminance({ r: 255, g: 255, b: 255 }), 1);
-  assert.equal(contrastRatio({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }), 21);
-  assert.equal(contrastRatio({ r: 12, g: 34, b: 56 }, { r: 12, g: 34, b: 56 }), 1);
-});
-
-test("skin tokens default to the host palette", () => {
-  const tokens = resolveRecoveryTokens();
-  assert.deepEqual(tokens, {
-    accent: "rgb(180, 83, 9)",
-    builtInBorder: "rgb(180, 83, 9)",
-    background: "rgb(255, 255, 255)",
-    foreground: "rgb(49, 82, 79)",
-    radius: 999,
-    font: "ui-sans-serif, system-ui, sans-serif",
-    size: "small",
-    hitTarget: 28,
-    fontSize: 11,
-  });
-});
-
-test("a readable skin palette is kept and translucent backgrounds become opaque", () => {
-  const tokens = resolveRecoveryTokens({
-    accent: "#47dcc4",
-    background: "rgba(9, 19, 23, 0.4)",
-    foreground: "#edf8f5",
-  });
-  assert.equal(tokens.accent, "rgb(71, 220, 196)");
-  assert.equal(tokens.background, "rgb(9, 19, 23)");
-  assert.equal(tokens.foreground, "rgb(237, 248, 245)");
-});
-
-test("an unreadable colour group falls back as a whole", () => {
-  const lowForeground = resolveRecoveryTokens({ background: "#777777", foreground: "#888888", accent: "#47dcc4" });
-  assert.equal(lowForeground.background, "rgb(255, 255, 255)");
-  assert.equal(lowForeground.foreground, "rgb(49, 82, 79)");
-  assert.equal(lowForeground.accent, "rgb(180, 83, 9)");
-
-  const lowAccent = resolveRecoveryTokens({ background: "#ffffff", foreground: "#31524f", accent: "#eeeeee" });
-  assert.equal(lowAccent.accent, "rgb(180, 83, 9)");
-  assert.ok(contrastRatio(parseCssColor(lowAccent.accent)!, parseCssColor(lowAccent.background)!) >= RECOVERY_MIN_ACCENT_CONTRAST);
-  assert.ok(contrastRatio(parseCssColor(lowAccent.foreground)!, parseCssColor(lowAccent.background)!) >= RECOVERY_MIN_FOREGROUND_CONTRAST);
-});
-
-test("radius, font and size tokens are sanitized and host minimums win", () => {
-  assert.equal(resolveRecoveryTokens({ radius: "12px" }).radius, 12);
-  assert.equal(resolveRecoveryTokens({ radius: "2000px" }).radius, 999);
-  assert.equal(resolveRecoveryTokens({ radius: "-5px" }).radius, 0);
-  assert.equal(resolveRecoveryTokens({ radius: "1em" }).radius, 999);
-  assert.equal(resolveRecoveryTokens({ radius: "12" }).radius, 999);
-
-  assert.equal(
-    resolveRecoveryTokens({ font: 'Tahoma, "Segoe UI", sans-serif' }).font,
-    'Tahoma, "Segoe UI", sans-serif',
-  );
-  for (const font of ["url(https://example.invalid/a.woff2)", "Tahoma; color: red", "x".repeat(121)]) {
-    assert.equal(resolveRecoveryTokens({ font }).font, "ui-sans-serif, system-ui, sans-serif", font);
-  }
-
-  assert.equal(resolveRecoveryTokens({ size: "medium" }).hitTarget, 32);
-  assert.equal(resolveRecoveryTokens({ size: "medium" }).fontSize, 12);
-  assert.equal(resolveRecoveryTokens({ size: "large" }).hitTarget, 36);
-  assert.equal(resolveRecoveryTokens({ size: "large" }).fontSize, 13);
-  assert.equal(resolveRecoveryTokens({ size: "huge" }).size, "small");
-  for (const metrics of Object.values(RECOVERY_SIZE_METRICS)) {
-    assert.ok(metrics.hitTarget >= RECOVERY_MIN_HIT_TARGET);
-    assert.ok(metrics.fontSize >= RECOVERY_MIN_FONT_SIZE);
-  }
-});
-
 test("the mode gate does not flap between the anchor and the fallback", () => {
   let state = INITIAL_SLOT_MODE_STATE;
   // The first valid check slots immediately, even under the anti-flap rule.
@@ -259,14 +166,3 @@ test("rect overlap ignores edge contact and sub-pixel slivers", () => {
   assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(99.5, 0, 50, 40)), false);
   assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(0, 60, 100, 40)), false);
 });
-
-test("the built-in button border only uses an accent visible on its fixed light background", () => {
-  // Passes against the dark skin background, but vanishes on #fff7ed.
-  const pale = resolveRecoveryTokens({ background: "#141414", foreground: "#ffffff", accent: "#fff7ec" });
-  assert.equal(pale.accent, "rgb(255, 247, 236)");
-  assert.equal(pale.builtInBorder, "rgb(180, 83, 9)");
-  assert.ok(contrastRatio(parseCssColor(pale.builtInBorder)!, RECOVERY_BUILT_IN_BUTTON_BACKGROUND) >= RECOVERY_MIN_ACCENT_CONTRAST);
-
-  const strong = resolveRecoveryTokens({ background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" });
-  assert.equal(strong.builtInBorder, "rgb(29, 78, 216)");
-});
diff --git a/web/src/services/host-slot-placement.ts b/web/src/services/host-slot-placement.ts
index c061f66..c1b34e8 100644
--- a/web/src/services/host-slot-placement.ts
+++ b/web/src/services/host-slot-placement.ts
@@ -17,6 +17,15 @@ import type { SkinChromeSlotAlign } from "../../../src/shared/skin-chrome.js";
 import type { HostOwnedLayer } from "./host-owned-layer.js";
 import { isHostPartReachable, type HostPartRect } from "./host-chrome-visibility.js";
 import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
+import {
+  RECOVERY_CONTROL_DEFAULTS,
+  applyHostControlTokens,
+  createHostControlColorProbe,
+  findSkinRoot,
+  resolveHostControlTokens,
+  type HostControlTokens,
+  type HostControlColorProbe,
+} from "./host-control-tokens.js";
 
 export interface SlotViewport {
   width: number;
@@ -190,229 +199,6 @@ export function nextSlotModeState(
   };
 }
 
-/* ------------------------------------------------------------------ *
- * Style tokens
- * ------------------------------------------------------------------ */
-
-export type RecoverySizeTier = "small" | "medium" | "large";
-
-export interface RecoverySizeMetrics {
-  /** Host-enforced minimum button hit target in CSS pixels. */
-  readonly hitTarget: number;
-  /** Host-enforced minimum font size in CSS pixels. */
-  readonly fontSize: number;
-}
-
-export const RECOVERY_MIN_HIT_TARGET = 28;
-export const RECOVERY_MIN_FONT_SIZE = 11;
-export const RECOVERY_MIN_FOREGROUND_CONTRAST = 4.5;
-export const RECOVERY_MIN_ACCENT_CONTRAST = 3;
-
-/** Host-controlled metrics; a skin can choose a tier, never a smaller size. */
-export const RECOVERY_SIZE_METRICS: Readonly> = {
-  small: { hitTarget: RECOVERY_MIN_HIT_TARGET, fontSize: RECOVERY_MIN_FONT_SIZE },
-  medium: { hitTarget: 32, fontSize: 12 },
-  large: { hitTarget: 36, fontSize: 13 },
-};
-
-export interface RecoveryRawTokens {
-  /** Computed-style colour values; unresolved CSS values are rejected. */
-  accent?: string;
-  background?: string;
-  foreground?: string;
-  radius?: string;
-  font?: string;
-  size?: string;
-}
-
-export interface RecoveryTokens {
-  accent: string;
-  /**
-   * Border of the built-in-skin button, which keeps its own fixed light
-   * background (`#fff7ed`). The skin accent is used only when it stays visible
-   * against that background; otherwise the host default accent is used there.
-   */
-  builtInBorder: string;
-  background: string;
-  foreground: string;
-  radius: number;
-  font: string;
-  size: RecoverySizeTier;
-  hitTarget: number;
-  fontSize: number;
-}
-
-export interface RgbColor {
-  r: number;
-  g: number;
-  b: number;
-}
-
-/** CSS custom properties a skin declares on the anchor or an ancestor. */
-export const RECOVERY_SKIN_TOKEN_PROPERTIES = {
-  accent: "--skin-recovery-accent",
-  background: "--skin-recovery-background",
-  foreground: "--skin-recovery-foreground",
-  radius: "--skin-recovery-radius",
-  font: "--skin-recovery-font",
-  size: "--skin-recovery-size",
-} as const;
-
-/** Host-owned variables set inside the closed shadow root. */
-export const RECOVERY_APPLIED_VARIABLES = {
-  accent: "--ws-recovery-accent",
-  builtInBorder: "--ws-recovery-builtin-border",
-  background: "--ws-recovery-background",
-  foreground: "--ws-recovery-foreground",
-  radius: "--ws-recovery-radius",
-  font: "--ws-recovery-font",
-  hitTarget: "--ws-recovery-hit",
-  fontSize: "--ws-recovery-font-size",
-} as const;
-
-const DEFAULT_ACCENT: RgbColor = { r: 180, g: 83, b: 9 };
-/** Fixed background of the built-in-skin button (`#fff7ed`). */
-export const RECOVERY_BUILT_IN_BUTTON_BACKGROUND: RgbColor = { r: 255, g: 247, b: 237 };
-const DEFAULT_BACKGROUND: RgbColor = { r: 255, g: 255, b: 255 };
-const DEFAULT_FOREGROUND: RgbColor = { r: 49, g: 82, b: 79 };
-const DEFAULT_RADIUS = 999;
-const DEFAULT_FONT = "ui-sans-serif, system-ui, sans-serif";
-const MAX_RADIUS = 999;
-const MAX_FONT_LENGTH = 120;
-const FONT_FAMILY_PATTERN = /^[A-Za-z0-9 ,'"-]{1,120}$/;
-
-/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
-export function parseCssColor(value: string | undefined | null): RgbColor | null {
-  if (!value) return null;
-  const text = value.trim().toLowerCase();
-  const hex = /^#([0-9a-f]{3,8})$/.exec(text);
-  if (hex) {
-    const digits = hex[1];
-    if (digits.length === 3 || digits.length === 4) {
-      return {
-        r: Number.parseInt(digits[0] + digits[0], 16),
-        g: Number.parseInt(digits[1] + digits[1], 16),
-        b: Number.parseInt(digits[2] + digits[2], 16),
-      };
-    }
-    if (digits.length === 6 || digits.length === 8) {
-      return {
-        r: Number.parseInt(digits.slice(0, 2), 16),
-        g: Number.parseInt(digits.slice(2, 4), 16),
-        b: Number.parseInt(digits.slice(4, 6), 16),
-      };
-    }
-    return null;
-  }
-
-  const fn = /^rgba?\(([^()]*)\)$/.exec(text);
-  if (!fn) return null;
-  const parts = fn[1].replace(/\//g, " ").split(/[\s,]+/).filter(Boolean);
-  if (parts.length < 3 || parts.length > 4) return null;
-  const channels: number[] = [];
-  for (const part of parts.slice(0, 3)) {
-    const percent = part.endsWith("%");
-    const parsed = Number.parseFloat(part);
-    if (!Number.isFinite(parsed)) return null;
-    const channel = percent ? parsed * 2.55 : parsed;
-    channels.push(Math.round(Math.min(255, Math.max(0, channel))));
-  }
-  return { r: channels[0], g: channels[1], b: channels[2] };
-}
-
-export function formatRgb(color: RgbColor): string {
-  return `rgb(${color.r}, ${color.g}, ${color.b})`;
-}
-
-/** WCAG 2.x relative luminance, 0 (black) to 1 (white). */
-export function relativeLuminance(color: RgbColor): number {
-  const channel = (value: number): number => {
-    const normalized = Math.min(255, Math.max(0, value)) / 255;
-    return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
-  };
-  return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b);
-}
-
-export function contrastRatio(first: RgbColor, second: RgbColor): number {
-  const lighter = Math.max(relativeLuminance(first), relativeLuminance(second));
-  const darker = Math.min(relativeLuminance(first), relativeLuminance(second));
-  return (lighter + 0.05) / (darker + 0.05);
-}
-
-export function isRecoverySizeTier(value: unknown): value is RecoverySizeTier {
-  return value === "small" || value === "medium" || value === "large";
-}
-
-function sanitizeRadius(value: string | undefined): number {
-  if (!value) return DEFAULT_RADIUS;
-  const match = /^(-?\d+(?:\.\d+)?)px$/i.exec(value.trim());
-  if (!match) return DEFAULT_RADIUS;
-  const radius = Number.parseFloat(match[1]);
-  return Number.isFinite(radius) ? Math.min(MAX_RADIUS, Math.max(0, radius)) : DEFAULT_RADIUS;
-}
-
-function sanitizeFont(value: string | undefined): string {
-  if (!value) return DEFAULT_FONT;
-  const font = value.trim().replace(/\s+/g, " ");
-  if (!font || font.length > MAX_FONT_LENGTH || !FONT_FAMILY_PATTERN.test(font) || !/[A-Za-z0-9]/.test(font)) {
-    return DEFAULT_FONT;
-  }
-  return font;
-}
-
-/**
- * Sanitize skin-provided tokens. Colours are all-or-nothing: a readable
- * foreground/background pair and a visible accent keep the skin palette;
- * otherwise the whole colour group reverts to the host palette so a skin can
- * never make the recovery action unreadable.
- */
-export function resolveRecoveryTokens(raw: RecoveryRawTokens = {}): RecoveryTokens {
-  const accent = parseCssColor(raw.accent) ?? DEFAULT_ACCENT;
-  const background = parseCssColor(raw.background) ?? DEFAULT_BACKGROUND;
-  const foreground = parseCssColor(raw.foreground) ?? DEFAULT_FOREGROUND;
-  const readable = contrastRatio(foreground, background) >= RECOVERY_MIN_FOREGROUND_CONTRAST
-    && contrastRatio(accent, background) >= RECOVERY_MIN_ACCENT_CONTRAST;
-  const palette = readable ? { accent, background, foreground } : {
-    accent: DEFAULT_ACCENT,
-    background: DEFAULT_BACKGROUND,
-    foreground: DEFAULT_FOREGROUND,
-  };
-  const sizeValue = raw.size?.trim();
-  const size = isRecoverySizeTier(sizeValue) ? sizeValue : "small";
-  const metrics = RECOVERY_SIZE_METRICS[size];
-  const builtInBorder = contrastRatio(palette.accent, RECOVERY_BUILT_IN_BUTTON_BACKGROUND) >= RECOVERY_MIN_ACCENT_CONTRAST
-    ? palette.accent
-    : DEFAULT_ACCENT;
-  return {
-    accent: formatRgb(palette.accent),
-    builtInBorder: formatRgb(builtInBorder),
-    background: formatRgb(palette.background),
-    foreground: formatRgb(palette.foreground),
-    radius: sanitizeRadius(raw.radius),
-    font: sanitizeFont(raw.font),
-    size,
-    hitTarget: metrics.hitTarget,
-    fontSize: metrics.fontSize,
-  };
-}
-
-/** Apply (or clear) host-owned variables on the control inside the shadow root. */
-export function applyRecoveryTokens(control: HTMLElement, tokens: RecoveryTokens | null): void {
-  const style = control.style;
-  if (!tokens) {
-    for (const property of Object.values(RECOVERY_APPLIED_VARIABLES)) style.removeProperty(property);
-    return;
-  }
-  style.setProperty(RECOVERY_APPLIED_VARIABLES.accent, tokens.accent);
-  style.setProperty(RECOVERY_APPLIED_VARIABLES.builtInBorder, tokens.builtInBorder);
-  style.setProperty(RECOVERY_APPLIED_VARIABLES.background, tokens.background);
-  style.setProperty(RECOVERY_APPLIED_VARIABLES.foreground, tokens.foreground);
-  style.setProperty(RECOVERY_APPLIED_VARIABLES.radius, `${tokens.radius}px`);
-  style.setProperty(RECOVERY_APPLIED_VARIABLES.font, tokens.font);
-  style.setProperty(RECOVERY_APPLIED_VARIABLES.hitTarget, `${tokens.hitTarget}px`);
-  style.setProperty(RECOVERY_APPLIED_VARIABLES.fontSize, `${tokens.fontSize}px`);
-}
-
 /* ------------------------------------------------------------------ *
  * DOM binding
  * ------------------------------------------------------------------ */
@@ -506,14 +292,6 @@ export function resolveSkinAnchor(
   return null;
 }
 
-/** The active skin's root element; the token source while no anchor is usable. */
-export function findSkinRoot(skinId: string | undefined, doc: Document = document): Element | null {
-  for (const root of doc.querySelectorAll(".ws-skin-root")) {
-    if (!skinId || root.getAttribute("data-ws-skin") === skinId) return root;
-  }
-  return null;
-}
-
 export interface HostSlotModeChange {
   mode: "slotted" | "floating";
   reason?: SlotFailureReason;
@@ -560,7 +338,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
   let lastReason: SlotFailureReason | undefined;
   let currentAnchor: HTMLElement | null = null;
   let observer: ResizeObserver | null = null;
-  let probe: HTMLElement | null = null;
+  const colorProbe: HostControlColorProbe = createHostControlColorProbe(layer.shadow);
   let frame: number | undefined;
   let timer: ReturnType | undefined;
   let disposed = false;
@@ -570,45 +348,14 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
   const requestFrame = (callback: FrameRequestCallback): number => win.requestAnimationFrame(callback);
   const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle);
 
-  function ensureProbe(): HTMLElement | null {
-    if (probe) return probe;
-    probe = doc.createElement("span");
-    probe.setAttribute("aria-hidden", "true");
-    probe.style.cssText = "position:absolute;left:-9999px;top:0;width:0;height:0;visibility:hidden;pointer-events:none;";
-    layer.shadow.append(probe);
-    return probe;
-  }
-
-  /** Resolve a CSS colour through the browser, inside the closed shadow root. */
-  function probeColor(raw: string | undefined): string | undefined {
-    if (!raw) return undefined;
-    const element = ensureProbe();
-    if (!element) return undefined;
-    // An invalid value leaves the previous colour in place. Probe against two
-    // different sentinels so a real token equal to one of them still resolves.
-    const resolveWith = (sentinel: string): string => {
-      element.style.color = sentinel;
-      element.style.color = raw;
-      return win.getComputedStyle(element).color;
-    };
-    const first = resolveWith("rgb(1, 2, 3)");
-    if (first !== "rgb(1, 2, 3)") return first;
-    const second = resolveWith("rgb(4, 5, 6)");
-    return second === "rgb(4, 5, 6)" ? undefined : second;
-  }
-
-  function readTokens(source: Element | null): RecoveryTokens {
-    if (!source) return resolveRecoveryTokens();
-    const style = win.getComputedStyle(source);
-    const read = (property: string): string | undefined => style.getPropertyValue(property).trim() || undefined;
-    return resolveRecoveryTokens({
-      accent: probeColor(read(RECOVERY_SKIN_TOKEN_PROPERTIES.accent)),
-      background: probeColor(read(RECOVERY_SKIN_TOKEN_PROPERTIES.background)),
-      foreground: probeColor(read(RECOVERY_SKIN_TOKEN_PROPERTIES.foreground)),
-      radius: read(RECOVERY_SKIN_TOKEN_PROPERTIES.radius),
-      font: read(RECOVERY_SKIN_TOKEN_PROPERTIES.font),
-      size: read(RECOVERY_SKIN_TOKEN_PROPERTIES.size),
-    });
+  function readTokens(source: Element | null): HostControlTokens {
+    if (!source) return resolveHostControlTokens(null, "host.recovery", colorProbe.probeColor, RECOVERY_CONTROL_DEFAULTS);
+    return resolveHostControlTokens(
+      win.getComputedStyle(source),
+      "host.recovery",
+      colorProbe.probeColor,
+      RECOVERY_CONTROL_DEFAULTS,
+    );
   }
 
   function clearPlacement(): void {
@@ -656,7 +403,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
     const tokenSource = anchorElement
       ?? (options.skinId ? findSkinRoot(options.skinId, doc) : null);
     const tokens = readTokens(tokenSource);
-    applyRecoveryTokens(control, tokenSource ? tokens : null);
+    applyHostControlTokens(control, tokenSource ? tokens : null);
 
     const controlBox = control.getBoundingClientRect();
     maxSize = {
@@ -783,9 +530,8 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
       win.removeEventListener("resize", schedule);
       win.removeEventListener("scroll", schedule, { capture: true });
       clearPlacement();
-      applyRecoveryTokens(control, null);
-      probe?.remove();
-      probe = null;
+      applyHostControlTokens(control, null);
+      colorProbe.dispose();
     },
   };
 }
diff --git a/web/test/fixtures/host-slot-placement.html b/web/test/fixtures/host-slot-placement.html
index 3970e48..7a57413 100644
--- a/web/test/fixtures/host-slot-placement.html
+++ b/web/test/fixtures/host-slot-placement.html
@@ -31,10 +31,10 @@ const CSS = `
 .cap {
   position: fixed; inset: auto auto 12px 12px; margin: 0;
   display: flex; gap: 4px; padding: 4px; border: 0; pointer-events: auto;
-  background: var(--ws-recovery-background, #fff);
-  color: var(--ws-recovery-foreground, #31524f);
+  background: var(--ws-control-background, #fff);
+  color: var(--ws-control-foreground, #31524f);
 }
-.cap button { min-height: var(--ws-recovery-hit, 28px); padding: 0 8px; }
+.cap button { min-height: var(--ws-control-hit, 28px); padding: 0 8px; }
 `;
 try {
   const layer = createHostOwnedLayer("recovery", CSS);
@@ -113,7 +113,7 @@ try {
   binding.dispose();
   results.push({
     ...snap("disposed"),
-    leftoverAccent: control.style.getPropertyValue("--ws-recovery-accent"),
+    leftoverAccent: control.style.getPropertyValue("--ws-control-accent"),
   });
   output.textContent = JSON.stringify({ results, changes });
 } catch (error) {
diff --git a/web/test/host-chrome-recovery.test.mjs b/web/test/host-chrome-recovery.test.mjs
index 1a05e2c..e3e1b5a 100644
--- a/web/test/host-chrome-recovery.test.mjs
+++ b/web/test/host-chrome-recovery.test.mjs
@@ -92,6 +92,13 @@ test("host chrome renders recovery and authorization in a closed-shadow top laye
   assert.match(hostChromeService, /export function activeHostSlot/);
   assert.match(hostChromeService, /HOST_SLOTTABLE_PART_IDS\.has\(part\)/);
   assert.match(hostChromeService, /isThirdPartySkinActive\(\)/);
+  // Host-owned controls share one sanitized token reader; no per-control palette copy.
+  assert.match(hostChrome, /bindHostControlTheme/);
+  assert.match(hostChrome, /--ws-control-background/);
+  assert.match(recoveryNotice, /SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS/);
+  assert.match(recoveryNotice, /--ws-control-background/);
+  assert.match(authorization, /PERMISSION_CONTROL_DEFAULTS/);
+  assert.match(authorization, /--ws-control-background/);
 
   // Authorization: showModal() inside the same host-owned mechanism.
   assert.match(authorization, /createHostOwnedLayer\('authorization'/);

From a353c328927cc3cefefbd940c942527a0776a524 Mon Sep 17 00:00:00 2001
From: OddTurtleHead <355182507+OddTurtleHead@users.noreply.github.com>
Date: Sun, 15 Nov 2026 17:14:42 +0800
Subject: [PATCH 06/12] fix: refresh host-control tokens on late skin CSS,
 resolve modern colours and refuse skin fonts

- bindHostControlTheme re-applies when  stylesheets or root attributes
  change, so a stored skin id themes the floating recovery capsule, skin-load
  banner and authorization dialog once its CSS actually arrives; the recovery
  root pass stands down while a slot binding owns the capsule tokens.
- The shadow-root probe converts oklch()/color-mix() results to sRGB via a
  1x1 canvas instead of silently dropping them to the default palette.
- Host-owned controls ignore font tokens naming a document @font-face, which
  could ship blank glyphs and erase the recovery/consent labels.
- Authorization body text uses the full sanitized foreground (the 76% mix
  could fall under the 4.5 contrast floor); theme refreshes before showModal.
- Browser fixture covers late CSS, oklch and font refusal; docs updated.
---
 docs/SKIN_DEVELOPMENT.md                     |   6 +-
 web/src/components/HostChrome.vue            |  13 ++-
 web/src/components/InstanceAuthorization.vue |   3 +-
 web/src/services/host-control-tokens.test.ts |  17 ++++
 web/src/services/host-control-tokens.ts      | 101 ++++++++++++++++---
 web/src/services/host-slot-placement.ts      |  14 +--
 web/test/fixtures/host-control-theme.html    |  75 ++++++++++++++
 web/test/host-chrome-recovery.test.mjs       |  34 ++++++-
 8 files changed, 232 insertions(+), 31 deletions(-)
 create mode 100644 web/test/fixtures/host-control-theme.html

diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md
index 4a3d937..62e3b26 100644
--- a/docs/SKIN_DEVELOPMENT.md
+++ b/docs/SKIN_DEVELOPMENT.md
@@ -501,7 +501,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 | `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 |
 | `--skin-recovery-border` | 胶囊和普通按钮的边框色。与背景的对比度必须 ≥ 3,否则使用宿主默认边框;不影响固定浅色底的「使用内置皮肤」按钮。 |
 | `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 |
-| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;其他值使用宿主默认字体。 |
+| `--skin-recovery-font` | 字体族列表,只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;列表中只要出现皮肤用 `@font-face` 注册的字体就整项忽略(只认系统已安装字体和通用族名);其他值使用宿主默认字体。 |
 | `--skin-recovery-size` | `small`(默认)、`medium` 或 `large`。宿主映射为固定指标:按钮最小命中高度 28 / 32 / 36 px,最小字号 11 / 12 / 13 px;皮肤不能把这些值降到宿主下限以下。 |
 
 颜色建议使用 `#rgb`、`#rrggbb`、`rgb()` 或 `rgba()`;宿主通过影子根内的探针元素让浏览器解析颜色,再按 WCAG 相对亮度检查对比度。无效、缺失或无法解析的值使用宿主默认颜色(强调色 `#b45309`、背景 `#ffffff`、文字 `#31524f`)。
@@ -561,13 +561,13 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 }
 ```
 
-宿主从计算样式读取这些变量,通过影子根内的探针解析颜色,再写入控件自己的 `--ws-control-*` 变量;皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
+宿主从计算样式读取这些变量,通过影子根内的探针解析颜色(`oklch()`、`color-mix()` 等现代写法会先换算成 sRGB 再检查对比度),再写入控件自己的 `--ws-control-*` 变量;皮肤样式晚于皮肤 ID 加载、运行时插件追加样式时,宿主会自动重新读取,不需要刷新页面。皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
 
 - 背景强制不透明(alpha 视为 1)。
 - 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。
 - 边框与背景对比度 ≥ 3,否则使用宿主默认边框。
 - 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。
-- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符。
+- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;只认系统已安装字体和通用族名(`sans-serif` 等)。列表里只要有一个族名来自文档里的 `@font-face`(也就是皮肤自带字体),整项令牌就被忽略,因为自带字体可以把字形做成空白,让宿主控件的文字消失。应用 DOM 内的受保护控件不受此限制,照常可以在 `skin.css` 里用皮肤字体。
 - `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。
 - 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白,保证可读。
 - 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。
diff --git a/web/src/components/HostChrome.vue b/web/src/components/HostChrome.vue
index bf4ed35..189683b 100644
--- a/web/src/components/HostChrome.vue
+++ b/web/src/components/HostChrome.vue
@@ -178,11 +178,13 @@ const showRecovery = computed(() => shouldShowRecovery({
 const shortcutOpen = ref(false);
 const recoveryPopover = ref(null);
 
+let slotBinding: HostSlotBinding | undefined;
+
 /**
- * Theme the capsule even when the skin does not declare a slot. `bindHostSlot`
- * still reads the anchor first when a slot exists; this root-level pass covers
- * the floating capsule and is overwritten by the anchor values on the next
- * revalidation.
+ * Theme the capsule even when the skin does not declare a slot. While a slot
+ * binding exists it reads the anchor first and owns the tokens; this
+ * root-level pass covers the slot-less capsule and refreshes itself when the
+ * skin stylesheet arrives after the stored skin id.
  */
 const recoveryTheme = layer ? bindHostControlTheme({
   layer,
@@ -190,6 +192,8 @@ const recoveryTheme = layer ? bindHostControlTheme({
   part: "host.recovery",
   defaults: RECOVERY_CONTROL_DEFAULTS,
   source: () => findSkinRoot(hostChromeActiveSkinId.value),
+  // While a slot binding exists it owns the capsule tokens (anchor first).
+  active: () => !slotBinding,
 }) : null;
 
 const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
@@ -254,7 +258,6 @@ function onRecoveryFocusOut(event: FocusEvent) {
   compactPinned.value = false;
 }
 
-let slotBinding: HostSlotBinding | undefined;
 function syncSlotBinding() {
   slotBinding?.dispose();
   slotBinding = undefined;
diff --git a/web/src/components/InstanceAuthorization.vue b/web/src/components/InstanceAuthorization.vue
index 5676b90..59763ac 100644
--- a/web/src/components/InstanceAuthorization.vue
+++ b/web/src/components/InstanceAuthorization.vue
@@ -36,7 +36,7 @@ const AUTHORIZATION_LAYER_CSS = `
 :host { font: 14px/1.75 system-ui, -apple-system, "Segoe UI", sans-serif; }
 .ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid var(--ws-control-border,#dbe3f1);border-radius:var(--ws-control-radius,20px);background:var(--ws-control-background,#fff);color:var(--ws-control-foreground,#25324b);font-family:var(--ws-control-font,system-ui,-apple-system,"Segoe UI",sans-serif);font-size:var(--ws-control-font-size,14px);line-height:1.75;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
 .ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
-.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:var(--ws-control-foreground,#202e49)}.ws-instance-authorization p{margin:12px 0;color:color-mix(in srgb,var(--ws-control-foreground,#25324b) 76%,transparent)}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:color-mix(in srgb,var(--ws-control-accent,#5265df) 14%,var(--ws-control-background,#fff));color:var(--ws-control-accent,#5265df);font-size:28px}
+.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:var(--ws-control-foreground,#202e49)}.ws-instance-authorization p{margin:12px 0;color:var(--ws-control-foreground,#526079)}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:color-mix(in srgb,var(--ws-control-accent,#5265df) 14%,var(--ws-control-background,#fff));color:var(--ws-control-accent,#5265df);font-size:28px}
 .ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));border:1px solid var(--ws-control-border,#dce3f3);border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:var(--ws-control-hit,42px);padding:9px 16px;border:1px solid var(--ws-control-border,#d9e1ef);border-radius:var(--ws-control-radius,10px);background:color-mix(in srgb,var(--ws-control-foreground,#25324b) 6%,var(--ws-control-background,#fff));color:var(--ws-control-foreground,#43516d);font:600 var(--ws-control-font-size,14px)/1.5 var(--ws-control-font,system-ui);cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:var(--ws-control-accent,#5265df);color:var(--ws-control-on-accent,#fff);border-color:var(--ws-control-accent,#5265df)}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid var(--ws-control-accent,#5265df);outline-offset:3px}
 @media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
 `;
@@ -59,6 +59,7 @@ watch([dialog, hostChromeActiveSkinId], () => { theme?.apply(); }, { flush: 'pos
 watch(() => props.language, value => { authorizationLanguage.value = value; }, { immediate: true });
 watch([dialog, authorizationRequested, authorizationDecision], () => {
   if (!dialog.value || dialog.value.open || (authorizationDecision.value !== null && !authorizationRequested.value)) return;
+  theme?.apply();
   firstVisit.value = authorizationDecision.value === null;
   checked.value = authorizationDecision.value === true;
   dialog.value.showModal();
diff --git a/web/src/services/host-control-tokens.test.ts b/web/src/services/host-control-tokens.test.ts
index 5c89bcd..83cbe67 100644
--- a/web/src/services/host-control-tokens.test.ts
+++ b/web/src/services/host-control-tokens.test.ts
@@ -14,6 +14,7 @@ import {
   SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
   applyHostControlTokens,
   contrastRatio,
+  fontFamilyNames,
   hasHostControlTokens,
   hostControlTokenKey,
   hostControlTokenProperty,
@@ -248,3 +249,19 @@ test("WCAG contrast follows the relative-luminance formula", () => {
   assert.equal(contrastRatio({ r: 12, g: 34, b: 56 }, { r: 12, g: 34, b: 56 }), 1);
   assert.ok(HOST_CONTROL_MIN_FOREGROUND_CONTRAST > HOST_CONTROL_MIN_ACCENT_CONTRAST);
 });
+
+test("host controls ignore fonts registered by a skin @font-face", () => {
+  assert.deepEqual(fontFamilyNames(`"Wave Font", 'Other' , sans-serif`), ["wave font", "other", "sans-serif"]);
+  const webFonts = new Set(["blank glyphs"]);
+  const isWebFont = (family: string) => webFonts.has(family);
+  const resolve = (font: string) => resolveHostControlTokens(
+    style({ "--skin-host-font": font }),
+    "app.skin-load-recovery",
+    raw => raw,
+    SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
+    isWebFont,
+  ).font;
+  assert.equal(resolve('"Blank Glyphs", sans-serif'), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
+  assert.equal(resolve("Tahoma, 'blank glyphs'"), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
+  assert.equal(resolve('Tahoma, "Segoe UI", sans-serif'), 'Tahoma, "Segoe UI", sans-serif');
+});
diff --git a/web/src/services/host-control-tokens.ts b/web/src/services/host-control-tokens.ts
index fdf3bc1..71b9fbf 100644
--- a/web/src/services/host-control-tokens.ts
+++ b/web/src/services/host-control-tokens.ts
@@ -268,12 +268,20 @@ function sanitizeRadius(value: string | undefined, fallback: number, maxRadius:
   return Number.isFinite(radius) ? Math.min(maxRadius, Math.max(0, radius)) : fallback;
 }
 
-function sanitizeFont(value: string | undefined, fallback: string): string {
+/** Lower-cased family names from a `font-family` list, quotes removed. */
+export function fontFamilyNames(value: string): string[] {
+  return value.split(",").map((name) => name.trim().replace(/^["']|["']$/g, "").trim().toLowerCase()).filter(Boolean);
+}
+
+function sanitizeFont(value: string | undefined, fallback: string, isWebFont: WebFontCheck): string {
   if (!value) return fallback;
   const font = value.trim().replace(/\s+/g, " ");
   if (!font || font.length > MAX_FONT_LENGTH || !FONT_FAMILY_PATTERN.test(font) || !/[A-Za-z0-9]/.test(font)) {
     return fallback;
   }
+  // A skin-supplied @font-face can ship glyph-less outlines and blank the
+  // control's label, so host-owned controls only accept installed/generic fonts.
+  if (fontFamilyNames(font).some(isWebFont)) return fallback;
   return font;
 }
 
@@ -308,6 +316,9 @@ function mergeRawTokens(...layers: readonly HostControlRawTokens[]): HostControl
 }
 
 type ColorProbe = (raw: string | undefined) => string | undefined;
+/** True when a (lower-cased, unquoted) family is provided by a document @font-face. */
+type WebFontCheck = (family: string) => boolean;
+const NO_WEB_FONTS: WebFontCheck = () => false;
 
 function resolvePalette(
   raw: HostControlRawTokens,
@@ -362,12 +373,14 @@ export function hasHostControlTokens(
  * unreadable, the resolver retries the global layer and finally the built-in
  * palette, so a skin can never make a protected control unreadable. The
  * border is optional and must stay visible against the resolved background.
+ * Fonts registered by the document (skin `@font-face`) are ignored.
  */
 export function resolveHostControlTokens(
   style: Pick | null,
   part: string,
   probeColor: ColorProbe,
   defaults: HostControlDefaults,
+  isWebFont: WebFontCheck = NO_WEB_FONTS,
 ): HostControlTokens {
   const partTokens = readTokenSet(style, (token) => hostControlTokenProperty(part, token));
   const globalTokens = readTokenSet(style, (token) => HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES[token]);
@@ -399,7 +412,7 @@ export function resolveHostControlTokens(
     foreground: formatRgb(palette.foreground),
     border: formatRgb(border),
     radius: sanitizeRadius(merged.radius, defaults.radius, defaults.maxRadius),
-    font: sanitizeFont(merged.font, defaults.font),
+    font: sanitizeFont(merged.font, defaults.font, isWebFont),
     size,
     hitTarget,
     fontSize,
@@ -432,6 +445,11 @@ export interface HostControlThemeBindingOptions {
   defaults: HostControlDefaults;
   /** The active skin root (or a slot anchor) to read token values from. */
   source: () => Element | null;
+  /**
+   * When this returns false another owner (the recovery slot binding) is
+   * writing the control's tokens, so `apply()` leaves them untouched.
+   */
+  active?: () => boolean;
 }
 
 export interface HostControlThemeBinding {
@@ -441,13 +459,29 @@ export interface HostControlThemeBinding {
 
 /**
  * Bind one host-owned control to the active skin's token set. The returned
- * binding owns the hidden colour probe and never stores a token value on the
- * skin side; callers re-apply it when the active skin or the control changes.
+ * binding owns the hidden probe and never stores a token value on the skin
+ * side. Callers re-apply it when the active skin or the control changes; the
+ * binding also re-applies itself when stylesheets in `` or the document
+ * root attributes change, because a stored skin id is known before its CSS
+ * (and therefore its tokens) has been injected.
  */
 export function bindHostControlTheme(options: HostControlThemeBindingOptions): HostControlThemeBinding {
-  let probe: HostControlColorProbe | null = null;
-  return {
+  let probe: HostControlProbe | null = null;
+  let observer: MutationObserver | null = null;
+  const doc = options.layer.shadow.ownerDocument;
+  const win = doc.defaultView;
+
+  // MutationObserver already batches a burst of changes into one callback.
+  // Frames are avoided on purpose: they do not run in background tabs.
+  if (win && typeof win.MutationObserver === "function") {
+    observer = new win.MutationObserver(() => binding.apply());
+    observer.observe(doc.head, { childList: true, subtree: true, characterData: true });
+    observer.observe(doc.documentElement, { attributes: true });
+  }
+
+  const binding: HostControlThemeBinding = {
     apply() {
+      if (options.active && !options.active()) return;
       const control = options.control();
       if (!control) return;
       const source = options.source();
@@ -462,14 +496,20 @@ export function bindHostControlTheme(options: HostControlThemeBindingOptions): H
         applyHostControlTokens(control, null);
         return;
       }
-      probe ??= createHostControlColorProbe(options.layer.shadow);
-      applyHostControlTokens(control, resolveHostControlTokens(style, options.part, probe.probeColor, options.defaults));
+      probe ??= createHostControlProbe(options.layer.shadow);
+      applyHostControlTokens(
+        control,
+        resolveHostControlTokens(style, options.part, probe.probeColor, options.defaults, probe.isWebFont),
+      );
     },
     dispose() {
+      observer?.disconnect();
+      observer = null;
       probe?.dispose();
       probe = null;
     },
   };
+  return binding;
 }
 
 /** The active skin root; the token source for controls without a slot anchor. */
@@ -480,19 +520,23 @@ export function findSkinRoot(skinId: string | undefined, doc: Document = documen
   return null;
 }
 
-export interface HostControlColorProbe {
+export interface HostControlProbe {
   /** Resolve a CSS colour through the browser, inside the closed shadow root. */
   probeColor(raw: string | undefined): string | undefined;
+  /** True when `family` (lower-cased, unquoted) comes from a document `@font-face`. */
+  isWebFont(family: string): boolean;
   dispose(): void;
 }
 
 /**
- * A hidden probe element for resolving arbitrary CSS colour syntax (for
- * example `color-mix()` or `oklch()`) to a concrete `rgb()` value.
+ * A hidden probe for resolving arbitrary CSS colour syntax (for example
+ * `color-mix()` or `oklch()`) to a concrete `rgb()` value, and for spotting
+ * fonts that a skin registered itself.
  */
-export function createHostControlColorProbe(shadow: ShadowRoot): HostControlColorProbe {
+export function createHostControlProbe(shadow: ShadowRoot): HostControlProbe {
   const doc = shadow.ownerDocument;
   const win = doc.defaultView;
+  let canvas: CanvasRenderingContext2D | null | undefined;
   const element = doc.createElement("span");
   element.setAttribute("aria-hidden", "true");
   element.style.cssText = "position:absolute;left:-9999px;top:0;width:0;height:0;visibility:hidden;pointer-events:none;";
@@ -507,13 +551,42 @@ export function createHostControlColorProbe(shadow: ShadowRoot): HostControlColo
     return win.getComputedStyle(element).color;
   };
 
+  /**
+   * Browsers serialise `oklch()`, `lab()` and most `color-mix()` results in
+   * their own colour space instead of `rgb()`. Paint those into a 1×1 canvas
+   * to get sRGB channels the contrast check understands.
+   */
+  const toRgb = (computed: string): string | undefined => {
+    if (parseCssColor(computed)) return computed;
+    if (canvas === undefined) {
+      canvas = doc.createElement("canvas").getContext("2d", { willReadFrequently: true });
+      if (canvas) canvas.canvas.width = canvas.canvas.height = 1;
+    }
+    if (!canvas) return undefined;
+    canvas.clearRect(0, 0, 1, 1);
+    canvas.fillStyle = "#000";
+    canvas.fillStyle = computed;
+    canvas.fillRect(0, 0, 1, 1);
+    const [r, g, b] = canvas.getImageData(0, 0, 1, 1).data;
+    return formatRgb({ r, g, b });
+  };
+
   return {
     probeColor(raw) {
       if (!raw) return undefined;
       const first = resolveWith(raw, "rgb(1, 2, 3)");
-      if (first !== "rgb(1, 2, 3)") return first;
+      if (first !== "rgb(1, 2, 3)") return first === undefined ? undefined : toRgb(first);
       const second = resolveWith(raw, "rgb(4, 5, 6)");
-      return second === "rgb(4, 5, 6)" ? undefined : second;
+      return second === undefined || second === "rgb(4, 5, 6)" ? undefined : toRgb(second);
+    },
+    isWebFont(family) {
+      const fonts = doc.fonts;
+      if (!fonts) return false;
+      let found = false;
+      fonts.forEach((face) => {
+        if (!found && fontFamilyNames(face.family).includes(family)) found = true;
+      });
+      return found;
     },
     dispose() {
       element.remove();
diff --git a/web/src/services/host-slot-placement.ts b/web/src/services/host-slot-placement.ts
index c1b34e8..4050f44 100644
--- a/web/src/services/host-slot-placement.ts
+++ b/web/src/services/host-slot-placement.ts
@@ -20,11 +20,11 @@ import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
 import {
   RECOVERY_CONTROL_DEFAULTS,
   applyHostControlTokens,
-  createHostControlColorProbe,
+  createHostControlProbe,
   findSkinRoot,
   resolveHostControlTokens,
   type HostControlTokens,
-  type HostControlColorProbe,
+  type HostControlProbe,
 } from "./host-control-tokens.js";
 
 export interface SlotViewport {
@@ -338,7 +338,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
   let lastReason: SlotFailureReason | undefined;
   let currentAnchor: HTMLElement | null = null;
   let observer: ResizeObserver | null = null;
-  const colorProbe: HostControlColorProbe = createHostControlColorProbe(layer.shadow);
+  const probe: HostControlProbe = createHostControlProbe(layer.shadow);
   let frame: number | undefined;
   let timer: ReturnType | undefined;
   let disposed = false;
@@ -349,12 +349,12 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
   const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle);
 
   function readTokens(source: Element | null): HostControlTokens {
-    if (!source) return resolveHostControlTokens(null, "host.recovery", colorProbe.probeColor, RECOVERY_CONTROL_DEFAULTS);
     return resolveHostControlTokens(
-      win.getComputedStyle(source),
+      source ? win.getComputedStyle(source) : null,
       "host.recovery",
-      colorProbe.probeColor,
+      probe.probeColor,
       RECOVERY_CONTROL_DEFAULTS,
+      probe.isWebFont,
     );
   }
 
@@ -531,7 +531,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
       win.removeEventListener("scroll", schedule, { capture: true });
       clearPlacement();
       applyHostControlTokens(control, null);
-      colorProbe.dispose();
+      probe.dispose();
     },
   };
 }
diff --git a/web/test/fixtures/host-control-theme.html b/web/test/fixtures/host-control-theme.html
new file mode 100644
index 0000000..3d8e992
--- /dev/null
+++ b/web/test/fixtures/host-control-theme.html
@@ -0,0 +1,75 @@
+
+
+
+
+
+Host control theme fixture
+
+
+
+
+
pending
+ + + diff --git a/web/test/host-chrome-recovery.test.mjs b/web/test/host-chrome-recovery.test.mjs index e3e1b5a..2add711 100644 --- a/web/test/host-chrome-recovery.test.mjs +++ b/web/test/host-chrome-recovery.test.mjs @@ -169,7 +169,7 @@ test("the public-skin composable opts in only through chrome.json#visibleParts", assert.doesNotMatch(usePublicSkin, /\.test\(skin\.css\)/); }); -async function dumpDom(url) { +async function dumpDom(url, extraArgs = []) { return await new Promise((resolve, reject) => { const child = spawn(CHROME, [ "--headless=new", @@ -177,6 +177,7 @@ async function dumpDom(url) { "--disable-gpu", "--disable-dev-shm-usage", "--hide-scrollbars", + ...extraArgs, "--dump-dom", url, ], { stdio: ["ignore", "pipe", "pipe"] }); @@ -301,3 +302,34 @@ test("a declared slot docks the capsule and falls back at runtime", { skip: !CHR assert.equal(byName.disposed.atDefaultCorner, true); assert.equal(byName.disposed.leftoverAccent, ""); }); + +test("host control tokens follow late skin CSS, resolve modern colours and refuse skin fonts", { skip: !CHROME && "google-chrome is not installed" }, async (t) => { + const server = await createServer({ + root: webRoot, + configFile: path.join(webRoot, "vite.config.ts"), + logLevel: "silent", + server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false }, + }); + t.after(() => server.close()); + await server.listen(); + const address = server.httpServer?.address(); + const port = address && typeof address === "object" ? address.port : 0; + assert.ok(port, "Vite did not expose a listening port"); + + // The fixture awaits animation frames, so give headless Chrome virtual time. + const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-control-theme.html`, ["--virtual-time-budget=10000"]); + const match = dom.match(/
]*>([\s\S]*?)<\/pre>/);
+  assert.ok(match, "the fixture did not emit a result block");
+  const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/g, "&"));
+  assert.equal(payload.error, undefined, payload.error);
+  const byName = Object.fromEntries(payload.results.map((result) => [result.name, result]));
+
+  assert.equal(byName["before-skin-css"].inlineBackground, "", "tokens were applied before the skin declared any");
+  const late = byName["late-skin-css"];
+  assert.match(late.inlineBackground, /^rgb\(\d+, \d+, \d+\)$/, "late skin CSS did not re-theme the control");
+  assert.notEqual(late.inlineBackground, "rgb(255, 251, 235)", "the oklch() background fell back to the default palette");
+  assert.equal(late.background, late.inlineBackground);
+  assert.equal(late.inlineFont, "ui-sans-serif, system-ui, sans-serif", "a skin @font-face reached a host-owned control");
+  assert.equal(byName["system-font"].inlineFont, 'Tahoma, "Segoe UI", sans-serif');
+  assert.equal(byName["after-dispose"].inlineBackground, late.inlineBackground, "a disposed binding kept observing the document");
+});

From 0df25e4892b9a3e1fdec8e9aa76642fb2aa239e9 Mon Sep 17 00:00:00 2001
From: OddTurtleHead <355182507+OddTurtleHead@users.noreply.github.com>
Date: Sun, 15 Nov 2026 18:04:25 +0800
Subject: [PATCH 07/12] fix: close review gaps in host-control fonts, on-accent
 contrast and protected filter values

- Host-owned controls refuse font tokens naming the compiler's scoped skin
  font prefix (ws-), so a skin @font-face gated behind a non-matching @media
  (absent from document.fonts) cannot blank labels after a resize; the theme
  binding also re-reads tokens on viewport resize for @media-scoped tokens.
- A token palette is accepted only if black or white text reaches 4.5:1 on its
  accent; mid-tone accents (~4.23:1) now fall back as a group.
- Protected app-DOM controls reject var()/attr() for filter, clip and
  content-visibility, which could smuggle opacity(0)/rect(0,0,0,0)/hidden past
  the literal hide checks; literal filters and other parts are unchanged.
- Docs and tests updated (unit + headless-Chrome fixture).
---
 docs/SKIN_DEVELOPMENT.md                     | 12 +++++-----
 src/shared/skin-css.test.ts                  | 14 +++++++++++
 src/shared/skin-css.ts                       | 20 ++++++++++++----
 web/src/services/host-control-tokens.test.ts | 16 +++++++++++++
 web/src/services/host-control-tokens.ts      | 25 ++++++++++++++++----
 web/test/fixtures/host-control-theme.html    | 16 +++++++++++++
 web/test/host-chrome-recovery.test.mjs       |  4 ++++
 7 files changed, 92 insertions(+), 15 deletions(-)

diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md
index 62e3b26..10289e5 100644
--- a/docs/SKIN_DEVELOPMENT.md
+++ b/docs/SKIN_DEVELOPMENT.md
@@ -514,7 +514,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 
 28 个受保护部件里,`host.recovery`、`app.skin-load-recovery` 和授权对话框由宿主在闭合 Shadow DOM 中绘制,`host.permission` 目前没有渲染点;其余 25 个都渲染在 `.ws-skin-root` 内(服务器/频道密码弹窗也在根内,不是 `Teleport`)。开放皮肤(schemaVersion 3/4)可以直接用 `skin.css` 给它们换肤;宿主只保留「不能隐藏 / 不能移出视口 / 不能禁用 / 使用内置皮肤的路径不能被切断」四条底线。
 
-**应用 DOM 内的受保护控件。** 颜色、`var()` 颜色、纯色/渐变/包内位图背景、边框、圆角、`font-family`/`font-size`、内边距、宽高、`box-shadow`、`text-shadow`、`filter`、`outline` 等纯视觉属性都可以写:
+**应用 DOM 内的受保护控件。** 颜色、`var()` 颜色、纯色/渐变/包内位图背景、边框、圆角、`font-family`/`font-size`、内边距、宽高、`box-shadow`、`text-shadow`、`filter`(字面值)、`outline` 等纯视觉属性都可以写:
 
 ```css
 [data-ws-part="voice.audio-dock.microphone"],
@@ -541,7 +541,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 | 控件 | 每部件前缀 | 说明 |
 | --- | --- | --- |
 | `host.recovery` | `--skin-recovery-*` | 兼容原有令牌;写到锚点、锚点祖先或皮肤根上都有效 |
-| `app.skin-load-recovery` | `--skin-load-recovery-*` | 皮肤加载失败时出现的顶部横幅;只换肤,不参与停靠 |
+| `app.skin-load-recovery` | `--skin-load-recovery-*` | 皮肤加载失败时出现的顶部横幅;只换肤,不参与停靠。令牌取自横幅出现时的**活动**皮肤:加载失败后宿主会退回内置皮肤(内置皮肤不声明令牌),所以失败皮肤自己的值通常不会作用在自己的横幅上,横幅保持默认琥珀色 |
 | 授权对话框(`host.permission` 概念) | `--skin-permission-*` | `host.permission` 没有 DOM 渲染点;令牌作用于宿主自己的授权对话框 |
 
 每个每部件令牌都有全局回退:`--skin-host-accent`、`--skin-host-background`、`--skin-host-foreground`、`--skin-host-border`、`--skin-host-radius`、`--skin-host-font`、`--skin-host-size`。每部件值优先于全局值。例如:
@@ -561,15 +561,15 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 }
 ```
 
-宿主从计算样式读取这些变量,通过影子根内的探针解析颜色(`oklch()`、`color-mix()` 等现代写法会先换算成 sRGB 再检查对比度),再写入控件自己的 `--ws-control-*` 变量;皮肤样式晚于皮肤 ID 加载、运行时插件追加样式时,宿主会自动重新读取,不需要刷新页面。皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
+宿主从计算样式读取这些变量,通过影子根内的探针解析颜色(`oklch()`、`color-mix()` 等现代写法会先换算成 sRGB 再检查对比度),再写入控件自己的 `--ws-control-*` 变量;皮肤样式晚于皮肤 ID 加载、运行时插件追加样式、窗口尺寸变化让 `@media` 里的令牌生效时,宿主会自动重新读取,不需要刷新页面。皮肤不能写入 Shadow DOM 内部,也不能替换结构令牌。安全底线与其他受保护控件一致:
 
 - 背景强制不透明(alpha 视为 1)。
 - 文字与背景对比度必须 ≥ 4.5,强调色与背景 ≥ 3;任一不达标时整组颜色回退到宿主默认,而不是只改一项。
 - 边框与背景对比度 ≥ 3,否则使用宿主默认边框。
 - 圆角只接受 px 并限制上限(恢复胶囊 999px,横幅和授权对话框 64px)。
-- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;只认系统已安装字体和通用族名(`sans-serif` 等)。列表里只要有一个族名来自文档里的 `@font-face`(也就是皮肤自带字体),整项令牌就被忽略,因为自带字体可以把字形做成空白,让宿主控件的文字消失。应用 DOM 内的受保护控件不受此限制,照常可以在 `skin.css` 里用皮肤字体。
+- 字体族只允许字母、数字、空格、逗号、引号和连字符,最长 120 字符;只认系统已安装字体和通用族名(`sans-serif` 等)。列表里只要有一个族名来自文档里的 `@font-face`,或带有编译器给皮肤字体加的 `ws-` 作用域前缀(包括放在暂未生效的 `@media` 里的字体),整项令牌就被忽略,因为自带字体可以把字形做成空白,让宿主控件的文字消失。应用 DOM 内的受保护控件不受此限制,照常可以在 `skin.css` 里用皮肤字体。
 - `size` 只接受 `small`、`medium`、`large`,并且只能把命中区域/字号调大;恢复胶囊为 28/32/36px 命中区域、11/12/13px 字号,横幅和授权对话框以自身更大的内置尺寸为下限。
-- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白,保证可读。
+- 授权对话框的主按钮文字色由宿主根据强调色自动选择黑/白;如果黑白两种文字在强调色上都达不到 4.5,这组颜色同样整体回退到宿主默认。
 - 恢复胶囊停靠后如果锚点消失、被遮挡或压到其他受保护控件,仍会回退到默认位置;横幅固定在顶部,授权对话框始终是顶层模态框,二者不参与停靠,因此不会因为皮肤布局而找不到。
 
 `Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)和「使用内置皮肤」的重置路径完全不受令牌影响。旧皮肤继续写 `--skin-recovery-*` 也能工作;新皮肤建议优先使用全局 `--skin-host-*`,只在需要区分具体控件时写每部件覆盖。
@@ -731,7 +731,7 @@ v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显
 
 上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。`host.watermark`、`host.hint`、`host.voice-status-decoration` 默认不渲染,`chrome.json#visibleParts` 才是它们的开启开关。
 
-关键帧与普通声明遵循同一套受保护控件检查,但只检查动画能够**停留**的帧:`to` / `100%` 始终检查;`from` / `0%` 仅在引用它的声明(含同一主体上另一条规则的方向 / 填充 / 播放状态长属性)使用 `reverse`、`alternate`、`alternate-reverse` 方向、`backwards` / `both` 填充模式或 `paused` 播放状态时检查;转义的 `to` / `from` 与 `1e2%` 这类写法按停留帧识别;`50%` 等中间帧不会因为过渡状态被拒绝,缺少 `to` / `100%` 时结束状态回到元素自身样式(`paused` 配合负延迟、或超长动画停在中间帧属于已知残留,由闭合 Shadow DOM 的恢复胶囊兜底)。受保护控件上被拒绝的写法包括 `display: none`、`visibility: hidden|collapse`、`opacity` ≤ 0.01(含 `0`、`0%`、`0e0`、`calc(0)` 等)、`pointer-events: none`、`filter` / `-webkit-filter` 的 `opacity(≤0.01)` / `brightness(0)`、`transform` / `scale` 的零缩放、`content-visibility: hidden`、`clip-path` 的 `inset(...)`(任一边对合计 ≥ 100%)、`circle(0)` / `ellipse(0 …)`、`clip: rect(0,0,0,0)`,以及 `mask` / `mask-image` 的 `alpha(0)` / `luminance(0)` 或全透明渐变色标;`polygon()` 等装饰性裁切不受限制。受保护主体的判定会展开 `:is()` / `:where()` 参数、双重否定 `:not(:not(X))` 与 `:nth-child(An+B of S)` / `:nth-last-child(...)` 的 `S`,`[data-ws-part="…" i]` 按不区分大小写匹配。把控件移出视口只在明显越界时拒绝:负向 ≤ -1000px 或 ≤ -100%,正向 ≥ 2000px 或 ≥ 200%(`margin` / `inset` / `left` / `right` / `top` / `bottom` / `translate` / `transform`,含简单 `calc()` 与 `matrix()` 平移);`scale`、`rotate` 和小幅平移不受影响。`host.plugins.overlay` 的布局锁在关键帧中复用普通声明的属性锁:停留帧里的定位、变换等锁定属性只能取中性或单位变换(`none`、`auto`、`static`、`0`、`scale(1)`、`translateY(0)`、`rotate(0deg)` 或 CSS 全局关键字),尺寸属性仅在达到视口尺寸时拒绝(含 `calc(50vw * 2)`);入场动画停在这些值时通过。受保护控件和 `host.plugins.overlay` 上的 `animation` / `animation-name` 也不能用 `var()` / `attr()` 间接指定动画名。只被可选/装饰部件引用的关键帧仍可隐藏它们,v3 对非受保护部件的隐藏只给出警告。校验器是恢复路径的最后一道安全网,不是布局或视觉质量检查;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
+关键帧与普通声明遵循同一套受保护控件检查,但只检查动画能够**停留**的帧:`to` / `100%` 始终检查;`from` / `0%` 仅在引用它的声明(含同一主体上另一条规则的方向 / 填充 / 播放状态长属性)使用 `reverse`、`alternate`、`alternate-reverse` 方向、`backwards` / `both` 填充模式或 `paused` 播放状态时检查;转义的 `to` / `from` 与 `1e2%` 这类写法按停留帧识别;`50%` 等中间帧不会因为过渡状态被拒绝,缺少 `to` / `100%` 时结束状态回到元素自身样式(`paused` 配合负延迟、或超长动画停在中间帧属于已知残留,由闭合 Shadow DOM 的恢复胶囊兜底)。受保护控件上被拒绝的写法包括 `display: none`、`visibility: hidden|collapse`、`opacity` ≤ 0.01(含 `0`、`0%`、`0e0`、`calc(0)` 等)、`pointer-events: none`、`filter` / `-webkit-filter` 的 `opacity(≤0.01)` / `brightness(0)`、`transform` / `scale` 的零缩放、`content-visibility: hidden`、`clip-path` 的 `inset(...)`(任一边对合计 ≥ 100%)、`circle(0)` / `ellipse(0 …)`、`clip: rect(0,0,0,0)`,以及 `mask` / `mask-image` 的 `alpha(0)` / `luminance(0)` 或全透明渐变色标;`polygon()` 等装饰性裁切不受限制。受保护主体的判定会展开 `:is()` / `:where()` 参数、双重否定 `:not(:not(X))` 与 `:nth-child(An+B of S)` / `:nth-last-child(...)` 的 `S`,`[data-ws-part="…" i]` 按不区分大小写匹配。把控件移出视口只在明显越界时拒绝:负向 ≤ -1000px 或 ≤ -100%,正向 ≥ 2000px 或 ≥ 200%(`margin` / `inset` / `left` / `right` / `top` / `bottom` / `translate` / `transform`,含简单 `calc()` 与 `matrix()` 平移);`scale`、`rotate` 和小幅平移不受影响。`host.plugins.overlay` 的布局锁在关键帧中复用普通声明的属性锁:停留帧里的定位、变换等锁定属性只能取中性或单位变换(`none`、`auto`、`static`、`0`、`scale(1)`、`translateY(0)`、`rotate(0deg)` 或 CSS 全局关键字),尺寸属性仅在达到视口尺寸时拒绝(含 `calc(50vw * 2)`);入场动画停在这些值时通过。受保护控件和 `host.plugins.overlay` 上的 `animation` / `animation-name` 也不能用 `var()` / `attr()` 间接指定动画名;受保护控件上的 `filter` / `-webkit-filter`、`clip` 与 `content-visibility` 同样只接受字面值,不能用 `var()` / `attr()`(否则变量可以绕过上面的隐藏检查),其他部件不受影响。只被可选/装饰部件引用的关键帧仍可隐藏它们,v3 对非受保护部件的隐藏只给出警告。校验器是恢复路径的最后一道安全网,不是布局或视觉质量检查;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
 
 皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。v3 也不能用大的负 `margin*`、`inset`/`translate` 等把受保护控件移出视口,或把 `host.plugins.overlay` 及其后代改成定位全屏、放大到覆盖视口(`zoom` 等);这些写法会在导入时被拒绝。装饰性宿主外壳(`host.watermark`、`host.hint`、`host.voice-status-decoration`、`host.plugins.launcher`)和普通页面部件不受布局锁限制,可以自由使用 flex/grid、重定位、自定义尺寸、大背景和动画;固定定位或极端 `z-index` 只会给出提示。开放皮肤(v3/v4)的布局与视觉质量由官方库的人工审核保证,编译器不会阻止一般性的布局回归。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
 
diff --git a/src/shared/skin-css.test.ts b/src/shared/skin-css.test.ts
index 0c5d251..6943b80 100644
--- a/src/shared/skin-css.test.ts
+++ b/src/shared/skin-css.test.ts
@@ -386,11 +386,25 @@ test("protected controls accept every purely visual property", () => {
     '[data-ws-part="voice.audio-dock.microphone"] { clip-path: inset(100%); }',
     '[data-ws-part="voice.audio-dock.microphone"] { transform: translateY(-9999px); }',
     ':root { --skin-pull: -9999px; } [data-ws-part="voice.audio-dock.microphone"] { margin-left: var(--skin-pull); }',
+    // Literal filter/clip/content-visibility hiding is rejected, so a variable
+    // must not smuggle the same value past the check.
+    ':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { filter: var(--skin-x); }',
+    ':root { --skin-x: opacity(0); } [data-ws-part="voice.audio-dock.microphone"] { -webkit-filter: var(--skin-x); }',
+    ':root { --skin-x: rect(0, 0, 0, 0); } [data-ws-part="voice.audio-dock.microphone"] { clip: var(--skin-x); }',
+    ':root { --skin-x: hidden; } [data-ws-part="voice.audio-dock.microphone"] { content-visibility: var(--skin-x); }',
   ]) {
     assert.throws(() => compile(css), /must remain available|must remain on screen|cannot use indirect values/, css);
   }
 });
 
+test("indirect filter values stay free outside protected controls", () => {
+  for (const version of [2, 3] as const) {
+    assert.doesNotThrow(() => compileSkinCss(':root { --skin-glow: drop-shadow(0 0 4px #0ff); } [data-ws-part="voice.header"] { filter: var(--skin-glow); }', "demo-skin", new Set(), version));
+  }
+  // Literal visual filters remain allowed on protected controls.
+  assert.doesNotThrow(() => compile('[data-ws-part="voice.audio-dock.microphone"] { filter: drop-shadow(0 0 4px #0ff) saturate(1.2); }'));
+});
+
 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; }'),
diff --git a/src/shared/skin-css.ts b/src/shared/skin-css.ts
index 363fc9e..384a49d 100644
--- a/src/shared/skin-css.ts
+++ b/src/shared/skin-css.ts
@@ -84,6 +84,14 @@ const INDIRECT_VALUE_PROPERTIES = new Set([
   "margin-block", "margin-block-start", "margin-block-end",
   "margin-inline", "margin-inline-start", "margin-inline-end",
 ]);
+/**
+ * Visual properties whose literal hiding values (`filter: opacity(0)`,
+ * `clip: rect(0 0 0 0)`, `content-visibility: hidden`) are rejected on
+ * protected controls. They stay free on every other part, but a protected
+ * control may not take them from `var()`/`attr()`, which would hide the
+ * same value from the static check.
+ */
+const PROTECTED_INDIRECT_HIDE_PROPERTIES = new Set(["filter", "clip", "content-visibility"]);
 /** Attributes a skin author must never use to reach outside the public hooks. */
 const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
   HOST_SKIN_ATTRIBUTE,
@@ -319,11 +327,13 @@ export function compileSkinCss(source: string, id: string, assets: SkinCssAssets
     if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) {
       throw declaration.error("Executable CSS values are not allowed.");
     }
-    if (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && restingFrame && /\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 indirectValue = restingFrame && /\b(?:var|attr)\s*\(/i.test(decodedValue);
+    if (indirectValue && protectedTarget
+      && (INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) || PROTECTED_INDIRECT_HIDE_PROPERTIES.has(unprefixedProperty))) {
+      throw declaration.error(`The required control "${protectedTarget}" cannot use indirect values for visibility or positioning.`);
+    }
+    if (indirectValue && !protectedTarget && INDIRECT_VALUE_PROPERTIES.has(unprefixedProperty) && !canHideTarget && schemaVersion < 3) {
+      throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
     }
     // An indirect animation name is checked at the declaration site. Locked
     // host chrome (the plugin overlay) uses the same rule, otherwise a
diff --git a/web/src/services/host-control-tokens.test.ts b/web/src/services/host-control-tokens.test.ts
index 83cbe67..aa4b3f8 100644
--- a/web/src/services/host-control-tokens.test.ts
+++ b/web/src/services/host-control-tokens.test.ts
@@ -15,6 +15,7 @@ import {
   applyHostControlTokens,
   contrastRatio,
   fontFamilyNames,
+  formatRgb,
   hasHostControlTokens,
   hostControlTokenKey,
   hostControlTokenProperty,
@@ -194,6 +195,17 @@ test("global tokens theme the banner and the authorization dialog", () => {
   assert.ok(contrastRatio(parseCssColor(dialog.onAccent)!, parseCssColor(dialog.accent)!) >= 4.5);
   assert.equal(dialog.hitTarget, 46);
 
+  // A mid-grey accent passes 3:1 on white, but neither black nor white text
+  // reaches 4.5:1 on it (best is ~4.23), so the palette falls back as a group.
+  const midTone = resolveHostControlTokens(
+    style(prefixed("host", { background: "#ffffff", foreground: "#000000", accent: "#7b7b7b" })),
+    "host.permission",
+    raw => raw,
+    PERMISSION_CONTROL_DEFAULTS,
+  );
+  assert.equal(midTone.accent, formatRgb(PERMISSION_CONTROL_DEFAULTS.accent));
+  assert.ok(contrastRatio(parseCssColor(midTone.onAccent)!, parseCssColor(midTone.accent)!) >= 4.5);
+
   const override = resolveHostControlTokens(
     style({ ...prefixed("host", { background: "#102030", foreground: "#ffffff", accent: "#47dcc4" }), ...prefixed("load-recovery", { background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" }) }),
     "app.skin-load-recovery",
@@ -264,4 +276,8 @@ test("host controls ignore fonts registered by a skin @font-face", () => {
   assert.equal(resolve('"Blank Glyphs", sans-serif'), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
   assert.equal(resolve("Tahoma, 'blank glyphs'"), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
   assert.equal(resolve('Tahoma, "Segoe UI", sans-serif'), 'Tahoma, "Segoe UI", sans-serif');
+  // Compiled skin faces are always `ws--`; a face gated behind a
+  // non-matching @media is not in document.fonts yet but must still be refused.
+  assert.equal(resolve('"ws-community-evil-blank", sans-serif'), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
+  assert.equal(resolve("Tahoma, ws-community-evil-blank"), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
 });
diff --git a/web/src/services/host-control-tokens.ts b/web/src/services/host-control-tokens.ts
index 71b9fbf..f4297ca 100644
--- a/web/src/services/host-control-tokens.ts
+++ b/web/src/services/host-control-tokens.ts
@@ -147,6 +147,14 @@ const ON_ACCENT_DARK: RgbColor = { r: 17, g: 24, b: 39 };
 const MAX_RADIUS = 999;
 const MAX_FONT_LENGTH = 120;
 const FONT_FAMILY_PATTERN = /^[A-Za-z0-9 ,'"-]{1,120}$/;
+/**
+ * The skin compiler renames every skin/plugin `@font-face` family to
+ * `ws-[-]-` (see `compileSkinCss` in
+ * src/shared/skin-css.ts), so that prefix identifies a skin font even when the
+ * face is not in `document.fonts` yet (for example behind a non-matching
+ * `@media` that activates after the token was accepted).
+ */
+const SCOPED_SKIN_FONT_PREFIX = "ws-";
 
 /** Defaults for the recovery capsule: white surface, teal text, amber accent. */
 export const RECOVERY_CONTROL_DEFAULTS: HostControlDefaults = {
@@ -281,7 +289,7 @@ function sanitizeFont(value: string | undefined, fallback: string, isWebFont: We
   }
   // A skin-supplied @font-face can ship glyph-less outlines and blank the
   // control's label, so host-owned controls only accept installed/generic fonts.
-  if (fontFamilyNames(font).some(isWebFont)) return fallback;
+  if (fontFamilyNames(font).some((name) => name.startsWith(SCOPED_SKIN_FONT_PREFIX) || isWebFont(name))) return fallback;
   return font;
 }
 
@@ -334,7 +342,10 @@ function resolvePalette(
 
 function paletteReadable(palette: { accent: RgbColor; background: RgbColor; foreground: RgbColor }): boolean {
   return contrastRatio(palette.foreground, palette.background) >= HOST_CONTROL_MIN_FOREGROUND_CONTRAST
-    && contrastRatio(palette.accent, palette.background) >= HOST_CONTROL_MIN_ACCENT_CONTRAST;
+    && contrastRatio(palette.accent, palette.background) >= HOST_CONTROL_MIN_ACCENT_CONTRAST
+    // Primary actions put host-chosen text on the accent; mid-tone accents
+    // where neither black nor white reaches the text floor are rejected.
+    && contrastRatio(readableOnAccent(palette.accent), palette.accent) >= HOST_CONTROL_MIN_FOREGROUND_CONTRAST;
 }
 
 function resolveBorder(
@@ -373,7 +384,8 @@ export function hasHostControlTokens(
  * unreadable, the resolver retries the global layer and finally the built-in
  * palette, so a skin can never make a protected control unreadable. The
  * border is optional and must stay visible against the resolved background.
- * Fonts registered by the document (skin `@font-face`) are ignored.
+ * Fonts registered by the document (skin `@font-face`) and names carrying the
+ * compiler's scoped skin-font prefix (`ws-`) are ignored.
  */
 export function resolveHostControlTokens(
   style: Pick | null,
@@ -463,7 +475,8 @@ export interface HostControlThemeBinding {
  * side. Callers re-apply it when the active skin or the control changes; the
  * binding also re-applies itself when stylesheets in `` or the document
  * root attributes change, because a stored skin id is known before its CSS
- * (and therefore its tokens) has been injected.
+ * (and therefore its tokens) has been injected, and on viewport resize, because
+ * tokens may be declared inside `@media`.
  */
 export function bindHostControlTheme(options: HostControlThemeBindingOptions): HostControlThemeBinding {
   let probe: HostControlProbe | null = null;
@@ -478,6 +491,9 @@ export function bindHostControlTheme(options: HostControlThemeBindingOptions): H
     observer.observe(doc.head, { childList: true, subtree: true, characterData: true });
     observer.observe(doc.documentElement, { attributes: true });
   }
+  // Tokens declared inside `@media` change with the viewport, not the DOM.
+  const onResize = (): void => binding.apply();
+  win?.addEventListener("resize", onResize, { passive: true });
 
   const binding: HostControlThemeBinding = {
     apply() {
@@ -505,6 +521,7 @@ export function bindHostControlTheme(options: HostControlThemeBindingOptions): H
     dispose() {
       observer?.disconnect();
       observer = null;
+      win?.removeEventListener("resize", onResize);
       probe?.dispose();
       probe = null;
     },
diff --git a/web/test/fixtures/host-control-theme.html b/web/test/fixtures/host-control-theme.html
index 3d8e992..1e500f4 100644
--- a/web/test/fixtures/host-control-theme.html
+++ b/web/test/fixtures/host-control-theme.html
@@ -61,6 +61,22 @@ const addSkinStyle = (css) => {
   await frames();
   results.push(snap("system-font"));
 
+  // A compiled skin face behind a non-matching @media is absent from
+  // document.fonts; its scoped `ws-` name must still be refused.
+  addSkinStyle(`@media (max-width: 1px) { @font-face { font-family: "ws-community-theme-fixture-blank"; src: url(data:font/woff2;base64,AAAA); } }
+    .ws-skin-root { --skin-host-font: "ws-community-theme-fixture-blank", sans-serif; }`);
+  await frames();
+  results.push(snap("media-gated-skin-font"));
+
+  // Tokens declared inside @media follow the viewport without a DOM change.
+  const viewportStyle = addSkinStyle(`@media (min-width: 1px) { .ws-skin-root { --skin-host-background: #102030; } }`);
+  await frames();
+  const beforeResize = control.style.getPropertyValue("--ws-control-background");
+  viewportStyle.sheet.cssRules[0].media.mediaText = "(max-width: 1px)";
+  window.dispatchEvent(new Event("resize"));
+  await frames();
+  results.push({ ...snap("media-token-resize"), beforeResize });
+
   theme.dispose();
   addSkinStyle(`.ws-skin-root { --skin-host-background: #ffffff; --skin-host-foreground: #111111; }`);
   await frames();
diff --git a/web/test/host-chrome-recovery.test.mjs b/web/test/host-chrome-recovery.test.mjs
index 2add711..f1ac1ee 100644
--- a/web/test/host-chrome-recovery.test.mjs
+++ b/web/test/host-chrome-recovery.test.mjs
@@ -331,5 +331,9 @@ test("host control tokens follow late skin CSS, resolve modern colours and refus
   assert.equal(late.background, late.inlineBackground);
   assert.equal(late.inlineFont, "ui-sans-serif, system-ui, sans-serif", "a skin @font-face reached a host-owned control");
   assert.equal(byName["system-font"].inlineFont, 'Tahoma, "Segoe UI", sans-serif');
+  assert.equal(byName["media-gated-skin-font"].inlineFont, "ui-sans-serif, system-ui, sans-serif", "a media-gated skin @font-face reached a host-owned control");
+  const resized = byName["media-token-resize"];
+  assert.equal(resized.beforeResize, "rgb(16, 32, 48)", "an @media token was not applied");
+  assert.notEqual(resized.inlineBackground, resized.beforeResize, "a viewport change did not refresh @media tokens");
   assert.equal(byName["after-dispose"].inlineBackground, late.inlineBackground, "a disposed binding kept observing the document");
 });

From e46d7a0eb75b8ee2d665c023dcaad0c83eed24b0 Mon Sep 17 00:00:00 2001
From: OddTurtleHead <355182507+OddTurtleHead@users.noreply.github.com>
Date: Sun, 15 Nov 2026 20:59:48 +0800
Subject: [PATCH 08/12] fix: move floating host controls off skin controls at
 runtime

The recovery capsule and the fallback application-library launcher float in
fixed viewport corners. In v0.3.2 that already covered the microphone in the
Persona/host-chrome skins, the whole Harbor audio dock, the Cancel/Create
buttons of mobile bottom sheets and a Send button behind the launcher.

Add host-floating-placement: every 400 ms (and shortly after each click) the
host samples the skin's visible, topmost interactive controls and moves the
floating control to the least-covering corner/edge position, weighting
protected parts and open dialogs higher, avoiding the other host floating
control, and folding the capsule to its mark when every position collides.
It never moves under the pointer or focus and leaves a docked (slotted)
capsule to the slot binding. Runtime only: no new skin.css restriction.
---
 docs/SKIN_DEVELOPMENT.md                      |   2 +
 package.json                                  |   2 +-
 web/src/components/HostChrome.vue             |  61 +++-
 web/src/components/PluginPanel.vue            |  22 +-
 .../services/host-floating-placement.test.ts  |  80 +++++
 web/src/services/host-floating-placement.ts   | 322 ++++++++++++++++++
 web/src/styles/plugin-overlay.css             |   5 +
 .../fixtures/host-floating-placement.html     |  99 ++++++
 web/test/host-chrome-recovery.test.mjs        |  43 +++
 9 files changed, 629 insertions(+), 7 deletions(-)
 create mode 100644 web/src/services/host-floating-placement.test.ts
 create mode 100644 web/src/services/host-floating-placement.ts
 create mode 100644 web/test/fixtures/host-floating-placement.html

diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md
index 10289e5..4085681 100644
--- a/docs/SKIN_DEVELOPMENT.md
+++ b/docs/SKIN_DEVELOPMENT.md
@@ -492,6 +492,8 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
 
 **这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
 
+**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框等;禁用的“发送”按钮也算,受保护部件和打开的对话框/底部弹层里的控件权重更高)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置;处处都会遮挡时,收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停或焦点在胶囊内时不会移动。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。
+
 **样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
 
 | 令牌 | 规则 |
diff --git a/package.json b/package.json
index c6a147d..69e0fdb 100644
--- a/package.json
+++ b/package.json
@@ -11,7 +11,7 @@
   "scripts": {
     "dev": "tsx src/index.ts",
     "build": "tsc",
-    "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/test/host-chrome-recovery.test.mjs",
+    "test": "node --import tsx --test src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
     "verify": "npm test && npm run build && npm run web:build",
     "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
     "skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
diff --git a/web/src/components/HostChrome.vue b/web/src/components/HostChrome.vue
index 189683b..f141dae 100644
--- a/web/src/components/HostChrome.vue
+++ b/web/src/components/HostChrome.vue
@@ -38,6 +38,7 @@
       @focusout="onRecoveryFocusOut"
       class="ws-host-recovery"
       :class="{ 'ws-host-recovery-compact': compact }"
+      :data-ws-float="slotMode === 'slotted' ? undefined : floatPosition"
       :tabindex="compact || compactPinned ? 0 : undefined"
       data-ws-host-recovery
       role="region"
@@ -83,6 +84,11 @@ import {
   type HostOwnedLayer,
 } from "../services/host-owned-layer.js";
 import { bindHostSlot, type HostSlotBinding } from "../services/host-slot-placement.js";
+import {
+  bindFloatingAvoidance,
+  type FloatingAvoidance,
+  type FloatingPosition,
+} from "../services/host-floating-placement.js";
 import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
 import { thirdPartyAllowed } from "../services/instance-authorization.js";
 import {
@@ -117,6 +123,13 @@ const RECOVERY_LAYER_CSS = `
   pointer-events: auto;
 }
 .ws-host-recovery:popover-open { display: flex; }
+/* Runtime collision avoidance (host-floating-placement.ts): when the default
+   corner would cover a skin control, the floating capsule moves. A docked
+   (slotted) capsule carries no data-ws-float and uses inline placement. */
+.ws-host-recovery[data-ws-float$="right"] { left: auto; right: max(12px, env(safe-area-inset-right)); }
+.ws-host-recovery[data-ws-float^="top"] { bottom: auto; top: max(12px, env(safe-area-inset-top)); }
+.ws-host-recovery[data-ws-float^="middle"] { bottom: auto; top: 50%; translate: 0 -50%; }
+.ws-host-recovery[data-ws-float$="center"] { left: 50%; translate: -50% 0; }
 .ws-host-recovery-mark {
   display: inline-flex;
   align-items: center;
@@ -231,11 +244,19 @@ const shortcutExpanded = ref(false);
 /** A tap/click on the compact mark keeps it expanded (no hover on touch). */
 const compactPinned = ref(false);
 
-const compact = computed(() => Boolean(slotConfig.value?.compact)
-  && slotMode.value === "slotted"
-  && !compactHold.value
-  && !shortcutExpanded.value
-  && !compactPinned.value);
+/**
+ * Floating (not docked) capsule: corner chosen at runtime so it does not cover
+ * skin controls, and folded to its mark when every corner collides.
+ */
+const floatPosition = ref("bottom-left");
+const floatCompact = ref(false);
+let floatingAvoidance: FloatingAvoidance | undefined;
+
+const compact = computed(() => !shortcutExpanded.value
+  && !compactPinned.value
+  && (slotMode.value === "slotted"
+    ? Boolean(slotConfig.value?.compact) && !compactHold.value
+    : floatCompact.value));
 
 function onRecoveryEscape() {
   shortcutOpen.value = false;
@@ -279,6 +300,33 @@ function syncSlotBinding() {
   });
 }
 
+function bindFloating() {
+  floatingAvoidance?.dispose();
+  floatingAvoidance = undefined;
+  const control = recoveryPopover.value;
+  if (!control || !layer) return;
+  const host = layer.host;
+  floatingAvoidance = bindFloatingAvoidance({
+    element: control,
+    isSelf: node => node === host || host.contains(node),
+    margins: { top: 12, right: 12, bottom: 38, left: 12 },
+    defaultPosition: "bottom-left",
+    apply: next => { floatPosition.value = next; },
+    compactSize: () => {
+      const hit = Number.parseFloat(getComputedStyle(control).getPropertyValue("--ws-control-hit")) || 28;
+      return { width: hit + 10, height: hit + 10 };
+    },
+    onCompactChange: next => { floatCompact.value = next; },
+    // Never move the capsule under the user's pointer or focus, and leave a
+    // docked capsule to the slot binding.
+    paused: () => slotMode.value === "slotted"
+      || shortcutExpanded.value
+      || compactPinned.value
+      || control.matches(":hover")
+      || Boolean(layer.shadow.activeElement),
+  });
+}
+
 function syncPopover() {
   syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
 }
@@ -318,6 +366,7 @@ watch([recoveryVisible, recoveryPopover], () => {
   void nextTick(() => {
     syncPopover();
     slotBinding?.revalidate();
+    floatingAvoidance?.revalidate();
   });
 }, { flush: "post" });
 watch([recoveryPopover, hostChromeActiveSkinId], () => {
@@ -340,12 +389,14 @@ onMounted(() => {
   void nextTick(() => {
     syncPopover();
     syncSlotBinding();
+    bindFloating();
   });
 });
 onBeforeUnmount(() => {
   if (reachabilityTimer) clearInterval(reachabilityTimer);
   if (compactHoldTimer) clearTimeout(compactHoldTimer);
   slotBinding?.dispose();
+  floatingAvoidance?.dispose();
   recoveryTheme?.dispose();
   window.removeEventListener("resize", refreshLauncherReachability);
   window.removeEventListener("keydown", onKeydown, true);
diff --git a/web/src/components/PluginPanel.vue b/web/src/components/PluginPanel.vue
index 3ee5dba..aac36a1 100644
--- a/web/src/components/PluginPanel.vue
+++ b/web/src/components/PluginPanel.vue
@@ -1,6 +1,6 @@