Compare commits

...
174 Commits
Author SHA1 Message Date
illusia 48c2fb3948 Merge dev into master 2026-10-12 23:39:18 +08:00
ILLUSIA 224a641372 fix: repair KAAK controls and add invite link action 2026-10-12 23:38:35 +08:00
illusia 19274cf0ee Merge dev into master
# Conflicts:
#	web/src/voice/screen-share.ts
2026-10-12 23:12:27 +08:00
illusia 45bec91daa fix: correct identity provider test callback 2026-10-12 23:09:24 +08:00
illusia 7fd1ea96fe feat: complete runtime and KAAK skin updates 2026-10-12 23:06:55 +08:00
illusia c994722016 fix(screen-share): preserve AV1 fallback priority 2026-10-12 13:53:52 +08:00
LainHE 7a6e054fe9 fix(screen-share): use sender capabilities for codec preference
setCodecPreferences requires codecs from RTCRtpSender.getCapabilities;
feeding it RTCRtpReceiver.getCapabilities throws InvalidModificationError
in Chrome and the swallowed exception left VP8 as the negotiated codec.
Switch the capability source so H264/AV1 preferences actually apply.
2026-10-12 13:51:49 +08:00
LainHE d919dbd82a feat(web-client): allow users to pick screen share bitrate limit
Add a bitrate select to the screen share settings dialog (auto by
resolution, or a fixed 1.5/3/5/8/12 Mbps cap), persist the choice in
localStorage, and pass it through ScreenShareOutputSettings.maxBitrate
so configureScreenShareVideoSender applies the user-chosen budget
instead of only the height-scaled default.
2026-10-12 13:51:49 +08:00
illusia f74e211d0f Merge pull request #28 from LainHE/pr/screen-share-quality 2026-10-12 13:50:02 +08:00
illusia 458f95c2dc feat: refine KAAK navigation and join experience 2026-10-12 13:49:35 +08:00
illusia 319a16f384 Add server navigation controls across modes 2026-10-12 12:01:51 +08:00
illusia c6eeb49f44 fix: unify KAAK password dialog confirm labels 2026-10-12 11:37:53 +08:00
illusia 05220b7a6e style: include KAAK connection password field 2026-10-12 11:25:49 +08:00
illusia 53324ef02b style: match KAAK password dialogs to reference 2026-10-12 11:23:31 +08:00
illusia 2f5cdcba90 feat: remember server and channel passwords locally 2026-10-12 11:08:35 +08:00
illusia 9c8647df50 fix: pass channel password flags from TeamSpeak SDK 2026-10-12 10:51:34 +08:00
illusia cec2a81549 fix: show password protected channels 2026-10-12 10:34:06 +08:00
illusia ff508a8eb9 Fix collapsed KAAK share stage 2026-10-12 10:03:42 +08:00
illusia 8a46691dbb Fix KAAK screen share layout bounds 2026-10-12 09:58:08 +08:00
illusia 64b24d0452 Expand screen-share player to content width 2026-10-12 09:43:33 +08:00
illusia 833357e278 Fix screen-share letterboxing across skins 2026-10-12 09:38:26 +08:00
illusia acdc7a2330 Fix missing screen share player 2026-10-12 08:25:57 +08:00
illusia 42190909e3 Fix screen share player fallback width 2026-10-12 08:10:17 +08:00
illusia a4e54d6341 Fix screen share player sizing 2026-10-11 23:36:58 +08:00
illusia 13499541e0 fix(voice): enable screen share in built-in member cards 2026-10-11 23:30:09 +08:00
illusia df2ff79e15 fix(skins): show active screen sharing across bundled themes 2026-10-11 23:17:11 +08:00
illusia d9749ac12f docs: record screen-share skin fix verification 2026-10-11 23:06:57 +08:00
illusia 8b5db8af1f fix(skins): expose screen-share status to custom members 2026-10-11 23:06:06 +08:00
illusia 7fe8719812 style: show noise suppression disabled state 2026-10-11 22:20:12 +08:00
illusia 0a77bdcaca docs: record channel tree drag drop work 2026-10-11 22:12:32 +08:00
illusia e800d75b7b feat: restore channel-tree member drag and drop 2026-10-11 22:12:05 +08:00
illusia 3476d4716a feat: add KAAK context menu to channel tree members 2026-10-11 21:40:14 +08:00
illusia 3459c8410c record KAAK menu update status 2026-10-11 21:14:17 +08:00
illusia 10739a7c7e style KAAK member context menu 2026-10-11 21:13:56 +08:00
illusia fb39aabbe2 docs(kaak): record banner handshake fix 2026-10-11 20:41:07 +08:00
illusia 6c57868903 fix(voice): read server banner from client handshake 2026-10-11 20:40:01 +08:00
illusia 398a4d6c7f feat(kaak): render TeamSpeak server banner 2026-10-11 19:50:35 +08:00
illusia 766a9b9b5a feat(kaak): refine compact voice dock controls 2026-10-11 19:30:42 +08:00
illusia 96d2ebae01 feat(kaak): match channel sidebar and audio dock reference 2026-10-11 19:20:57 +08:00
illusia b13bdf1eb2 feat(kaak): add trusted server switcher and channel tree 2026-10-11 18:37:13 +08:00
illusia 17fb27b89a fix: expose server identity and refine KAAK client 2026-10-11 17:14:56 +08:00
illusia e8164abafe docs(kaak): record popover stacking fix 2026-10-11 15:23:16 +08:00
illusia a1051b989e fix(kaak): layer audio popovers above metrics 2026-10-11 15:22:55 +08:00
illusia a84a12ced4 docs(kaak): record control dock fix 2026-10-11 13:02:43 +08:00
illusia 938bb0646d fix(kaak): restore dock controls and feedback 2026-10-11 13:01:47 +08:00
illusia 2f32d47036 docs(kaak): record control dock push 2026-10-11 12:51:02 +08:00
illusia 25148dd343 fix(kaak): move noise control into lower row 2026-10-11 12:49:28 +08:00
Corrupted ILLUSIA cf692174da docs(kaak): record rebuilt skin package 2026-10-11 12:39:11 +08:00
Corrupted ILLUSIA a43e6750ef docs(kaak): record corrected dock layout 2026-10-11 12:37:43 +08:00
Corrupted ILLUSIA 729e413196 fix(kaak): keep noise control in lower row 2026-10-11 12:36:56 +08:00
Corrupted ILLUSIA 93c9c2532a docs(kaak): record dock update pushed 2026-10-11 12:31:59 +08:00
Corrupted ILLUSIA 74ee82a927 feat(kaak): match provided voice dock layout 2026-10-11 12:31:02 +08:00
Corrupted ILLUSIA b9f3272210 docs(kaak): record compact dock push 2026-10-11 10:44:19 +08:00
Corrupted ILLUSIA 0ad7386fcd style(kaak): match supplied compact dock layout 2026-10-11 10:43:31 +08:00
Corrupted ILLUSIA 4adc712562 style(kaak): compact voice control dock 2026-10-11 10:25:33 +08:00
Corrupted ILLUSIA f5c0d66c10 docs(kaak): record 3.1.54 push 2026-10-11 10:13:47 +08:00
Corrupted ILLUSIA 13f4ddac4d feat(kaak): refine voice dock visuals 2026-10-11 10:12:16 +08:00
Corrupted ILLUSIA 16df12e4b2 fix(skin-editor): hide dev controls from visitors 2026-10-11 08:48:36 +08:00
Corrupted ILLUSIA 8cde1eae5a docs(kaak): sync latest checkpoint 2026-10-11 08:37:39 +08:00
Corrupted ILLUSIA 1391e02dd5 feat(kaak): add member card context actions 2026-10-11 08:36:34 +08:00
Corrupted ILLUSIA f3325458f4 docs(kaak): record local acceptance blocker 2026-10-11 08:19:55 +08:00
Corrupted ILLUSIA 72297c79b4 docs(kaak): record member actions checkpoint 2026-10-11 08:14:25 +08:00
Corrupted ILLUSIA bdd8e39a35 feat(kaak): expose member volume actions 2026-10-11 08:12:55 +08:00
Corrupted ILLUSIA 1e4fa08220 docs(kaak): record channel state checkpoint 2026-10-11 07:54:05 +08:00
Corrupted ILLUSIA 9f11d11b55 feat(kaak): isolate chat visibility per channel 2026-10-11 07:53:04 +08:00
Corrupted ILLUSIA fe578bcb60 docs(kaak): record pushed preview checkpoint 2026-10-11 07:43:23 +08:00
Corrupted ILLUSIA 650c1e0a6a style(kaak): animate performance sampling feedback 2026-10-11 07:41:32 +08:00
Corrupted ILLUSIA 5596735d4a style(kaak): unify active speaker feedback 2026-10-11 07:25:32 +08:00
Corrupted ILLUSIA 2ef21a7da5 docs(kaak): clarify branch checkpoint 2026-10-11 07:20:35 +08:00
Corrupted ILLUSIA c5146a5734 docs(kaak): update clone checkpoint 2026-10-11 07:19:23 +08:00
Corrupted ILLUSIA b01127c461 docs(kaak): preserve complete clone worklog 2026-10-11 07:11:10 +08:00
Corrupted ILLUSIA 2e67eaaa54 docs(kaak): record noise controls checkpoint 2026-10-11 07:10:16 +08:00
Corrupted ILLUSIA cb504c95bc feat(kaak): surface noise controls in audio settings 2026-10-11 07:06:49 +08:00
illusia 7c3e32d671 docs(kaak): record audio settings checkpoint 2026-10-11 06:50:19 +08:00
illusia 2a80ade08b feat(kaak): match audio settings layout 2026-10-11 06:49:53 +08:00
Corrupted ILLUSIA 2fcea5622b feat(kaak): unify audio accent feedback 2026-10-11 06:25:33 +08:00
Corrupted ILLUSIA 62a358796f feat(kaak): match KOOK channel typography 2026-10-11 06:14:17 +08:00
illusia 3f68050c81 feat(kaak): refine participant stage feedback 2026-10-11 06:00:05 +08:00
illusia 01ad967e30 feat(kaak): align KOOK brand accents 2026-10-11 05:50:00 +08:00
illusia a73a6b1a1e feat(kaak): refine volume slider states 2026-10-11 05:46:01 +08:00
illusia 0453bc6d4a feat(kaak): match device picker geometry 2026-10-11 05:41:07 +08:00
illusia c29109e898 docs(kaak): clarify voice chat defaults 2026-10-11 05:27:20 +08:00
Corrupted ILLUSIA 794b3f0ae0 docs(kaak): refresh clone checkpoint 2026-10-11 05:22:52 +08:00
Corrupted ILLUSIA 9cc6e7b765 fix(kaak): match audio label typography 2026-10-11 05:20:24 +08:00
illusia fbcbe994f0 fix(audio): keep device menus within viewport 2026-10-11 05:13:13 +08:00
Corrupted ILLUSIA 1951884d12 fix(skin): register public audio controls 2026-10-11 05:06:39 +08:00
Corrupted ILLUSIA 463f803881 fix(kaak): match audio title weight 2026-10-11 04:55:33 +08:00
illusia 61332ed846 fix(audio): show desktop volume controls 2026-10-11 04:45:06 +08:00
Corrupted ILLUSIA f3565f9859 docs(kaak): record successful dev sync 2026-10-11 04:26:20 +08:00
Corrupted ILLUSIA a3bdee9063 fix(kaak): apply skin typography to home surface 2026-10-11 04:24:25 +08:00
Corrupted ILLUSIA 2d92ca82f4 fix(kaak): match audio settings typography 2026-10-11 04:21:12 +08:00
illusia 10379829d8 fix(audio): keep volume hover panels reachable 2026-10-11 04:02:44 +08:00
illusia 5da11b41f9 fix(kaak): smooth member speaking glow 2026-10-11 04:00:04 +08:00
illusia deb5ca4e43 fix(voice): improve performance panel dismissal 2026-10-11 03:53:14 +08:00
illusia 3ff6507943 feat(kaak): animate voice channel group collapse 2026-10-11 03:38:37 +08:00
illusia e02ce7c546 feat(kaak): animate member name hover labels 2026-10-11 03:30:56 +08:00
illusia 8e580e7e18 feat(kaak): match KOOK audio device picker 2026-10-11 03:20:34 +08:00
illusia 70cc6c3bbf docs(kaak): record interaction fidelity audit 2026-10-11 02:47:39 +08:00
illusia ed6bf3a6ec docs(kaak): describe hidden chat panel 2026-10-11 02:20:24 +08:00
illusia 17a76fc1fd docs(kaak): record collapsed chat node 2026-10-11 02:06:33 +08:00
illusia ff207df20d feat(kaak): hide collapsed voice chat panel 2026-10-11 02:05:51 +08:00
illusia 5ca90c0914 docs(kaak): record channel selection feedback 2026-10-11 01:39:45 +08:00
illusia 19e693c270 feat(kaak): show channel join confirmation 2026-10-11 01:39:12 +08:00
illusia 2b6903f00a docs(kaak): record interaction polish progress 2026-10-11 01:32:43 +08:00
illusia 83902e0fb5 feat(kaak): refine interaction feedback and permissions 2026-10-11 01:31:44 +08:00
illusia bdd0c3473c feat(kaak): refine audio controls and diagnostics 2026-10-11 00:47:06 +08:00
illusia afa1e89136 fix(kaak): keep voice heading visible with chat open 2026-10-10 23:53:53 +08:00
illusia 5d27b9e4a8 fix(kaak): match KOOK member name visibility 2026-10-10 23:35:26 +08:00
illusia 7ea19e14eb docs: clarify KOOK channel entry checkpoint 2026-10-10 23:06:18 +08:00
illusia efa8f76787 docs: record KAAK reference checkpoint 2026-10-10 23:04:23 +08:00
illusia 8105a07171 fix(kaak): keep participant names visible 2026-10-10 22:53:56 +08:00
illusia 42cf4fbb8a docs: track KAAK clone progress 2026-10-10 22:40:22 +08:00
Corrupted ILLUSIA a3bf476db6 feat(kaak): show channel occupancy limits 2026-10-10 22:25:01 +08:00
Corrupted ILLUSIA 387462d89a feat(kaak): animate participant membership changes 2026-10-10 22:02:46 +08:00
Corrupted ILLUSIA 498a728d04 feat(kaak): match KOOK muted participant badge 2026-10-10 21:48:28 +08:00
Corrupted ILLUSIA 9c0fa35d38 feat(skin): improve KAAK collapsed voice stage 2026-10-10 21:28:19 +08:00
Corrupted ILLUSIA afc58799d9 feat(kaak): match KOOK voice participant tiles 2026-10-10 21:03:54 +08:00
Corrupted ILLUSIA 212bd9db2c feat(kaak): match KOOK voice dock actions 2026-10-10 20:37:23 +08:00
Corrupted ILLUSIA 5824754912 feat(kaak): match open KOOK voice stage 2026-10-10 20:13:24 +08:00
Corrupted ILLUSIA a1f92cedb2 feat(kaak): keep server rail colors stable 2026-10-10 19:51:00 +08:00
Corrupted ILLUSIA 8aefed83d1 feat(kaak): match KOOK voice chat presentation 2026-10-10 19:40:41 +08:00
Corrupted ILLUSIA 19c85ce1f5 feat(kaak): align voice room with KOOK layout 2026-10-10 19:33:48 +08:00
Corrupted ILLUSIA 7fb5e1d6ea feat(kaak): add collapsible voice channel group 2026-10-10 19:18:52 +08:00
Corrupted ILLUSIA b9c017f9aa feat(kaak): match KOOK server rail icons 2026-10-10 19:11:12 +08:00
Corrupted ILLUSIA d9b83f12cc feat(kaak): enrich channel chat message rows 2026-10-10 18:52:11 +08:00
Corrupted ILLUSIA 36ece5e582 feat(kaak): center voice participant rows 2026-10-10 18:41:05 +08:00
illusia f1f50d393a fix(kaak): keep full voice roster visible 2026-10-10 18:30:29 +08:00
illusia f6ef471960 feat(skins): refine KAAK voice channel chat 2026-10-10 18:25:22 +08:00
LainHE 20bde72c8b fix(screen-share): use sender capabilities for codec preference
setCodecPreferences requires codecs from RTCRtpSender.getCapabilities;
feeding it RTCRtpReceiver.getCapabilities throws InvalidModificationError
in Chrome and the swallowed exception left VP8 as the negotiated codec.
Switch the capability source so H264/AV1 preferences actually apply.
2026-10-10 18:02:36 +08:00
LainHE 1c328995aa feat(web-client): allow users to pick screen share bitrate limit
Add a bitrate select to the screen share settings dialog (auto by
resolution, or a fixed 1.5/3/5/8/12 Mbps cap), persist the choice in
localStorage, and pass it through ScreenShareOutputSettings.maxBitrate
so configureScreenShareVideoSender applies the user-chosen budget
instead of only the height-scaled default.
2026-10-10 18:01:04 +08:00
illusia 7b31c9106a feat(skins): refine KAAK voice room fidelity 2026-10-10 17:15:02 +08:00
illusia 7f5d3e1b3c feat(skins): refine KAAK voice workspace fidelity 2026-10-10 16:27:46 +08:00
illusia ad0aa5c120 fix(skins): correct full-surface layout and KAAK audio dock 2026-10-10 15:53:51 +08:00
illusia 54805f8928 feat(skins): add complete KAAK voice workspace skin 2026-10-10 15:53:51 +08:00
illusia f2e5695bb6 feat(skins): complete visual component CRUD authoring 2026-10-10 15:53:51 +08:00
illusia 3fd8e76a98 test(skins): verify surface deletion recovery 2026-10-10 15:53:51 +08:00
illusia da0472383d fix(skins): preserve screen capture user activation 2026-10-10 15:53:51 +08:00
illusia fd4b0c6da2 test(skins): verify live component CRUD preview 2026-10-10 15:53:51 +08:00
illusia 100a8f49ee test(skins): verify editor focus restoration 2026-10-10 15:53:51 +08:00
illusia 16f28ca348 fix(skins): refresh plugin assets when switching skins 2026-10-10 15:53:51 +08:00
illusia 0c4cc344ef feat(skins): add component authoring workflow 2026-10-10 15:53:51 +08:00
illusia 96c29394f3 feat(skin): add bounded plugin runtime and Harbor voice sample 2026-10-10 15:53:50 +08:00
illusia 8f097ec597 feat(skin): broaden runtime UI output 2026-10-10 15:53:50 +08:00
illusia b0b4a02a21 feat(skin): preserve screen share user gesture 2026-10-10 15:53:50 +08:00
illusia e20219b010 feat(skin): make runtime plugins locally reorderable 2026-10-10 15:53:50 +08:00
illusia 1499d60bc0 feat(skin): add local sibling ordering 2026-10-10 15:53:50 +08:00
illusia 11a07eae0f fix(skin): register runtime plugin layout parts 2026-10-10 15:53:50 +08:00
illusia 35cb6ad6df feat(skin): bridge trusted plugin actions 2026-10-10 15:53:50 +08:00
illusia 1aa29158ef feat(skin): project bounded read data into Wasm plugins 2026-10-10 15:53:50 +08:00
illusia 7650bd650b feat(skin): connect v4 runtime prototype to WebClient 2026-10-10 15:53:50 +08:00
illusia 7993b38eee feat(skin): support approved Wasm plugin prototype 2026-10-10 15:53:50 +08:00
illusia 26b74c5be4 feat(skin): prototype bounded wasm UI event loop 2026-10-10 15:53:50 +08:00
illusia dd0d779e49 feat(skin): render voice members under channels 2026-10-10 15:53:49 +08:00
illusia 54c77bcb27 feat(skin): prototype bounded UI callback inputs 2026-10-10 15:53:49 +08:00
illusia c3810a177a feat(skin): widen bounded wasm ui output 2026-10-10 15:53:49 +08:00
illusia ab36825a56 docs(skin): reject iframe as plugin network boundary 2026-10-10 15:53:49 +08:00
illusia 067f0c4403 feat(skin): expose custom nodes to layout editor 2026-10-10 15:53:49 +08:00
illusia c243f272fe feat(skin): bind plugin approval to package digest 2026-10-10 15:53:49 +08:00
illusia 81c35356b4 feat(skin): validate v4 plugin packages 2026-10-10 15:53:49 +08:00
illusia 17e4d78e52 feat(skin): define full plugin runtime target 2026-10-10 15:53:49 +08:00
illusia d137b41b5c feat(skin): add validated runtime UI output bridge 2026-10-10 15:53:49 +08:00
illusia 7047d71678 feat(skin): add bounded UI output bridge 2026-10-10 15:53:49 +08:00
illusia 849eb1a6d9 feat(skin): expand schema v3 voice interactions 2026-10-10 15:53:49 +08:00
illusia d505815f28 feat(skin): add approved full-page surface composition 2026-10-10 15:53:48 +08:00
illusia eabc78f36a feat(skin): add v3 declarative plugin components 2026-10-10 15:53:48 +08:00
illusia 02441410a0 feat(web): implement open skin layouts and migrate Illusia 2026-10-10 15:53:38 +08:00
illusia 58559cf839 fix(web): unify quick server history and favorites 2026-10-09 13:42:56 +08:00
illusia b6e4d349a2 feat(web): add skinnable favorite server switching 2026-10-09 10:35:01 +08:00
illusia ae1cd707be docs: credit contributor for PR #25 2026-10-09 00:26:27 +08:00
illusia efa0b85a0e fix: preserve invites on nickname lookup failure 2026-10-09 00:26:21 +08:00
Corrupted ILLUSIA 75893339c5 Merge pull request #25 from yichen11818/codex/teamspeak-server-aliases
feat: support TeamSpeak server nickname connections
2026-10-08 23:51:02 +08:00
yumi 60d3cfd569 feat: support TeamSpeak server nickname connections 2026-10-08 23:48:47 +08:00
illusia 35dde81cc2 docs: keep release notes out of project home page 2026-10-08 12:19:19 +08:00
illusia ebca754ca5 docs: refresh v0.2.6 project documentation 2026-10-08 12:07:06 +08:00
219 changed files with 36889 additions and 3242 deletions

No files matched your search

@@ -1,11 +1,11 @@
---
name: webspeak-skin-development
description: Create, refine, package, and verify WebSpeak visual skins while preserving the product's translated content, fixed component geometry, and interactions.
description: Create, refine, package, and verify WebSpeak v1 visual, v2 layout, v3 open skins, and the v4 plugin package envelope, including declarative public interfaces, full-page surfaces, and permission-gated TeamSpeak interactions.
---
# WebSpeak skin development
Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSIA built-in skin, or skin-facing UI hooks. A skin changes artwork and visual treatment; WebSpeak owns page structure, text, and behavior. The administrator console is deliberately outside the skin scope.
Use this skill when editing or authoring a WebSpeak `.wskin` package, a built-in skin, or skin-facing UI hooks. v1/v2 packages are visual/layout data; v3 may compose bounded declarative UI from its own nodes, rearrange public UI, and replace the visible home/voice page with a validated surface. v4 adds approved runtime plugins: bounded Wasm runs in a disposable worker and emits a validated generic HTML/SVG node tree; plugin-local CSS and scalar UI state are supported. JavaScript files remain validated and cached, never executed. Optional host widgets are trusted primitives, not the limit of custom UI. WebSpeak owns TeamSpeak behavior and the administrator console is outside the skin scope.
## Before editing
@@ -16,17 +16,42 @@ Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSI
## Preserve the interface
- Keep WebSpeak's translations and semantic content as the baseline. Add `content.json` only when a text override is an explicit part of the request; never use it to implement visual artwork.
- Skin only with supported visual CSS and package-local images/fonts. The upload validator rejects layout, positioning, sizing, spacing, clipping, text-flow, and interaction-geometry changes. Do not work around it with selectors, pseudo-elements, or animation.
- Never hide or obstruct critical controls, make a card or player move/resize, change a floating menu into a modal, or make artwork intercept pointer input. Keep `/admin/**` unskinned.
- Follow the schema-specific CSS rules: v1/v2 reject layout changes; v3 allows layout, placement, size, typography, and visibility changes within the skin root. Keep CSS package-local, scoped to public hooks, and free of external resources or executable values. Do not describe v3's fixed element, attribute, data, and action registries as complete customization; the target is a versioned, isolated plugin runtime with author-owned UI structure, CSS, and local logic.
- v3 can replace or obscure normal page controls. A surface must request `ui.surface.replace` and stays disabled until the user approves it. Custom interfaces can use their own declarative nodes and CSS; embed optional host widgets only when a trusted WebSpeak control is useful. Available widget IDs are registered in `src/shared/skin-plugin.ts`; each stateful host widget may appear once per page. Preserve usable microphone, disconnect, device-settings, screen-share and recovery paths at desktop and mobile sizes. Verify both the return-to-built-in-UI and restore-built-in-skin buttons. The host recovery and permission UI render outside the skin root. Keep `/admin/**` unskinned.
- `components.json` schema v1 is legacy; v2 adds `mode: "surface"` and optional allowlisted host-widget nodes; v3 expands bounded declarative composition, data bindings, events and permission-gated voice actions. v3 keeps its fixed tag/attribute/data/action registries; use v4 when a skin needs its own UI logic or generic HTML/SVG tree.
- For full-page custom interfaces, author the messages, composer, channel selection, audio controls and member presentation as skin-owned nodes wherever the safe data/action API supports them. Treat host widgets as optional trusted leaves for capabilities that must remain inside WebSpeak, such as screen capture and live media playback. Schema v3 conditions may compare local state with a permissioned repeated item and render explicit empty states; host actions may run on committed `change`, submit, or explicit activation, while live `input` remains local-only.
- The v4 runtime is enabled in production for Wasm only. A plugin must pass the local digest-bound approval before a disposable worker starts. The module has a 256 KiB source cap, 4 MiB linear-memory cap, 10,000,000 fuel cap, 100 ms execution deadline and a 64 MiB interpreter container cap; the WebClient governor allows two active jobs, up to 64 pending jobs, and a 120-second queue deadline. Each job may emit one UTF-8 JSON UI document of up to 256 KiB. The host validates schema v3/v4/v5/v6 and renders nodes itself; it never inserts plugin HTML. Standard tags and scalar attributes are allowed within size limits. Script, embedded browsing, navigation/external resource attributes, inline `style`, event-handler attributes and dangerous elements are rejected. Custom element names become inert `div` placeholders, so page-registered Web Components do not run.
- `env.ui_input_read` supplies at most 64 KiB per run, including plugin-local scalar state, a safe event record and a public-data projection capped at 48 KiB. The projection contains only fields permitted by the plugin manifest; never pass TeamSpeak addresses, credentials, SDK objects, media streams or private application objects. `ui.input.read` is a separate opt-in for text and checkbox/select values; tell users that browser autofill may be included, and never request password/file/hidden values. Keep server-list labels and opaque identifiers separate from addresses and credentials. Use `servers.quickList` plus `quickServers.switch` when a custom UI should show favorites and recent servers together.
- Host actions can be requested only by a run caused by a real browser-trusted UI event. The host rechecks the plugin grant, action permission, arguments and current session; a guest cannot supply its own trust flag. The first bridge permits one action per event run. Async Wasm cannot be assumed to preserve transient user activation: use the trusted `voice.screen-share-start` host widget for screen capture. Host widgets execute in WebSpeak and do not grant author code access to private widget state.
- The v4 package parser is shared by client import and server registration. It accepts `plugins.json` schema v1 with local `plugins/<id>/` JS/Wasm/CSS/assets, a 256 KiB descriptor cap, 256 KiB entry cap, 512 KiB CSS cap and 32 assets per plugin. It supports widget/surface modes and semantic mount slots. Plugin CSS is compiled under the plugin component scope; the host consent and recovery controls stay outside that scope. v4 plugin roots, components and DOM nodes participate in local layout editing. Keep v1–v3 unable to reference executable files. Cross-browser end-to-end validation and independent security review remain outstanding; marketplace and dedicated plugin-management UX are deferred with the administrator-panel redesign.
- Use the host's reserved artwork hooks for layered character art and the headphone scene. Prefer transparent assets and `background-size: contain` where the reference requires the full character or chibi to remain visible; arrange the artwork around the fixed hook rather than changing its geometry.
- Build visual depth with separate background, surface, and foreground artwork already exposed by the hooks. Avoid duplicate static decorations when an animated replacement exists. For motion, keep waveforms/sonar smooth and restrained, honor reduced-motion preferences, and retain readable focus, error, mute, and speaking states.
- Keep skin-specific CSS variables under `--skin-*`. Use only package-local assets and confirm their redistribution rights.
## Verify and package
1. Compare the implementation with its visual reference at desktop and narrow widths. Check the homepage, voice workspace, empty chat, member list, screen-share player, selectors, and `/demo`; verify no crop, overflow, text collision, or control overlap.
1. Compare the implementation with its accessible visual reference at desktop and narrow widths. Check the homepage, voice workspace, empty chat, member list, screen-share player, selectors, and `/demo`; verify no crop, overflow, text collision, or control overlap. Record exactly which reference pages and states were observed; do not imply that unvisited pages or states were verified.
2. Check all five interface languages, day/night modes, keyboard focus, and reduced-motion behavior. Confirm the admin console is unchanged.
3. Run `npm test` and `npm --prefix web run build`. Fix validator or build failures rather than weakening the layout guardrails.
3. Run the relevant skin-package tests and application build after a related batch of changes. Fix validation failures rather than weakening v1/v2 boundaries, v3 permission and event checks, surface limits, or the host-widget allowlist.
4. Package the contents of the skin directory so `manifest.json` is at the archive root, then import it through `/admin/skins` and retest the installed `.wskin` in a visitor session.
The three shipped skins—default day, default night, and ILLUSIA—are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them.
Keep README files beside the package source instead of inside `.wskin`: the skin importer rejects undeclared files such as `README.zh-CN.md`.
The shipped default day, default night, and ILLUSIA skins are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them. A permission request is not a grant; verify the deny and revoke paths. Do not claim a skin was visually verified against an external reference unless that page was actually accessible.
## Current project sequencing
- The user has explicitly set the order: finish and stabilize the generic skin authoring system before implementing a reference skin. Do not keep browsing reference pages or redesigning the framework during skin implementation.
- The public-client component editor stores authoring overrides in per-skin/per-version local-storage keys. A malformed document must not render; allow that one version's saved edit to be cleared without disturbing other skins. Route every import and edit through the shared declarative component parser; never weaken the tag/attribute, data-path, permission, action, or host-widget checks to make an edit fit.
- Treat data-ws-* as host-reserved DOM metadata: preserve backward parsing of older skin packages, but strip those attributes at the rendering boundary and reject them in new authoring saves.
- Component-tree CRUD includes component creation, duplication, deletion and ordering; node creation, duplication, deletion and sibling ordering; JSON property edits; undo/redo; and components.json import/export. Give duplicated nodes fresh stable layout-part identifiers. Preserve a usable base page and host recovery controls when a custom surface is removed.
- Before beginning the reference skin, verify tree CRUD, empty documents, safe schema migration, version-scoped persistence, import/export round trips, rejection of unsafe/over-permissioned trees, skin/page switching, and recovery. Run the related tests and server/client builds as one batch, then retain a stable checkpoint.
- Once that gate passes, only make small framework fixes for concrete incompatibilities found while implementing the voice-only reference. Do not expand unrelated application code or repeat visual-reference collection without a specific unresolved question.
## Integration findings
- A full-page surface is a separate user-approved capability (`ui.surface.replace`); package installation alone must leave the built-in page visible.
- The “restore built-in skin” control must use an unconditional selection function, not the skin-load-error-only recovery handler.
- Custom quick-server layouts should use the unified favorites/recent collection and opaque host tokens. Labels that match the underlying address are redacted before projection; never expose target addresses or credentials to skin data bindings.
- KOOK voice-only visual reference: the first two user-authorized rooms were accessible in the in-app browser. Observed voice membership nested under the channel tree, the lower-left connection card with screen-share and audio controls, and the persistent central chat/right member panes. Microphone remained off and the client was disconnected after inspection. No server/room identifiers, member names, or chat content were retained. Keep discovery, events, companion shop, ads, and operator/admin surfaces out of this skin.
- Report the exact system constraints discovered during implementation in both the roadmap and this skill. Keep each step reversible: preserve a clean tested checkpoint before changing package/runtime protocol versions, do not rewrite or push history without an explicit request, and keep v1/v2/v3 behavior isolated from new plugin capabilities.
+1
View File
@@ -1,6 +1,7 @@
node_modules/
dist/
web/dist/
web/skin-wasm-interpreter/target/
mobile/node_modules/
web/android/.gradle/
web/android/build/
+40 -22
View File
@@ -4,40 +4,58 @@
### 中文
- 修复 [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10) 中 Docker/Compose 短主机名解析和 HTTPS 健康检查问题;实现 [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9) 的 TeamSpeak 身份导入、转换与导出;加固 [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) 静音状态同步及 [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7) TS6 屏幕共享清理流程。
- 实现 [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) 所需的公网媒体地址、IPv6 候选和语音 STUN 管理配置;修复 [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) 所报告的连接后漏掉既有 TS6 原生屏幕共享的问题。媒体直连仍要求 UDP 路径可达,需按部署环境配置并验证。
- 改善语音与 WebRTC 会话稳定性:隔离连接切换后的音频、目录和统计事件,改进 Opus 协商及连续编码状态,并修复静音麦克风时伴奏被一并静音的问题。
- 优化移动端语音控制、屏幕常亮和窄屏布局;改进管理后台状态生命周期与语音工作区组件结构。
- 发布包提供 Windows x64 与 Linux x64/ARM64;Docker 镜像支持 amd64/arm64;增加 Android 客户端 APK,包含 arm64-v8a、armeabi-v7a、x86_64 三种构建。Android APK 使用 debug 签名,供侧载测试,不代表已完成真机 TeamSpeak 语音验收。
- **工程结构重构:** 将集中在单体语音桥接中的职责拆分为 TeamSpeak 命令处理、会话事件、会话音频、语音协议和屏幕共享协调模块,并提取共享的客户端命令、服务端消息、音频与屏幕共享契约。前端把大型语音页面和管理页面拆成 Vue 组件、composables 与服务模块;管理操作、服务器设置和皮肤管理各自拥有状态与请求生命周期,客户端、管理页和移动端样式也分开维护。重连和页面切换时由所属会话/页面清理事件、媒体资源与未完成操作。
- **语音链路稳定性:** 将 SDK 事件、成员目录、头像下载、麦克风采集、远端播放、性能统计和屏幕共享状态绑定到对应连接或页面生命周期,避免旧连接的迟到事件污染新会话。重构 Opus 连续编码和 WebRTC 参数协商,只协商网关实际支持的音频参数;切换麦克风或伴奏设置时尽可能保留正在工作的采集链路,闭麦时伴奏仍可播放。
- **[#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10):** 修复 Docker/Compose 中短主机名的 DNS 回退,并让 HTTPS 部署的健康检查使用对应协议。
- **[#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9):** 支持导入 TeamSpeak 3 身份 INI 或身份字符串、转换并导出兼容身份;本地校验格式及公私钥一致性。
- **[#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) / [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7):** 静音同步遇到服务端频率限制时有限重试,并阻止切换会话或重连前的旧请求覆盖当前状态;TS6 屏幕共享清理等待服务器确认、附带清理原因,并对频率限制有限重试。
- **[#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12):** 管理员可配置公网媒体地址、IPv6 候选和语音 STUN,以适配反向代理或 TCP 隧道后的 UDP 媒体路径。STUN 只发现候选地址,不中继媒体;直连仍要求客户端能访问配置的 UDP/IPv6 路径。
- 修复 [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) 指出的新 WebSpeak 会话漏掉既有 TS6 原生屏幕共享的问题;由重构后的服务器级协调器实现发现与同步。改善移动端语音控制和窄屏布局,并在语音会话期间保持屏幕常亮。
- **发布与验证:** Windows x64、Linux x64/ARM64 发布包;Docker 镜像提供 amd64/arm64;Android 提供 arm64-v8a、armeabi-v7a 和 x86_64 APK,另附 SHA-256 校验文件。Windows ARM64 未发布,因为当前 Opus 原生依赖不支持该构建目标。Android APK 使用 debug 签名;自动化构建通过不等于 Android 真机 TeamSpeak 连接及双向语音已验收。
### English
- Fixed Docker/Compose short-hostname resolution and HTTPS health checks in [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10); implemented TeamSpeak identity import, conversion, and export for [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9); hardened mute-state synchronization for [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) and TS6 screen-share cleanup for [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7).
- Added the public media address, IPv6-candidate, and voice-STUN controls requested by [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12), and fixed the missed-existing-TS6-share case described in [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13). Direct media still requires a reachable UDP path and deployment-specific configuration and testing.
- Improved voice and WebRTC session stability by isolating audio, directory, and statistics events across reconnects, tightening Opus negotiation and encoder continuity, and keeping accompaniment audible while the microphone is muted.
- Refined mobile voice controls, screen wake behavior, and narrow layouts; improved administration state lifecycles and voice-workspace component boundaries.
- Added Windows x64 and Linux x64/ARM64 packages; Docker images support amd64/arm64. Android APKs are available for arm64-v8a, armeabi-v7a, and x86_64. They use debug signing for sideload testing; real-device TeamSpeak voice has not been validated.
- **Structural refactor:** Split the former concentrated voice bridge into TeamSpeak command handling, session events, session audio, voice protocol, and screen-share coordination modules, with shared contracts for client commands, server messages, audio, and screen sharing. Decomposed the large voice and admin views into Vue components, composables, and service modules. Admin operations, server settings, and skin management now own their request and state lifecycles; client, admin, and mobile styles are maintained separately. Sessions and pages clean up their own events, media resources, and pending work during reconnects or navigation.
- **Voice-path reliability:** Bound SDK events, member directories, avatar transfers, microphone capture, remote playback, performance statistics, and share state to the owning connection or page so late work from an old session cannot affect a new one. Kept Opus encoder continuity and negotiated only audio parameters supported by the gateway. Microphone or accompaniment changes preserve a working capture path where possible, and accompaniment remains audible while the microphone is muted.
- **[#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10):** Fixed Docker/Compose DNS fallback for short hostnames and made health checks use HTTPS when the deployment is configured for TLS.
- **[#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9):** Added import from TeamSpeak 3 identity INI files or identity strings, conversion and export of compatible identities, and local format/key-pair validation.
- **[#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) / [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7):** Added bounded retries after server flood responses and prevented requests from an old session from overwriting the current mute state. TS6 share cleanup now waits for server confirmation, carries a cleanup reason, and retries flood responses within limits.
- **[#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12):** Added administrator settings for the public media address, IPv6 candidates, and voice STUN for deployments behind reverse proxies or TCP tunnels. STUN discovers candidates; it does not relay media. Direct media still needs a reachable configured UDP/IPv6 path.
- Fixed the missed-existing-TS6-share case reported in [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) with the refactored per-server coordinator. Refined mobile voice controls and narrow layouts, and kept the screen awake during voice sessions.
- **Packages and validation:** Windows x64 and Linux x64/ARM64 packages; Docker images for amd64/arm64; Android APKs for arm64-v8a, armeabi-v7a, and x86_64, plus SHA-256 checksums. Windows ARM64 is not included because the current native Opus dependency does not support that build target. APKs use debug signing; a successful automated build does not confirm TeamSpeak connectivity or two-way voice on a physical Android device.
### Deutsch
- Docker-/Compose-Auflösung kurzer Hostnamen und HTTPS-Gesundheitsprüfungen aus [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10) behoben; Import, Konvertierung und Export von TeamSpeak-Identitäten für [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9) ergänzt; Stummschaltungssynchronisierung aus [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) und TS6-Bildschirmfreigabe-Bereinigung aus [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7) gehärtet.
- Die in [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) gewünschten Einstellungen für öffentliche Medienadresse, IPv6-Kandidaten und Sprach-STUN ergänzt; den Fall verpasst synchronisierter, bereits aktiver TS6-Freigaben aus [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) behoben. Direkte Medien benötigen weiterhin einen erreichbaren UDP-Pfad und deployment-spezifische Konfiguration und Tests.
- Sprach- und WebRTC-Sitzungen stabilisiert, Opus-Aushandlung verbessert und Begleitton bei stummgeschaltetem Mikrofon erhalten. Mobile Sprachsteuerung, Bildschirm-Wachhalten und schmale Layouts wurden überarbeitet.
- Windows-x64- und Linux-x64/ARM64-Pakete sowie Docker-Images für amd64/arm64 ergänzt. Android-APKs gibt es für arm64-v8a, armeabi-v7a und x86_64; sie sind für Seiteneinladungstests debug-signiert. Reale TeamSpeak-Sprachtests auf Geräten sind nicht bestätigt.
- **Strukturelle Überarbeitung:** Die zuvor konzentrierte Sprachbrücke wurde in TeamSpeak-Befehle, Sitzungsereignisse, Sitzungsaudio, Sprachprotokoll und Bildschirmfreigabe-Koordination aufgeteilt. Gemeinsame Verträge für Client-Befehle, Servernachrichten, Audio und Freigaben wurden extrahiert. Große Sprach- und Admin-Ansichten wurden in Vue-Komponenten, Composables und Dienste zerlegt. Admin-Aktionen, Servereinstellungen und Skin-Verwaltung besitzen getrennte Zustands- und Anfragelebenszyklen; Client-, Admin- und Mobilstile werden separat gepflegt. Sitzungen und Seiten räumen eigene Ereignisse, Medienressourcen und laufende Vorgänge bei Wiederverbindung oder Navigation auf.
- **Stabilität der Sprachverbindung:** SDK-Ereignisse, Mitgliederverzeichnis, Avatarübertragungen, Mikrofonaufnahme, Wiedergabe, Leistungsstatistiken und Freigabestatus sind an die jeweilige Verbindung oder Seite gebunden. Verspätete Ergebnisse älterer Sitzungen wirken dadurch nicht auf eine neue Verbindung. Opus-Kodierkontinuität und Aushandlung wurden verbessert. Mikrofon- oder Begleittonänderungen erhalten möglichst die funktionierende Aufnahme; Begleitton bleibt bei stummgeschaltetem Mikrofon hörbar.
- **[#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10):** DNS-Fallback für kurze Docker-/Compose-Hostnamen behoben; Gesundheitsprüfungen verwenden bei TLS-Konfiguration HTTPS.
- **[#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9):** Import aus TeamSpeak-3-Identitätsdateien im INI-Format oder Identitätszeichenfolgen, Konvertierung und Export kompatibler Identitäten sowie lokale Prüfung von Format und Schlüsselpaar ergänzt.
- **[#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) / [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7):** Begrenzte Wiederholungen nach Server-Flood-Antworten ergänzt und verhindert, dass alte Sitzungsanfragen den aktuellen Stummschaltungsstatus überschreiben. Die TS6-Bereinigung wartet auf Serverbestätigung, übermittelt den Bereinigungsgrund und wiederholt Flood-Antworten begrenzt.
- **[#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12):** Admin-Einstellungen für öffentliche Medienadresse, IPv6-Kandidaten und Sprach-STUN ergänzt. STUN ermittelt Kandidaten, leitet aber keine Medien weiter; direkte Medien benötigen weiterhin einen erreichbaren UDP-/IPv6-Pfad.
- Den in [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) gemeldeten Fall bereits laufender, nach dem Beitritt nicht entdeckter TS6-Freigaben mit der überarbeiteten serverweiten Koordination behoben. Mobile Sprachsteuerung und schmale Layouts verbessert; der Bildschirm bleibt während Sprachsitzungen aktiv.
- **Pakete und Prüfung:** Windows x64, Linux x64/ARM64 und Docker amd64/arm64; Android-APKs für arm64-v8a, armeabi-v7a und x86_64 mit SHA-256-Datei. Windows ARM64 fehlt, weil die aktuelle native Opus-Abhängigkeit dieses Buildziel nicht unterstützt. APKs sind debug-signiert; ein erfolgreicher CI-Build bestätigt keine TeamSpeak-Verbindung und keinen Zweiwege-Sprachtest auf einem Android-Gerät.
### Русский
- Исправлены разрешение коротких имён Docker/Compose и HTTPS-проверки работоспособности из [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10); добавлен импорт, преобразование и экспорт идентификаторов TeamSpeak для [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9); усилена синхронизация микрофона из [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) и очистка трансляции экрана TS6 из [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7).
- Добавлены настройки публичного адреса медиа, IPv6-кандидатов и голосового STUN по запросу [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12); исправлен пропуск уже запущенной трансляции TS6 после подключения из [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13). Для прямого медиа по-прежнему нужен доступный UDP-маршрут и настройка конкретного развёртывания.
- Повышена устойчивость голосовых сессий и WebRTC: события аудио, каталога и статистики изолированы при переподключении, улучшены согласование Opus и непрерывность кодирования; музыка сопровождения остаётся слышна при выключенном микрофоне. Улучшены мобильные элементы управления и узкие экраны.
- Доступны пакеты Windows x64 и Linux x64/ARM64, Docker-образы — для amd64/arm64. Android APK собраны для arm64-v8a, armeabi-v7a и x86_64 и подписаны отладочным ключом для установки вручную; голос TeamSpeak на реальных устройствах не проверен.
- **Перестройка архитектуры:** Монолитный голосовой шлюз разделён на обработку команд TeamSpeak, события сессий, аудио сессии, голосовой протокол и координацию демонстрации экрана; общие контракты клиента и сервера вынесены отдельно. Крупные голосовые и административные страницы разделены на Vue-компоненты, composables и сервисы. Операции администратора, настройки сервера и управление скинами получили собственные циклы состояния и запросов; стили клиента, админ-панели и мобильной версии разделены. Сессии и страницы очищают принадлежащие им события, медиа и незавершённые операции при переподключении или переходе.
- **Устойчивость голосовой связи:** События SDK, каталог участников, передача аватаров, захват микрофона, воспроизведение, статистика и состояние демонстрации привязаны к текущему подключению или странице. Поздние результаты старой сессии не затрагивают новую. Улучшены непрерывность кодирования Opus и согласование параметров; изменение микрофона или фоновой музыки по возможности сохраняет работающий захват, а музыка слышна при выключенном микрофоне.
- **[#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10):** Исправлен DNS-fallback для коротких имён Docker/Compose; HTTPS-проверка состояния использует HTTPS при включённом TLS.
- **[#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9):** Добавлен импорт идентификатора TeamSpeak 3 из INI-файла или строки, преобразование и экспорт совместимой идентичности, локальная проверка формата и пары ключей.
- **[#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) / [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7):** Добавлены ограниченные повторы после ограничения частоты сервером; старый запрос не может перезаписать состояние микрофона после смены сессии. Очистка трансляции TS6 ожидает подтверждения сервера, передаёт причину и ограниченно повторяет запросы после flood-ответа.
- **[#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12):** Добавлены параметры публичного адреса медиа, IPv6-кандидатов и голосового STUN. STUN только обнаруживает адреса и не ретранслирует медиа; для прямой передачи нужен доступный UDP/IPv6-маршрут.
- Исправлен случай пропуска уже запущенной демонстрации TS6, описанный в [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13), с помощью переработанного координатора для каждого сервера. Улучшены мобильное управление голосом и узкие экраны; во время голосовой сессии экран не гаснет.
- **Пакеты и проверка:** Windows x64, Linux x64/ARM64, Docker amd64/arm64, Android APK для arm64-v8a, armeabi-v7a и x86_64, файл SHA-256. Windows ARM64 не включён, так как текущая нативная зависимость Opus не поддерживает эту цель. APK подписаны отладочным ключом; успешная сборка CI не подтверждает подключение TeamSpeak и двусторонний голос на реальном Android-устройстве.
### 日本語
- [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10) の Docker/Compose 短縮ホスト名解決と HTTPS ヘルスチェックを修正。[#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9) の TeamSpeak ID インポート・変換・エクスポートを実装し、[#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) のミュート同期と [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7) の TS6 画面共有終了処理を強化しました。
- [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) の要望に沿って公開メディアアドレス、IPv6 候補、音声 STUN の設定を追加し、[PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) が報告した接続前から存在する TS6 画面共有の見落としを修正しました。直接メディア通信には到達可能な UDP 経路と環境ごとの設定・検証が必要です。
- 音声/WebRTC セッションの安定性を改善し、再接続後に古い音声・ディレクトリ・統計イベントが混ざらないようにしました。Opus のネゴシエーションと連続エンコードを改善し、マイクをミュートしても伴奏が聞こえるよう修正しました。モバイル操作と狭い画面のレイアウトも改善しました。
- Windows x64 と Linux x64/ARM64 のサーバーパッケージ、amd64/arm64 の Docker イメージに対応。Android APK は arm64-v8a、armeabi-v7a、x86_64 を用意しました。APK はサイドロードテスト向けのデバッグ署名で、実機 TeamSpeak 音声は未検証です。
- **構造の大規模リファクタリング:** 集中していた音声ゲートウェイを TeamSpeak コマンド、セッションイベント、セッション音声、音声プロトコル、画面共有コーディネーターに分割し、クライアントコマンド、サーバーメッセージ、音声、画面共有の共通契約を抽出しました。大規模な音声・管理画面を Vue コンポーネント、composable、サービスに分割しました。管理操作、サーバー設定、スキン管理は個別の状態・リクエストライフサイクルを持ち、クライアント、管理画面、モバイルのスタイルも分離しました。再接続や画面遷移時は、各セッション/画面が自身のイベント、メディア、未完了処理を破棄します。
- **音声経路の安定性:** SDK イベント、メンバー一覧、アバター転送、マイク取得、再生、統計、共有状態を接続または画面のライフサイクルに紐付け、古いセッションの遅延処理が新しい接続に影響しないようにしました。Opus の連続エンコードとネゴシエーションを改善し、ゲートウェイが対応する音声パラメーターだけを交渉します。マイクや伴奏の変更時は可能な限り正常な取得経路を維持し、ミュート中も伴奏を再生します。
- **[#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10):** Docker/Compose の短縮ホスト名に対する DNS フォールバックを修正し、TLS 設定時のヘルスチェックを HTTPS にしました。
- **[#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9):** TeamSpeak 3 の ID INI または文字列からのインポート、互換 ID の変換・エクスポート、形式と鍵ペアのローカル検証を追加しました。
- **[#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) / [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7):** サーバーの flood 制限後に回数制限付きで再試行し、古いセッションの要求が現在のミュート状態を上書きしないようにしました。TS6 画面共有の終了処理はサーバー確認を待ち、理由を渡し、制限付きで再試行します。
- **[#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12):** 公開メディアアドレス、IPv6 候補、音声 STUN の管理設定を追加しました。STUN は候補アドレスを検出するだけでメディアを中継しません。直接通信には到達可能な UDP/IPv6 経路が必要です。
- [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) が報告した、接続前から開始済みの TS6 画面共有を見落とす問題を、再構成したサーバー単位のコーディネーターで修正しました。モバイル音声操作と狭い画面を改善し、音声セッション中は画面を点灯状態に保ちます。
- **パッケージと検証:** Windows x64、Linux x64/ARM64、Docker amd64/arm64、Android arm64-v8a・armeabi-v7a・x86_64 の APK と SHA-256 ファイルを提供します。現在の Opus ネイティブ依存が対象をサポートしないため Windows ARM64 は含みません。APK はデバッグ署名で、CI 成功は実機 TeamSpeak 接続や双方向音声の確認を意味しません。
## [0.2.5] — 2026-09-27(相对 0.2.4)
+8 -4
View File
@@ -43,8 +43,10 @@
- [Deutsch](./docs/README.de.md)
- [Русский](./docs/README.ru.md)
- [日本語](./docs/README.ja.md)
- [皮肤开发规范](./docs/SKIN_DEVELOPMENT.md)
- [WebSpeak 皮肤开发 Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
- [皮肤开发规范 / Skin Development Guide](./docs/SKIN_DEVELOPMENT.md)
- [更开放的皮肤系统路线图](./docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)
- [更开放的皮肤系统规格与权限沙箱](./docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)
- [皮肤开发 Agent Skill / Skin Development Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
## 社区 · Community
@@ -72,9 +74,11 @@ Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music
## Contributors · 贡献者
感谢提交 PR 的贡献者:
感谢通过 PR 改进 WebSpeak 的贡献者。以下按 GitHub 的合并记录列出;上方 0.2.6 摘要只描述本版本实际纳入的改动。
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2):浏览器端报错翻译与提示改造。
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) 改进浏览器端报错翻译;[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) 修正缩放、浮动布局和首页脚注。
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持通过 TeamSpeak 注册昵称连接,并在设置、收藏和邀请中保留昵称目标。
## 许可证 · License · Lizenz · Лицензия · ライセンス
+686
View File
@@ -0,0 +1,686 @@
# KAAK 语音界面复刻工作记录
这份记录用于跨会话续接。开始新一轮工作前,先看这里的“当前检查点”和“下一步”,再检查对应代码或 KOOK 原始页面;完成一个有意义的修改节点后追加记录,不按零碎操作逐条记。
## 固定范围和做事方式
- 以 KOOK 已商业化的语音房间页面为参考。遇到不确定或看起来不合理的交互、样式、动画时,先核对 KOOK 原始页面,再决定是否改动。
- 当前只复刻语音客户端体验。KOOK 独立的文字频道列表暂缓;只做随当前语音频道展开、可收起的文字聊天。
- WebSpeak 引擎只接受可复用的通用能力改进,不为 KAAK 单独适配。修复限定在已确认的问题,不顺手扩展无关代码。
- 相关节点累积后统一验证,避免每个小改动都重跑完整验证。
- 记录中不放服务器地址、密码、密钥、成员名单、聊天内容或其他隐私数据。
## 当前检查点(2026-10-12)
- KAAK 当前源码版本为 3.1.78;最近新增 TeamSpeak 服务器横幅与欢迎语展示,沿用客户端握手携带的真实服务器信息并在缺少内容时隐藏卡片;同时保留真实服务器名与收藏/历史快速切换入口,并以宿主频道树呈现嵌套语音频道、频道成员头像和状态。服务器显示名过滤像地址的内容;快速切换不向皮肤暴露连接目标。控制坞保留 WebSpeak 现有分享、降噪、伴奏、麦克风、扬声器和设置操作;降噪关闭状态新增红色斜杠提示;已移除无效的录制占位,仅保留屏幕共享和伴奏入口。频道树成员行与成员卡片右键均使用 KOOK 深色浮层格式,菜单项和行为仍为 WebSpeak 原有操作;频道树成员行支持悬停反馈和跨频道拖放移动。屏幕共享播放器限定在中央语音舞台内,具有明确响应高度;成员卡片使用播放器下方剩余区域。3.1.55 的横向单行方案已被用户明确否决,不再沿用;3.1.53 已移除皮肤布局运行时对宿主控件强加的 44px 尺寸。
- 语音布局、成员卡、频道/聊天收起、音量反馈、性能卡片、设备下拉交互和字体层级均已有对应实现;音频设置标签为 KOOK 已记录的 14px/400,表单卡与字段行按实测宽度/行高调整。
- 直接观察记录覆盖语音侧栏/频道树、成员卡与悬停姓名、当前语音频道聊天开合、语音坞、音频设置字体及设备列表尺寸和状态。独立文字频道不复刻;KOOK 的付费分享呈现不复刻,WebSpeak 自带屏幕分享入口和播放器保留。
- 设备选择菜单已按皮肤实际高度限位;KAAK 音频滑杆、性能反馈、字体和成员卡交互均有对应实现。3.1.66 完整验证为 680/680,服务端 TypeScript 构建、前端类型检查和生产构建通过。用户已明确 KOOK 音乐语音频道附带聊天默认收起、普通语音频道默认展开。TeamSpeak `ChannelInfo` 与皮肤上下文没有音乐类别字段;当前实现按频道分别记住聊天开合,尚不能判断从未设置过的频道是否为音乐频道。
- 本轮从 KOOK 原页读取了可见频道树的 DOM 计算字体规格;成员舞台当前未加载,截图读取超时,未推断其具体像素尺寸或动画时长。
- KOOK 音频设置页可读到 732px 主内容区、660px 表单卡、72px 字段行及 268/320px 标签/控件列;当前设备名属于隐私数据,不记录。
- 本轮侧栏浏览器已加载 KAAK 本地连接页;展开身份选项后,导入身份按钮保持紧凑,导出身份因当前没有身份而禁用。连接按钮没有让页面进入语音工作区,因此本轮无法从浏览器目视确认左下控制坞。
- KOOK 设置页还展示降噪开关与档位入口;KAAK 只使用 WebSpeak 已有的通用降噪开关,不复制专有算法或档位。
- 成员和聊天动态状态已有初步实现;后续继续按现有原页观察逐项细化动画和布局,不将缺少原页证据的参数写成实测值。
## 已完成的修改节点
- 语音房间整体布局已按 KOOK 的语音客户端结构实现:左侧服务器栏与频道树、中心成员舞台、右侧当前语音频道聊天、左下语音控制坞。独立文字频道列表不在本轮范围。
- 频道树支持折叠语音分组;当前语音频道的文字聊天在房间内展开或收起,不需要离开语音房间。
- 中心成员呈现已从小头像列表调整为宽比例成员卡片,使用宿主可信成员卡展示可用头像,并对说话、静音和成员加入/离开提供状态样式与动画。
- 成员姓名标签遵循聊天面板状态:聊天展开时静止隐藏,悬停卡片时显示;聊天收起时固定显示在左下角。姓名以外的成员卡布局和状态副行保持当前设计。
- 语音坞复用 WebSpeak 宿主的音频和断开控件;皮肤提供外观,不接管底层语音实现。KAAK 暂不提供付费屏幕分享功能。
- 最近节点增加了通用频道占用数和容量数据投影,KAAK 在有限容量频道显示上限,在未限制容量时不显示上限。此数据能力位于共享 TeamSpeak 频道模型,不是 KAAK 专属引擎分支。
## 本次原页核对(2026-10-10)
- 两个授权语音频道都在首次进入后显示右侧当前频道聊天面板,麦克风保持关闭。没有发送消息,也没有操作管理员功能。
- 展开聊天时成员卡在静止状态不显示姓名;悬停卡片后左下角出现姓名标签。收起聊天后标签保持显示,成员舞台随之扩宽。
- 原页末尾关闭临时 KOOK 标签;账号离开了语音频道。
## 本轮修改节点(2026-10-10)
- 参考页面观察:聊天展开时中心舞台仍保留频道名和实时人数标题,横向成员卡居中显示头像,静音标记位于卡片右上角。
- 对照当前本地 KAAK 截图,成员卡比例、头像位置和静音标记已接近;明确差异是皮肤在聊天展开时隐藏了舞台标题。
- 修改内容与范围:移除这一条 KAAK CSS 隐藏规则,保持通用组件与语音引擎不变;皮肤版本升至 3.1.24,并同步内置目录、包测试和说明文档。
- 当前浏览器验收保持静音、未发消息、未操作管理员功能;验收结束后关闭临时标签。
- 影响文件:KAAK 样式、版本目录、分发包、包测试及参考/工作文档;不改 WebSpeak 引擎。
- 验证结果:皮肤包构建、前端构建通过;皮肤目录与包测试 23/23 通过。本地连接页截图确认聊天展开时中心标题现已可见,成员姓名仍按规则隐藏;麦克风关闭。测试后关闭 KOOK 和本地标签。
## 最近一次代码验证
本轮验证:
- `npm run skin:kaak:build`、`npm run web:build` 通过;web 构建包含 Vue 类型检查。
- `node --import tsx --test web/src/services/skin-pack.test.ts web/src/services/skin-catalog.test.ts`:23/23 通过。
- 本地浏览器确认:KAAK 性能面板可展开;音频配置弹窗的设备选择和音量滑杆按新样式显示;语音坞不再挂载屏幕分享入口。没有切换设备、调整真实音量或运行麦克风测试;麦克风关闭,随后退出了临时语音连接。
- 上次全量 `npm test` 在基线 `620eb04` 为 653/654 通过,唯一失败是既有 `voice.member.mic-status` 布局钩子注册测试。此项与本轮样式节点无关,因此本轮没有重跑全量套件;后续累积相关改动后统一验证。
同时修正了 [KOOK 语音界面参考](./KOOK_VOICE_REFERENCE.zh-CN.md) 中把中心区和右侧区写反的旧描述,并保留“独立文字频道列表不在当前范围”的边界。
## 下一步
1. 成员进入/离开、说话状态和聊天栏宽度已有皮肤动画;继续与 KOOK 的具体动效逐项对照,避免只按组件类别推断相似。
2. 为音乐/普通语音频道两种首次进入默认状态寻找通用且明确的分类来源;在来源可用前,不按频道名称猜测。KOOK 独立文字频道仍在本轮范围之外。
## 本轮修改节点(2026-10-11)
- 参考页面观察:KOOK 的连接状态入口是语音坞内的紧凑信号柱;个人菜单里的语音设置按输入设备、输出设备、输入音量、输出音量分组,并使用下拉框与滑杆。麦克风测试只记录可见布局,没有运行。
- 修改内容与范围:KAAK 加入 WebSpeak 现有的通用语音性能面板 widget,并把触发器收敛为信号柱按钮;将音频设置弹窗、设备选择、滑杆、音量悬浮卡片改为 KAAK 深色与绿色强调风格,调整字体层级和焦点/悬停反馈。移除 KAAK 的屏幕分享入口和播放器,并隐藏成员卡中的分享操作。通用成员卡验证时强制要求屏幕分享读写权限,因此保留必需声明;KAAK 没有挂载分享操作 widget。仅改 KAAK 皮肤、包测试和文档,不改 WebSpeak 音频引擎。
- 屏幕分享按用户要求不作为复刻目标;没有操作分享入口。
- 浏览器观察与本地连接期间麦克风保持关闭,没有发送消息、切换设备、拖动真实音量滑杆或进行管理员操作;设备标签和服务器信息不记录。
- 影响文件/提交:KAAK 组件配置、样式、版本目录、分发包、包测试、参考记录和本工作日志;本地提交为 `feat(kaak): refine audio controls and diagnostics`,待网络恢复后推送。
- 验证结果:`npm run skin:kaak:build`、`npm run web:build` 通过;皮肤包与目录测试 23/23 通过。侧栏浏览器本地验收确认性能卡片可展开、音频设置控件正常呈现、分享启动按钮缺席;没有更换设备、调整音量或运行麦克风测试。
- 当前状态与下一步:音量、设备设置和性能状态样式节点完成;下一节点聚焦成员状态动画与音乐语音频道初始聊天状态,并只按 KOOK 原页的可见证据修改对应皮肤。
## 后续节点记录格式
### YYYY-MM-DD:节点标题
- 参考页面观察:
- 修改内容与范围:
- 影响文件/提交:
- 验证结果:
- 当前状态与下一步:
## 本轮修改节点(2026-10-11,KAAK 3.1.28)
- 目标范围:按用户要求继续覆盖主界面以外的细节,重点记录音量反馈、性能卡片、字体层级和设备选择;屏幕分享因属于付费功能而跳过。
- 修改内容与范围:音量滑杆以共享的进度变量显示即时位置,补充拇指悬停/键盘焦点反馈;性能卡片增加短进入动画、数字等宽对齐和可读字号;设备下拉框补充方向标识及悬停、禁用、选中反馈,并支持减少动态效果偏好。通过通用受限组件参数让皮肤明确关闭不使用的屏幕分享 UI,成员卡不再接收分享状态/操作,性能卡不展示分享统计,KAAK 相应移除分享读写权限。通用 WebSpeak 改动只提供受限组件选项,不为 KAAK 引入特例逻辑。
- 文档和分发包:更新开放皮肤组件参数及权限说明、KAAK 使用说明、组件配置和 3.1.28 分发包。
- 验证结果:`npm run skin:kaak:build`、`npm run build`、`npm run web:build` 通过;相关皮肤和编辑器测试 54/54 通过。完整 `npm test` 为 654/655,唯一失败仍为 `src/shared/skin-layout.test.ts` 中 `voice.member.mic-status` 未注册断言,与本轮触及的文件和行为无关。`git diff --check` 通过。
- 验收边界:代码检查和前端构建验证了新交互样式可运行;此前侧栏浏览器已确认性能卡片可展开、设备选项和音量滑杆可见,但本轮没有逐项操作新加的悬停/键盘状态。没有实际切换输入/输出设备、拖动音量、启动麦克风测试或操作屏幕分享,因此不记录为真实音频设备行为验收通过。
- 影响文件/提交:KAAK 组件与样式、可信组件选项和权限校验、组件宿主类型、测试、皮肤说明及打包文件;提交 `83902e0` 已推送至 `dev`。
- 当前状态与下一步:3.1.28 已提交并推送;下一步确认音乐类语音频道首次进入时附带聊天的默认状态,并按原页可见行为继续逐项打磨。
## 本轮修改节点(2026-10-11,KAAK 3.1.31)
- 参考依据:在 KOOK 原始语音设置中直接查看设备选择和字体。设备触发器约 40px、列表最高约 240px、选项约 32px;列表可滚动,当前项有底色,箭头随展开旋转。确认中英文字体栈以 PingFang SC 优先,字段标签为 14px。没有选择真实设备或改变音量、麦克风状态。
- 修改内容与范围:把 WebSpeak 原有音频设置中的输入/输出原生选择框替换为同一通用组件 `AudioDeviceSelect`;支持点击展开、方向键、Home/End、Enter/Space、Esc、Tab 和标签前缀定位,并在列表打开时按视口调整位置。音频控制 composable 同时接受旧 DOM Event 与新组件发出的设备 ID 字符串,保持旧调用兼容。KAAK 的设备选择器补充 KOOK 深色列表、32px 选项、悬停/选中/键盘态、旋转箭头和字体继承;未针对 KAAK 修改连接或音频引擎。
- 文档和分发包:KAAK 版本升至 3.1.31,更新皮肤公开部件目录、KOOK 观察记录、皮肤说明、内置目录版本与两份分发包。
- 浏览器验收:使用侧栏浏览器打开本地合成设备预览,不触碰真实设备。确认列表展开、8 个选项可见、方向键移动活动项、Enter 选择并更新显示、Esc 关闭;最终计算样式为 KOOK 字体栈、14px/40px 触发器和每项 32px。实际音频设置页未能进入语音工作区,因此这次验收证明控件自身和样式,不宣称真实设备切换通过。
- 验证结果:此前同一修改组的皮肤目录、皮肤包和音频控制定向测试 34/34 通过,`npm run web:build` 与 `npm run build` 通过;加入字体继承样式后重新构建 KAAK 包,并在浏览器确认最终字体与选项尺寸。最终提交前再统一运行相关定向测试、前端构建和 `git diff --check`。
- 影响文件:通用音频设备选择组件、音频设置接入、兼容回调、通用样式、KAAK 样式/版本/分发包、相关测试及说明文档。暂存的本地预览文件已在验收后删除。
- 当前状态与下一步:设备选择、字体和设置控件反馈节点完成;继续对照 KOOK 逐项打磨成员状态动画、音量反馈和音乐频道聊天初始状态。屏幕分享按用户要求跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.32)
- 参考依据:已授权 KOOK 原页此前直接观察到,聊天展开时成员姓名默认隐藏、悬停成员卡后出现;聊天收起时姓名保持可见。本轮尝试再次读取 KOOK 页时浏览器桥接超时,因此只使用这条已记录的可见行为,不声称新确认了动画时长。
- 修改内容与范围:发现 KAAK 原有 `display:none/block` 会让姓名标签瞬时出现/消失。改为只在聊天展开时使用 opacity、轻微上移和 visibility 过渡;收起聊天时继续常显。既有 `prefers-reduced-motion` 规则会缩短过渡。仅改 KAAK CSS、分发包、皮肤版本、对应包断言和说明,不改成员组件或语音引擎。
- 文档和分发包:KAAK 升至 3.1.32,更新说明与两份分发包。
- 验证结果:`npm run skin:kaak:build`、皮肤目录/分发包定向测试 23/23、`npm run web:build` 和 `git diff --check` 均通过。侧栏浏览器中的本地合成成员卡预览确认聊天展开时标签从 opacity 0/隐藏过渡到 opacity 1/可见,并上移 4px;这验证 KAAK CSS 行为,不是在线 KOOK 对照。KOOK 原页本轮未能完成视觉复核,动画时长未宣称与 KOOK 精确一致。
- 当前状态与下一步:成员姓名悬停反馈从瞬时切换改为可访问的短过渡。音乐频道聊天初始状态仍未实现:TeamSpeak 公开频道模型没有音乐/普通类型字段,不能可靠按频道名猜测;已向用户询问默认策略。继续打磨前先解决可从现有数据识别的体验差异;屏幕分享按要求跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.33)
- 问题依据:当前 KAAK 的语音分组通过 `when` 条件卸载频道列表,只有重新展开时执行入场动画;收起时内容瞬间消失。频道分组折叠/展开是已实现的核心交互,开合反馈应一致。
- 修改内容与范围:保持频道列表节点挂载,根据已存在的分组状态用 CSS grid 轨道、淡出和轻微位移收起/展开;在关闭过渡结束时将列表设为不可见,防止键盘/辅助技术继续访问隐藏的频道。减少动态效果偏好下清除隐藏延迟。仅改 KAAK 组件声明与样式,没有修改 WebSpeak 渲染引擎、TeamSpeak 连接或频道数据。
- 分发包与说明:KAAK 升至 3.1.33,更新组件包、目录版本和相应测试断言。
- 验证结果:皮肤包构建、相关包测试、前端构建及 `git diff --check` 合并后执行;侧栏浏览器用本地合成频道列表确认收起时高度归零、淡出,展开后恢复可见。KOOK 原页本轮浏览器桥接仍不可读,因此只记录为改善 KAAK 开合反馈,不宣称与原站精确动画时长一致。
- 当前状态与下一步:分组开合从只动画展开调整为双向过渡。当前仍待确认音乐频道聊天初始策略;TeamSpeak 数据没有音乐类别标记,继续等待用户选择,不按频道名猜测。屏幕分享继续跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.29)
- 参考依据:已记录的 KOOK 原页行为是频道首击选中并提示再次点击,第二击才进入;当前 KAAK 只有选中边框和无障碍双击说明,缺少可见提示。本轮尝试重新读取侧栏 KOOK 页时,浏览器桥接在读取标签状态阶段超时,因此没有把旧观察写成新观察。
- 修改内容与范围:在选中的非当前语音频道行显示“ 双击加入 ”提示,加入后隐藏;提示淡入轻移并尊重减少动态效果偏好。仅改 KAAK 声明式组件、皮肤样式与文档,没有改 TeamSpeak 连接/加入逻辑或通用宿主行为。
- 文档和分发包:KAAK 版本升至 3.1.29,内置目录与分发包同步;包测试覆盖提示条件、文本和加入后隐藏样式。
- 验证结果:`npm run skin:kaak:build`、`npm run web:build` 通过;`node --import tsx --test web/src/services/skin-pack.test.ts web/src/services/skin-catalog.test.ts` 23/23 通过;`git diff --check` 通过。
- 影响文件/提交:KAAK 声明式频道行、皮肤样式、说明、测试、内置版本和两份分发包;提交 `19e693c` 已推送至 `dev`。前端浏览器桥接读取 KOOK 标签超时,本轮未完成侧栏浏览器的视觉验收。
- 当前状态与下一步:3.1.29 已提交推送;正在按直接截图修正 KOOK 聊天收起/展开布局。音乐语音频道初始状态仍待单独确认。
## 本轮修改节点(2026-10-11,KAAK 3.1.30)
- 参考页面观察:在第二个已授权普通语音频道中,聊天首次进入时展开;点击聊天栏右上收起控件后,整条右侧聊天栏消失,成员舞台扩展占满主区域,舞台标题和实时人数仍留在顶端,右上出现重新打开聊天的按钮。收起状态下成员名仍可见。麦克风保持静音,没有发送消息或使用管理员功能;完成后离开语音房间。
- 修改内容与范围:KAAK 收起态将聊天轨道宽度收至零并淡出面板,成员舞台跨越空轨道扩展;舞台标题行出现绿色聊天展开按钮。打开/收起共用同一个本地皮肤状态,移动断点同步将聊天高度收至零,尊重减少动态效果偏好。仅改 KAAK 声明式组件与 CSS,不改语音引擎或宿主连接逻辑。
- 音乐频道边界:本次观察的是普通语音频道,不能证明音乐频道进入时聊天是否默认收起;该问题继续保持待确认,不按猜测更改默认值。
- 文档和分发包:KAAK 版本升至 3.1.30,更新 KOOK 参考页、包测试、内置目录与分发包。
- 验证结果:`npm run skin:kaak:build`、`npm run web:build` 通过;皮肤包与目录测试 23/23 通过;`git diff --check` 通过。侧栏浏览器已加载 KAAK 连接页;确认本地连接配置指向用户授权的测试目标,但连接结束后回到连接页,未进入语音工作区,所以聊天收起/重开态尚未完成视觉验收。没有触发麦克风、发送消息或操作管理功能。
- 影响文件/提交:KAAK 组件定义、样式、参考/工作记录、包测试、内置版本和分发包;提交 `ff207df` 已推送至 `dev`。
- 当前状态与下一步:3.1.30 已提交推送;浏览器连接通路可用后再核验收起/重开态。音乐语音频道的初始聊天状态仍需单独确认;音量、设备选择、性能卡片和字体继续按 KOOK 原页的具体状态逐项对照,只改对应皮肤节点。
- 文档跟进:复查 KAAK 英文说明时发现仍把收起态描述为“窄轨道”;已改为整栏隐藏、舞台扩展和标题栏重开入口,与 3.1.30 实现及 KOOK 参考记录一致。
## 本轮进度记录(2026-10-11,交互细节二次对照)
- 用户要求:复刻范围要覆盖交互反馈和字体细节,包括音量、性能卡片和设备选择;付费屏幕分享继续跳过,并要求及时记录、提交、推送 `dev`。
- 原页观察:语音坞上下两排的连接/断开与音频控件布局已在 KOOK 原页再次确认;麦克风保持关闭。没有进入设置菜单,也没有更换设备、拖动音量或运行麦克风测试。
- 代码盘点:对应样式与控件反馈已在 3.1.28 节点实现;当前待办是逐态验收,而非再造重复样式。个人菜单点击超时,浏览器桥接不稳定,未基于推测改代码。详细控件记录见 [KOOK 语音界面参考](./KOOK_VOICE_REFERENCE.zh-CN.md)。
- 本次提交范围:仅补充本轮可核实的 KOOK 语音坞观察、麦克风状态和尚未验证的交互清单;没有代码行为变化,因此不重跑构建/测试。
- 当前状态与下一步:该文档节点提交后推送 `dev`;后续恢复可靠的侧栏浏览器访问后,先验收 KAAK 音量滑杆的悬停/键盘与数值反馈、设备下拉展开态、性能卡片开合态,再按证据集中修皮肤节点;不切换真实设备、不改变音量、不运行麦克风测试。
## 本轮修改节点(2026-10-11,KAAK 3.1.34)
- 问题依据:性能卡片此前只有入口按钮可关闭,点击卡片外不会收起,Escape 也没有关闭/焦点返回;现有 KAAK 动画只覆盖打开。
- 修改内容与边界:为通用性能面板增加外部指针按下收起、Escape 收起并把键盘焦点还给触发按钮;用 Vue Transition 暴露开合状态钩子。该交互可供所有皮肤复用,不包含 KAAK 特例行为;KAAK CSS 实现进入/退出淡入与轻移,并尊重减少动态效果偏好。没有改性能采样、音频状态或 TeamSpeak 连接逻辑。
- 文档与分发包:KAAK 升至 3.1.34,更新说明、包版本断言、动画样式断言并重建两份 `.wskin`。
- 原页核查:尝试从当前 KOOK 页读取音频相关控件时浏览器桥接超时;本节点只依据现有性能卡片代码和此前记录,没有新增 KOOK 行为或动效时长的断言。
- 验证结果:`npm run skin:kaak:build`、`npm run web:build` 通过;皮肤包与目录定向测试 23/23 通过;`git diff --check` 通过。侧栏浏览器本地合成预览确认外部点击后 `aria-expanded=false`、Escape 后同样收起且焦点返回触发按钮,并检查卡片样式和网络数据布局。没有连接 TeamSpeak 或操作真实音频设备、音量、麦克风、屏幕分享。
- 影响文件/提交:通用性能面板组件、KAAK 样式/说明/工作日志、皮肤包测试、内置目录包与两个分发包;随本节点提交推送 `dev`。
- 当前状态与下一步:性能卡片有一致的关闭路径、开合动画和可访问焦点返回。KOOK 原页本轮桥接超时,没有新增观察或声称逐帧一致。此前待确认的音乐语音频道首次进入时聊天默认状态仍未得到用户选择,不能从现有 TeamSpeak 频道模型可靠判断;下一节点继续处理能直接核实的语音交互/字体差异,屏幕分享保持跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.35)
- 问题依据:成员卡片说话态会改变外框阴影,但卡片原有过渡列表只包含边框与背景色,所以外框发光会突然出现/消失。KAAK 布局隐藏状态文字,当前不可见的紫色文字波形不作为此节点改动目标。
- 修改内容与边界:将 `box-shadow` 加入成员卡片已有的状态过渡,让同一个实时说话态驱动的边框与发光同步变化。仅改 KAAK 皮肤样式、包版本和说明,不改成员组件、实时语音状态或 WebSpeak 宿主。
- 原页核查:KOOK 页加载后,语音行点击与后续状态读取连续超时;本节点沿用已记录的成员卡和实时说话状态,不新增 KOOK 动效或颜色结论。
- 文档与分发包:KAAK 升至 3.1.35,更新成员卡说明、样式包断言、内置目录版本及两份分发包。
- 验证结果:`npm run skin:kaak:build`、`npm run web:build` 通过;皮肤包与目录定向测试 23/23 通过;`git diff --check` 通过。未连接语音房间,因此没有声称对真实说话状态的动态验收;不启用麦克风或改变真实音频状态。
- 影响文件/提交:KAAK 成员卡样式、版本目录、说明、工作日志、包测试和两份分发包;随本节点提交推送 `dev`。
- 当前状态与下一步:说话态的可见外框发光不再突变。继续从可核实的 KOOK 语音交互与现有皮肤映射中挑选成组节点;音乐频道聊天默认状态仍待用户确认,屏幕分享按要求跳过。
## 本轮修改节点(2026-10-11,语音坞音量浮层)
- 问题依据:通用语音坞的音量弹层与控制按钮相隔 10px,装饰箭头没有填满间隙;鼠标从按钮移向滑杆时可能离开 hover 区域,导致弹层先收起。这影响输入/输出音量滑杆的直接操作。
- 修改内容与边界:在弹层下沿增加透明的 10px 指针命中桥,保留现有可见间距、箭头和弹层动画。属于跨皮肤可复用的通用交互修正,不加 KAAK 专属引擎逻辑,也不改变音量值/音频控制行为。
- 原页核查:当前 KOOK 页面加载成功,但语音行点击及随后状态读取超时;本节点依据可复现的 WebSpeak CSS 几何问题处理,不把它写成 KOOK 原页观察。
- 验证结果:`npm run web:build` 通过;音频控制定向测试 11/11 通过;`git diff --check` 通过。修复增加透明命中区域,未拖动真实音量、切换设备或启用麦克风。
- 影响文件/提交:通用语音坞弹层样式与本工作日志;功能属于宿主通用修正,KAAK 皮肤包版本不变;验证后提交并推送 `dev`。
- 当前状态与下一步:鼠标从音量按钮移向弹层时,命中区域覆盖视觉间距,滑杆不再因 hover 丢失而闪退。后续继续检查语音设置中的滑杆/设备选择和频道聊天交互,沿已记录证据分组推进;屏幕分享仍跳过。
## 本轮修改节点(2026-10-11,音频设置字体与滑杆规格)
- 问题依据:KOOK 原页记录的设置分区标题为 16px/600、滑杆拇指为 16px;KAAK 对应样式仍为 14px 默认粗细和 15px 拇指,视觉层级与交互目标偏小。
- 修改内容与边界:仅调整 KAAK 音频设置分区标题字号/字重,以及 Chromium/Firefox 音量滑杆拇指尺寸与垂直对齐。保留 14px 设备/音量字段标签和既有悬停、焦点反馈;设备选择器既有 40px 触发器、32px 选项、240px 最大高度已符合记录,不改组件行为。
- 原页核查:使用已有 KOOK 设置页记录作为直接规格依据;本节点不操作真实设备、音量、麦克风或麦克风测试。
- 文档与分发包:KAAK 升至 3.1.36,更新音频样式说明与包版本断言,并重建两份 `.wskin` 分发包。
- 验证结果:`npm run skin:kaak:build`、`npm run web:build` 通过;`node --import tsx --test web/src/services/skin-pack.test.ts web/src/services/skin-catalog.test.ts` 23/23 通过;`git diff --check` 通过。未操作真实设备、音量或麦克风。
- 同步状态:修改已提交到本地 `dev`;GitHub 推送连续遇到连接重置,远端同步待网络恢复后重试。
- 影响文件/提交:KAAK 样式、清单、说明、皮肤包断言和工作日志;不改 WebSpeak 宿主或语音引擎。
- 当前状态与下一步:音频设置标题和滑杆尺寸与已记录的 KOOK 规格一致。继续针对有原页证据的交互反馈推进,屏幕分享仍跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.37 字体覆盖)
- 问题依据:KAAK 语音工作区和音频设置弹窗使用 KOOK 优先字体栈,但连接首页根节点没有设置字体,表单控件随 WebSpeak 宿主继承 Inter,页面切换时会出现字体跳变。
- 修改内容与边界:仅给 KAAK 连接首页根组件应用皮肤已有的 KOOK 字体栈,使标题、说明、表单和按钮保持一致。没有更改宿主全局字体或其他皮肤。
- 原页核查:字体栈依据 KOOK 设置页的已记录观察;当前浏览器桥接连接超时,未声称本轮重新打开页面验证。
- 文档与分发包:KAAK 升至 3.1.37,更新目录版本、包版本断言、说明及两份 `.wskin` 分发包。
- 验证结果:`npm run skin:kaak:build`、`npm run web:build` 通过;`node --import tsx --test web/src/services/skin-pack.test.ts web/src/services/skin-catalog.test.ts` 23/23 通过;`git diff --check` 通过。
- 同步状态:Git HTTPS 到 443 的直连仍不可用;通过 GitHub 仓库连接器按预期 SHA 快进推送 3.1.36 与 3.1.37 两个提交(`2d92ca8`、`a3bdee9`)。已在本地重建相同提交对象,`dev` 与 `origin/dev` 同步。
- 影响文件/提交:KAAK 首页样式、清单、内置目录、包测试、说明和工作日志;不改 WebSpeak 宿主或语音引擎。
- 当前状态与下一步:KAAK 三个主要表面共享相同字体栈。继续核对 KOOK 语音工作区与 KAAK 的成员、聊天和设置交互,屏幕分享按要求跳过。
## 本轮修改节点(2026-10-11,桌面音频设置音量控件)
- 问题依据:在已授权的本地 KAAK 语音工作区打开音频设置时,桌面布局只显示输入/输出设备等设置,输入音量和扬声器/耳机音量滑杆被 `isMobileViewport` 条件隐藏;移动端已有这两组控件。设备选择器键盘高亮与关闭、性能卡片打开和 Escape 关闭也已在同一工作区复核,未改变设备选择或音频状态。
- 修改内容与边界:移除输入音量、输出音量两组控件的移动端专属显示条件,使桌面和移动端共用原有数值、事件处理及样式。没有触碰音频引擎、设备选择逻辑或其他页面;KOOK 原页本轮浏览器桥接无法读取,没有将本地实现写成新的 KOOK 观察。
- 浏览器验收:桌面音频设置的辅助树已出现“输入音量”和“扬声器 / 耳机”滑杆,页面预览也确认输入滑杆显示正常。没有拖动滑杆、更换设备、运行麦克风测试或启用麦克风;测试连接已安全退出。
- 验证结果:代码及工作记录完成后统一验证;修复后的本地页面确认两组控件存在且没有模板残留字符,`npm run web:build` 和 `git diff --check` 均通过。
- 当前状态与下一步:桌面设置现在可直接调节输入和输出音量,原有设备键盘交互与性能卡片反馈保持不变;字体规格沿用此前已记录的 KAAK 音频设置修正。屏幕分享继续跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.38 音频设置标题字重)
- 差异依据:KOOK 语音设置页记录为主标题 32px/600;KAAK 已设 32px,但没有覆盖宿主标题的默认粗体,字重因而未跟随记录的 600 规格。
- 修改内容与边界:仅在 KAAK 音频设置皮肤样式为标题显式指定 600 字重,并添加包样式断言。没有改 WebSpeak 通用样式或标题组件。
- 原页核查:KOOK 原页浏览器桥接本轮不可读;沿用既有《KOOK 语音界面参考》中的直接页面规格,没有新增原页观察。
- 验证与分发:升 KAAK 包版本到 3.1.38,重建示例包和内置分发包;将与桌面音量控件节点合并进行包测试、前端构建及差异检查。
- 当前状态与下一步:音频设置标题在 KAAK 中明确使用 32px/600。继续从现有直接观察和可访问的实际控件差异中推进,不凭未观察的页面行为猜测;付费屏幕分享继续排除。
## 本轮修改节点(2026-10-11,补齐静音状态与设备选择器布局部件)
- 问题依据:`VoiceMemberCards.vue` 的成员静音标记以及 `AudioDeviceSelect.vue` 的容器、触发按钮、箭头、菜单和选项均已声明为公开 `data-ws-part`,文档也已列出;稳定布局注册表漏掉这 6 个部件,公开钩子覆盖测试因此失败,布局编辑器无法单独调整它们。
- 修改内容与边界:将 6 个部件补入语音页面公共组件注册表,并把设备选择触发按钮标记为宿主交互组件,保留触控目标约束。其他部件可独立布局和设置可见性。只改通用皮肤布局元数据及断言,不改音频设备选择、麦克风状态读取、真实音频行为或 KAAK 皮肤包。
- 依据与兼容:这些部件原本就属于文档化公开接口,也已被 KAAK CSS 使用;本次补齐注册表不增加新行为、不改变皮肤包内容或版本。
- 验证结果:公开钩子扫描无遗漏;`src/shared/skin-layout.test.ts` 8/8、完整 `npm test` 656/656、`npm run build` 和 `npm run web:build` 均通过,`git diff --check` 通过。
- 当前状态与下一步:成员静音图标和音频设备选择器子部件现在可被布局系统分别识别和自定义。继续按已记录的 KOOK 行为推进视觉与交互细节;音乐频道首次进入时聊天状态仍缺少直接观察,不按频道名猜测。
## 本轮修改节点(2026-10-11,设备选择菜单视口适配)
- 问题依据:设备下拉菜单按触发器位置打开,但原定位逻辑在可用空间不足时仍强制至少 80px 高;屏幕较矮或弹窗靠近底边时,列表会超出视口。KOOK 参考中的菜单最高约 240px、选项约 32px,超长列表可滚动。
- 修改内容与边界:将菜单定位计算抽为可复用的纯函数;根据上下方实际空间选择开口方向并限高,同时将菜单宽度约束在窄视口内。保留 240px 最大高度和 32px 选项尺寸,空间不足时继续在菜单内滚动。只修通用设备选择组件的视口适配,不切换设备、不碰音频值或设备权限,也不加入 KAAK 专属运行逻辑。
- KAAK 对应:KAAK 使用同一宿主设备选择器,仍保留其已记录的字体、深色菜单、选中/悬停/键盘态和箭头反馈;无需变更皮肤包版本。
- 验证:定位边界测试 4/4、完整 `npm test` 660/660、`npm run build`、`npm run web:build` 和 `git diff --check` 均通过。本节点未进行浏览器视觉验收或触碰真实音频设备;测试验证的是菜单几何边界。
- 当前状态与下一步:菜单不再靠最小高度越过视口边界。后续继续把音量交互、性能状态卡与字体层级按已记录证据逐项验收;付费屏幕分享仍跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.39 音频设置标签字重)
- 差异依据:KOOK 设置页的设备和音量字段标签记录为 14px/400;KAAK 已是 14px,但宿主 `.settings-label` 的 500 字重仍被继承,细节与参考不一致。
- 修改内容与边界:只在 KAAK 音频设置皮肤中将 `.settings-label` 显式设为 400,百分比数值继续保留强调字重。同步 KAAK 包版本、内置目录、包断言、英文说明和两份分发包;不改通用宿主字体、不影响其他皮肤或音频行为。
- 验证:`npm run skin:kaak:build`、包样式断言、完整 `npm test` 660/660、`npm run build`、`npm run web:build` 和 `git diff --check` 均通过;未做浏览器视觉验收,不改变真实音量或设备。
- 当前状态与下一步:字段标签与已有 KOOK 字号/字重记录一致。后续继续推进实际语音房间交互和有直接参考依据的样式细节;屏幕分享仍跳过。
## 本轮规格澄清(2026-10-11,音乐语音频道聊天默认状态)
- 用户明确:普通语音频道的随语音聊天默认展开;音乐语音频道也有随语音房间显示的聊天,但默认收起。KOOK 独立文字频道列表仍不在当前复刻范围。
- 参考记录已区分直接观察与用户补充:原页直接观察覆盖两个普通语音频道;音乐频道的默认状态依据用户提供的信息,本轮没有在 KOOK 原页重新验证。
- 代码检查:TeamSpeak `ChannelInfo` 和传给皮肤的 `session.channels` 均没有音乐/普通频道类别字段,因此皮肤不能可靠地自动应用这两种初始状态。当前不按名称猜测,也不修改 KAAK 或 WebSpeak 行为。
- 当前状态与下一步:继续按已有计划覆盖界面、交互反馈和字体;若要支持不同的初始聊天状态,先从通用频道元数据中取得明确类别,再按该数据实现。屏幕分享继续跳过。
- 影响文件/提交:仅更新 KOOK 参考记录与本工作日志;不涉及代码或分发包。`git diff --check` 通过,无需重跑构建和测试。
## 本轮修改节点(2026-10-11,KAAK 3.1.40 设备菜单几何与状态)
- 差异依据:KOOK 公开语音页静态样式资源显示选择框/菜单为 12px 圆角、菜单内边距 8px;选项为 32px 高、8px 圆角、上下间隔 2px、左右内边距 8px。深色菜单底色为 `#25262a`、文字为 `#e6eaf0`、品牌绿为 `#6cbf00`,悬停约 6% 白色、选中约 10% 白色。与当前 KAAK 的 9px/7px 圆角、4px 菜单内边距、12px 选项内边距和更亮的菜单底色存在明确差异。
- 修改内容与边界:KAAK 音频设置设备选择器 CSS 对齐触发器/菜单圆角、选项节奏、箭头位置/旋转、颜色和悬停/选中对比。发现通用定位器按固定 32px 行高估算高度,与皮肤可自定义的 2px 行间距不兼容;现改为测量渲染后菜单的自然高度再按视口限高。该定位改进不含 KAAK 分支;设备键盘操作和音频逻辑保持不变。
- 文档与分发包:KAAK 升至 3.1.40,更新静态样式参考和 CSS 包断言,重建示例与内置 `.wskin` 分发包。
- 验证:皮肤包构建通过;完整 `npm test` 661/661、`npm run build`、`npm run web:build` 和 `git diff --check` 通过。新增定位测试覆盖皮肤自定义菜单自然高度,既有视口边界测试也通过。此次只读取公开 CSS 资产,没有控制用户浏览器、选择设备或改变音频状态;未做本地视觉验收。
- 影响文件/提交:KAAK 样式、清单、内置目录、通用设备菜单定位、相关测试、参考/工作文档和两个分发包。
- 当前状态与下一步:设备菜单尺寸、状态色和视口适配已更新;后续仍需在允许的本地浏览器里核对真实计算样式及剩余交互状态,再选择下一项成组修改。
## 本轮修改节点(2026-10-11,KAAK 3.1.41 音量滑杆状态)
- 差异依据:KOOK 已加载的公开音频滑杆样式显示 4px 轨道、16px 滑块和 2px 品牌绿描边;悬停时出现 3px 光圈。KAAK 原样式滑块底色偏绿、常态带外阴影,悬停/键盘焦点时还额外放大 1.12 倍,并在整个滑杆周围绘制矩形焦点框。
- 修改内容与边界:KAAK 音量滑杆改为 KOOK 的品牌绿填充、半透明白色未填充轨道、白色滑块与绿色边框;悬停和键盘焦点使用同类圆形 3px 光圈,移除额外缩放及矩形焦点框。只改皮肤样式、包版本、包断言和参考/工作文档,不改音量值处理或音频引擎。
- 验证:`npm run skin:kaak:build`、完整 `npm test` 661/661、`npm run build`、`npm run web:build` 和 `git diff --check` 均通过。本轮只读取 KOOK 公开滑杆 CSS,没有拖动真实滑杆或改变音量;未做本地视觉验收。
- 影响文件/提交:KAAK 滑杆样式、清单、内置目录、测试、KOOK 参考/工作记录及两个分发包。
- 当前状态与下一步:音量滑块尺寸、颜色和悬停反馈已按公开样式更新;继续核对成员舞台/聊天交互的具体布局与动画,屏幕分享仍跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.42 KOOK 品牌强调色)
- 差异依据:KOOK 深色主题公开样式变量为品牌主色 `#6cbf00`、hover `#7ac51a`、active `#60ab00`;KAAK 的全局强调色和成员说话光环仍用 `#58c877` 系列,音频滑杆/设备选择器已先行按 KOOK 主色修正,页面其余高亮因此不一致。
- 修改内容与边界:统一 KAAK 皮肤的强调色变量、成员说话描边/光环、音频设置按钮和麦克风电平为 KOOK 品牌色;保持透明度层级和现有动效不变。只改皮肤包、颜色断言和说明,不改通用组件或语音引擎。
- 文档与分发包:KAAK 升至 3.1.42,更新示例说明与包断言,重建两份 `.wskin`。
- 验证:皮肤包重建、完整 `npm test` 661/661、`npm run build`、`npm run web:build` 和 `git diff --check` 均通过。本轮只核对公开 CSS 变量,没有控制页面或音频状态,未做本地视觉验收。
- 影响文件/提交:KAAK 颜色样式、版本清单、目录版本、包测试和文档及两个分发包。
- 当前状态与下一步:全局强调色已与 KOOK 品牌绿统一;之后继续核对成员舞台和聊天面板的可见细节,屏幕分享仍跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.43 成员舞台呈现)
- 问题依据:用户直接指出只复刻组件类型不够,KOOK 中间的成员呈现和动画明显更完整。代码检查发现 KAAK 宽卡片内头像只有 64px;说话波形写在状态文字上,但聊天展开/收起两种布局都将该文字 `display:none`,动态反馈实际不可见。
- 观察边界:本轮 KOOK 原页无障碍树未提供中心成员卡信息,浏览器截图读取超时;没有据此声称测得 KOOK 的精确头像尺寸或动效时长。此次用用户的直接对比反馈确定方向,并修复 KAAK 自身可验证的显示问题。
- 修改内容与边界:桌面头像放大到 104px,中等屏幕 76px、窄屏 68px;实时说话时围绕头像显示品牌色脉冲环,并在卡片右下角显示可见波形标记,即使聊天展开、姓名隐藏也能看见。保留现有成员进入/离开转场和减少动态效果支持;只改 KAAK 样式、皮肤版本、包断言和说明,不改成员组件或语音引擎。
- 文档与分发包:KAAK 升至 3.1.43,重建示例及内置 `.wskin`。
- 验证:完整 `npm test` 661/661、`npm run build`、`npm run web:build` 和 `git diff --check` 通过;最后增加伪元素生成声明后,重建两份皮肤包并通过 KAAK 分发包定向测试。
- 当前状态与下一步:本轮优先修复成员舞台“头像偏小且说话反馈不可见”的具体差距;下一步继续核对聊天面板和语音控件的呈现细节,屏幕分享仍按要求跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.44 频道树字体层级)
- 差异依据:读取 KOOK 当前页面可见 DOM 的计算样式,服务器标题为 16px/700,分组标题 12px/700,频道标题 14px/700,人数/容量 12px/400 且文字色为主色约 40% 不透明度。KAAK 原样式对应字号为 13/10/13 与 10px,后续覆盖后分组字重仍为 800、频道字号 14 但未明确字重、人数 11。
- 修改内容与边界:KAAK 频道面板改为实测字号、字重、行高和人数/容量低对比度;窄屏服务器标题继续按现有断点缩小,窄屏分组文字继续收起。只改 KAAK 样式、版本、皮肤包断言和文档,不改通用组件。
- 观察边界:只读取通用样式属性,没有记录服务器/频道文本、标识或成员信息。当前页面的成员舞台仍在加载状态,本轮不宣称核实了成员区的像素或动效。
- 文档与分发包:KAAK 升至 3.1.44,重建示例与内置 `.wskin`。
- 验证:皮肤包重建、完整 `npm test` 661/661、`npm run build`、`npm run web:build` 和 `git diff --check` 均通过。
- 当前状态与下一步:频道导航文字层级现在有直接 DOM 计算样式依据;后续继续核对聊天面板和语音控件的呈现细节,屏幕分享仍按要求跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.45 音频/性能强调色统一)
- 问题依据:3.1.42 已将 KAAK 的主强调色调整为 KOOK 深色主题绿,但性能入口、性能数值、音量百分比和音频设置图标仍保留数种薄荷绿旧值,hover 提示和读数不一致。
- 修改内容与边界:新增 KOOK 主色/hover 色变量,并将性能卡片入口、hover/focus、指标、音量读数、设置分区图标和设置滑杆读数统一到同一色阶。只改 KAAK CSS、版本、皮肤包断言和说明;不改音量事件、性能采样、设备选择或通用宿主逻辑。
- 原页核查:当前浏览器桥接没有返回已打开的 KOOK 标签,直接页面读取也不可用;本节点只沿用参考文档已记录的 KOOK 公共主题色,不声称本轮新增原页观察。
- 文档与分发包:KAAK 升至 3.1.45,重建示例包和内置 `.wskin`。
- 验证:`npm run skin:kaak:build` 成功,示例和内置包均由当前 3.1.45 源码重建;`npm run verify` 全部通过,测试 661/661,服务端 `tsc` 和前端 Vue 类型检查/生产构建通过;`git diff --check` 通过。没有可用 KOOK 浏览器标签,本节点未做在线视觉复验。
- 当前状态与下一步:语音/音频控件的强调状态现在复用 KOOK 色阶;继续核对频道聊天和成员交互的具体动效,屏幕分享继续跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.46 音频设置表单比例与字段排布)
- 问题依据:KOOK 原始设置页可直接读取 660px 宽、`#25262a` 底色、16px 圆角的音频表单卡;字段行为 72px 高、16px 24px 内边距,标签列/控件列约 268/320px,标签 14px/400。KAAK 原弹窗更窄,设备标签和控件纵向堆叠,字体值虽已接近但信息密度和布局仍不一致。
- 修改内容与边界:为通用音频设置控件加入设备与音量字段的结构分组;KAAK 皮肤将输入/输出设备和音量控件排成 72px 横向字段行,并把输入/输出两组放入同一张深色圆角卡片。窄屏切换为纵向字段。没有改设备选择、音量调节、麦克风测试或任何音频状态逻辑。
- 原页核查:只读取已打开 KOOK 设置页的通用尺寸和计算字体;未选择设备、移动滑杆、运行麦克风测试,也未记录设备名称。
- 文档与分发包:参考文档补充主内容/卡片/字段比例和完整字体行高;KAAK 示例说明及包版本更新至 3.1.46,示例和内置 `.wskin` 已由当前源码重建。
- 验证:皮肤包构建通过;完整测试 661/661、服务端 `tsc`、前端 Vue 类型检查/生产构建和 `git diff --check` 均通过。浏览器主页可加载,但新版皮肤权限待用户批准,因此未进行音频设置面板目视验收。
- 影响文件/提交:音频设置组件模板(仅增加通用语义分组)、KAAK 样式/清单/目录版本/包断言、KOOK 参考和工作记录、示例说明及两个皮肤包。
- 当前状态与下一步:功能提交 `2a80ade` 已推送到 `dev`;待本地批准当前版本后,再补做音频设置面板的浏览器目视验收。之后继续成组核对语音控件交互和字号,避免每个小节点重复全量测试。
## 本轮修改节点(2026-10-11,KAAK 3.1.47 设置页降噪入口)
- 问题依据:已打开的 KOOK 语音设置页把降噪开关及档位入口放在语音设置中;WebSpeak 已有对应的通用降噪开关,但桌面端只在语音坞悬浮面板出现,设置页仅移动端显示。
- 修改内容与边界:通用音频设置页在桌面和移动端都显示现有降噪开关;KAAK 将其排入同一张设置卡的横向字段行。开关仍调用 WebSpeak 现有布尔降噪状态,不新增音频处理算法、档位或 KAAK 专属逻辑。
- 原页核查:只读取语音设置页的栏目与控件存在性;不记录输入/输出设备名称,也未切换降噪、设备或音量。
- 文档与分发包:KOOK 参考/KAAK 说明补充该入口及能力边界;版本更新至 3.1.47,示例与内置 `.wskin` 已重建。
- 验证:完整测试 661/661、服务端 `tsc`、前端 Vue 类型检查/生产构建和 `git diff --check` 均通过。浏览器目视验收仍待本地用户批准当前皮肤版本的权限。
- 影响文件/提交:音频设置组件及通用样式、KAAK 皮肤样式/清单/内置目录/断言、KOOK 参考与 KAAK 说明/工作记录、两个皮肤包。
- 当前状态与下一步:本节点已验证并推送到 `dev`(GitHub 提交 `cb504c95`)。音频设置面板的目视验收仍待用户批准 KAAK 3.1.47 权限;之后再选下一个有原页依据的成员/聊天动画节点。
## 本轮修改节点(2026-10-11,KAAK 3.1.48 成员说话状态色)
- 差异依据:成员说话时头像光环和波形标记使用 KAAK/KOOK 已记录的品牌绿,但同一状态副行仍硬编码为紫色 `#b2a8ff`,造成一个成员卡内部反馈色不一致。本轮没有取得新的 KOOK 页面状态树,依据限于已有 KOOK 品牌色记录和当前源码差异。
- 修改内容与边界:说话状态副行复用 KAAK `--skin-kaak-accent`,与头像光环、波形和其他强调反馈一致。只改 KAAK 皮肤,不改共享成员组件、说话状态事件或语音引擎。
- 文档与分发包:版本更新至 3.1.48,更新 KAAK 说明与皮肤包断言,重建示例和内置 `.wskin`。
- 验证:`npm run skin:kaak:build`、`npm run verify`(661 项通过、服务端 `tsc`、前端 `vue-tsc`/Vite 构建)和 `git diff --check` 通过。验证的是颜色令牌与分发包内容;没有据此声称完成 KOOK 说话态视觉验收。
- 影响文件:KAAK CSS、版本清单/目录、示例与内置分发包、包测试、说明及本工作记录。
- 当前状态与下一步:说话文字反馈已和同卡片的绿色情绪反馈统一;下一节点继续精确核对成员/聊天动画。KOOK 页面无障碍树当前无法读取,原页视觉核查待浏览器恢复后补做;屏幕分享仍按用户要求跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.49 性能卡刷新反馈)
- 问题依据:KAAK 性能卡的“立即测量”按钮在采样期间会禁用,卡片底部也显示采样状态,但按钮图标没有动态变化;用户要求把交互反馈也纳入复刻。本节点补全 WebSpeak 诊断卡片自身的忙碌反馈,不声称这是 KOOK 的专有交互。
- 修改内容与边界:仅当刷新按钮处于禁用采样状态时旋转刷新图标;尊重系统减少动态效果设置。未修改测量逻辑、采样频率、性能指标、音频/网络行为或其他皮肤。
- 文档与分发包:KAAK 升至 3.1.49,更新包版本断言与说明,并重建示例和内置 `.wskin`。
- 验证:`npm run skin:kaak:build` 与完整 `npm run verify` 通过;后者包含全部测试、服务端构建及前端类型检查/生产构建。`git diff --check` 通过(仅有仓库既有 LF/CRLF 转换提示);未进行新的 KOOK 页面读取或本地皮肤目视验收。
- 影响文件:KAAK CSS、manifest/内置目录版本、包测试、示例说明、工作记录和两个分发包。
- 当前状态与下一步:功能提交 `650c1e0` 已推送到 `dev`,刷新测量状态增加明确的图标反馈;随后回到有直接 KOOK 观察依据的成员/聊天样式与交互节点,屏幕分享继续跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.50 频道聊天开合状态隔离)
- 问题依据:KAAK 的 `chatopen` 是整页单一状态;在一个语音频道收起聊天会让切换后的另一频道也保持收起,与用户明确给出的普通/音乐语音频道默认行为不相符。
- 修改内容与边界:为通用声明式皮肤组件增加受权限约束的 `stateScope`,将 KAAK 工作区的局部 UI 状态限定到公开的 `session.status.channelId`。每个当前频道独立保留聊天开合状态;其他皮肤与未声明作用域的旧组件行为不变。作用域仅接受已投影的公开标量字段,并要求对应读取权限。
- 能力边界:TeamSpeak 当前没有可靠的音乐频道类型字段,新频道仍按 KAAK 声明的默认展开;用户可在音乐频道收起一次,之后在本次工作区生命周期内与其他频道状态分开保留。没有按房间名或成员猜测频道类型。
- 文档与分发包:KAAK 升至 3.1.50,更新 skin 包说明、目录版本和分发包;新增 schema 权限/路径测试及运行时切换频道状态测试。
- 验证:皮肤包构建通过;`src/shared/skin-plugin.test.ts`、`skin-extension-ui.test.ts`、`skin-pack.test.ts` 共 64 项通过,完整 `npm run verify` 通过(包含全部测试、服务端构建、前端类型检查和 Vite 生产构建),`git diff --check` 通过。未进行 KOOK 页面新操作或本地音频状态更改。
- 影响文件:声明式皮肤 schema、皮肤运行时、KAAK 组件配置/版本/分发包、包测试、KAAK 说明及本工作记录。
- 当前状态与下一步:功能提交 `9f11d11` 已推送到 `dev`,本节点修复了跨房间聊天状态串扰;仍需取得显式频道类别,才能自动应用音乐默认收起。随后继续推进有 KOOK 原页证据的成员/聊天呈现差异。
## 本轮修改节点(2026-10-11,KAAK 3.1.51 成员卡片音量入口)
- 问题依据:KAAK 的声明式语音工作区用中央成员卡替代原成员侧栏;检查宿主实现发现成员操作菜单(含个人音量滑杆)只通过移动端卡片按钮进入,KAAK 桌面成员卡无法打开该菜单。该问题来自本仓库代码核查,不声称本轮在 KOOK 原页观察到了相同按钮位置或动画。
- 修改内容与边界:给通用 `voice.member-cards` 小组件增加受 schema v3 校验的可选 `memberActions` 配置;默认关闭以保持其他皮肤行为,KAAK 显式开启。非本人卡片提供宿主操作菜单按钮,指针点击按位置打开、键盘触发时锚定到按钮;KAAK 用 44px 可触达目标和短暂渐显表现桌面 hover/键盘焦点状态,触屏常驻,并尊重减少动态效果偏好。菜单及个人音量仍由 WebSpeak 宿主执行;皮肤代码不读取音量值、不控制音频引擎,也没有增加权限或接口。
- 文档与分发包:更新公共小组件选项和布局钩子说明;KAAK 升至 3.1.51,示例包和内置 `.wskin` 均由当前源文件重建。
- 验证:完整测试 663/663、服务端 `tsc`、前端 `vue-tsc` 与 Vite 生产构建通过;`git diff --check` 通过。测试覆盖声明选项校验、宿主部件注册、包版本及 KAAK 实际启用配置。没有操作真实音量、设备或麦克风。
- 当前状态与下一步:功能提交 `bdd8e39` 已推送到 `dev`,远端包清单确认 3.1.51。成员卡现在能访问宿主个人音量菜单;后续继续按已记录的 KOOK 原页观察推进聊天/成员的呈现反馈,音乐频道自动识别仍受 TeamSpeak 缺少频道类型数据的限制,付费屏幕分享继续跳过。
## 本轮修改节点(2026-10-11,KAAK 3.1.52 成员卡右键操作)
- 参考依据:KOOK 官方《主持人模式教程》说明,在全体成员页面右键成员卡片可打开成员操作。本轮无法读取 KOOK 当前原页的浏览器 DOM,但以该官方交互说明作为操作入口依据,不记录或推断该菜单在语音舞台的精确样式。
- 修改内容与边界:KAAK 启用 `memberActions` 的桌面成员卡现在响应右键并复用原有宿主操作菜单;菜单锚定指针位置。普通按钮点击继续按指针定位,键盘触发继续锚定按钮;触屏仍显示原操作按钮。本人成员不弹出针对其他成员的菜单。没有新增宿主动作、皮肤权限或音频控制逻辑。
- 文档与分发包:KAAK 升至 3.1.52,更新 KOOK 参考、皮肤说明、包版本断言并重建示例与内置 `.wskin`。
- 验证:`npm run skin:kaak:build`、完整 `npm run verify`(666/666 测试、服务端 TypeScript 构建、前端类型检查和 Vite 生产构建)及 `git diff --check` 均通过。侧栏浏览器当前无法读取 KOOK 页面;本地语音连接入口仍超时,不能目视验收成员菜单。没有调整真实音量、切换设备或开启麦克风。
- 影响文件:成员卡事件、通用成员菜单指针定位 helper 及测试、KAAK 版本/目录/说明/分发包、KOOK 参考和本工作记录。
- 当前状态与下一步:这补上了 KOOK 已有操作入口在 KAAK 成员卡上的映射;代码与本记录一并同步至 `dev`。按用户要求,本轮完成后当前阶段结项;剩余主观观感由用户从使用者视角判断。
## 本轮修改节点(2026-10-11,皮肤编辑器控件与临时权限默认值)
- 问题依据:普通皮肤用户能看到用于开发恢复/权限管理的悬浮按钮,以及皮肤编辑器入口;皮肤权限确认会遮挡开发验收界面。
- 修改内容与范围:新增管理员会话校验后的“编辑器模式”开关;未登录管理员时隐藏布局、组件结构、权限管理与界面恢复工具,离开编辑模式或管理员会话失效时收起编辑器。皮肤组件权限提示暂时关闭,声明权限在 schema 检查、Wasm 支持校验和代码摘要校验后自动授权;原有沙箱与宿主动作校验保留。权限集合变化会重置组件本地状态。
- 临时策略:`PROMPT_FOR_SKIN_PERMISSIONS` 当前为 `false`,恢复公开皮肤分发前应重新启用权限确认。
- 验证:`npm run verify` 通过,670/670 测试、服务端 TypeScript 构建、前端类型检查和 Vite 生产构建均通过;管理员会话正反例、开发期自动授权和控件隐藏测试通过。
- 影响文件:编辑器模式状态服务、布局/组件/运行时插件入口、权限授权服务、对应测试和测试清单。
- 当前状态与下一步:管理员登录后可从页面开启临时编辑模式;普通用户不再看到开发悬浮工具或权限确认。正式发布前恢复权限确认开关。
## 本轮修改节点(2026-10-11,KAAK 3.1.53 左下控制坞与控件尺寸)
- 参考与范围:按 KOOK 原页的左下控制坞分区,连接/性能/断开分开排列;屏幕分享独占一行,底部依次为语音活动、降噪、麦克风、扬声器。按用户要求只复刻分享入口位置,观看继续使用 WebSpeak 原生播放器;KOOK 付费菜单及相邻功能不复刻。
- 修改内容:KAAK 控制坞修复断开与性能入口重叠;加入带状态切换的分享开始/停止入口和房间内 WebSpeak 播放器;桌面“语音活动”打开已有音频配置页,保留原设备选择、VOX 阈值和音量交互。移动端使用对应四项音频操作布局。
- 控件尺寸修复:皮肤布局运行时不再给所有注册交互控件强加 44px 最小宽高,避免范围滑杆、复选框和身份导入/导出按钮被拉伸;保留可访问性元数据,尺寸由宿主和皮肤样式决定。声明式绑定校验也修正为接受已登记的驼峰路径,以支持分享状态条件。
- 文档与分发包:KAAK 升至 3.1.53,更新内置目录版本、参考说明和本工作记录,重建示例与内置 `.wskin`。
- 验证:`npm run skin:kaak:build` 成功;`npm run verify` 全部通过(670/670 测试、服务端 TypeScript 构建、前端类型检查和 Vite 生产构建);`git diff --check` 无空白错误。
- 本地验收:侧栏浏览器加载本地 KAAK 连接页;身份选项截图中导入按钮保持紧凑、导出按钮在没有身份时正常禁用。连接按钮没有让页面进入语音区,因此未目视确认控制坞的实际布局;未开启麦克风或操作设备。
- 当前状态:代码、皮肤包和记录已完成;本轮尚未提交或推送。语音区目视验收受本地连接入口未切页限制,剩余细微观感由用户在实际使用中判断。
## 本轮修改节点(2026-10-11,KAAK 3.1.54 控制坞图标与分享按钮精修)
- 参考与问题:用户提供的 KOOK 控制坞截图中,语音活动、降噪、麦克风和扬声器有清楚分工;当前实现把语音活动和降噪都画成同一条波形,且分享入口偏矮、字太小、底色和描边对比不足。
- 修改内容:语音活动改用独立活动波形;降噪使用带净化标记的专属图标。固定图标盒尺寸和居中,降噪启用态使用更明显的圆角方形底色,避免 hover 位移造成图形漂移。分享按钮采用更接近 KOOK 的深绿灰填充、清晰绿描边、较大圆角和 15px/600 中文字重;窄屏下同步收紧高度。
- 文档与分发包:KAAK 升至 3.1.54;示例与内置皮肤包、目录版本及版本断言一并更新。
- 验证与推送:`npm run verify` 全部通过(670/670 测试、服务端 TypeScript 构建、前端类型检查和 Vite 生产构建);已快进推送 `dev`,远端 KAAK 版本确认是 3.1.54。连接页目前未能进入语音舞台,本轮不把浏览器截图验收描述为已通过。
## 本轮修改节点(2026-10-11,KAAK 3.1.55 控制坞紧凑化)
- 参考与目标:按用户给的紧凑样例优化比例与节奏,不照搬其布局;保留 WebSpeak 现有分享、语音活动、降噪、麦克风、扬声器和离开交互。
- 修改内容:桌面端把分享主按钮与音频操作放在同一行,按钮压至 34px 高,音频图标按钮为 32px;字号统一到 12px 层级、图标收至 15–16px。降噪启用态改用低饱和浅绿底,不再使用 52px 大色块。外框、阴影和按钮描边减轻,圆角收为 7–8px,hover/active 聚焦于细微颜色反馈。窄屏保留分享和操作分两行,底栏高度从 140px 缩至 122px,触控尺寸保持 36px。
- 版本与验证:KAAK 升至 3.1.55;示例包和内置 `.wskin`、目录版本及版本断言一起更新。皮肤 CSS 解析、皮肤包构建、670/670 测试、服务端构建、前端类型检查和 Vite 生产构建均通过。
- 本地验收限制:本轮依据两张用户截图做比例调整;若语音连接仍无法进入工作区,不声称完成了浏览器内实时目视验收。
## 本轮修改节点(2026-10-11,KAAK 3.1.56 按用户 HTML 样例重排控制坞)
- 参考与目标:用户提供了完整 HTML/CSS 样例,明确要求以该实现为基础并按图复刻。采用其中 264px 面板宽度、暗灰底色、28px 主操作、37px 方形操作、23px 底部控制行和分隔线尺寸;撤销 3.1.55 的横向单行排列。
- 修改内容与边界:桌面控制坞按样例拆成标题、分享/小操作、语音控制三层;顶部分享、降噪和伴奏分别接到现有宿主控件,底部保留语音活动、麦克风和扬声器。移动端维持紧凑触控尺寸,并按同一层次排布。未新增录音能力:样例中的“REC”没有对应产品功能,因此该位使用现有降噪开关;没有修改 WebSpeak 引擎或音频行为。
- 版本与分发包:KAAK 升至 3.1.56;更新目录版本和样式断言,重建示例与内置 `.wskin`。
- 验证:皮肤包构建通过;完整 `npm run verify` 为 670/670 测试通过,服务端 TypeScript、前端类型检查和 Vite 生产构建通过。最后微调窄屏标题列后重新构建皮肤包,皮肤包/目录定向测试 23/23 通过,`git diff --check` 通过。没有将静态样例预览称作语音工作区实机验收。
- 当前状态:实现已按用户 HTML 结构落到 KAAK 样式;本地提交 `d40441d` 已经推送到 `dev`(远端提交 `0ad7386`)。语音工作区尚未做实时浏览器目视验收。
## 本轮修改节点(2026-10-11,KAAK 3.1.57 降噪与设置入口重新排布)
- 参考与目标:用户补充了当前面板及理想底排截图。顶排只留屏幕分享和伴奏;底排在“语音感应”一侧使用设置齿轮,之后依次降噪、麦克风、扬声器;降噪需与同排控件水平对齐。
- 修改内容与范围:桌面皮肤网格改为四列两行,分享按钮跨前三列、伴奏占右侧;语音活动设置入口显示齿轮,降噪移入底排第二列并使用同一行高;麦克风和扬声器置于其右侧。移动端沿用相同次序,并显示现有伴奏开关。只调整通用房间音频控件的现有入口标识与 KAAK 排列/样式,没有新增音频功能。
- 文档与分发包:KAAK 升至 3.1.57,更新版本断言和工作记录,重建示例与内置 `.wskin`。
- 验证:待集中运行皮肤包构建、完整验证和差异检查;实时语音工作区目视验收另行记录,不用静态 CSS 断言代替视觉验收。
- 当前状态:布局与图标调整完成,待验证并推送 `dev`。
## 本轮修改节点(2026-10-11,KAAK 3.1.58 按用户 HTML 原型细化)
- 参考与目标:用户提供完整控制坞 HTML,明确 264px 面板、三列动作区、顶排主操作与底排语音控件的紧凑尺寸。按其实际结构把分享放在左侧宽列,右侧放两个小按钮;底排设置入口与麦克风、扬声器对齐。
- 修改内容与范围:桌面与移动端均按分享/降噪/伴奏在顶排,语音感应文字加齿轮/麦克风/扬声器在底排重排。原型里的 REC 不对应现有录音能力,因此该位置绑定已有降噪功能,没有添加假录制按钮。设置图标移至文字右侧,断开连接改用语义正确的电源图标。
- 文档与分发包:KAAK 升至 3.1.58,更新目录版本与布局断言,重建示例和内置 `.wskin`。
- 验证:皮肤包构建通过;完整 `npm run verify` 通过(670/670 测试、服务端 TypeScript 构建、前端类型检查和 Vite 生产构建);差异空白检查通过。实时语音工作区目视验收另行记录。
- 当前状态:实现与验证完成;本地提交 `bc8151e` 已推送到 `dev`(远端提交 `74ee82a`)。实时语音工作区尚未做本轮实时视觉验收。
## 本轮修改节点(2026-10-11,KAAK 3.1.59 修正控制坞按钮位置)
- 参考与目标:以现有目标说明为准:顶排只放屏幕分享与伴奏;降噪在底排、位于麦克风左侧。用户新提供的 HTML 用于细化 264px 面板比例、动作按钮尺寸、分隔线、齿轮位置和断开图标。
- 修改内容与范围:修正 3.1.58 中把降噪放在顶排的问题。桌面和移动端均恢复四列排列:分享横跨前三列、伴奏占顶排最右侧;底排依次是语音感应/齿轮、降噪、麦克风、扬声器。REC 不对应现有功能,故不显示。
- 文档与分发包:KAAK 升至 3.1.59,更新布局断言,并重建示例与内置 `.wskin`。
- 验证:皮肤包构建通过;皮肤包与目录定向测试 23/23 通过,新增布局断言后皮肤包测试 21/21 通过;差异空白检查通过。实时语音工作区目视验收另行记录。
- 当前状态:位置修正与定向验证完成;本地提交 `90f7c6a` 已同步到 `dev`(远端提交 `729e413`)。实时语音工作区尚未做本轮目视验收。
## 本轮修改节点(2026-10-11,KAAK 3.1.60 控制坞降噪按钮归位)
- 参考与目标:按用户标注的 KOOK 截图,波形“+”降噪控件位于底排,紧接语音活动/设置入口,排在麦克风左侧;屏幕分享与音乐留在顶排。
- 修改内容与原因:3.1.59 已声明降噪放在底排,但实际控件仍出现在顶排。控制坞的嵌套网格与 `subgrid` 让内部音频控件的位置没有可靠映射到外层网格。本次让 KAAK 桌面音频控件直接参与控制坞网格,并隐藏 room-panel 中不需要的重复说明文本;移动布局同样让操作按钮直接映射到四列网格,固定语音活动、降噪、麦克风、扬声器的次序。未修改宿主控件或音频功能。
- 版本与分发包:KAAK 升至 3.1.60;补充包测试断言,重建示例和内置 `.wskin`。
- 验证:皮肤包构建及定向测试 21/21 通过;完整 `npm run verify` 通过(670/670 测试、服务端 TypeScript 构建、前端类型检查与 Vite 生产构建),`git diff --check` 通过。尚未做实时语音工作区目视复核。
- 影响文件:KAAK 控制坞 CSS、皮肤清单/目录版本、皮肤包测试、示例与内置 `.wskin`、本工作记录。
- 当前状态:依据截图完成布局并通过自动验证;本地提交 `9249e0c` 已推送到 `dev`(远端提交 `25148dd`)。尚未做实时语音工作区目视复核。
## 本轮修改节点(2026-10-11,KAAK 3.1.61 恢复退出图标与伴奏反馈)
- 用户反馈:控制坞退出按钮图标消失,伴奏按钮点击后没有明显作用;前一轮截图还显示降噪按钮垂直错位。
- 修改内容与范围:退出按钮在皮肤 CSS 中补回电源图标;降噪按钮清除继承的外边距和内边距;伴奏按钮明确可点击层级,并让共享成功后的按下状态与未启用态视觉区分。桌面和移动控制坞都覆盖相应样式;不改 WebSpeak 通用音频引擎。
- 功能核查:伴奏按钮已连接到宿主的启动/停止处理器,启动会请求浏览器选择共享音频来源,并要求语音会话协商成功 WebRTC;未建立 WebRTC 时宿主会给出当前已有提示。截图无法确认实际连接协商状态,因此本轮只修复皮肤表现并以代码核查确认事件链,不能据此宣称已完成真实房间伴奏验收。
- 文档与分发包:KAAK 升至 3.1.61;已更新皮肤目录和版本断言,并重建示例与内置 `.wskin`。
- 验证与推送:皮肤包构建、定向语音/皮肤测试(172 项)和完整 `npm run verify`(670/670 测试、服务端 TypeScript、前端类型检查及 Vite 生产构建)通过;`git diff --check` 通过。代码核查确认伴奏操作已有浏览器来源选择和 WebRTC 宿主链路,但未在真实语音房触发采集,因此不将其记为实机功能验收。已基于远端最新 `dev` 安全移植并推送至提交 `938bb06`,未重写历史。
## 本轮修改节点(2026-10-11,KAAK 3.1.62 修正性能卡片浮层层级)
- 用户反馈:性能指标弹出卡片遮挡音量悬浮面板。
- 修改内容与范围:将 KAAK 性能组件的堆叠层级从 24 降至 8,使它继续浮在普通内容上方,同时低于音量控件的 20 层悬浮面板;只调整皮肤层级,不改通用弹窗或性能组件。
- 文档与分发包:KAAK 升至 3.1.62,更新层级断言并重建示例与内置 `.wskin`。
- 验证与推送:皮肤包构建、皮肤包/目录定向测试 23/23 通过,`git diff --check` 通过;已完成层级差异断言。已基于远端 `dev` 安全移植并推送至提交 `a1051b9`,未重写历史。
## 本轮修改节点(2026-10-11,KAAK 3.1.65 服务器切换和嵌套频道树)
- 目标:让左侧频道列展示 TeamSpeak 实际服务器身份、收藏/历史服务器切换入口和真实嵌套语音频道成员;不添加独立文字频道组,不改语音坞或聊天布局。
- 修改内容与范围:将服务器名和连接状态加入安全会话投影;过滤像 IP、域名或连接目标的显示名。新增通用 `voice.server-switcher` 宿主组件,使用本机不透明标识调用原有连接流程;新增 `voice.channel-tree` 宿主组件,按 TeamSpeak 深度构建层级、展示频道人数/上限、成员头像和静音/说话/离开状态,并支持展开、选择及双击加入。头像仅在可信宿主组件内使用;公共部件注册和触控尺寸一并更新。
- 文档与分发包:KAAK 升至 3.1.65;更新开放皮肤宿主控件权限、部件名及 KAAK 示例说明,重建示例包和内置 `.wskin`。
- 验证:`npm run skin:kaak:build` 通过;`npm run verify` 通过(679/679 测试、服务端 TypeScript 构建、前端类型检查和 Vite 生产构建)。自动验证不替代连接真实频道后的视觉验收,本节点未做实际设备、语音或频道切换操作。
- 影响文件:通用皮肤插件白名单/安全投影、WebClient 组件挂载、新增频道树与服务器菜单、KAAK 组件树/样式/版本目录/包、部件和权限测试及文档。
- 当前状态:实现与自动验证完成;浏览器中的实时语音视觉复核尚待用户从使用者视角确认。
## 本轮修改节点(2026-10-11,KAAK 3.1.66 频道栏与音频坞按原型复刻)
- 目标:按用户提供的 HTML 复刻第二列及其底部音频面板,保留真实 TeamSpeak 数据与 WebSpeak 控件逻辑;不扩展到其他页面和皮肤。
- 频道栏:宽度恢复为原型的 304px;将服务器名、TeamSpeak/连接状态标签、服务器切换和可用频道搜索组合成一个可信宿主头部。搜索实时筛选频道名称并自动展开命中路径。KAAK 专属的频道树行高为 38px、成员行为 29px,头像 22px;父频道折叠只收起子频道,成员仍显示。当前频道使用绿色细指示条。
- 音频坞:宽度改为 282px,左右留白 11px,使用原型的深灰背景、17px 圆角、顶部 29px 操作与分隔线。屏幕分享、降噪、伴奏、设置、麦克风和扬声器继续调用现有 WebSpeak 功能;录音位只显示禁用的样式占位,不声称实现录音。
- 兼容性边界:频道树的新展示方式通过可选宿主布局声明启用,其他皮肤不变;所有视觉覆盖均限定在 KAAK 作用域。没有改动语音引擎或加入录音能力。
- 版本与分发包:KAAK 升至 3.1.66;更新示例和内置目录,重建示例 `.wskin` 与内置 `.wskin`。
- 验证:`npm run skin:kaak:build` 与 `git diff --check` 通过;定向测试 46/46、完整 `npm run verify` 680/680 通过,服务端 TypeScript、前端类型检查与生产构建通过。未在真实语音频道做浏览器目视验收。
- 当前状态:实现和自动验证完成;按既有指示提交并推送到 `dev`。
## 本轮修改节点(2026-10-11,KAAK 3.1.67 音频坞精修)
- 目标:移除录制占位,顶行只保留屏幕共享与伴奏;按用户示意收紧降噪、麦克风、扬声器一行,并把左侧设置入口改为齿轮在前的“语音设置”。
- 修改范围:仅调整 KAAK 示例布局、作用域样式、宿主音频设置按钮文案和各端的相同控件排列;保留现有分享、降噪、伴奏、麦克风、扬声器、打开设置的行为,不增加录制功能。
- 视觉行为:降噪/麦克风按钮列收窄至 28px;语音设置组靠左排列,右侧控件保持独立紧凑分组;移动布局同步收紧。
- 版本与分发包:KAAK 升至 3.1.67;重建示例和内置 `.wskin`。
- 验证:皮肤包重建成功;`npm run verify` 的 680 项测试全部通过,服务端 TypeScript 构建、前端类型检查与生产构建通过;`git diff --check` 通过。
- 当前状态:实现与自动验证完成;按既有指示提交并推送到 `dev`。
## 本轮修改节点(2026-10-11,KAAK 3.1.68 服务器横幅与欢迎语)
- 目标:按网页示例为语音侧栏增加服务器横幅和欢迎内容,数据来自当前 TeamSpeak 虚拟服务器;不添加示例站点的运营内容或无效控件。
- 数据与安全边界:宿主从 SDK 提供的 TeamSpeak `initserver` 握手信息读取公开横幅 URL 和欢迎语;限制 URL 长度并只接受无凭据的 HTTP(S) 地址,欢迎语限长后作为纯文本显示。字段仅进入 WebSpeak 的公共服务器信息消息,不将连接目标或身份材料交给皮肤代码。字段为空时隐藏相应内容。
- 界面与兼容:新增受信任的 `voice.server-banner` 宿主组件,放在服务器头部和频道树之间;皮肤可调整图片、欢迎卡片、图标、标题和正文部件。样式限制在 KAAK 作用域,其他皮肤保持现有表现。
- 版本与分发包:KAAK 升至 3.1.68;更新组件定义、目录、开发文档、示例包及内置 `.wskin`。
- 验证:皮肤包构建与完整 `npm run verify` 通过(682/682 测试,服务端 TypeScript、前端类型检查和 Vite 生产构建通过);`git diff --check` 通过。
- 当前状态:实现及自动验证完成,按既有指示提交并推送到 `dev`。
## 本轮修复节点(2026-10-11,普通客户端权限下读取服务器横幅)
- 用户反馈:TeamSpeak 桌面客户端能显示已设置的横幅图片和欢迎语,WebSpeak 页面却没有横幅。
- 根因:WebSpeak 曾在连接后额外执行 `serverinfo`;实际测试连接返回“权限不足”,导致 SDK 查询失败后字段被置空。TeamSpeak 连接握手 `initserver` 已包含横幅 URL 和欢迎语,SDK 之前只保留了服务器名与图标。
- 修改范围:SDK 将握手中的横幅 URL、欢迎语加入公开 `ServerInfo`;WebSpeak 改读握手字段并继续做 URL/长度校验,删除依赖额外 `serverinfo` 权限的读取。没有改皮肤布局或图片样式。
- 实测:用已授权测试连接确认握手能提供横幅 URL 和欢迎语;本次 `serverinfo` 查询确实因权限不足被拒绝。测试输出只记录字段是否存在、长度和协议,不记录 URL 或服务器地址。
- 推送与部署:SDK `main` 已推送至 `956d29c`,WebSpeak `dev` 已推送至 `6c57868`;本地 3040 已重启,HTTP 200。实际测试连接的握手可读取横幅 URL 和欢迎语;浏览器需刷新并重新连接后才能目视确认。
## 本轮精修节点(2026-10-11,KAAK 3.1.69 成员卡右键菜单格式)
- 参考依据:在 KOOK 原页对成员卡执行右键,直接核对了菜单的深色浮层、圆角边框、音量滑杆分隔区和悬停行格式;没有抄入 KOOK 的操作项。
- 现状与范围:WebSpeak 的成员卡右键入口和宿主菜单已在 3.1.52 实现。本轮只为 KAAK 的 `voice.context-menu` 添加皮肤限定样式;成员音量、私聊、戳一戳、私语目标、复制昵称和移动成员全部沿用 WebSpeak 现有功能与事件。
- 修改内容:深色面板、标题分隔、音量区分隔线、紧凑灰色动作行、绿色键盘焦点和同风格的移动成员子菜单;窄屏继续使用原有底部菜单布局。未修改宿主菜单组件、事件或其他皮肤。
- 分发与文档:KAAK 版本升至 3.1.69,目录版本、示例包与内置 `.wskin` 同步更新;补充菜单格式与功能边界说明。
- 验证:`npm run skin:kaak:build`、定向皮肤包测试 21/21、完整 `npm run verify`(682/682 测试、服务端 TypeScript、前端类型检查与 Vite 生产构建)及 `git diff --check` 均通过。3040 当前活动语音标签上确认中央成员卡右键会显示 WebSpeak 现有菜单;为避免打断正在连接的语音会话,没有刷新该标签,因此新 CSS 需页面重新加载后目视验收。
- 当前状态:提交 `10739a7` 已推送到 `dev`;3040 的静态构建和皮肤包已更新,当前已连接的浏览器标签仍加载旧资源,页面重新加载后可验收新菜单样式。菜单功能没有引入 KOOK 专属操作。
## 本轮纠正节点(2026-10-11,KAAK 3.1.70 频道树成员行右键菜单)
- 目标澄清:用户截图标注的是左侧频道树中语音频道下方的成员行。3.1.69 只给已有的中央成员卡右键菜单加了 KOOK 格式,未实现此次真正要求的频道树入口;现记录并补上这个差异。
- 修改内容与范围:频道树的宿主成员行右键时,复用 WebSpeak 现有 `MemberActionsMenu`,菜单内的成员音量、私聊、戳一戳、私语目标、复制昵称和移动成员逻辑不变。仅当皮肤为 `voice.channel-tree` 显式设置 `memberActions: true` 时启用;KAAK 开启,其他皮肤默认关闭。没有增加皮肤动作 API 或改动频道树的选择/加入行为。
- 视觉:菜单继续使用 KAAK 3.1.69 已有的 KOOK 深色圆角浮层样式;本节点不改其他组件样式。
- 分发与文档:KAAK 升至 3.1.70,同步示例、目录和内置皮肤包;补充开放皮肤选项说明,明确树成员行右键与成员卡入口的区别。
- 验证:KAAK 皮肤包构建通过;完整 `npm run verify` 通过(682/682 测试、服务端 TypeScript 构建、前端类型检查与 Vite 生产构建);`git diff --check` 通过。3040 返回 HTTP 200,且 WebClient 生产资源包含频道树成员右键事件与既有菜单部件;未打断活动页面或语音会话做浏览器手动点击。
- 当前状态:功能、文档、皮肤包构建和自动验证完成,已一并提交并推送到 `dev`。
## 本轮修复节点(2026-10-11,KAAK 3.1.71 频道树成员交互)
- 用户反馈:频道树成员行需要像频道行一样有悬停高亮和手型光标,并恢复拖放成员到目标频道的移动操作。
- 根因:右键菜单修复只接回了成员菜单入口;旧成员面板仍保留 `onMemberDragStart`、`onChannelDragOver`、`onChannelDrop` 等宿主处理函数,但声明式频道树没有绑定这些事件,成员行也没有 `draggable` 属性。
- 修改范围:给 `voice.channel-tree` 增加默认关闭的 `memberDragDrop` 选项;成员行标记可拖动(本人行除外),目标频道行接入现有宿主拖放/移动逻辑并展示拖入状态。KAAK 单独开启;所有高亮和光标样式均限于 KAAK 频道树,其他皮肤默认不变。未新增移动 API、皮肤动作或服务器权限绕过。
- 验证:KAAK 示例包与内置包已从同一组件/样式源重建;`npm run verify` 通过(682/682 测试、服务端 TypeScript 构建、前端类型检查及 Vite 生产构建),`git diff --check` 通过。自动验证确认新的 widget 选项经 schema 校验且 KAAK 包启用;没有在真实语音房间拖动成员,避免实际移动在线用户。
- 当前状态:实现和构建已完成;功能提交 `e800d75` 已推送至 `dev`。3040 使用新生产构建,页面和皮肤包均返回 HTTP 200;浏览器已有的活动语音标签未刷新。
## 本轮精修节点(2026-10-11,KAAK 3.1.72 降噪关闭状态提示)
- 用户反馈:语音坞的降噪开关启停状态不明显,希望关闭时与麦克风/扬声器一样出现红色斜杠。
- 修改范围:给降噪按钮增加仅表示关闭状态的皮肤钩子,在 KAAK 语音坞内复用麦克风/扬声器的红色斜杠样式;同时覆盖 KAAK 移动端按钮。音频处理逻辑、默认皮肤和其他皮肤均不变。
- 验证:KAAK 示例包和内置包已从同一源码重建;完整 `npm run verify` 通过(682/682 测试、服务端 TypeScript 构建、前端类型检查和 Vite 生产构建),`git diff --check` 通过。
- 当前状态:实现与自动验证完成并已在本地提交;向 GitHub 推送时 HTTPS 连接被重置,SSH 方式没有已配置的密钥,网络恢复后需重试推送。3040 当前可提供新构建,活动浏览器标签尚未刷新。
## 本轮修复节点(2026-10-11,整页替换皮肤显示屏幕共享状态)
- 用户反馈:除 KAAK 外,其他皮肤看不到正在共享屏幕的成员。
- 根因:共享状态由 WebSpeak/TeamSpeak 共用链路检测;KAAK 使用带共享状态的宿主成员卡片,其他整页替换示例则自行绘制成员行,而公开成员数据没有共享标记,导致传输层已发现的共享无法映射到自绘成员列表。
- 修改范围:给 `session.members` 增加 `screenSharing` 与 `screenShareStreamId`,两字段单独要求 `voice.screenShare.read`;自绘皮肤用 `voice.joinScreenShare` 观看时还需 `voice.screenShare.control`。按原有限定权限投影到 Wasm,未将 TeamSpeak SDK 对象或连接信息暴露给皮肤。
- 示例皮肤:Open Voice Surface 与 Harbor 的成员列表现可显示共享标记并提供观看按钮;KAAK 的宿主成员卡片和屏幕共享逻辑不变。
- 验证:Open Voice Surface 与 Harbor `.wskin` 已从各自组件源码重建;共享字段权限与运行时投影专项测试通过,包含屏幕共享 UI/皮肤包测试的完整套件 684/684 通过;`npm run build`、`npm run web:build` 与 `git diff --check` 通过。提交 `8b5db8a` 已推送至 `dev`;本地 3040 的页面和新 WebClient 资源均返回 HTTP 200,资源内含新成员共享字段。没有真实共享中的频道可用于端到端观看验收。
## 本轮皮肤更新(2026-10-11,内置皮肤与 KAAK 显示共享状态)
- 目标:让内置浅色、深色、ILLUSIA 和 KAAK 四款皮肤都清晰呈现活跃屏幕共享状态及观看入口。
- 实现:浅色/深色给宿主成员卡的直播标记和观看按钮加入匹配主题的配色;ILLUSIA 更新其开放皮肤 CSS;KAAK 更新成员卡直播标记、波形和观看按钮。KAAK 组件树显式保持 `screenShare: true`;修正文档原先错误地声称其关闭了共享 UI 的说明。未改屏幕采集和 WebRTC 传输逻辑。
- 版本与分发:浅色/深色升至 1.0.1,ILLUSIA 升至 2.0.1,KAAK 升至 3.1.73。新增可复用的 ILLUSIA `.wskin` 构建脚本;重建 ILLUSIA 与 KAAK 示例包及内置分发包。
- 验证:皮肤目录和包定向测试 24/24 通过;`npm run verify` 全部通过(685/685 测试、服务端构建、前端类型检查及 Vite 生产构建);`git diff --check` 通过。3040 上 ILLUSIA 包返回 3,545,262 字节、KAAK 包返回 21,761 字节,均与刚构建的分发包长度一致。没有正在共享的真实语音会话可供目视确认动态标记和观看行为。
- 当前状态:代码、皮肤包、记录和自动验证已完成;按持续指示推送到 `dev`。
## 本轮纠正(2026-10-11,修复 KAAK 以外成员卡不显示共享)
- 用户验收指出:更新后仍只有 KAAK 可见共享状态。此前只补主题样式,没有让成员卡实际开启该功能。
- 根因:`VoiceMemberCards.showScreenShare` 是可选 Boolean prop,Vue 会把未传入的 Boolean prop 解析为 `false`。KAAK 的 widget 配置显式传 `screenShare: true`,而默认宿主成员卡未传,因此浅色、深色和 ILLUSIA 页面将共享检测与观看 UI 全部关闭。样式包版本更新不会改变这个运行时默认值。
- 修复:将成员卡的 `showScreenShare` 默认值设为 `true`,默认宿主模板也显式开启;皮肤仍可通过 `screenShare: false` 关闭。远端流检测/观看现在仅依赖共享控制,不再错误依赖本机共享状态对象;本机启停控件仍要求状态对象。
- 回归测试:真实 SSR 渲染 `VoiceMemberCards`,不给本机共享状态,只提供活动远端共享和控制,确认生成共享标记与观看按钮;另确认显式 `screenShare: false` 完全隐藏这组 UI。定向屏幕共享测试 8/8 通过。
- 验证:`npm run verify` 通过(687/687 测试、服务端 TypeScript 构建、前端类型检查与生产构建)。实际活动语音房间暂不可用,尚未目视确认动态流;本地构建产物已更新。
- 当前状态:修复及自动验证完成;按持续指示提交并推送至 `dev`,并更新本地 3040。
## 本轮修复节点(2026-10-11,屏幕共享播放器尺寸)
- 用户反馈:播放器占满内容区,但共享画面只占左侧一部分,右侧空白过大,整体尺寸与源画面不匹配。
- 根因:播放器舞台固定为 16:9,且宽度始终铺满内容区;没有根据接收视频的实际分辨率和方向调整舞台尺寸。
- 修改范围:读取视频元数据,按源画面比例缩放播放器,最大宽度 1100px、最大高度不超过视口可用高度;窗口或内容区变化时重新计算。全屏仍填满屏幕,加载中的占位画面保留 16:9。只改通用屏幕共享播放器,不改皮肤组件或其他界面。
- 回归验证:定向屏幕共享 UI 测试 9/9 通过;新增竖屏、横屏尺寸上限和无效分辨率的计算测试。`npm run verify` 全部通过(688/688 测试、服务端构建、前端类型检查和生产构建);`git diff --check` 通过。
## 本轮回归修复(2026-10-12,播放器加载阶段宽度)
- 用户反馈:屏幕共享播放窗口消失。
- 根因:上一轮把外框设为 `fit-content`,但视频和控件都是绝对定位;元数据尚未就绪时播放器没有内在宽度,外框可能折叠。
- 修复:给外框明确的 1100px 上限默认宽度;视频元数据就绪后外框与舞台同步收缩到计算尺寸,全屏同步恢复视口尺寸。
- 回归验证:新增无视频元数据时仍有可见默认宽度的样式断言;屏幕共享 UI 测试 10/10 通过,`npm run verify` 全部通过(689/689 测试、服务端构建、前端类型检查和生产构建);`git diff --check` 通过。
## 本轮回归排查(2026-10-12,点击观看共享卡住)
- 用户反馈:观看按钮进入“观看中”状态后,播放窗口仍不显示;先前也报告点击观看会卡住。
- 根因:观看状态分别由 `screenShareViewing` 和 `screenShareViewingStreamId` 保存,UI 卡片用后者、播放器用前者,二者可能失步;同时播放器通过函数 ref 更新响应式尺寸对象,重渲染时会反复触发 ref,形成布局渲染反馈。播放器自身也没有压过语音活动装饰层。
- 修复:以当前观看流 ID 作为唯一观看状态;尺寸改为对 DOM 样式做幂等更新,并在 ref 节点未变化时跳过;移除父级 `ResizeObserver`;播放器提升到装饰层之上。共享流及窗口尺寸仍按视频元数据、视口变化和全屏状态更新。
- 验证:屏幕共享定向测试 16/16 通过;`npm run verify` 全部通过(690/690 测试、服务端 TypeScript 编译、前端类型检查与 Vite 生产构建);`git diff --check` 通过。3040 返回当前构建入口 200,新版 WebClient JS(438,183 字节)和 CSS(160,719 字节)均返回 200。
## 本轮播放器精修(2026-10-12,固定画布并以黑边适配视频)
- 用户补充目标:播放器保持固定的宽屏画布;共享画面比例与画布不同时完整显示,并在空余区域留黑边。
- 修改范围:WebSpeak 通用播放器在内容区内最多 1100px 宽、固定 16:9 比例;移除按视频元数据改写舞台宽高的逻辑,视频使用 `object-fit: contain`,舞台和视频底色为黑色。浅色、深色、ILLUSIA 和 KAAK 都明确保留黑色留边;三款内置皮肤版本分别升至 1.0.2、1.0.2、2.0.2,KAAK 升至 3.1.74,并重建 ILLUSIA 与 KAAK 示例及内置 `.wskin` 包。全屏仍铺满视口;不裁切、不拉伸视频。
- 回归验证:断言验证固定画布、完整显示、四款皮肤黑边规则和皮肤包版本同步;`npm run verify` 通过(690/690 测试、服务端构建、前端类型检查与 Vite 生产构建);两款可分发皮肤包均可导入且示例包与内置包字节一致;`git diff --check` 通过。3040 提供的 WebClient JS(437,529 字节)和 CSS(160,602 字节)均返回 HTTP 200;CSS 包含播放器舞台、`object-fit: contain` 和黑底规则。
## 本轮播放器布局调整(2026-10-12,横向铺满并压低高度)
- 用户反馈:以 ILLUSIA 二次元皮肤为例,播放器右侧留白过大、整体偏高。
- 修改范围:这是通用播放器改动,所有皮肤的舞台宽度改为填满可用内容区;桌面高度控制在视口高度的 64% 且不超过 640px,窄屏控制在 58% 且不超过 480px。源视频继续按比例完整显示,超出画布的区域留黑;未改任何皮肤布局或业务行为。
- 验证:`npm run verify` 通过(690/690 测试、服务端构建、前端类型检查及 Vite 生产构建);屏幕共享 UI 回归断言覆盖全宽、桌面高度上限与黑边规则;`git diff --check` 通过。
## 本轮播放器区域修复(2026-10-12)
- 用户反馈:KAAK 语音页的共享播放器和成员卡片互相覆盖,播放器没有限制在自己的布局区域。
- 根因:KAAK 语音舞台里的播放器宿主是可收缩的 flex 子项,但播放器画面有固定高度;宿主被压缩后,画面仍绘制到成员卡片区域。语音舞台也允许子内容溢出。
- 修改范围:只修改 KAAK 皮肤。播放器宿主不再收缩,宽度限制在中央语音舞台列,并按 16:9 高度参与布局;语音舞台裁剪溢出,成员卡片独立使用剩余高度并滚动。窄屏把舞台自身设为滚动区,播放器限高,卡片保留横向名单区域。KAAK 升至 3.1.75;WebSpeak 通用播放器逻辑和其他皮肤未改。
- 验证:重建 KAAK 示例与内置 `.wskin`;新增分发包样式断言;`npm run verify` 通过(690/690 测试、服务端 TypeScript 构建、前端类型检查与 Vite 生产构建)。尚未对活动语音会话做浏览器目视验收。
## 本轮播放器高度回归修复(2026-10-12)
- 用户反馈:上次布局修复后,其他皮肤播放器正常,但 KAAK 播放器塌缩为一条线。
- 根因:播放器组件在非全屏状态会以内联 `aspect-ratio: auto` 覆盖皮肤 CSS;KAAK 先前设置 `height: auto`,而视频与控件为绝对定位,因此舞台失去可计算高度。
- 修复范围:仅 KAAK 皮肤显式设定桌面和窄屏播放器高度,保持视频 `object-fit: contain` 和黑边;保留播放器与成员卡片分区布局,不改宿主播放器逻辑或其他皮肤。KAAK 升至 3.1.76。
- 验证:示例和内置 `.wskin` 已重建;高度断言和完整 `npm run verify` 通过(690/690 测试、服务端构建、前端类型检查与 Vite 生产构建);`git diff --check` 通过。3040 的新版 KAAK 包返回 HTTP 200(21,950 字节);未做活动语音会话的浏览器目视验收。
## 本轮频道图标回归修复(2026-10-12)
- 用户反馈:频道树的上锁频道仍显示喇叭,当前频道标题仍显示半圆图标。
- 根因:TeamSpeak 初始频道查询未请求 flags,密码标记无法进入共享频道模型;KAAK 当前频道标题使用皮肤模板中的固定半圆字符。此外,已安装的 KAAK 包按皮肤版本复用,本地 3.1.76 包会覆盖服务端更新后的同版本包。
- 修复:初始查询请求 `channellist -flags`,将密码状态送到树形频道图标;普通成员栏也按同一状态显示锁或喇叭。KAAK 标题符号换为喇叭,并升至 3.1.77 触发本地包更新。
- 验证:完整验证通过(692/692 测试、服务端构建、前端类型检查和生产构建);示例皮肤包与内置包同步。3040 已重启并返回健康状态;未在浏览器中进行目视验收。
### 频道锁图标复查
- 用户反馈:`msicbot` 确认设有密码,但频道树仍显示喇叭。
- 根因:服务器在订阅目录时已发送 `channel_flag_password=1`,但 SDK 的 `ChannelInfo` 解析器没有把这个公开标志放进目录快照;普通客户端随后执行独立 `channellist` 查询会收到权限错误,所以 WebSpeak 没有第二条数据来源。
- 修复:SDK 新增可选的 `ChannelInfo.passwordProtected`,从频道列表和频道编辑通知解析 `channel_flag_password`;WebSpeak 锁定新版 SDK。频道密码本身不会读取或传输。
- 验证:真实上海测试连接的 WebSpeak `TSClient` 收到 `msicbot passwordProtected=true`;SDK 全量测试 72 通过、类型检查、lint 和构建通过,改动文件格式检查通过。WebSpeak `npm run verify` 通过(693/693);3040 已重启,健康接口、首页和生产 JS 均返回 HTTP 200。全仓格式检查仍报 53 个未格式化文件。
## 本轮浏览器凭据记忆(2026-10-12)
- 用户要求浏览器记住 TeamSpeak 服务器密码和曾成功进入的加密频道密码,减少重复输入。
- IndexedDB 升至版本 4,新增独立 `credentials` 仓库;记录按规范化服务器目标隔离,频道凭据再按频道 ID 区分。凭据仅保存在当前浏览器,不写入 WebSpeak 服务端;“清除本地数据”会一并删除凭据。
- 连接和频道切换先尝试本地凭据,只有成功连接或成功切入频道后才保存。服务器或频道拒绝旧密码时删除对应记录并显示原密码输入框。切换服务器会清除当前内存密码,避免误带到另一个目标。
- 验证:`npm run verify` 通过(696/696 测试、服务端构建、前端类型检查和 Vite 生产构建);新增浏览器凭据隔离及连接对话框回归测试。3040 健康接口返回 200,线上静态入口引用的 WebClient 生产包返回 200,包内容含服务器与频道凭据实现。
- 安全边界:凭据存于浏览器本地 IndexedDB,未加密;同源脚本可访问它们。
## 本轮密码对话框样式(2026-10-12)
- 用户要求服务器密码和频道密码都按截图改成 KAAK 深色紧凑弹窗。
- 两个宿主对话框增加稳定的 `auth.password.*` 皮肤钩子;KAAK 包负责尺寸、深色表面、字段、按钮与移动视口样式。KAAK 连接表单中的服务器密码字段也使用同款深色输入外观。密码输入、错误文案、关闭、取消、提交和服务器重试仍使用原宿主逻辑,其他皮肤不变。KAAK 升至 3.1.78。
- 验证:重建示例和内置 KAAK 包;皮肤包与布局钩子测试通过,`npm run verify` 通过(696/696 测试、服务端构建、前端类型检查和 Vite 生产构建),`git diff --check` 通过。3040 健康接口、入口页、WebClient JS/CSS 和新版 KAAK 包均返回 HTTP 200;皮肤包大小与构建产物一致。
## 本轮密码弹窗按钮文案统一(2026-10-12)
- 用户反馈:KAAK 皮肤中服务器密码和频道密码弹窗的绿色确认按钮文字换行难看,要求统一为“确定”。
- 修改范围:KAAK 下两个密码弹窗的主按钮统一显示“确定”,其他皮肤继续使用原有本地化文案;服务器重试、频道提交、取消和错误状态逻辑保持不变。
- 验证与部署:`npm run verify` 通过(696/696 测试、服务端构建、前端类型检查与 Vite 生产构建);3040 健康接口与首页返回 200,生产 WebClient JS 返回 200,大小与本地构建一致(440,272 字节),并包含“确定”文案。静态构建已供 3040 使用,无需重启服务。
## 本轮服务器导航新增入口(2026-10-12)
- 用户要求所有皮肤、任意连接模式下,在进入语音页后都能从左侧服务器导航栏添加服务器。新增入口由 WebSpeak 宿主提供:普通导航栏保留原加号;替换式皮肤的 `server-rail` / `quick-rail` 也由宿主注入分隔线和加号,不依赖单个皮肤包。KAAK 加号按 58×58px、18px 圆角样式呈现,KAAK 升至 3.1.79 并重建示例与内置 `.wskin`。
- open 模式沿用现有添加对话框,保存收藏后连接新目标。fixed 模式点击加号只显示“该功能已被管理员关闭”,不会打开表单、保存收藏或连接;固定目标策略仍由服务端执行,未放宽。
- fixed 模式下收藏服务器入口保留可点击事件并以禁用态样式呈现;点击其他服务器的快速入口(通用侧栏、窄屏栏、服务器切换器及皮肤服务器轨道)显示“管理员不允许切换TS服务器”。
- 验证:服务器轨道注入、可信点击、受限状态无原生禁用、指定中文提示、受限数据投影和 KAAK 分发包定向测试通过(78/78);`npm run verify` 全部通过(698/698 测试、服务端 TypeScript、前端类型检查与 Vite 生产构建);`git diff --check` 通过。
## 本轮 KAAK 首页与 myTS 按钮(2026-10-12)
- 用户提供首页示例,要求 KAAK 首页按示例改造。首页采用左右分栏、绿色品牌展示区和白色服务器连接卡片,沿用宿主原有连接表单、密码处理、身份和中继选择逻辑,并由宿主显示真实连接状态;窄屏自动纵向排列。
- 连接卡片右上绿色装饰区新增“使用myts登录”按钮和 `myts` 字样,仅点击时提示“这个功能还在开发中”,不实现或调用 myTS 登录。
- KAAK 升至 3.1.80,重建示例皮肤和内置分发包。
- 验证:定向皮肤测试 51/51 通过;完整 `npm run verify` 通过(701/701 测试、服务端 TypeScript 构建、前端 Vue 类型检查与 Vite 生产构建);3040 的健康接口、首页和 WebClient JS 均返回 HTTP 200,服务端 JS 字节数与本地构建一致,包含按钮和提示文案;示例与内置 KAAK 包完全一致,版本 3.1.80。
### myTS 入口按截图收紧
- 用户要求移除卡片上的胶囊按钮外观,将 `myts` 字样完全放进右上角绿色三角,并倾斜显示。
- 去掉按钮底色、边框和额外徽标;保留该区域的无底色键盘可达按钮与“使用myts登录”无障碍名称,点击仍提示“这个功能还在开发中”。文字向左上倾斜 45° 并裁切在绿色角内。
- KAAK 升至 3.1.81;定向皮肤测试 51/51、完整 `npm run verify`(701/701 测试、服务端构建、前端类型检查与生产构建)通过,`git diff --check` 通过。3040 首页、健康接口、WebClient JS 与皮肤包均返回 HTTP 200;3040 上的皮肤包字节与源包一致。
### 首页表单收尾(2026-10-12)
- 按用户截图将右上角 `myts` 文字改为顺时针旋转 45°。
- KAAK 首页服务器密码框改为白底浅色样式,并覆盖浏览器自动填充背景和文字色,避免保存密码时出现黑边或蓝底。
- 将“目标频道”字段移出“设备身份选项”折叠区;身份记忆、导入和导出仍留在折叠区内。
- KAAK 升至 3.1.82。定向皮肤测试 51/51、完整 `npm run verify`(701/701 测试、服务端构建、前端类型检查与生产构建)通过,`git diff --check` 通过。3040 健康接口、首页和 WebClient JS 返回 HTTP 200;3040 皮肤包与本地分发包 SHA-256 一致。
### 服务器密码弹窗改为浅色(2026-10-12)
- 用户要求将服务器密码弹窗从深色改为浅色。服务器密码弹窗新增明确的公开状态标记,KAAK 仅对服务器密码弹窗应用白色卡片、浅色输入框、深色文字和匹配的取消/关闭悬停样式;频道密码弹窗继续保留深色方案,绿色“确定”按钮和原有密码重试逻辑不变。
- KAAK 升至 3.1.83;定向皮肤测试 51/51、完整 `npm run verify`(701/701 测试、服务端构建、前端类型检查与生产构建)通过。3040 健康接口、首页和 WebClient JS 返回 HTTP 200,分发包与本地构建一致。
### 语音页工具移入左侧导航栏(2026-10-12)
- 移除 KAAK 语音页顶栏,将服务器列表改为独立滚动;左侧服务器栏底部固定显示宿主提供的加号、皮肤切换和语言切换工具,并以分隔线与服务器列表隔开。
- 语言按钮沿用宿主现有语言选项、切换和保存逻辑,按钮视觉标签为“文/A”;语言菜单和皮肤菜单都从工具方块旁弹出,并在较矮窗口中调整位置。
- KAAK 升至 3.1.85;`npm run skin:kaak:build` 与完整 `npm run verify` 通过(701/701 测试、服务端 TypeScript、前端类型检查和 Vite 生产构建),`git diff --check` 通过。3040 健康接口、首页、WebClient JS 和 KAAK 皮肤包均返回 HTTP 200;服务器皮肤包 SHA-256 与本地一致。
### 频道树成员屏幕共享标记(2026-10-12)
- 频道树成员正在共享时,在成员行末尾显示带绿色底色的显示器图标;状态由 WebSpeak 当前活跃共享流的成员归属驱动,普通成员不显示。覆盖常规与 KAAK 侧栏两种频道树布局,保留成员右键菜单及拖放行为。
- 将新标记纳入公开皮肤部件注册表和皮肤开发文档,标记自带通用样式,因此内置和自定义皮肤都可见。
- 屏幕共享 UI 定向测试 10/10 通过;完整 `npm run verify` 通过(702/702 测试、服务端构建、前端类型检查与生产构建);`git diff --check` 通过。3040 健康接口、首页、新版 WebClient JS/CSS 均返回 HTTP 200,生产资源含共享标记和绿色样式。
### KAAK 语言切换入口使用翻译图标(2026-10-12)
- 用户要求把 KAAK 语音页左侧栏语言入口改为截图中的翻译图标,并在连接首页右上角增加同款入口,方便其他语言用户切换界面。
- 沿用 WebSpeak 已有语言菜单、选择事件和语言偏好保存逻辑;只在 KAAK 皮肤中显示纯翻译符号,不使用参考图的青绿色背景。侧栏沿用深灰工具块,首页在右上角提供中性色按钮。通用语言控件默认继续隐藏该图标,其他皮肤不受视觉影响。
- KAAK 升至 3.1.86;`npm run skin:kaak:build` 和完整 `npm run verify` 通过(702/702 测试、服务端构建、前端类型检查与 Vite 生产构建),`git diff --check` 通过。3040 健康接口、首页、WebClient JS/CSS 和新版皮肤包均返回 HTTP 200;3040 皮肤包与本地分发包 SHA-256 一致。
+48
View File
@@ -0,0 +1,48 @@
# KOOK 语音客户端界面参考
本文依据用户授权查看的 KOOK 网页语音工作区,记录 WebSpeak 可复刻的语音界面。范围限定在指定服务器的前两个语音频道;不保存服务器或房间名称、标识、成员身份、聊天内容、截图或连接凭据。
## 界面结构与呈现
- 最左侧是纵向服务器栏;服务器内容区在其右侧,包含服务器信息和按组排列的频道。
- KOOK 有独立文字频道列表。它属于文字频道导航,不是语音频道附带的聊天;当前 WebSpeak 只复刻语音频道旁的聊天,不复刻这组独立文字频道。
- 语音分组行显示图标、频道名称及人数/上限。加入语音频道后,成员以缩进项目出现在频道行下方。
- 对当前页面已渲染的频道树读取计算样式:服务器标题为 16px/700,分组标题为 12px/700,频道标题为 14px/700,人数/容量为 12px/400、主文字色约 40% 不透明度。只记录通用样式值,不保留任何服务器或频道文字。
- 进入语音频道后,中央区域显示成员舞台。成员卡片为宽比例矩形,头像居中,静音状态标记放在卡片右上角。聊天展开时,姓名在静止状态下隐藏,悬停卡片后以紧凑标签显示在左下角;聊天收起时,姓名标签保持可见。
- 当前语音频道的文字聊天显示在右侧面板。面板标题对应当前语音频道,消息区占据主体,输入框固定在底部;展开时右上角有收起入口。收起后右侧聊天面板完全隐藏,中央成员舞台横向扩展,舞台标题栏右侧出现重新打开聊天的按钮。
- 左下方语音控制坞显示当前连接状态和离开入口,也有屏幕分享控件。KOOK 的屏幕分享呈现涉及付费功能,因此不复刻其额外菜单与付费交互;用户要求保留 WebSpeak 自带的分享入口和观看界面。
- 语音坞固定在频道栏底部:连接信号与当前房间状态在上排,断开入口靠右;音频控制集中在下排。当前原页截图中麦克风为关闭状态;这次没有点击音频控件,也没有改变该状态。
- 顶部客户端下载提示、服务器广告、推广卡、发现与运营页面都不属于 WebSpeak 皮肤范围。
## 交互观察
- 语音频道第一次点击后会选中频道并提示再次点击;再次点击才进入。加入后成员出现在该频道下方,当前语音频道聊天和语音控制坞同时出现。
- 本次首次进入的两个授权普通语音频道中,当前频道聊天默认展开。用户补充说明:KOOK 音乐语音频道也带有随语音房间显示的聊天,但默认收起。前一项是原页直接观察,后一项按用户提供的参考行为记录。
- 聊天展开时,成员卡默认不显示姓名;鼠标移到卡片上后姓名标签出现。收起聊天后,成员卡姓名持续显示,即使鼠标停在聊天收起控件附近也没有隐藏。
- KOOK 官方[主持人模式教程](https://help.kookapp.cn/65ea/067e)说明,在全体成员页面右键成员卡片可执行成员操作。KAAK 中央成员卡沿用 WebSpeak 已有的成员操作菜单,补充了右键入口;这记录的是操作方式映射,不代表已测得该菜单在 KOOK 语音舞台中的精确样式或位置。
- 当前语音频道聊天展开时,中心成员舞台仍保留频道名和实时人数标题;成员卡是横向大卡片,头像居中,静音标记位于右上角。
- 从一个已加入频道切换到另一个授权普通频道时,成员归属和当前聊天标题随目标频道变化;本次切换前聊天面板已展开,所以切换后仍展开。音乐频道默认收起是用户补充的参考行为,本次原页直接观察未覆盖音乐频道。
- 本次查看期间麦克风保持关闭,没有发送消息,也没有操作管理员功能。
- 当前页面呈现了中心成员舞台和右侧语音频道聊天;早期记录里“中心聊天、右侧成员列表”的描述与实际语音房间页面不符,已由本次原页观察更正。
## 音频与连接状态控件
- 左下语音坞用绿色信号柱表示连接状态,断开入口单独放在右上;屏幕分享入口独占一行,底部音频开关排列为语音活动、降噪、麦克风、扬声器。KAAK 保留 WebSpeak 原生的分享观看界面,不复刻 KOOK 的付费分享菜单,也不实现其旁边的额外功能。
- KOOK 的语音设置可从个人菜单进入,页面把输入/输出设备选择、麦克风输入音量和语音输出音量放在深色表单区内;输入设备附近提供本地麦克风测试和降噪开关,另有降噪档位入口。
- 设备选择是自绘下拉列表:选择框约 40px 高,选项列表可滚动、最多约 240px 高,每项约 32px;当前项有浅色底,箭头在开合时旋转。对照 KOOK 公开样式资源后补充:触发框和菜单为 12px 圆角,菜单内边距 8px;选项为 8px 圆角、上下间隔 2px、左右内边距 8px,深色菜单底色为 `#25262a`,文本为 `#e6eaf0`,品牌主色/hover/active 分别为 `#6cbf00`、`#7ac51a`、`#60ab00`,悬停与选中底色分别约为白色 6% 与 10% 透明度,菜单阴影为 2px/8px、黑色 32% 透明度。此项来自静态样式资源,不代表本轮重新操作了页面。我们此前只展开并收起输入设备列表,没有选择设备。
- 设置页采用 PingFang SC 优先的中英文字体栈。主标题为 32px/600、38px 行高,分区标题 16px/600、22px 行高,设备和音量标签 14px/400、20px 行高。公开滑杆样式显示音轨为 4px、圆形拇指为 16px 并带 2px 品牌绿描边;悬停时出现 3px 光圈。没有拖动滑杆,因此不推断声音反馈或音量更新动画。
- 本次从已打开的设置页读取计算布局:主内容宽约 732px,内容区内边距为 40px 16px 60px 56px;音频表单卡为 660px 宽、390px 高,底色 `#25262a`、圆角 16px。卡内横向字段行高 72px、内边距 16px 24px,标签列约 268px、控件列约 320px、列间距 24px;本地麦克风测试区域高约 100px,音轨高约 32px。只记录尺寸和通用样式,不记录设备名称。
- KAAK 对应使用通用宿主设备选择控件,交互包含点击展开、方向键/Home/End 导航、回车选择、Esc 收起和输入名称的快速定位;皮肤定义展开列表、选中/悬停/键盘态与 KOOK 字体。性能卡片仍是 WebSpeak 自己的诊断入口,不声称 KOOK 具有该面板。
- 本次本地 KAAK 对照打开了 WebSpeak 的音频配置弹窗,没有更换设备、移动音量、启动麦克风测试或开启麦克风。设备名称不写入文档。
- 连接状态图标点击后未显示单独性能卡片。KAAK 将 WebSpeak 已有的通用性能面板做成紧凑状态入口;它是 KAAK 自己的诊断卡片,不能据此声称 KOOK 具有相同面板。
- 本轮再次查看了已授权语音频道的工作区:左侧宽度约 80px、频道栏约 290px,语音坞贴近频道栏底部;中心是成员舞台,右侧为频道文字聊天。另打开语音设置并展开后收起输入设备列表,没有选择设备、调整音量、运行麦克风测试或改变麦克风状态。
## WebSpeak 实现映射
1. 服务器栏映射为 WebSpeak 的收藏/历史快速切换栏。
2. 左侧频道树只映射 TeamSpeak 语音频道及在线成员;KOOK 的独立文字频道组不在当前范围。
3. 中央区域映射为语音成员舞台,使用 WebSpeak 的成员卡片和公开状态。
4. 右侧映射为当前 TeamSpeak 语音频道附带的文字聊天,可在语音房间内展开或收起。
5. 左下控制坞继续调用 WebSpeak 宿主音频、断开和屏幕分享控件;KAAK 只复刻 KOOK 控制坞的入口分布,分享播放沿用 WebSpeak 自带界面。
皮肤负责布局和视觉;TeamSpeak 连接及控制仍由 WebSpeak 宿主执行并校验。只复刻授权观察到的语音客户端行为,不复刻 KOOK 的发现、陪玩、派对、商城、活动、推广或管理后台。
+183
View File
@@ -0,0 +1,183 @@
# 更开放的皮肤系统路线图
皮肤只作用于 WebSpeak 的公开连接首页和语音工作区。完成态要求作者能把公开界面几乎完整地做成自己的应用:所有公开组件都能重新排列、换皮、显隐或由作者自定义组件替代;作者可为自定义界面编写布局、样式和本地交互逻辑,不受固定宿主控件目录限制。TeamSpeak 连接、聊天、频道和音频行为仍由宿主能力层执行,管理后台、管理 API、演示设施及 KOOK 运营/广告页面不在范围内。
现有 v1/v2/v3 是兼容基础,不是“万物皆插件”的完成态。v3 的标签/属性、数据路径和宿主动作均为有限白名单;v4 有界 Wasm UI 已在生产构建开放,并保留摘要绑定的本地授权、权限投影和全局 worker 治理。浏览器端到端验证及独立安全审查仍未完成。不得用“支持自定义节点”或“支持整页 surface”宣称已经实现完整自定义。
零新增预算是持续约束:不因皮肤系统引入付费托管、CDN、域名或存储。商城与管理员面板重做由后续阶段共同规划;优先复用公开 GitHub 仓库、版本化 Release 附件和现有免费能力,不能把隐私配置发布到公共目录。
## 已完成的兼容基础
### R0:边界与威胁模型
已明确基础组件由宿主维护、管理后台排除、作者代码默认不执行、用户能够恢复内置皮肤,以及新增数据能力必须经过宿主授权。
### R1:公开组件和恢复入口
公开页面稳定钩子与组件注册表已建立。恢复布局、皮肤加载错误处理和权限管理由宿主可信界面提供,位于皮肤样式作用域之外。
### R2:声明式布局
schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖、撤销/重做、导入导出及错误恢复。schema v1 视觉皮肤继续兼容。
### R3:开放皮肤与受控组件
皮肤包 schema v3 的客户端和服务端包校验、CSS 布局能力、声明式组件渲染、按组件权限审批与撤销、公开数据代理及有限宿主动作已接入。旧的 components.json schema v1 使用受限 JSON 节点,不运行作者 JavaScript 或 WebAssembly。宿主对每次动作重新校验。
自定义 UI 使用作者定义的节点和 CSS,不要求从固定宿主控件目录里选布局。宿主控件只是可以嵌入的可选可信功能块;页面交互按组件权限连接到有限、逐项校验的现有 TeamSpeak 功能。
### R3.1:扩展声明式交互(进行中)
- components.json schema v3 兼容 schema v1/v2,同时扩大节点/深度/列表上限,并增加键盘、指针、上下文菜单和拖放交互事件。
- 新增自己的麦克风/扬声器、音量、离开状态、悄悄话、断开连接和屏幕共享等宿主动作及逐项权限;皮肤只调用现有 WebSpeak 流程。
- 新增音频、悄悄话和屏幕共享的公开状态数据,不向组件提供私有 SDK 对象、地址、原始音频或屏幕流。
- 被动 focus/blur/hover/drag-start/drag-over 只能更新本地 UI 状态;触发宿主动作需要明确用户操作,输入/change 仍不能触发连接、切房或消息发送。
- 已获准并实际查看指定服务器前两个语音频道;麦克风全程关闭。只把左侧服务器栏/频道树、中心聊天、右侧成员栏和左下语音控制卡作为 KOOK 语音工作区参考,不记录房间标识、成员名单或聊天内容。详细观察记录见[KOOK 语音界面参考](./KOOK_VOICE_REFERENCE.zh-CN.md)。
- 频道树中的已加入语音频道会缩进显示成员项;底部语音卡集中显示频道、连接质量、离开、屏幕共享及音频控件。加入语音后中心聊天和右侧成员区仍可见。观察结束后已断开并关闭质量反馈提示;未发消息、未开启麦克风/摄像头,也未使用管理员功能。
- KAAK 示例现可在频道列表项下受限重复显示对应频道成员;该嵌套列表必须同时获准 `session.members.read`,并由宿主限制单组件实际渲染节点总量,避免多层重复造成界面膨胀。
### R3.2:受限作者逻辑运行时(有界 Wasm 已开放,持续审查中)
- 现有 JavaScript Worker 因缺少硬内存配额继续关闭;Wasmi 解释器用独立 Worker、解释器内存上限、扩展燃料上限和超时终止运行非可信 Wasm。
- 当前增量加入 `env.ui_emit_json`:单次运行最多输出一次、不超过 256 KiB 的 UTF-8 UI 数据,和组件包大小限制一致。宿主只接收有界 JSON,不执行 HTML/JS;TeamSpeak 动作仅通过 schema v6 受限动作效果申请,并由 WebClient 的独立宿主桥校验。
- 已实现严格 UTF-8 大小、JSON 与 schema v3/v4/v5/v6 输出校验,以及供 `SkinPluginOutlet` 使用的合并入口;schema v4 可生成标准 HTML/SVG 元素、普通属性、包内图片,并使用作用域隔离的 CSS;schema v5 额外携带有界标量状态和命名事件回调,schema v6 可附带单个宿主动作效果。自定义标签渲染为惰性占位 `div`,不实例化页面中可能注册的 Web Component。
- Wasm 有界输入协议新增 `env.ui_input_read`:每次运行最多读取一次、最多 64 KiB 的 JSON,包含插件本地标量状态、单个安全事件和按权限投影的公开数据快照(快照最多 48 KiB)。频道、成员、聊天、收藏/历史、音频、悄悄话、屏幕共享数据只输出清单声明权限对应的字段;连接地址、凭据、SDK 对象与未知字段不会从公开数据投影进入 guest。UI 事件只在浏览器 `isTrusted` 事件触发时由宿主组件发出;DOM/Event 对象不跨边界,只传事件名、组件/处理器 ID,以及受限的键盘字段。只有清单声明并经用户批准 `ui.input.read` 后,文本框/选择框值和勾选状态才会进入 guest;未授权时仅传事件元数据。生成的密码、文件和隐藏输入始终拒绝;输入值与状态还会二次限长验证。协议不含“trusted”自报字段,作者代码不能把字段伪装成宿主授权。
- Wasm UI 循环现用于生产 v4 插件:初始渲染、可信 UI 回调、授权数据变化均拆成逐次 Worker 调用;每次回调按先后顺序执行、最多排队 8 项。调用前重新检查回调 ID 与上次生成的 UI 一致,输入状态键只能来自该组件声明,输出再次经过 schema 4/5/6 校验。关闭时终止当前 Worker、清空等待队列。宿主动作只能跟随可信 UI 回调,不会从初始渲染或数据刷新触发。
- `SkinRuntimePlugin` 已接入权限化数据投影和首版宿主动作桥:插件需通过摘要绑定授权后才能运行;每次调用只收到清单允许的、经字段白名单筛选的数据副本。数据变化会在 100 ms 合并窗口后触发下一次独立调用。动作请求只接受 schema v6 单个宿主动作效果,且必须来自可信 UI 事件触发的同一轮 Wasm 调用;宿主再按插件声明权限和现有会话状态校验。受限 Wasm 已在生产构建开放;插件商城、widget 布局和独立安全审查仍未完成。
- 该动作桥是有界原型,不代表浏览器瞬时用户激活可跨越异步 Wasm 执行。动态 UI 可使用经 `voice.screenShare.control` 权限门控的 `voice.screen-share-start` 宿主按钮,在可信点击处理器内直接调用屏幕采集入口;运行时动作桥现拒绝 `voice.startScreenShare`,避免异步 Wasm 调用丢失浏览器激活。仍需在支持的浏览器中端到端验证按钮、授权和系统选择器行为;后续还需完成插件布局与安装管理,并评估不同浏览器的资源和事件边界。
- v4 现可支持作者用 Wasm 逻辑、通用安全节点树与包内 CSS 创建公开客户端界面;“完整插件平台”仍未完成。JavaScript 执行、专用安装/布局管理体验、商城、跨浏览器端到端验证和独立安全审查仍是后续工作。
### R3.3:自定义插件运行时(生产路径已接入,安全验收未完成)
授权、摘要校验、Wasm 生命周期、生成 UI 渲染、插件 CSS、权限化数据投影、首版宿主动作桥和 worker 资源治理已连到 WebClient,并通过本仓库 612 项测试、服务端构建和 Web 生产构建。生产路径只运行有界 Wasm;JavaScript 插件继续关闭。该运行时已能表达作者自定义的标准 HTML/SVG 节点树、包内 CSS、本地状态和受权限限制的 TeamSpeak 动作,但跨浏览器端到端验证和独立安全审查尚未完成,因此不能称为已完成的全量插件平台。
- v4 包格式的首个节点已落地:客户端和服务端共用 `plugins.json` 描述校验器,校验插件 ID、版本、页面、模式、权限、入口/样式/素材路径与重复 surface;客户端分开缓存插件文件,服务端校验文件存在和大小,并对文本入口/样式验证 UTF-8。
- 新增插件本地授权的安全基础:SHA-256 摘要绑定插件描述和所有声明文件,授权记录同时绑定皮肤/插件版本、API 版本、摘要与权限策略版本。任一代码、样式、素材、挂载模式或权限变化都会使旧授权不匹配。摘要不是发布者签名,亦不证明包来源可信。
- v4 入口支持 `.js` 与 `.wasm`;客户端对 Wasm 做固定导入/导出 ABI 预检,并按 MIME 类型分别缓存。服务端登记接受有大小上限的 Wasm 二进制,不运行它。
- v4 Wasm 适配器已接入 WebClient 的本地授权 UI 和页面生命周期。用户授权前不会创建 Worker;授权绑定皮肤版本、插件描述、入口、样式、素材及权限策略摘要。页面切换会关闭插件循环,撤销、运行失败或卸载会终止 Worker、移除插件样式和对象 URL,并恢复宿主页面。
- 已将有界 UI 循环接到生成节点树:Wasm 输出通过 schema 校验后由宿主渲染,不执行 HTML;只接收可信浏览器事件,组件状态和输入值继续限长。插件模式从 v4 描述继承,节点与 CSS 按插件 ID 隔离。插件 CSS 仅在明确授权且有有效输出后加载,并仅能引用全局皮肤资源和该插件自己的资源。
- 当前宿主只支持 Wasm 插件、`ui.surface.replace`、受限只读数据权限、可选的 `ui.input.read`,以及由现有权限表覆盖的 TeamSpeak 动作。数据投影不包含 TeamSpeak 地址、凭据或内部 SDK 对象;插件读取自己输入控件中的值必须单独声明 `ui.input.read`,而批准提示会说明浏览器自动填入的值也可能被读取。动作只能作为可信 UI 事件同轮 Wasm 输出中的单个效果提出,宿主再复核插件权限、当前批准状态、动作参数和会话可用性。JavaScript 插件与未实现的控制权限会显示为未支持状态,不会执行。
- 插件访问弹窗支持逐页批准、暂不启用、查看/撤销本皮肤的全部授权,并为 surface 提供切回标准界面和恢复内置皮肤入口。授权摘要或插件文件校验失败时关闭运行,不执行代码。
- 继续新增 opt-in 的插件协议,不给旧 v1/v2/v3 包追溯增加代码执行能力;同一皮肤可将界面分成多个独立、可排序、可显示/隐藏、可单独授权和回退的插件。
- Wasm 插件输出不再经过 v3 的固定标签、属性和数据绑定注册表:可生成标准 HTML/SVG 标签与普通属性,使用插件专属 CSS、图片、有限本地状态和命名事件回调;渲染由宿主创建,危险标签/属性、外部资源和自定义 Web Component 行为被拒绝或惰性替换。读取哪些公开数据及请求哪些 TeamSpeak 动作仍由 manifest 权限表限制;宿主控件目录只是可选的可信原生组件。
- v4 每个插件现有独立稳定的可编辑布局根,插件容器与插件根使用 Grid,使既有每皮肤、每设备布局编辑器可以分层调整插件整体和内部节点的顺序、位置、尺寸、显隐及安全外观;覆盖保存在本地宿主状态。widget 的可选 `mount` 字段现在可选择与页面匹配的公开宿主槽位;旧包未声明时继续挂在页面级插件宿主,surface 不能声明槽位。插件 ID、组件 ID 与布局根使用无碰撞标识。CSS/插件沙箱边界保持独立。
- 插件对 TeamSpeak 的读取和操作经明确列举的权限、脱敏投影和宿主能力桥接;命令总由宿主校验参数、当前会话和权限。双击等事件只改变插件化界面的触发方式,不更改 TeamSpeak 协议,也不影响未启用该插件的其他皮肤。
- 沙箱架构已选择为有界 Wasm 解释器运行于可终止的独立 Worker。此前 iframe 可通过自身导航外带获批数据,因此否决在有 DOM 的 iframe 中直接执行作者 JavaScript;JS Worker 因缺少硬内存配额仍不进入生产。此决定及触发原因保留在下方问题记录中。
- 已有 JavaScript 安全原型把作者代码放在没有 DOM/导航上下文的 data Worker 中;由于 JS Worker 没有硬内存上限,它仍不在生产执行。v4 Wasm 已通过有界解释器、通用节点树/CSS、命名事件回调和生产页面生命周期满足作者自定义界面的基础需求;后续重点是压测、跨浏览器验证和独立审查,不退回固定原生控件目录。
- 生产 Wasm UI 输出支持 schema v3/v4/v5/v6:v4 提供标准 HTML/SVG、普通属性和包内图片;v5 增加安全事件名到作者处理器 ID 的映射与本地状态;v6 可在事件触发的同轮输出中提出一个经插件权限校验的宿主动作。节点/组件/属性/文本仍有硬上限,危险加载、导航、脚本和事件属性会被拒绝。要求瞬时浏览器用户激活的能力仍须由可信宿主控件提供,并在真实浏览器验证。
- 插件生命周期已有批准前不加载、版本/内容变化重新确认、页面切换关闭、撤销销毁、超时/输出限额、错误恢复和旧包兼容;读取权限覆盖当前登记的数据类别,动作只允许现有 permission/action 表内能力。仍需做资源耗尽压测、跨浏览器端到端测试和独立安全审查;商城和专用插件管理体验留到管理员面板重做阶段。
- 复核零新增预算约束:插件及本地素材随皮肤包分发,不依赖 CDN、外部脚本托管或付费沙箱服务。
#### R3.3 问题记录
- 首个 v4 沙箱候选把 opaque-origin iframe 当成了“无网络”边界。复核浏览器规则发现沙箱 frame 仍有自己的文档和 URL 导航能力,`allow-top-navigation` 仅控制顶层页面;当前 MDN browser-compat-data 也没有 `navigate-to` 指令条目。因而 `connect-src 'none'`、禁用表单/弹窗和 CSP 元标签不足以证明获批数据不会通过 frame 导航外传。否决 iframe 直接执行作者 JS 的方案;JS Worker 仍因缺少硬内存上限保持生产关闭。之后改用有界 Wasm 解释器承载作者逻辑,并由可信宿主创建/校验通用自定义 UI 树与 CSS。
- Wasm UI 输出原先经过扩展校验后又送入 v3 固定标签/属性解析器,导致打开节点协议时整份扩展 UI 被悄悄丢弃。现改为分别校验基础皮肤和生成输出,只在组件 ID 不冲突且合并数量有界时组合,并额外把自定义标签渲染为惰性 `div`;生产 WebClient 已通过 v4 宿主渲染此输出。
- 运行时 UI 宿主最初将 `components: []` 占位文档交给要求至少一个组件的皮肤解析器,导致只有运行时插件的界面不会进入合并渲染路径。现仅在存在动态输出时把该内部空占位识别为 v3 容器;普通导入文档仍要求有效组件。
- 动态输出曾受 16 KiB 与展示标签/属性双重限制,复杂语音工作区难以由作者节点表达。现把单次输出提高到与组件包一致的 256 KiB,并接受普通标准 HTML/SVG 名称和普通属性;脚本、嵌入浏览器、外部资源/导航、事件属性及行内 CSS 仍通过明确拒绝列表保持隔离,样式走已隔离的插件 CSS。需要继续做浏览器端到端安全审查与结构上限压测。
- 一次性 Wasm 运行先前没有宿主发回本地界面状态或交互事件的入口。现增加每次调用只读一次、64 KiB 封顶的 `ui_input_read`、输出 schema v5 命名回调和生产 UI 重跑循环;宿主事件只传安全字段,不信任作者可伪造的“用户手势”标记。WebClient 摘要授权、页面生命周期、生成 UI 渲染、插件 CSS 装载、权限化只读数据投影及全局资源治理均已接入。现有首版动作桥允许同一可信事件触发的 Wasm 调用提出一个宿主动作;运行时插件整体及其节点现可本地排序。仍需真实浏览器验证瞬时手势行为并完成独立安全审查。
- 初次接入时,v4 surface 授权 UI 曾只列出权限却无法控制真实运行;循环关闭也没有联动移除 style 节点和对象 URL。现将授权状态绑定到实际启动路径,并在撤销、换页、失败、卸载时统一清理;v3 与 v4 对同一页声明 surface 时在导入阶段拒绝,避免两个整页 UI 互相覆盖。
- 运行时输入事件此前会默认把插件输入框的值发回 Wasm,清单没有独立同意项。现增加 `ui.input.read` opt-in;未批准时只传事件元数据,文本与勾选值不跨边界。授权 UI 显示权限用途,并提示浏览器自动填充值也可能暴露给插件;密码、文件、隐藏字段仍被拒绝。
### R3.4:声明式自定义节点布局编辑(已实施)
- 发现本地布局编辑器只登记了 WebSpeak 静态组件;皮肤 `components.json` 中自定义元素能用 CSS 排版,但不能由用户逐项移动、改尺寸或隐藏。
- 为每个自定义组件根和每个实际 DOM 节点生成带 page/component 的动态布局 ID,接入现有每皮肤、每设备的本地覆盖、撤销/重做、导入导出和恢复流程。
- 修复 v4 插件组件此前因布局 ID 包含插件和组件两层身份、未被动态注册器识别而无法编辑的问题;使用长度有界的组合标识后,插件布局根、组件根与子节点都能复用同一套本地覆盖。
- 显式 `part` 名称用于保持关键节点覆盖稳定;未命名节点采用组件树路径,树结构调整可能改变对应覆盖。声明式可操作节点仍按至少 44 px 触控目标进行校验。
- 本节点扩展的是已授权渲染的皮肤 UI;v4 插件布局根、组件根与节点现复用本地位置、顺序、尺寸和显隐编辑器。专用管理界面及独立安全审查仍未完成。
### R3.5:插件语义挂载槽位(已实施首版)
- `plugins.json` 为 widget 增加可选 `mount`;共享解析器按公开页面校验槽位,surface 继续直接组成页面,不接受 mount。未声明 mount 的旧包继续挂在页面级插件宿主。
- WebClient 在首页头部/内容/页脚,以及语音服务器栏、工作区头部、语音活动、聊天、频道成员面板、音频 dock、移动导航和全局浮层提供稳定锚点。插件根由固定槽位映射挂入;不能指定任意 CSS selector 或管理员页面。
- 插件 mount 字段纳入 SHA-256 授权摘要,避免修改挂载位置沿用旧批准。插件 CSS 和本地布局覆盖仍控制实际外观、尺寸、排序和隐藏。
- 发现并记录的问题:挂载锚点会随首页/语音页切换、surface 替换和连接模式条件渲染而暂时消失;宿主须在 DOM 更新后重新查询锚点,缺失时回退,防止插件被 Teleport 到脱离页面的旧节点而看似丢失。尚需补充真实浏览器切页与 surface 覆盖验证。
### R3.6:插件运行资源治理(已实施首版)
- WebClient 对所有运行时插件共用 FIFO Wasm worker 管理器:同时执行最多 2 个任务,等待队列最多 64 项,最长等待 120 秒。这样单次解释器上限不再被最多 64 个插件无界并发叠加。
- 切页、撤权或宿主卸载时会取消排队任务;活动任务沿用原有 worker 终止流程。队列满或等待超时会以明确的运行错误停止该插件,不扩大权限或绕过执行限制。
- 为队列顺序、容量、取消、重复释放和超时补充了单元测试。Wasm 已在生产构建开放;该节点完善了运行资源边界,但不代表独立安全审查已完成。
- 当前授权页中的“发现”路由展示了陪玩匹配、店铺列表、排行榜等运营内容;这些页面明确排除在 KOOK 语音客户端复刻范围之外。
### R3.7:完整 surface 的状态和表单交互(已实施首批)
- 复刻样例暴露了 v3 声明式界面的两个实际缺口:条件只能和静态常量比较,不能把用户选中的行与重复数据关联;宿主动作也被禁止绑定到提交后的 `change`,导致自定义滑杆等控件只能显示、无法驱动 TeamSpeak。
- 扩展 schema v3 条件,使其可将本地状态与权限化重复项字段比较,并可针对有读取权限的公开集合声明空态。v1/v2 不接受这些新增字段,既有包继续保持原边界。
- 允许 `change` 上的宿主动作,保留 `input` 仅更新本地状态的规则;滑杆松手、选择器提交等已提交交互可以调用权限内动作。WebClient 音量入口接受浏览器范围控件提交的数值字符串并在宿主端校验和夹限。
- Harbor Voice 首次把聊天消息/输入框、麦克风/扬声器/音量/断开、悄悄话和频道选中态改为皮肤自有结构与 CSS;单击仅选中,双击复用现有 TeamSpeak 切换流程。屏幕采集和实时视频仍由可信宿主控件执行,皮肤可重排并完全换肤。
- 已为条件解析、集合空态、表单事件及 Harbor `.wskin` 结构补回归测试;仍需在真实语音会话中验证控件行为和桌面/移动视觉效果。
### R4:整页皮肤界面和宿主控件组合(核心路径已接入,完整验收待完成)
- components.json schema v2 引入、schema v3 继续支持 `mode: "surface"`,允许替换首页或语音工作区的完整可见页面;旧 schema v1/v2 继续兼容。
- v3 surface 继续兼容受限节点、受控 CSS、公开数据绑定及白名单动作;需要自定义本地逻辑或不受 v3 固定节点表约束时使用 v4 Wasm 插件。
- 整页替换要求用户单独批准 `ui.surface.replace`;页面权限确认、撤销入口和恢复控件由宿主绘制。
- 可选宿主控件 ID 包括连接表单、皮肤/语言选择器、频道成员面板、语音成员卡、聊天、音频控制、屏幕共享、悄悄话、性能面板和退出控件。控件只在 WebSpeak 内执行,作者代码无法读取其私有状态;每个有状态控件每页仅可挂载一次。自定义声明式元素不受此注册表限制。
- 为完整定制常用服务器栏提供脱敏的收藏/历史列表与宿主切换动作;地址、密码和身份材料仍留在 WebSpeak 内。
- 页面权限确认、撤销入口和“返回标准界面”控件在皮肤 CSS 作用域之外。页面替换被拒绝或退出时,原生首页/语音工作区重新显示。
- 补充导入、旧包兼容、页面替换、权限拒绝/撤销、宿主控件及皮肤切换回归。
- 已提供 v3 首页/语音工作区 surface 样例及 KAAK 语音外观样例;它们验证现有格式,不代表插件系统目标已完成。KAAK 不引入发现、广告、陪玩、活动或商城页面。
- KOOK 参考皮肤只实现语音客户端体验;不复制运营、广告、陪玩、活动和商城页面。当前发现页确实把陪玩匹配、店铺卡片和推荐内容放在独立发现工作流中,这些都不纳入客户端复刻。只有能实际查看的公开/授权界面才作为视觉依据。
#### R4 问题记录
- 初版 surface 可以在没有任何数据/API 权限时直接替换页面,安装皮肤即可能显示仿制界面。现要求 surface 额外申请 `ui.surface.replace`,用户批准前继续显示 WebSpeak 原页面,并覆盖拒绝与撤销路径。
- surface 的“恢复内置皮肤”按钮误接到仅用于皮肤加载错误的回退函数,正常皮肤下点击无效。已改为明确切换到当前主题对应的内置皮肤,并增加授权/撤销回归。
- 初版自定义服务器栏只有收藏数据,缺少最近连接项。新增 `servers.quickList` 和宿主切换动作,使用不透明令牌,不下放目标地址或凭据。
- 收藏名/最近连接显示名有时会直接等于服务器地址;投影数据前增加地址匹配与泛化标签,避免通过“显示名”字段间接暴露连接目标。
- 已获准进入 KOOK 服务器前两个语音房间。结合可访问结构和截图确认:左侧为服务器轨道与频道树,中间继续显示当前文字频道聊天,右侧是在线/离线成员栏,左下连接卡显示频道、信号、离开、屏幕共享与音频控制;自己的语音成员项挂在频道行下。进入与切换通过再次点击频道完成,麦克风状态保持关闭。未发消息、未使用管理员功能,也未记录房间标识、成员名单或聊天内容。退出后语音质量反馈提示已关闭。陪玩店、活动通知、广告及其他运营页面不作为参考。
- 用户指出“有限自定义”与目标不符。核查确认 v3 固定标签/属性白名单、六种可重复数据集、模板插值和有限宿主动作不足以实现目标。该差距已由 R3.3 的 v4 Wasm UI 生命周期、通用安全节点树、插件 CSS 和命名事件回调补齐;跨浏览器验证及独立安全审查仍待完成。
- 已确认 schema 支持 `dblclick`。KAAK 频道行现在只在双击时请求宿主加入频道;这属于单个皮肤包的界面映射,其他皮肤与 TeamSpeak 协议保持不变。
## 下一阶段
### R5:通用组件作者编辑器与皮肤系统稳定门禁(进行中)
- 在开始移植任何外部语音客户端界面前,先完成皮肤系统自身的可用性和稳定性。此顺序由用户明确指定;系统完成后,参考皮肤阶段只允许为具体兼容问题做小修。
- 当前已接入本地组件编辑器首批能力:新建/复制/删除/排序组件,选中组件树节点,添加/复制/删除/排序节点,编辑完整组件或节点 JSON,撤销/重做,以及按皮肤 ID 和版本本地保存、导入导出 components.json。没有组件文件的皮肤也可以从空 schema v3 文档开始;复制节点时会重新生成稳定布局标识,避免两个节点共用同一编辑目标。
- 编辑器导入、每次保存和运行时渲染统一复用 components.json schema 校验。危险标签/属性、未注册数据路径、未声明权限、越权动作、重复状态型宿主控件、超深或超大的树都必须拒绝;本地编辑不能赋予包外权限,也不能访问管理员页面、服务器地址、口令或身份材料。
- 存储现按皮肤 ID 和版本分键;单份损坏数据可以单独清除并恢复原包,不影响其他皮肤。宿主保留的 data-ws-* 属性不会由作者节点写入渲染 DOM。
- 编辑器操作按钮和选择器现在保留至少 44 px 触控高度,支持 Escape 关闭并在打开/关闭时移动焦点。窄屏面板已改用安全区锚点,并在支持时依据动态视口高度限制面板,降低虚拟键盘遮挡编辑区的概率;仍需在真实 Android/iOS 浏览器键盘弹出场景验收。两个宿主作者编辑器均 Teleport 到 body,并共用顶层提升逻辑;支持 Popover API 的浏览器中,宿主编辑器进入浏览器顶层,皮肤组件不能创建或触发 popover 来覆盖它。旧浏览器保留普通固定定位和最高层级回退,仍需实际浏览器矩阵验收。权限确认与恢复入口也位于皮肤 CSS 作用域之外。组件新增权限仍由宿主按既有权限机制要求批准;删除整页 surface 后应自然回到 WebSpeak 页面和宿主恢复控件。
- 稳定门禁至少覆盖:组件/节点完整 CRUD 与撤销重做;导入导出往返;空组件文档;旧 schema v1/v2 只读兼容并在首次编辑时安全升到 v3;存储按皮肤版本隔离且坏数据可独立恢复;非法或越权文档不保存、不渲染;页面切换、皮肤切换及恢复入口不丢失。
- 2026-10-10 的统一验证通过:645 项测试通过,服务端 TypeScript 构建、前端类型检查与 Vite 生产构建通过。作者数据层测试已纳入根测试门禁,并补充连续复制时的布局 ID 冲突检查;门禁发现根节点复制 API 可返回无法插入树的孤立节点,现已在共享 CRUD 函数中拒绝。编辑器到渲染出口的集成回归已证明组件和节点的新增、复制、排序、修改、删除能即时更新页面预览;拒绝授权、增加组件权限后的重新同意、撤销授权或删除最后一个已授权 surface 都会安全恢复宿主页面,未批准的 surface 不会显示。删除树中最后一个图片引用节点后资源 URL 会及时释放,重新添加节点和 outlet 销毁也有集成回归。随后补查发现宿主作者编辑器可能被皮肤 CSS 的高层级覆盖,现已将组件编辑器和布局编辑器都 Teleport 到 body,并在支持 Popover API 时提升到浏览器顶层;v3/v4 皮肤组件都不能声明或触发 popover 或 popovertarget。回归覆盖编辑器位于皮肤根外、无 Popover API 时的固定定位回退、损坏数据的界面恢复、v1/v2 包首次编辑升级到 v3,以及组件文件导入后经界面导出的往返。根皮肤 CSS 与 v4 插件 CSS 现在共用前后端同一校验器,覆盖选择器作用域、转义后的 url()/local()、远程资源和包内素材路径;服务端会在保存皮肤包前执行相同规则。随后验证宿主拒绝 Wasm 输出时不会提交未展示的组件树,并以 2,000 个并发请求压力检查全局 Wasm 调度器的 2 个运行槽、64 个排队槽、溢出拒绝、FIFO 排空及队列计数最终归零;另有回归确认执行超过期限的 Worker 会被宿主终止并释放句柄。真实 Wasmi 解释器还接受了 240 KiB JSON 输出,并在复制前拒绝 256 KiB + 1 字节的输出。更新后的全量 645 项测试、服务端 TypeScript 构建、前端类型检查与 Vite 生产构建再次通过。这仍不代表真实窄屏作者体验、跨浏览器行为或独立安全复核已经验收。
- 随后补查发现节点树把根节点路径与“组件级编辑”都编码为空字符串,导致根节点虽可通过组件 JSON 间接修改,却无法从树中选中并用节点编辑器直接更新。现用独立 `root` 选择键区分两种状态,并补了界面回归,证明根节点可以选中和替换;组件/子节点操作不变。编辑器与共享 CRUD 定向测试 18 项通过;随后统一验证 645 项测试、服务端 TypeScript 构建、Vue 类型检查和 Vite 生产构建全部通过。
- 后续检查发现“添加子节点/同级节点”仍固定生成 `div/span`,其他元素只能手写 JSON,降低了任意组件的直接编辑能力。新增节点类型选择器,复用 schema 导出的安全 HTML/SVG 元素清单,也可直接插入文本节点;每次保存仍经过同一组件 schema、权限与属性校验。组件树回归覆盖根替换、直接插入 `button` 和文本节点,并逐项验证选择器列出的所有安全元素从新增、保存、实时预览、稳定布局目标到删除都能走通;同时确认节点排序及撤销/重做会同步更新组件文档与预览顺序。SVG 根和分组节点也使用合理的初始结构。随后补充布局运行时回归,验证任意组件子节点的本地位置、尺寸、显隐覆盖生效,交互节点仍保留 44 px 最小触控目标。最新统一验证为 647 项测试全部通过,服务端 TypeScript 构建、Vue 类型检查和 Vite 生产构建均通过。
- 曾怀疑客户端接受 v4 包级 `layout.json` 而服务端未读取。重新对照后确认服务端与客户端都解析并校验该字段,服务端测试也已覆盖有效布局、缺失文件和未注册布局 ID;该疑点已排除,无需代码修复。此后新增的布局集成回归专门覆盖任意组件子节点,避免把根节点支持误当成完整节点布局支持。
- 组件渲染器原先只按素材路径缓存 Blob URL,切换皮肤后同名图片可能沿用旧皮肤素材,旧 URL 也会一直留到卸载;现改为同时绑定 Blob,并在资源替换、皮肤切换或组件卸载时释放。对应缺失素材和换包回归已加入自动化验证。
- 真实浏览器实测完成 ILLUSIA v1 样例作者流程:修复旧 schema 解析时自动补入的 `mode: widget` 被首次编辑升级器再次拒绝的问题;组件编辑器现可挂载,并已在 390 px 窄屏实际新增/删除组件和节点。组件与布局编辑器在内置 Chromium 中均检查了 44 px 触控目标、Escape 关闭和焦点返回;组件编辑器另在 390×500 的键盘高度模拟视口确认面板仍可滚动、关闭控件可见且无横向溢出。测试编辑已清除。合并本轮改动后的全量验证通过:647 项测试、服务端构建、前端类型检查和 Vite 生产构建通过。该浏览器检查只覆盖当前内置 Chromium;Android/iOS 真实虚拟键盘、Edge/Firefox/Safari 矩阵及独立安全复核仍未完成。
- 随后发现声明式组件本地状态只按皮肤 ID 和组件 ID 缓存,会在切换皮肤版本时串用,也可能在组件删除或撤权后被后续重新启用恢复。现按皮肤 ID、版本、组件命名空间和组件 ID 隔离,并在组件退出当前授权渲染集合时清理;状态键删除或类型变化也会清除/重置,类型不变的用户值保留。集成回归覆盖版本切换、删除后重建、状态 schema 修改、权限扩展重新同意和撤权后再批准。最新统一验证为 648 项测试通过,服务端 TypeScript 构建、Vue 类型检查与 Vite 生产构建通过;`git diff --check` 通过。浏览器验收按用户确认采用侧栏内置 Chromium,不要求多机或跨浏览器矩阵;独立安全复核仍作为更广泛插件安全工作的单独事项记录。
- 随后在隔离的内置 Chromium 本地应用实例中端到端操作编辑器:从 ILLUSIA 当前包新增组件,组件立即进入首页预览;修改组件名称、根节点为 `article` 并添加 `button`,再把子节点改为 `strong`,树视图与预览同步更新;删除子节点和组件后,首页回到宿主页面。最后使用“清除本地修改”确认 ILLUSIA 包数据已恢复,临时测试覆盖已清空。用户确认这项侧栏浏览器验收可作为通过标准,不要求多机或 Edge/Firefox/Safari 矩阵;本目标的 CRUD 浏览器验收已通过。
- R5 完成门槛包括:编辑器能完整管理组件和节点;更新后页面即时预览;导入、导出、版本隔离、坏数据恢复及旧格式迁移可靠;客户端与服务端对每种包格式采用一致校验;键盘与窄屏作者流程可用;授权拒绝/撤销、恢复原生页面、插件销毁与资源回收通过针对性验证;浏览器行为和资源边界在侧栏浏览器中验收,独立安全复核单独记录,不要求多机矩阵。
- R5 门槛通过前暂停新增参考皮肤功能和视觉扩展。R6 现有样例作为回归材料保留,之后只因明确的样例阻塞做小范围系统修补,不再反复重做通用架构或重新采集参考页面。
### R6:KOOK 语音客户端体验复刻(等待 R5 通过)
- 已在用户授权范围内查看首两个语音频道;记录频道树、嵌套语音成员、中心聊天、成员栏与左下语音控制坞。麦克风保持关闭,未发送消息,也未使用管理员操作。
- Harbor Voice `.wskin` 已有首页和语音工作区 surface。本批由皮肤组件负责频道选中、消息渲染/输入和悄悄话界面;底部麦克风/扬声器嵌入经权限门控的 WebSpeak 音频控件,使用户继续使用既有灵敏度设置。频道单击仅选中,双击才通过宿主现有流程加入,屏幕采集按钮和视频流由 WebSpeak 执行并仍可由皮肤外观覆盖。频道缩进读取现有公开树深度,成员显示说话/静音/离开状态,服务器栏底部展示当前 TeamSpeak 昵称,未扩展宿主数据字段。修改源码后可用 `npm run skin:harbor:build` 重建导入包。
- 移动布局保留服务器/频道导航、聊天、成员和语音控制;频道下的成员嵌套在窄屏隐藏,避免横向频道栏被撑高。本轮在隔离预览中确认首页 surface 在桌面视口和 390×844 窄屏下均无裁切;语音 surface 尚未用 TeamSpeak 会话做端到端视觉验收,授权撤销和宿主恢复也仍待浏览器验收。
- 打包验证发现 `.wskin` 导入器拒绝包内 `README.zh-CN.md` 等未声明文件;说明文档需留在源码目录外,压缩包只收录清单及声明资源。
- 只复刻语音客户端体验;发现、陪玩、活动、广告、商城和管理后台页面明确排除。只记录可实际访问的授权页面,不保留服务器/房间标识、成员名单或聊天内容。
### R7:作者体验与兼容性
- 已提供可导入的完整 surface 示例,记录权限清单和桌面/移动布局:[`open-voice-surface.wskin`](./examples/OPEN-VOICE-SURFACE.md)。
- 对首页连接、收藏快速切换、频道切换、成员区、聊天、音频和屏幕共享进行端到端验收。
- 检查产品支持语言、键盘焦点、触屏、拒绝授权、撤销和恢复路径。
- 更新皮肤开发技能、公开控件索引和各语言用户文档。
### R8:皮肤商城与管理员面板重做时交付
- 商城目录、发现、安装、更新、回退、下架与撤销同管理员面板改造一起设计;后台本身保持不可皮肤化。
- 首选人工审查的静态清单和 Release 附件,列出来源、版本、许可证、包校验值和组件权限。
- 对目录不可用、版本冲突、撤销及离线场景提供可靠回退。
- 维持零新增服务费用;任何无法在现有免费资源内解决的规模问题,重新确认预算后再处理。
- 不默认加入评分、评论、付款、付费托管或第三方账号接入。
## 迁移和验收
- v1、v2 皮肤包继续按原有规则校验;皮肤包 schema v3 才有开放 CSS 和组件能力。
- components.json schema v1/v2/v3 继续导入;schema v2 起可声明 surface 和宿主控件,schema v3 扩展自定义交互与权限动作。
- 未知版本、字段、权限、数据路径、动作、控件和素材类型都拒绝导入;v1–v3 的未知节点/属性拒绝,v4 Wasm 输出接受经过语法与危险能力检查的通用标签/标量属性,并将自定义标签降为惰性占位。
- 每次将相关修改合并成一批统一运行验证,避免每个小节点重复跑全套构建。
- 管理端、运营页面和语音服务内部行为不因开放皮肤系统而扩展。
+114
View File
@@ -0,0 +1,114 @@
# 更开放的皮肤系统规格
状态:v1/v2/v3 是兼容实现,不是“万物皆插件”目标的完成态。v4 有界 Wasm 运行时已在生产构建开放,包含摘要绑定授权、页面生命周期、隔离的动态 UI/CSS 渲染、错误恢复、语义挂载槽位、首版 TeamSpeak 动作桥,以及按清单权限筛选的公开数据投影;频道、成员、聊天、收藏/历史与音频/共享状态可通过有界输入快照供插件自绘。普通 JavaScript 仍不执行。跨浏览器端到端验证和独立安全审查仍未完成。阶段记录和问题节点见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md),当前包格式见[皮肤开发规范](./SKIN_DEVELOPMENT.md)。
## 1. 目标与范围
完整目标中,皮肤作者可以用自己的插件组件、DOM、CSS 和本地逻辑排列、替换、隐藏或重做公开客户端界面中的任何视觉元素,也可以重建首页和完整语音工作区。连接、频道、聊天、音频、收藏/历史、共享等基础能力始终由 WebSpeak/TeamSpeak 宿主保留;皮肤能替换其展示和交互入口,但不能删除或篡改底层业务能力。宿主恢复入口、权限管理和安全提示位于皮肤之外,任何插件失效、拒绝授权或撤销后都能回到原生可用界面。
当前 v1/v2/v3 只能达到该目标的一部分:v3 组件依赖有限标签、属性、数据和动作白名单;v4 Wasm 已接入授权生命周期、宿主渲染、受限 UI 事件回路、按读取权限筛选的数据投影、首版 TeamSpeak 动作桥,以及插件布局根、组件根与节点的布局覆盖。插件整体和内部节点均可在 Flex/Grid 父容器中分别排序;widget 可声明公开页面挂载槽位,surface 可直接重做公开页面。v3/v4 包可以通过可选 `layout.json` 提供作者默认布局,用户本地覆盖单独保存;v4 专用插件安装/管理界面、Wasm 作者工具和跨浏览器验证仍未完成,独立安全审查也尚未进行。本规格区分已实现行为与后续工作,不以当前限制重新定义完成态。
适用页面为连接首页、语音工作区和公开演示页。管理员面板及其数据、管理 API 明确排除,不读取皮肤包。语音服务的运营、广告、陪玩、活动和商店等页面不属于语音客户端皮肤范围。
### 可移植包与运行时边界
`.wskin` 是皮肤完整的分发单元:样式、公开页面/组件结构、文案、布局、美术资源、插件描述及允许的本地逻辑均随包携带。皮肤任务不得为单款皮肤修改或部署核心客户端、服务端或宿主控件。作者使用已经发布的版本化 schema、公开数据字段、宿主控件和受权限保护的动作;实例通过导入同一包获得同一款皮肤。
连接会话、服务端配置等动态运行时数据仍由宿主提供,并通过明确版本的公开上下文交给皮肤;TeamSpeak 网络、身份凭据和敏感行为仍由宿主保管。若通用协议缺少所有皮肤都可复用的数据或动作,应先作为独立的平台能力定义稳定字段、权限、用户激活要求、兼容策略和测试,再发布运行时;之后皮肤只在 `.wskin` 中消费已发布接口。禁止把单款皮肤的 UI 或业务判断放进宿主控件注册表。
同一兼容 WebSpeak/API 版本导入相同 `.wskin` 文件时,无需实例单独部署前端改动即可使用。兼容范围由 `minAppVersion`、组件 schema 与插件 `apiVersion` 决定;实例数据、管理员设置、视口及用户授权属于运行输入,不打包进皮肤,也不应导致皮肤源码分叉。
## 2. 包格式与执行模型
皮肤格式按版本区分:v1 保持视觉皮肤兼容;v2 提供有界布局 JSON;v3 使用 open-skin 清单、受控 CSS 和声明式 components.json;v4 在 open-skin 包中增加必需的 plugins.json 和插件专属 JS/Wasm/CSS/素材路径。客户端与服务端共用 v4 插件描述校验器,并检查引用文件与大小;客户端额外验证 Wasm 入口的导入/导出 ABI。生产环境只在用户按摘要授权后执行受限 Wasm;JavaScript 仍仅校验和缓存。v1/v2 的 CSS 继续拒绝布局类声明,旧包不会因升级而获得新权限;v3/v4 才允许 CSS 控制公开页面中的布局、位置、尺寸、顺序、文字排版和显隐。
v3 自定义组件不是脚本插件。components.json schema v1 是既有格式;schema v2 增加 `mode: "surface"` 与宿主控件节点;schema v3 扩大自定义节点、嵌套、重复列表和声明式交互的边界,并增加映射到现有语音功能的动作。宿主仍解析固定元素/属性白名单、固定数据集合、简单绑定与有限动作,再由 Vue 创建节点。每个自定义组件根和每个有 DOM 的节点都会作为独立本地布局项,可移动、调整尺寸、改变外观或隐藏。节点指定 `part` 后使用该标识;未指定时使用树路径,树结构调整后旧的本地覆盖可能要重新设置。可操作节点保留至少 44 px 的触控目标。作者不必使用固定宿主控件目录,但 v3 仍不足以表达任意自定义 UI 逻辑和完整插件生命周期。管理员面板和演示页不能被 surface 替换。
宿主控件通过固定 ID 嵌入,始终由 WebSpeak 代码运行。当前可选注册表包括 `home.connection-form`、`home.connection-status`、`home.server-announcement`、`home.social-links`、`home.identity-provider`、`app.skin-switcher`、`app.language-switcher`、`voice.server-switcher`、`voice.server-header`、`voice.server-banner`、`voice.channel-tree`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls` 和 `voice.disconnect-control`。作者可以声明使用已发布的通用控件,但不得为单款皮肤改写或新增宿主控件;常规页面结构和视觉应由包内组件及 CSS 负责。每个控件在同一页面最多出现一次;未知 ID 或重复的有状态控件会拒绝导入。schema v3 的受保护控件会在导入时验证完整权限集合:音频控件要求 `audio.status.read`、`audio.microphone.control` 与 `audio.output.control`;聊天控件要求 `chat.channel.read` 与 `chat.channel.send`;成员卡片始终要求 `session.members.read` 与 `session.memberAvatars.read`;默认保留的屏幕共享成员操作要求 `voice.screenShare.read`、`voice.screenShare.control`,schema v3 可通过 widget 的 `options.screenShare: false` 同时隐藏共享状态和操作并移除这两项权限要求;性能卡片也可用该选项隐藏共享 WebRTC 指标;头像只在可信宿主控件内显示,不暴露给皮肤代码;屏幕共享播放器要求后两者;悄悄话控件要求 `voice.whisper.status.read` 与 `voice.whisper.control`;连接/断开控件要求 `voice.disconnect`。既有 schema v2 包仍按此前规则校验,`voice.screen-share-start` 则保留原有 `voice.screenShare.control` 要求。该控件仅限语音页;宿主按钮在可信点击处理器内直接开始屏幕采集,以保留浏览器要求的瞬时用户激活。作者可以不用这些控件,自行绘制界面并将点击、双击等事件绑定到公开数据与受权限保护的动作。`home.identity-provider` 是通用首页身份提供方入口,schema v3 必须提供 `options.identityProviderId` 和 `options.identityProviderLabel`;用户点击后宿主向通用身份提供方分发器提交稳定的 provider ID 与仅用于显示的名称。应用代码可以通过 `registerIdentityProviderAdapter` 注册宿主适配器;皮肤只能声明入口、不能注册适配器。当前未注册 MyTS 适配器,所以该按钮仍提示开发中;这只是通用接入接口,不表示 MyTS 登录协议或认证流程已经实现。
v1-v3 包不能提交 HTML 字符串、事件处理代码、JavaScript、WebAssembly、远程脚本、任意 URL、表单导航、浏览器存储访问或网络调用。v4 可携带本地 JS/Wasm/CSS;JS 仍只校验和缓存,Wasm 在生产构建中经本地摘要授权后运行一次性有界任务,并经宿主解析、渲染动态 UI。运行时支持 `ui.surface.replace`、限定的公开只读数据权限和首版宿主动作效果;投影前由宿主按插件清单过滤字段,总快照最多 48 KiB,`ui_input_read` 输入最多 64 KiB。动作效果限于可信 UI 事件触发的同一轮调用、单个动作,并复用现有动作权限与参数校验。所有版本都拒绝未知协议字段、权限、动作和数据路径;v1-v3 拒绝未知节点/属性,v4 Wasm 输出则对标签名做语法验证、拒绝具备脚本/导航/嵌入能力的标签与属性,并将自定义标签惰性渲染为普通 `div`。
自绘成员列表也可以按成员读取 `screenSharing` 和 `screenShareStreamId` 字段(需 `voice.screenShare.read`);`voice.joinScreenShare` 还需 `voice.screenShare.control`。完整页面替换后是否呈现共享标记/观看入口由皮肤组件树决定,宿主只会提供状态与受权限保护的观看动作。
### 2.1 插件协议(v4 包格式及有界 Wasm 生产运行路径已接入)
已实现的 v4 包描述为 `plugins.json` schema v1:每包 1–64 个插件,每个插件指定唯一小写 ID、语义版本、API 版本 1、`home`/`voice` 页面、`widget`/`surface` 模式、`plugins/<id>/` 下入口 JS 或 Wasm/可选 CSS、该目录中的图片/woff2 素材和现有权限表中的权限。入口扩展名决定默认运行时,也可显式写 `runtime: "javascript"` 或 `runtime: "wasm"`,且必须匹配扩展名。每页至多一个 v4 surface,且必须申请 `ui.surface.replace`;导入器也拒绝与同页 v3 surface 冲突。清单最多 256 KiB、插件入口最多 256 KiB、插件样式最多 512 KiB、每插件最多 32 个素材;引用文件必须存在且路径不重复。客户端与服务端复用同一解析器;客户端还对 Wasm 入口做固定 ABI 预检。SHA-256 摘要覆盖描述字段和入口、样式、全部素材;本机授权按皮肤、插件 ID 保存并绑定皮肤/插件版本、API 版本、文件摘要及权限策略版本。该摘要仅用于检测本机授权后包内容是否变化,不是发布者签名或来源证明。WebClient 已有逐页授权、Wasm 生命周期、schema 校验后的安全 UI 渲染和插件 CSS 装载;Wasm 只会在用户明确批准后运行,且生产执行受全局 worker 上限控制。动态 UI 可使用经过 manifest 权限校验的 `voice.screen-share-start` 宿主按钮;`voice.startScreenShare` 异步动作请求会被拒绝,屏幕采集必须由可信宿主按钮直接发起,以保留浏览器瞬时用户激活。
descriptor 通过可选 `mount` 字段定义 widget 的语义挂载位置;未设置时挂在页面级插件宿主。默认显隐、位置/尺寸和同级顺序不放进插件 descriptor,而由包级可选 `layout.json` 按 `skin.<page>.runtime_plugin_root_<plugin-id>` 等动态布局 ID 声明。通用布局编辑器可本地覆盖插件整体、插件组件根和其节点的位置、尺寸、显隐、安全外观及 Flex/Grid 同级顺序;用户本地覆盖优先于作者默认值。顺序只改视觉排列,不改变 DOM 与键盘焦点顺序。沙箱内代码不能改动其他插件的宿主容器或恢复控件。
v4 当前运行路径已不使用 v3 固定标签/属性/状态/动作表来构建插件 UI;插件可在受限输出协议内构建自定义 HTML/SVG 树、隔离 CSS 和本地交互,并把公开客户端页面替换或拆成可排序、显隐、独立授权和可回退的插件。危险的浏览器能力仍由标签/属性拒绝规则、字段限额与宿主权限桥约束;这不是不受限制的原始 DOM/JavaScript 环境。现有宿主控件只是可选的原生能力组件;连接/频道/聊天/音频等基础业务能力仍由 WebSpeak 保留、可由插件重新呈现,且始终能通过宿主恢复界面回到可信基础 UI。旧 v1/v2/v3 包继续按原验证与能力运行,不获得追溯性代码权限。
不能把有 DOM 的 iframe 当作无网络沙箱。opaque origin 可隔离父页面 DOM、Cookie 和本地存储,但嵌入式浏览上下文仍允许自身 URL 导航;sandbox 阻止顶层导航的规则不阻止 frame 自己导航。CSP `navigate-to` 不能作为跨浏览器安全保证,因此仅关闭 `connect-src`、表单、弹窗和外部子 frame 不能阻止通过 URL 导航外带已授权的数据。若未来 iframe 只充当宿主可信的 UI 容器,作者代码必须在没有 DOM/导航能力的另一个受限执行环境中运行;iframe 内不得直接运行作者 JS。
当前 JavaScript 原型由 opaque-origin iframe 承载一个无 DOM 的 data Worker,CSP 阻断其常规网络接口,Worker 消息不能导航外层页面;但 JavaScript Worker 没有硬内存配额,不能作为面向不可信公开皮肤的生产边界。Wasm 执行会先校验模块结构,再校验具体皮肤版本、插件、字节摘要和本地授权;每次运行使用可终止的有界解释器任务。用户批准后才启动,输出由宿主校验并创建安全节点,批准后才装载作用域限定的插件 CSS;切页、撤权和错误都会关闭任务并恢复基础页面。只读数据通过宿主白名单投影到 `ui_input_read`,不传递 WebClient 内部对象;来源权限来自已批准、摘要绑定的插件描述。数据变化会触发一轮新的有界执行。WebClient 另以 FIFO 队列限制单个页面实例的并发:最多 2 个活动 Wasm worker、64 个等待任务,等待超过 120 秒会拒绝执行;切页或撤权会取消仍在排队的任务。首版动作桥只接受可信 UI 事件同一轮 Wasm 调用提出的单个动作,并重新检查权限、参数和当前会话;浏览器瞬时用户激活不能跨越异步 Wasm 执行,因此 `voice.startScreenShare` 被拒绝,必须改用可信宿主共享按钮。仍需在支持的浏览器中端到端验收其余动作和资源边界,并完成独立安全审查。
作者逻辑不得直接持有宿主 DOM、网络、持久存储、TeamSpeak SDK 或原始媒体流。宿主只向独立、有界的执行环境提供按权限筛选的结构化数据和本地 UI 事件,并通过私有消息通道收发有界协议。读取插件输入框的用户值需要单独声明并获批 `ui.input.read`;未授权时事件仍可触发,但文本和勾选值不会传入插件。授权提示说明浏览器自动填充值也可能被读取;密码、文件和隐藏输入始终拒绝。当前运行时把可信 UI 事件与同一轮 Wasm 调用相关联,并只允许该轮输出一个动作效果;宿主随后复核清单权限、动作参数和当前会话。它没有可转移的一次性事件票据,也未证明异步 Wasm 执行后仍保留浏览器瞬时用户激活。后续协议仍需拒绝未知消息、跨插件转发、重放、过期事件票据、过大数据与未批准动作;不能信任作者逻辑自报“用户已点击”。
每个插件有稳定 ID、版本、入口文件、资源清单、页面/挂载点和细粒度 permission manifest。安装本身不运行代码;用户批准插件及权限后才加载;升级更改插件字节或权限后重新确认。撤销必须终止该插件的执行环境、关闭消息端口、清除临时数据和对象 URL;恢复按钮在插件宿主节点和皮肤 CSS 外。运行中断、加载失败、超时和更新均自动回到宿主基础界面。包内资源随 `.wskin` 本地分发,不要求新增 CDN、域名、账号或付费托管。
当前有界解释器 + 宿主 UI 桥接已在生产构建开放,但尚未通过独立安全审查。直接在 iframe 执行 JS 的候选已因自导航外传路径被否决。按用户确认,浏览器端到端验收以侧栏内置浏览器为准,不要求多机或跨浏览器矩阵;仍需测试恶意节点树、消息伪造/重放、CPU/内存耗尽、打包路径与浏览器崩溃恢复,并完成独立安全审查后再宣称更广泛的不可信插件安全边界通过。若浏览器无法保证必要的动作来源校验,则必须由宿主渲染对应交互控件或设计其他可信用户确认,不得退化为信任插件 JS。
每个组件只能声明 home、voice 或 demo 页面中的一个页面、一个有界的树和精确权限清单。components.json 全文不超过 256 KiB。schema v1/v2 保留旧上限(32 个组件、每组件 256 个节点、16 层深度、100 个重复行);schema v3 上限为 128 个组件、每组件 2048 个节点、32 层深度、250 个重复行、64 个本地状态值和 64 个动作。图片仅可通过包内 image 资源引用。文档字节上限仍优先生效,因此实际可用数量取决于包内容。
## 3. 可读数据和权限
现有 v3 组件权限按组件单独请求,用户在宿主确认界面查看用途后才启用。整页 surface 必须申请 `ui.surface.replace`,所以页面替换不会因皮肤包已安装而静默启用。授权按皮肤 ID、版本、页面、组件和权限策略版本保存;换版本或策略含义变化会重新询问。皮肤设置中的独立入口可查看和撤销授权;拒绝或撤销后对应组件不渲染、不触发动作。组件运行时本地状态按皮肤 ID、版本、命名空间和组件 ID 隔离,组件因删除、页面切换或权限不再满足而退出运行时后清除;修改状态定义时,已删除的键和类型变化的键清除或重置为新默认值,类型未变的现有值保留。
当前公开只读能力如下:
- session.status.read:连接状态、当前频道和显示名称。
- session.channels.read:公开频道树、频道名称、层级、当前人数、TeamSpeak 公布的频道人数上限及当前频道标志;不限人数的频道不显示上限,不包含服务器地址或频道密码。
- session.members.read:可见成员名称、由名称派生的首字标记、所在频道、在线状态、说话状态及本人标志;不提供成员头像图像。
- session.memberAvatars.read:允许可信 `voice.member-cards` 宿主控件显示当前可见成员的已缓存 TeamSpeak 头像;图像字节和 URL 不会传给皮肤声明树或 Wasm 插件上下文。
- chat.channel.read:当前公开文字频道中可见的消息。
- favorites.read:收藏项名称、类型、是否当前项和随机不透明本地令牌;不提供地址或凭据。
- servers.quickList.read:统一后的收藏和最近连接名称、当前项、分类与随机不透明本地令牌;不提供地址或凭据。
- audio.status.read:当前用户自己的麦克风/扬声器静音、噪声抑制和伴奏播放状态;不暴露音频数据。
- voice.whisper.status.read:悄悄话开关状态与已配置目标数量。
- voice.screenShare.status.read:当前用户自己的屏幕共享状态。
- voice.screenShare.read:当前可见共享的名称、来源、所有者显示名、音频标记和观看人数;不提供流内容。
当前宿主动作如下:
- session.copyInviteLink 需要 session.invite.copy,只复制当前公开服务器与频道的邀请链接;宿主会排除连接凭据。
- voice.joinChannel 需要 session.channel.join,只能请求加入当前页面公开可见的 TeamSpeak 频道,仍经过宿主和原有密码、权限流程。
- favorites.switch 需要 favorites.switch,只能让宿主按不透明令牌选择本机已有收藏并走原连接流程。
- quickServers.switch 需要 servers.quickList.switch,只能让宿主按不透明令牌选择本机已有收藏或最近连接并走原连接流程。
- chat.sendMessage 需要 chat.channel.send,只能发送到当前公开文字频道;不包括私聊。
- ui.setState 只修改该组件短暂的本地标量状态,不需要会话权限。
- v3 的 ui.toggleState 可切换该组件声明的布尔状态,不需要会话权限。
- v3 可在用户明确操作时切换自己的麦克风和扬声器静音、噪声抑制与伴奏、调整本地输出音量、打开音频设置、断开当前会话、设置自己的离开状态、启停悄悄话,以及开始/停止或加入/离开可见的屏幕共享;每项都需要对应权限,并继续走 WebSpeak 原有流程。`audio.toggleNoiseSuppression` 使用 `audio.microphone.control`,`audio.toggleAccompaniment` 使用 `audio.output.control`。
宿主控件节点只是把 WebSpeak 的原生界面放进皮肤布局,不向皮肤提供控件内部的数据对象。控件仍使用原来的连接、权限和用户事件检查;例如嵌入 `voice.chat-panel` 可以让用户继续使用原生聊天界面,但不会授予组件读取私聊内容的能力。
事件支持 click、dblclick、keydown/up、contextmenu、focus/blur、pointer 和 drag/drop 等受限事件;键盘动作仅响应 Enter、Space 或 Escape。输入和 change 事件不能调用宿主动作;focus/blur、pointerenter/leave、dragstart/over 这类被动事件只能改变组件本地状态,不能触发语音或其他宿主动作。敏感语音动作要求可信的明确用户操作。宿主再次检查当前频道、令牌、共享 ID 及动作参数;系统屏幕采集授权仍由浏览器/操作系统处理。皮肤不能读取原始音频或屏幕流、控制其他用户、读取身份密钥或调用 TeamSpeak 管理命令。
数据授权不是数据上传授权:组件没有任意联网或持久化 API,权限决定保存在本机。渲染进程不会把服务器地址、密码、身份私钥、访问令牌、Cookie、私聊、原始音频或屏幕流交给皮肤。
v4 插件应独立声明读取投影和宿主动作权限,授权键至少包含皮肤 ID、插件 ID、插件内容摘要/版本、权限策略版本和目标页面。插件升级、权限扩张或来源改变必须重新批准。读取数据由宿主按批准的字段即时投影;插件调用任何 TeamSpeak 动作时,宿主重新核权限、用户激活事件、当前会话和参数,不提供原生 SDK 对象。皮肤不获任意联网或持久化权限。
## 4. CSS 与基础组件
v1-v3 CSS 被重写到当前公开皮肤根节点;v4 插件 CSS 与宿主渲染的自定义 DOM 也限定在各自插件容器内,不运行作者脚本。插件 CSS 只有在用户批准该插件后才会装载。所有路径都不允许影响 `/admin/**`。页面权限提示、皮肤组件权限入口和“返回标准界面”控件由宿主放在皮肤插件/皮肤 CSS 之外,不能被作者样式隐藏。
v3 CSS 和 surface 可排列、替换或遮挡公开 UI,因此可能改变麦克风、退出、共享等控件的可见位置。宿主提供的“返回标准界面”和“恢复内置皮肤”控件以及组件权限确认和撤销入口在皮肤根节点之外;用户可立即退回 WebSpeak 页面,再用原生皮肤选择器切换皮肤。作者仍应在桌面和移动布局中保留语音操作的可达路径。
皮肤与 /admin/** 完全分离。不得将后台页面标记为公开皮肤页面,也不得通过资源、选择器或组件数据间接读取管理员内容。
## 5. 校验与回退
客户端导入和服务端登记都会校验 manifest、ZIP 路径、组件协议、所引用素材和文件限额;根皮肤 CSS 与 v4 插件 CSS 共用 CSS 编译器,校验语法、选择器作用域、包内素材路径和复杂度,并按 CSS 转义语义检查资源函数;v4 插件描述由共享解析器验证,JS 只作 UTF-8 和尺寸校验并缓存、不执行;Wasm 入口另行校验固定 ABI。生产构建中的 Wasm 生命周期有摘要授权 UI、可终止运行、动态输出解析、全局并发上限和插件样式清理。现有组件运行时会再次解析持久化的组件文档;无效输出不渲染。权限界面和恢复控件由宿主代码渲染。v3/v4 CSS 的作用域能降低跨应用影响,但 CSS 不是针对恶意脚本的沙箱。
皮肤载入错误不得清除用户布局或 TeamSpeak 会话。组件树为空、权限被拒绝或皮肤无效时,宿主本身和既有功能仍可由用户恢复。v4 每个插件需有独立错误边界;单个插件崩溃不能拖垮语音会话或其余插件,撤销必须立即销毁该插件运行环境。管理员后台仍沿用自己的样式和服务端管理流程。
## 6. 商城和预算约束
皮肤商城、公共目录和管理员面板重做不属于本轮实现,按路线图后续规划。未来优先使用公开 GitHub 仓库和 Release 附件等现有免费能力;若免费方案不能满足需求,需重新评估范围,不自动新增托管、CDN、域名或其他费用。公共目录不得包含内部服务器地址、密钥、测试节点或其他隐私数据。
## 7. 后续安全工作
- 扩展数据字段或宿主动作时,增加精确 schema、权限、明确用户事件约束和宿主侧运行时验证,不暴露内部 SDK 对象。新增宿主控件也必须登记固定 ID、明确页面和确认只在宿主内处理其私有状态;自定义声明式 UI 不应被限制为只能拼装这组控件。
- 对恶意输入、路径别名、拒绝授权、撤销、更新和皮肤切换增加测试;高敏能力必须单独设计。
- JavaScript Worker 运行时在生产构建保持关闭,因为它缺少硬内存配额。Wasm 解释器使用 64 MiB 容器上限、最多 4 MiB 扩展线性内存、10,000,000 燃料上限,外层 Worker 在 100 ms 后可终止执行;单个 WebClient 页面实例最多并发 2 个 Wasm worker,最多排队 64 个任务。
- Wasm 的 `env.ui_emit_json` 每次运行最多提交一次、最多 256 KiB 的 UTF-8 JSON。动态 UI 输出 schema v3 可用原声明式节点;v4 支持标准 HTML/SVG 节点、普通属性、隔离插件 CSS 和包内图片;v5 增加本地标量状态与事件名到处理器 ID 的映射;v6 可在可信 UI 事件触发的同一轮输出中提出一个宿主动作。生产 WebClient 经摘要授权后由宿主解析并创建节点,不把输出当 HTML 执行;自定义元素映射为惰性宿主 `div`,避免触发页面中注册的 Web Component。脚本、嵌入浏览器、外部资源/导航属性、事件属性、行内 CSS,以及可创建或触发浏览器顶层 Popover 的 `popover`、`popovertarget` 和 `popovertargetaction` 属性均会拒绝;作者样式通过包内隔离 CSS 提供。`env.ui_input_read` 每次 Wasm 调用最多读取一次、最多 64 KiB;本地状态和事件字段仍受限,公开数据快照最多 48 KiB,并经宿主读取权限映射与字段白名单投影。数据只存在于当前调用的输入中,不传 DOM/Event 对象或自报的可信标记。UI 循环可将可信事件或数据变化作为下一次有界 Wasm 调用输入,最多串行排队 8 项,并重新验证回调 ID 与组件状态归属。异步 Wasm 动作继续受插件声明权限和会话校验约束;`voice.startScreenShare` 必须走可信宿主控件,不能由异步动作桥调用。仍需完成其余动作的跨浏览器、资源耗尽测试和独立安全审查。
- 商城发布、签名、下架、更新和撤销设计与管理员面板重做一起验收,且保持零新增服务费用为默认约束。
+12 -4
View File
@@ -23,11 +23,12 @@ Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung kö
| Browserseitige Geräuschunterdrückung | Optionale Mikrofon-Geräuschunterdrückung in der Browseraufnahme, ohne zusätzliche serverseitige Audioverarbeitung. |
| Nachrichten und Aktionen | Kanal- und Serverchat, private Nachrichten, Anstupsen und Flüsterziele. |
| Desktop-Begleitton | Audio eines freigegebenen Fensters oder Browser-Tabs im aktuellen Kanal teilen. |
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele und widerrufbare Einladungslinks mit Ablaufzeit. |
| Administration | Ziele, Zugriff, WebRTC, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele, widerrufbare Einladungen sowie Import, Konvertierung, Prüfung und Export von TeamSpeak-3-Identitäten. |
| Administration | Ziele, Zugriff, öffentliche Medienadresse, IPv6-Kandidaten, Sprach-STUN, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
| Projektstruktur | In 0.2.6 wurden Sprach-Gateway, Sitzungsereignisse, Audio und Bildschirmfreigabe in Module aufgeteilt; Sprach- und Admin-Oberflächen in Komponenten, Composables und Dienste zerlegt und um Lebenszyklus- und Wiederverbindungstests ergänzt. |
| Skins | Geschützte Tages-, Nacht- und ILLUSIA-Skins sowie instanzverwaltete `.wskin`-Designs mit Aktivierungs- und Standardauswahl im Adminbereich. |
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
| Selbsthosting | Daten bleiben beim Betreiber; Docker-, Windows-x64- und Linux-x64-Bereitstellung sind verfügbar. |
| Selbsthosting | Daten bleiben beim Betreiber; Pakete für Windows x64 und Linux x64/ARM64, Docker für amd64/arm64 und Android-APKs für arm64-v8a, armeabi-v7a und x86_64. |
## 🖼️ Screenshots
@@ -154,7 +155,7 @@ Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entf
| Version | Datum | Zusammenfassung |
| --- | --- | --- |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | Gegenüber 0.2.5 #10 behoben, #9/#12 umgesetzt, #6/#7 abgesichert und den in PR #13 beschriebenen TS6-Freigabefall korrigiert; Sprach- und Mobilinteraktionen verbessert; Windows x64, Linux x64/ARM64, Docker amd64/arm64 und Android-APKs für drei ABIs ergänzt. |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | Gegenüber 0.2.5 wurden Sprach-Gateway, gemeinsame Protokolle, Sprachoberfläche und Admin-Module umfassend umstrukturiert; #6/#7/#10 behoben, #9/#12 umgesetzt und der in PR #13 gemeldete Fall bereits aktiver TS6-Freigaben behoben. Opus- und Sitzungslebenszyklen sowie mobile Steuerung verbessert. Pakete: Windows x64, Linux x64/ARM64, Docker amd64/arm64 und Android arm64-v8a/armeabi-v7a/x86_64. |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | `.wskin`-Skins, Aktivierungs-/Standardverwaltung und geschützte Tages-, Nacht- und ILLUSIA-Skins ergänzt; unfertiges Aurora-Voice-Beispiel entfernt, Skin-Ladeblitze, dunkle Bedienelemente und Artwork-Ebenen im Sprachbereich korrigiert sowie offiziellen Skin-Entwicklungs-Agent-Skill hinzugefügt. |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Plattformübergreifendes P2P-Bildschirmteilen zwischen Browsern und nativen TeamSpeak-6-Clients ergänzt; STUN-/externes-TURN-Konfiguration, Live-Player und Zuschauerstatus, Aufnahmeoptionen bis 1080p/60 FPS und WebRTC-Statistiken hinzugefügt; Bildschirmfreigabe-Interaktion verbessert und Besucherzählung ergänzt. |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Mitgliederplanung und direkte Verschiebung nach Berechtigung ergänzt; Avatar-, Stummschaltstatus- und Identitätsunterstützung hinzugefügt; Screenshots und Dokumentation für alle fünf Sprachen aktualisiert. |
@@ -246,3 +247,10 @@ Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain
| Begleitton | Nur auf dem Desktop verfügbar und WebRTC erforderlich. Bei Fenster- oder Tab-Freigabe auch Audio freigeben. |
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
| Sitzungslimit | Eine Instanz akzeptiert bis zu 100 aktive Browser-Sitzungen. |
## Kürzlich zusammengeführte Beiträge
- Die Liste folgt den GitHub-Merge-Einträgen; die Versionszusammenfassungen oben nennen nur Änderungen, die in der jeweiligen Version enthalten sind.
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) verbesserte Browser-Fehlermeldungen; [PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) korrigierte Skalierung, schwebendes Layout und Fußzeile der Startseite.
- [TimmySheep](https://github.com/TimmySheep) — [zusammengeführte PRs #13 und #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep) zu vorhandenen TS6-Freigaben, Seitenverhältnis, mobiler Sprache/Bildschirm-Wachhalten/Skin-Menü, Kanaloptionen der Identität, PWA/Design, Chatverlauf, Mitglieder-Audiozuständen und Mikrofonberechtigungen.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) ermöglichte Verbindungen über registrierte TeamSpeak-Nicknames und bewahrte Nickname-Ziele in Einstellungen, Favoriten und Einladungen.
+14 -4
View File
@@ -4,6 +4,8 @@
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors can join channels without installing a desktop client, while administrators manage the target servers, access policy, and runtime state from the web console.
Skin authors should start with the [skin development guide](./SKIN_DEVELOPMENT.md). A `.wskin` package is the portable deliverable: skin UI and assets travel with the package, while skin-only work should not require core runtime edits. The repository also includes the [WebSpeak skin development skill for agents](../.agents/skills/webspeak-skin-development/SKILL.md).
## Live demo
URL: <https://webspeak.example.invalid>
@@ -23,11 +25,12 @@ The public demo is hosted in Hong Kong and its network conditions and load may b
| Browser-side noise suppression | Optional microphone noise suppression runs at the browser capture stage, without adding server-side audio processing. |
| Messaging and actions | Channel chat, server chat, private messages, poke actions, and whisper targets. |
| Desktop accompaniment | Select an audio-enabled window or browser tab and share its sound with the current channel. |
| Identity and access | Remembered identity, visitor-defined targets, and revocable expiring invite links. |
| Administration | Manage targets, access policy, WebRTC, relays, invites, sessions, logs, diagnostics, and backups. |
| Identity and access | Remembered identity, visitor-defined targets, revocable expiring invite links, and TeamSpeak 3 identity import, conversion, validation, and export. |
| Administration | Manage targets, access policy, public media address, IPv6 candidates, voice STUN, relays, invites, sessions, logs, diagnostics, and backups. |
| Engineering structure | In 0.2.6, gateway voice, session events, audio, and screen-share coordination were split into modules; frontend voice and admin pages were decomposed into components, composables, and services, with lifecycle and reconnect tests. |
| Skins | Protected Day, Night, and ILLUSIA skins, plus instance-managed `.wskin` appearances with administrator enable/default controls. |
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
| Self-hosting | Data stays with the operator; Docker amd64/arm64, Windows x64 and Linux x64/ARM64 packages, and an Android client are provided. |
| Self-hosting | Data stays with the operator; packages include Windows x64 and Linux x64/ARM64, Docker supports amd64/arm64, and Android APKs target arm64-v8a, armeabi-v7a, and x86_64. |
## 🖼️ Screenshots
@@ -162,7 +165,7 @@ Disable and save the relay configuration to remove the relay option from the wel
| Version | Date | Summary |
| --- | --- | --- |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | Relative to 0.2.5, fixed #10, implemented #9/#12, hardened #6/#7, and fixed the existing-share discovery case reported in PR #13; improved voice and mobile interactions; added Windows x64, Linux x64/ARM64, amd64/arm64 Docker, and three-ABI Android packages. |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | Relative to 0.2.5, broadly refactored gateway voice, shared protocol, frontend voice workspace, and admin modules; fixed #6/#7/#10, implemented #9/#12 settings, and fixed the existing-TS6-share discovery case reported in PR #13. Improved Opus/session lifecycles and mobile controls. Packages: Windows x64, Linux x64/ARM64, Docker amd64/arm64, and Android arm64-v8a/armeabi-v7a/x86_64. |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | Added `.wskin` skins, administrator enable/default controls, and protected Day/Night/ILLUSIA built-ins; removed the unfinished Aurora Voice sample, fixed skin-load flashes, dark-control contrast, and voice-room artwork layering, and added the official skin-development Agent Skill. |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Added cross-platform P2P screen sharing between browsers and native TeamSpeak 6 clients; added STUN/external-TURN configuration, live player and viewer state, 1080p/60 FPS capture settings, and WebRTC statistics; refined screen-share interactions and added visitor numbering. |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Added channel member scheduling and permission-aware direct moves; added avatar, mute-state, and remembered-identity support; refreshed feature screenshots and documentation for all five languages. |
@@ -254,3 +257,10 @@ Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
| Accompaniment | Desktop only and requires WebRTC. Enable audio sharing when selecting a window or tab. |
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
| Session limit | One instance accepts up to 100 active browser sessions. |
## Recent contributors
- Listed from GitHub's merge records; the version summaries above describe only changes included in each release.
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) improved browser error translations; [PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) fixed scaling, floating layout, and the homepage footer.
- [TimmySheep](https://github.com/TimmySheep) — [merged PRs #13 and #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep), covering existing TS6 share discovery, share aspect ratio, mobile voice/wake/skin-menu behavior, identity channel options, PWA/theme work, chat history, member audio states, and microphone permission.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) added connections through registered TeamSpeak nicknames and preserved nickname targets in settings, favorites, and invitations.
+12 -3
View File
@@ -29,10 +29,12 @@
| ブラウザ側ノイズ抑制 | マイクのノイズ抑制をブラウザの音声取得段階で任意に使用でき、サーバー側の追加処理は不要です。 |
| チャットと操作 | チャンネル/サーバーチャット、個人メッセージ、つつく、ウィスパー対象。 |
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンク。 |
| 管理コンソール | 接続先、アクセス、WebRTC、中継、招待、セッション、ログ、診断、バックアップ。 |
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンクに加え、TeamSpeak 3 ID のインポート、変換、検証、エクスポート。 |
| 管理コンソール | 接続先、アクセス、公開メディアアドレス、IPv6 候補、音声 STUN、中継、招待、セッション、ログ、診断、バックアップ。 |
| プロジェクト構造 | 0.2.6 では音声ゲートウェイ、セッションイベント、音声処理、画面共有調整を分割し、音声・管理画面をコンポーネント、composable、サービスに整理しました。ライフサイクルと再接続のテストも追加しました。 |
| スキン | 保護された昼・夜・ILLUSIA スキンに加え、管理者が有効化とデフォルトを管理するインスタンス `.wskin` に対応。 |
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
| デプロイ | Windows x64、Linux x64/ARM64 パッケージ、Docker amd64/arm64、Android arm64-v8a・armeabi-v7a・x86_64 APK。 |
## 🖼️ インターフェースのスクリーンショット
@@ -135,7 +137,7 @@ npm start
| バージョン | 内容 |
| --- | --- |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | #10 を修正、#9/#12 の設定を実装し、#6/#7 を強化。PR #13 が報告した TS6 共有の見落としも修正しました。Windows x64、Linux x64/ARM64、Docker amd64/arm64、3 ABI の Android APK を追加しました。 |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 0.2.5 から音声ゲートウェイ、共有プロトコル、音声ワークスペース、管理モジュールを大規模に再構成。#6/#7/#10 を修正し、#9/#12 を実装。PR #13 が報告した既存 TS6 画面共有の検出漏れも修正しました。Opus、セッションのライフサイクル、モバイル操作を改善。Windows x64、Linux x64/ARM64、Docker amd64/arm64、Android arm64-v8a/armeabi-v7a/x86_64 APK を提供。 |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | `.wskin` スキン、管理者向けの有効化/デフォルト設定、保護された昼・夜・ILLUSIA 内蔵スキンを追加。未完成の Aurora Voice サンプルを削除し、読み込み時のちらつき、ダークモードの視認性、音声画面のアートレイヤーを修正。公式スキン開発 Agent Skill も追加しました。 |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | ブラウザと TeamSpeak 6 ネイティブクライアント間のクロスプラットフォーム P2P 画面共有を追加しました。STUN/外部 TURN 設定、プレーヤーと視聴者状態、1080p/60 FPS 取得設定、WebRTC 統計に対応し、共有操作と訪問者番号も改善しました。 |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | チャンネルメンバーの移動操作と権限に応じた直接移動を追加し、アバター表示、ミュート状態の同期、保存 ID の復元に対応しました。5 言語のスクリーンショットとドキュメントも更新しました。 |
@@ -149,3 +151,10 @@ npm start
## ライセンス
WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で公開されています。
## 最近マージされた貢献
- GitHub のマージ記録に基づく一覧です。上のバージョン概要には、各リリースに実際に含まれる変更のみを記載しています。
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) でブラウザのエラー翻訳を改善し、[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) で拡大縮小、フローティングレイアウト、ホームのフッターを修正。
- [TimmySheep](https://github.com/TimmySheep) — [マージ済み PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep)。既存 TS6 共有の検出、画面比率、モバイル音声・画面点灯・スキンメニュー、ID のチャンネル設定、PWA/テーマ、チャット履歴、メンバー音声状態、マイク権限などに貢献。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) で TeamSpeak の登録済みニックネームによる接続に対応し、設定・お気に入り・招待リンクにニックネームの接続先を保持。
+12 -3
View File
@@ -29,10 +29,12 @@
| Шумоподавление в браузере | Опциональное шумоподавление микрофона на этапе захвата в браузере без дополнительной обработки звука на сервере. |
| Чат и действия | Чат канала и сервера, личные сообщения, толчки и цели шёпота. |
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
| Идентичность и доступ | Сохранение идентичности, собственные цели и приглашения с ограничением срока и числа использований. |
| Панель администратора | Цели, доступ, WebRTC, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
| Идентичность и доступ | Сохранение идентичности, собственные цели, приглашения с ограничением срока и числа использований, а также импорт, преобразование, проверка и экспорт идентификаторов TeamSpeak 3. |
| Панель администратора | Цели, доступ, публичный адрес медиа, IPv6-кандидаты, голосовой STUN, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
| Структура проекта | В 0.2.6 голосовой шлюз, события сессий, аудио и координация демонстрации разделены на модули; голосовые и административные страницы — на компоненты, composables и сервисы. Добавлены тесты жизненного цикла и переподключения. |
| Скины | Защищённые дневная, ночная и ILLUSIA-темы, а также `.wskin` экземпляра с управлением включением и темой по умолчанию в панели администратора. |
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
| Развёртывание | Пакеты Windows x64 и Linux x64/ARM64, Docker amd64/arm64, Android APK для arm64-v8a, armeabi-v7a и x86_64. |
## 🖼️ Скриншоты интерфейса
@@ -135,7 +137,7 @@ npm start
| Версия | Изменения |
| --- | --- |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | Исправлена #10, реализованы настройки #9/#12, усилены исправления #6/#7 и исправлен случай из PR #13; улучшено мобильное управление; добавлены Windows x64, Linux x64/ARM64, Docker amd64/arm64 и Android APK для трёх ABI. |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | Относительно 0.2.5 масштабно перестроены голосовой шлюз, общие протоколы, голосовая область и модули администратора; исправлены #6/#7/#10, реализованы #9/#12 и случай с обнаружением уже активной демонстрации TS6 из PR #13. Улучшены Opus, жизненные циклы сессий и мобильное управление. Пакеты: Windows x64, Linux x64/ARM64, Docker amd64/arm64, Android arm64-v8a/armeabi-v7a/x86_64. |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | Добавлены скины `.wskin`, управление включением и темой по умолчанию, а также защищённые темы «День», «Ночь» и ILLUSIA; удалён незавершённый пример Aurora Voice, исправлены мерцание при загрузке скина, контраст элементов в тёмном режиме и слои иллюстраций в голосовом пространстве; добавлен официальный Agent Skill для разработки скинов. |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | Добавлена кроссплатформенная P2P-трансляция экрана между браузерами и нативными клиентами TeamSpeak 6; добавлены настройка STUN/внешнего TURN, проигрыватель и состояние зрителей, захват до 1080p/60 FPS и статистика WebRTC; улучшено управление трансляцией и добавлен номер посетителя. |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | Добавлены управление перемещением участников и прямое перемещение с учётом прав; поддержаны аватары, синхронизация микрофона и восстановление идентичности; обновлены скриншоты и документация для пяти языков. |
@@ -149,3 +151,10 @@ npm start
## Лицензия
WebSpeak распространяется по [GNU Affero General Public License v3.0 only](../LICENSE).
## Недавно объединённые вклады
- Список составлен по записям о слиянии на GitHub; сводки выше описывают только изменения, вошедшие в соответствующий релиз.
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) улучшил переводы ошибок браузера; [PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) исправил масштабирование, плавающую компоновку и нижний колонтитул главной страницы.
- [TimmySheep](https://github.com/TimmySheep) — [объединённые PR #13 и #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep): обнаружение активных трансляций TS6, пропорции экрана, мобильное аудио/подсветка экрана/меню скинов, канал в настройках идентичности, PWA/темы, история чата, состояние аудио участников и разрешение микрофона.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) добавил подключение по зарегистрированным именам TeamSpeak и сохранение имени цели в настройках, избранном и приглашениях.
+12 -2
View File
@@ -4,6 +4,8 @@
WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户无需安装桌面客户端即可从浏览器加入频道,管理员可以在控制台管理目标服务器、访问方式和运行状态。
皮肤开发请从[皮肤开发规范](./SKIN_DEVELOPMENT.md)开始;它以可移植 `.wskin` 为交付物,要求皮肤实现和素材随包分发,不为单款皮肤修改核心运行时代码。Agent 工作流见[WebSpeak Skin Development Skill](../.agents/skills/webspeak-skin-development/SKILL.md)。当前格式与安全边界见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)与[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)。
## 在线 Demo
地址:<https://webspeak.example.invalid>
@@ -23,7 +25,8 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
| 浏览器端降噪 | 提供可开关的麦克风降噪,在浏览器采集端处理,不增加服务器端音频处理压力。 |
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
| 身份与访问 | 支持身份保持、访客自定义目标和可撤销、可过期的邀请链接。 |
| 身份与访问 | 支持身份保持、访客自定义目标、可撤销/可过期邀请链接,以及 TeamSpeak 3 身份导入、转换、校验与导出。 |
| 工程结构 | 0.2.6 将网关语音、会话事件、音频和屏幕共享拆分为独立模块;前端语音与管理页拆分为组件、composables 和服务,并补充生命周期与重连测试。 |
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
| 皮肤 | 提供日间、夜间和 ILLUSIA 三款受保护皮肤,并支持实例自定义 `.wskin` 外观与管理员默认/启用管理。 |
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
@@ -164,7 +167,7 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
| 版本 | 日期 | 摘要 |
| --- | --- | --- |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | 相对 0.2.5 修复 #10、实现 #9/#12,并加固 #6/#7;修复 PR #13 所报告的既有屏幕共享漏同步;改善语音和移动端交互;发布 Windows x64、Linux x64/ARM64、Docker amd64/arm64 和 Android 三种 ABI 构建包。 |
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | 相对 0.2.5 大范围重构语音网关、共享协议、前端语音工作区与管理模块;修复 #6/#7/#10,完成 #9/#12 配置,并修复 PR #13 报告的既有 TS6 屏幕共享漏发现问题;改善 Opus/重连生命周期和移动端控制。提供 Windows x64、Linux x64/ARM64、Docker amd64/arm64,以及 Android arm64-v8a、armeabi-v7a、x86_64 APK。 |
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | 新增 `.wskin` 皮肤系统、管理员启用/默认管理和受保护的日间/夜间/ILLUSIA 内置皮肤;移除未完成 Aurora Voice 样例,修复皮肤加载闪烁、暗色控件可读性与语音界面美术层级,并加入官方皮肤开发 Agent Skill。 |
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | 新增浏览器与 TeamSpeak 6 原生客户端之间的跨端 P2P 屏幕共享;提供 STUN/外部 TURN 配置、直播播放器、观众状态、1080p/60 FPS 采集设置和 WebRTC 统计;优化屏幕共享交互并新增访客编号。 |
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | 新增频道成员调度与按权限直接移动;支持头像、静音状态同步和身份恢复;更新五种语言的功能截图与文档。 |
@@ -256,3 +259,10 @@ npm start
| 伴奏 | 仅桌面端提供且要求 WebRTC;选择窗口或标签页时还要勾选共享音频。 |
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
## 近期合并贡献者
- 以下依据 GitHub 合并记录列出;上方版本摘要只描述对应版本实际纳入的改动。
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) 改进浏览器端报错翻译;[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) 修正缩放、浮动布局和首页脚注。
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持通过 TeamSpeak 注册昵称连接,并在设置、收藏和邀请中保留昵称目标。
+198 -24
View File
@@ -1,8 +1,28 @@
# WebSpeak 皮肤开发规范
本文说明如何制作、校验并发布 WebSpeak `.wskin` 皮肤包。皮肤可为公开页面逐个部件定制二次元美术表现:背景、素材、配色、轮廓、圆角、阴影、头像装饰、按钮质感、滚动条颜色和播放器外观都可以自定义;但组件的位置、尺寸、排列、文字排版空间及交互结构由 WebSpeak 固定提供,皮肤不得重排或覆盖。
本文说明 v1 视觉皮肤、v2 声明式布局皮肤、v3 开放皮肤以及 v4 插件包格式。v1/v2 保持固定 CSS 几何边界;v3 可重排公开 UI、用自定义声明式节点构建界面,并用 components.json schema v2/v3 替换首页/语音工作区的整页可见界面。v4 有插件清单、文件校验和本地缓存;有界 Wasm 已接入 WebClient 授权、UI 生命周期、按清单过滤的只读数据投影、worker 资源治理和首版宿主动作桥,并在生产构建开放。作者 JavaScript 仍不执行;跨浏览器端到端验证和独立安全审查仍待完成。路线和安全边界见[路线图](./OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md)与[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)。
页面结构、必要控件和所有基础翻译均由 WebSpeak 提供。皮肤包不必携带文案;如果只包含样式与美术素材,所有界面文字仍由 WebSpeak 按当前语言显示。`content.json` 仅用于可选覆盖,缺少的语言或字段回退到 WebSpeak 的基础内容。皮肤不注入 HTML 或 JavaScript,也不改变语音、权限、连接、拖动和屏幕共享行为。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。**
## 目标:皮肤是可移植的外挂包
`.wskin` 是皮肤唯一的交付物。页面结构、样式、文案、布局、图片、字体和皮肤自己的组件/逻辑都应随包分发;导入皮肤不应要求为某款皮肤单独修改、部署或配置 WebSpeak 核心代码。宿主只提供稳定、通用且版本化的渲染和能力接口,皮肤包声明如何使用它们。
开发皮肤时,优先在包内完成工作:用 `skin.css` 和包内资源做视觉,用 `content.json` 提供皮肤文案,用 `layout.json` 提供默认排布,用 `components.json` 描述页面组件、数据绑定和已支持的交互;需要本地逻辑时,根据当前支持情况使用 v4 有界 Wasm。所有图片、字体、CSS 和插件文件都放进 `.wskin`,引用包内相对路径。不要为了单款皮肤给 `WebClient.vue`、宿主控件注册表、共享协议、服务端或其他核心运行时添加专用实现。
运行时数据和安全敏感的 TeamSpeak 行为仍由 WebSpeak 提供。皮肤只能读取当前协议明确公开的数据,并调用已支持、经用户授权和宿主复核的动作;包内 UI 消费这些输入并负责呈现。若多个皮肤确实缺少同一项通用数据或动作,应另立平台接口工作:先定义稳定字段/动作、权限和兼容版本,再由皮肤包使用。不要把平台接口改动伪装成某款皮肤的必要步骤,也不要为单个皮肤新增专用宿主控件。
可移植性由 WebSpeak 运行时与皮肤协议版本决定。清单的 `minAppVersion`、组件 schema、插件 `apiVersion` 必须对应实际使用的接口;兼容同一协议版本的 WebSpeak 实例应能导入并运行相同字节的 `.wskin`,无需单独部署该皮肤的前端代码。实例配置、公开服务器数据、屏幕尺寸和用户授权可以影响显示结果,但不改变包的实现。旧包继续遵循其声明的 schema 和宿主兼容规则。
开发者 Skill:[WebSpeak Skin Development](../.agents/skills/webspeak-skin-development/SKILL.md)。它给 Agent 提供皮肤任务的决策和交付步骤;本文件及[系统规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)是格式与接口的事实来源。
KOOK 语音界面参考仅覆盖用户授权的语音频道,语音区结构记录在[参考文档](./KOOK_VOICE_REFERENCE.zh-CN.md);发现、陪玩、活动、广告、商城和管理后台不属于复刻范围。
完整的 KOOK 语音端体验测试皮肤见 [KAAK](./examples/KAAK-VOICE.md):它复用 WebSpeak 可信宿主控件和公开 TeamSpeak 会话数据,不包含站点素材、运营页面或后台。Harbor Voice 保留为通用 surface 格式验证样例。
v3 保留安全的标准元素和属性白名单;组件可通过完整页面 surface 自己构建界面,不需要把聊天、音频或成员 UI 锁在固定宿主面板里。条件可比较权限化公开数据、重复项和皮肤本地状态,也可判断已登记公开集合是否为空。表单输入先留在宿主渲染的本地状态;宿主动作不能在逐字输入时触发,可在已提交的 `change`、表单提交或显式点击上触发。作者自定义代码逻辑由 v4 有界 Wasm 路径提供。生产构建中的 v4 Wasm 运行时已接入本地摘要授权、页面生命周期、动态 HTML/SVG 节点渲染、插件 CSS、权限化只读数据投影、宿主动作桥、语义挂载槽位和全局 worker 资源治理;目前支持 `session.status.read`、频道/成员/聊天、收藏/最近列表和音频/共享状态读取权限,以及 `ui.surface.replace`、`ui.input.read`。每份公开数据投影最多 48 KiB,只传清单准许的字段;Wasm 可生成自定义节点树、有限本地状态并响应命名 UI 事件。宿主动作只接受可信 UI 事件触发的同一轮输出中的单个请求,并重新检查插件权限、参数和当前会话;`dblclick` 可绑定到加入频道等已授权宿主动作。JavaScript 仍只校验和缓存,不执行。每个 v4 插件有独立布局根,用户可调整插件整体、组件根和 DOM 节点的位置、尺寸、显隐、安全外观及 Flex/Grid 同级显示顺序;`plugins.json` 可将 widget 放到公开页面的注册槽位,也可通过 surface 重做整页。这个边界能承载完整自定义客户端界面,但不等于已完成插件商城和作者管理平台;跨浏览器测试与独立安全审查尚未完成。
`.wskin` 包可为公开页面定制艺术表现。v1 提供 CSS 与美术资源;v2 另外携带受校验的布局 JSON;v3 可自由安排公开组件,并用 components.json 声明由宿主渲染的安全组件。所有版本均由 WebSpeak 保留基础组件的业务逻辑和 TeamSpeak 行为。
页面结构、必要控件和所有基础翻译均由 WebSpeak 提供。皮肤包不必携带文案;如果只包含样式与美术素材,所有界面文字仍由 WebSpeak 按当前语言显示。`content.json` 仅用于可选覆盖,缺少的语言或字段回退到 WebSpeak 的基础内容。皮肤不注入 HTML 或 JavaScript;授权后的交互只调用 WebSpeak 登记并校验过的 TeamSpeak 功能。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。**
可直接查看 [ILLUSIA 风示例源码](examples/illusia-voice/) 与 [示例说明](examples/ILLUSIA-VOICE.md)。它使用本地美术素材和 CSS 完整定制首页、语音房间、成员区、聊天空状态及播放器,同时沿用 WebSpeak 提供的基础翻译;也是管理控制台内置且不可移除的示例皮肤。
@@ -23,24 +43,30 @@ content.json # 可选:首页内容与多语言界面文案
assets/preview.jpg # 可选:管理后台显示的预览图,也可在 CSS 中使用
assets/background.webp # 可选:页面艺术素材
assets/brand.woff2 # 可选:自带字体
components.json # v3 可选:声明式组件或完整页面 surface
plugins.json # v4 必需:插件入口、页面、模式、权限与包内文件
plugins/<plugin-id>/index.js # v4 插件代码,目前只校验和缓存
plugins/<plugin-id>/index.wasm # v4 有界 Wasm 插件入口
plugins/<plugin-id>/style.css # v4 可选:插件样式,目前只校验和缓存
plugins/<plugin-id>/assets/ # v4 插件专属的本地图片或字体素材
```
所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。
所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。说明文档放在源码目录旁边,不能打进 `.wskin`;导入器会拒绝 `README.md` 等未声明文件。
### `manifest.json`
```json
{
"schemaVersion": 1,
"id": "community.illusia-voice",
"name": "ILLUSIA风",
"version": "1.0.25",
"author": "WebSpeak Project",
"license": "All rights reserved",
"id": "community.example-skin",
"name": "Example skin",
"version": "1.0.0",
"author": "Example author",
"license": "CC-BY-4.0",
"description": "A visual-only art skin using the WebSpeak interface translations.",
"entry": "skin.css",
"preview": "assets/background-composite.webp",
"minAppVersion": "0.2.6"
"minAppVersion": "0.2.7-preview"
}
```
@@ -57,6 +83,133 @@ assets/brand.woff2 # 可选:自带字体
清单不得重复声明同一个文件为 CSS、内容或预览入口。
### schemaVersion 2:声明式布局皮肤
v2 为 v1 增加一个必需布局文件。清单和布局 JSON 会在导入端及服务端分别验证;未知清单字段、权限、组件、布局字段及越界数值都会导致包被拒绝。v2 不支持 HTML、JavaScript、WebAssembly、远程资源或扩展插件代码。皮肤 CSS 仍使用当前解析器规则,不能控制几何布局和交互区域。
```json
{
"schemaVersion": 2,
"packageType": "layout-skin",
"id": "community.example-layout",
"name": "Example layout",
"version": "1.0.0",
"author": "Example author",
"license": "CC-BY-4.0",
"entry": "skin.css",
"layout": "layout.json",
"permissions": [],
"minAppVersion": "0.2.7"
}
```
布局只引用 WebSpeak 登记的稳定组件 ID。当前支持 `home`、`voice`、`demo` 页面及 `desktop`、`tablet`、`mobile` 三种设备配置。组件位置使用有界的水平/垂直偏移,尺寸使用缩放、宽、高,外观字段只接受六位十六进制颜色和受限圆角;`visible` 控制显示状态;`order` 在 -100 到 100 之间,仅当父容器使用 Flex 或 Grid 时改变同级显示顺序,不改变 DOM 和键盘焦点顺序。`home.security-note`、身份安全提示、连接状态与屏幕共享错误属于可信宿主 UI,不允许布局隐藏或改写。
示例 `layout.json`:
```json
{
"schemaVersion": 1,
"pages": {
"home": {
"desktop": {
"home.feature": { "x": 12, "y": 8, "scale": 1.05, "order": -1 },
"home.features": { "visible": false }
},
"tablet": { "home.join-card": { "width": 680 } },
"mobile": { "home.header": { "x": 0, "y": 4 } }
}
}
}
```
作者包中的布局是初始默认值。用户编辑内容单独存放在本地浏览器,覆盖作者默认值;支持撤销/重做、单个组件重置、整套布局恢复、导入和导出。更换设备宽度会选择对应设备配置,不会删除其他设备的值。恢复入口由宿主在皮肤根节点之外绘制,即使用户隐藏了页面组件,也能再次打开编辑器并恢复默认值。
v1 和 v2 都只支持公开页面。`/admin/**` 不加载布局、用户覆盖和皮肤组件编辑器。布局包没有数据/API 权限;后续插件必须另行设计独立沙箱与授权协议,不能通过增加 v2 清单字段取得能力。
### schemaVersion 3:开放皮肤和完整声明式页面
v3 清单的 packageType 固定为 open-skin,entry 指向 CSS,components 可选指向 components.json;与 v2 不同,v3 不声明 permissions,但可以可选声明 layout 指向作者默认布局 `layout.json`。组件文件可以省略。仅 v3 开放公开页面的 CSS 排版能力,v1/v2 仍按旧 CSS 规则校验。客户端导入和服务端登记使用同一共享组件 schema 与权限白名单。
components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。schema v1 维持旧兼容;schema v2 引入 `mode: "widget"`(默认)或 `mode: "surface"`,并提供可选宿主控件节点;schema v3 保持这些能力,扩大声明式 UI 的节点/状态/动作边界,并增加用户操作事件和语音功能动作。v3 仍使用固定元素/属性、公开数据集合和宿主动作白名单,不是任意 HTML 或任意脚本。每个组件需声明 id、name、page、accessibleName、permissions、actions 和 root,可选 state。page 接受 home、voice、demo;surface 仅可用于 home 和 voice,并且必须请求 `ui.surface.replace`。用户批准前不会显示 surface,撤销后宿主立即恢复普通页面。所有皮肤组件根节点及其中的每个可见元素都以动态布局项加入本地布局编辑器,可独立移动、缩放、改尺寸、改外观或隐藏。按钮、输入框及显式用户操作节点保留 44 px 最小触控区域。为让用户覆盖在树结构调整后仍能指向同一元素,请给重要节点设置稳定的 `part` 名称;未设置时按组件树位置生成标识。v4 包和插件运行时见[规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md);Wasm 生产运行已开启,作者 JavaScript 仍关闭。
普通节点使用白名单 HTML/SVG 元素。节点可包含 text、part、className、受限 attributes、包内图片 asset、bindValue、本地 repeat/when、events 和 children。文本与属性支持简单的双大括号数据路径;不支持表达式、HTML 字符串或脚本。重复列表可使用注册的公开集合;频道重复项仅能再重复其 `channel.members`,并且需要额外批准 `session.members.read`。宿主每个组件的实际渲染节点最多 8192 个,防止嵌套集合放大界面。v3/v4 的作者默认布局使用与 v2 相同的有界 layout schema;可通过 `skin.<page>.<component-id>` 指定声明式自定义组件,通过 `skin.<page>.runtime_plugin_root_<plugin-id>` 指定 v4 插件根。用户的本地布局覆盖优先于包默认值。schema v2 另允许固定宿主控件节点,例如:
申请 `session.channels.read` 的 `session.channels` 列表还提供 `memberCount`、两位数显示用的 `memberCountLabel`、`maxClients` 和 `maxClientsLimited`。后两个字段仅在 TeamSpeak 返回有效上限数据时出现;`maxClientsLimited: false` 表示频道不限人数。它们与频道树一起属于公开只读数据,不会授予服务器写入能力。
```json
{
"schemaVersion": 2,
"components": [{
"id": "example-voice-surface",
"name": "Example voice surface",
"page": "voice",
"mode": "surface",
"accessibleName": "Example voice workspace",
"permissions": ["ui.surface.replace"],
"actions": {},
"root": {
"tag": "main",
"children": [
{ "widget": "voice.channel-panel" },
{ "widget": "voice.member-cards" },
{ "widget": "voice.chat-panel" },
{ "widget": "voice.audio-controls" },
{ "widget": "voice.disconnect-control" }
]
}
}]
}
```
当前可选宿主控件 ID:`home.connection-form`、`home.connection-status`、`home.server-announcement`、`home.social-links`、`home.identity-provider`、`app.skin-switcher`、`app.language-switcher`、`voice.channel-panel`、`voice.member-cards`、`voice.chat-panel`、`voice.audio-controls`、`voice.screen-share-player`、`voice.screen-share-start`、`voice.whisper-controls`、`voice.performance-panel`、`voice.connection-controls`、`voice.disconnect-control`、`voice.server-header`、`voice.server-banner`、`voice.server-switcher`、`voice.channel-tree`。未知控件和同页重复控件会被拒绝;每个控件的状态和业务动作仍由 WebSpeak 内部处理。`home.identity-provider` 是通用身份提供方入口,需用 `options.identityProviderId` 和 `options.identityProviderLabel` 指定稳定提供方标识与显示名;宿主会把点击转交给应用代码的 `registerIdentityProviderAdapter` 分发接口,皮肤只能发起请求、不能注册适配器。当前没有 MyTS 适配器,所以 MyTS 入口仍提示开发中;这不代表已经实现登录认证。schema v3 会检查受保护控件所需权限:音频控件需 `audio.status.read`、`audio.microphone.control` 和 `audio.output.control`;聊天需 `chat.channel.read` 与 `chat.channel.send`;成员卡片始终需 `session.members.read` 和 `session.memberAvatars.read`;schema v3 可为成员卡片设置 `options.memberActions: true`,在非本人卡片上显示可信宿主成员操作入口(包含现有个人音量控件);也可为 `voice.channel-tree` 设置该选项,在非本人频道树成员行上启用右键菜单;菜单仍由 WebSpeak 宿主处理,皮肤不获得额外动作或数据接口。频道树还可单独设置 `options.memberDragDrop: true`,将非本人成员拖到另一频道行时复用 WebSpeak 现有移动成员操作;悬停和拖入高亮由皮肤样式控制,此选项默认关闭且只适用于频道树。成员卡片或性能卡片可设置 `options.screenShare: false`,同时隐藏共享 UI/指标并免除成员卡片所需的屏幕共享权限;默认成员共享操作仍需屏幕共享读取/控制权限;头像只在可信宿主控件内显示,不暴露给皮肤代码;屏幕共享播放器需 `voice.screenShare.read` 与 `voice.screenShare.control`;悄悄话控件需对应状态读取和控制权限;断开/连接控件需 `voice.disconnect`。既有 v2 包维持旧校验行为,`voice.screen-share-start` 仍像此前一样要求 `voice.screenShare.control`。该控件仅能放在语音页;宿主按钮在可信点击处理器内直接启动屏幕采集,避免异步 Wasm 回调丢失浏览器瞬时用户激活。自定义 UI 可以完全用普通声明式节点搭建,不需要采用这些控件。只显示收藏时可用 `favorites.items` 和 `favorites.switch`;若要将收藏与最近连接放在同一自定义栏,可用 `servers.quickList` 数据与 `quickServers.switch` 动作。服务器目标始终使用本机生成的不透明令牌,不把地址、密码或身份材料交给组件。频道行也可把 `voice.joinChannel` 绑定到双击事件,切房继续走 TeamSpeak 原有权限和密码流程。v3 还提供经独立权限保护的麦克风/扬声器、输出音量、噪声抑制、伴奏、离开状态、悄悄话、断开连接和屏幕共享动作;噪声抑制使用 `audio.toggleNoiseSuppression` 与 `audio.microphone.control`,伴奏使用 `audio.toggleAccompaniment` 与 `audio.output.control`。它们只调用 WebSpeak 已有操作,屏幕采集仍由浏览器或操作系统询问用户。
可信语音导航控件包括 `voice.channel-tree`、`voice.server-switcher` 和 `voice.server-header`。频道树要求 `session.channels.read`、`session.members.read`、`session.memberAvatars.read` 与 `session.channel.join`;头像只由宿主读取并在频道树中绘制。它可选 `layout: "server-sidebar"` 展示频道成员并让频道行与成员行分别控制折叠;未指定时保留默认呈现。独立服务器切换器要求 `servers.quickList.read` 与 `servers.quickList.switch`。服务器头部还要求 `session.status.read`,并在同一可信部件中组合服务器身份、状态、频道搜索和快速切换。两种入口都只接收不透明本地标识,点击后复用 WebSpeak 当前连接流程。v3 还可用 `session.invite.copy` 授权 `session.copyInviteLink`,让宿主复制当前公开服务器与频道的邀请链接并排除连接凭据。语音状态投影中的 `serverLabel` 会在看起来像 IP、域名或连接目标时省略,避免把地址显示为服务器名称。
示例包见 [KAAK voice 示例](./examples/KAAK-VOICE.md),其 components.json 使用完整首页与语音工作区 surface,展示收藏服务器、频道树、在线成员、聊天和可信语音控制的组合;[Open Voice Surface](./examples/OPEN-VOICE-SURFACE.md) 保留为通用格式验证脚手架。KAAK 的语音视觉参考来自用户授权进入的前两个语音房间;只记录布局,不保留服务器/房间标识、成员名或聊天内容。当前数据权限和宿主动作以[开放皮肤规格](./OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)中的清单为准。组件按本地用户授权后才渲染;权限对每个皮肤版本、页面和组件分别保存,可在宿主权限入口撤销。页面替换时,宿主会额外显示“返回标准界面”和“恢复内置皮肤”入口;拒绝授权或离开 surface 后,普通页面可立即恢复。
组件树有硬上限:components.json 256 KiB。schema v1/v2 上限为 32 个组件、每组件 256 个模板节点、16 层深度和 100 条重复记录;schema v3 上限为 128 个组件、每组件 2048 个模板节点、32 层深度和 250 个重复行,并允许 64 个本地标量状态与 64 个动作。Wasm 动态 UI 输出的 schema v4/v5/v6 有 256 KiB 总输出上限、最多 64 个组件、每个节点最多 64 个属性和 256 个子节点,并沿用每组件节点/深度限制;渲染器接受标准 HTML/SVG 元素及普通属性,而不是由元素/属性展示白名单限制。脚本、嵌入式浏览器、网络/导航属性、事件属性和行内 style 仍拒绝;样式通过经过隔离校验的插件 CSS 提供。包内图片通过专用资源字段引用,自定义元素映射为惰性 `div`。宿主只通过 `isTrusted` 用户事件发出剥离 DOM/Event 对象后的 `extension-event`,Wasm 侧只能经 `env.ui_input_read` 一次读取最多 64 KiB 的 JSON,包含插件本地状态、安全事件和宿主按插件读取权限投影的数据。每份数据投影最多 48 KiB,只含公开字段;地址、凭据、SDK 对象和未声明字段不会进入 guest。输入字段限长;生成界面中的 password/file/hidden 类型输入会拒绝。UI 循环已经接入 WebClient 授权生命周期,可把可信事件或最新数据快照作为下一次独立 Wasm 调用输入,最多串行排队 8 项并验证回调/状态归属;动作桥复核清单权限和会话状态。单个页面实例最多并发运行 2 个 Wasm worker,并限制最多排队 64 项。
图片资源只能从包内引用,CSS 不能读取外部 URL、脚本或浏览器存储。宿主动作需显式权限,并只能绑定可信的用户事件;输入或 change 事件不能触发宿主动作。focus/blur、hover 和 drag-start/over 等被动事件只可改动组件本地状态,不能触发语音操作。
注意:v3 CSS 和 surface 可以隐藏或遮挡普通语音控件。权限和返回标准界面提示由宿主在皮肤根之外绘制;其他界面控件仍受皮肤排版影响。测试时务必确保麦克风、设置、退出语音、屏幕共享操作和移动端导航仍有可达路径。组件演示页 /demo 使用合成数据,加入频道和聊天动作只更新演示状态;它不支持宿主控件或整页替换。
### 本地组件结构编辑器
公开客户端页可打开“组件结构”编辑器,直接管理当前皮肤版本的声明式组件树。它支持创建、复制、删除组件和节点、添加子节点或同级节点、调整顺序、编辑组件元数据与节点 JSON、撤销/重做,以及导入/导出 components.json。该编辑器不属于管理员面板,不加载到 /admin/**。
编辑器只保存本地 authoring 覆盖,键按皮肤 ID 和版本隔离;原始皮肤包不会被改写。导入及每次提交都会走 parseSkinPluginDocument 的同一 schema 和权限校验,运行时也再次验证从本地存储读出的文档。不能通过编辑器新增任意脚本、事件处理器属性、外部资源、未知数据路径、宿主保留的 data-ws-* 属性、未授权宿主动作或未登记的宿主控件。旧 v2 组件首次升级到 v3 时,编辑器会为受保护的内置宿主控件补齐对应权限声明;这不会自动批准权限,控件继续等待宿主授权 UI 明确确认。
旧 schema v1/v2 皮肤可以保持原样使用,第一次结构编辑时会把已验证的数据规范化为 schema v3;旧包自身不被升级或覆盖。schema v3 允许 components 为空:删除最后一个皮肤组件会恢复基础 WebSpeak 页面,宿主授权与恢复控件始终在皮肤内容之外。节点不能脱离组件根单独删除;重要节点应设置稳定 part 名称,避免树顺序变化后基于路径生成的布局覆盖指向其他节点。
系统开发顺序由用户明确指定:先完成并验证通用组件 CRUD、权限和数据边界、持久化及回退流程,并保存稳定检查点;之后才开始 KOOK 语音客户端皮肤。参考皮肤阶段只为具体兼容问题对框架做小修,不反复采集参考或重构框架。
### schemaVersion 4:插件包描述与有界 Wasm 运行时
v4 在 open-skin 包中增加必需的 `plugins` 路径。服务端登记和客户端导入共用 `plugins.json` schema v1 校验器;校验插件 ID、页面、模式、权限、文件归属、路径唯一性和包内文件大小,并将插件文件与普通皮肤素材分别缓存。客户端还会对 Wasm 入口执行固定导入/导出 ABI 预检。SHA-256 授权基础会绑定插件描述、入口、样式和全部素材;本机授权记录还会绑定皮肤/插件版本、API 版本和权限策略版本。摘要只能发现已授权内容被替换,不能证明发布者身份。WebClient 有本地授权对话框和 Wasm 运行生命周期;目前支持安全 UI 输出、可信 UI 事件回调、插件专属 CSS、按清单权限过滤的公开数据投影(单份最多 48 KiB)和首版单动作宿主桥。支持的数据读取权限包括 `session.status.read`、`session.channels.read`、`session.members.read`、`chat.channel.read`、`favorites.read`、`servers.quickList.read`、`audio.status.read`、`voice.whisper.status.read`、`voice.screenShare.status.read` 和 `voice.screenShare.read`,另支持 `ui.surface.replace`。`ui.input.read` 单独控制插件是否能收到用户在插件自有输入框中输入或被浏览器自动填入的值;未获授权时仍可收到事件类型,但不会收到文本或勾选值。密码、文件和隐藏输入始终拒绝。宿主动作仅可由可信 UI 事件触发,按清单权限、动作参数和会话状态再次校验;生产构建也有全局 worker 上限。跨浏览器验证和独立安全审查仍待完成。
v4 在 open-skin 包中增加必需的 `plugins` 路径,并允许沿用可选 `layout` 路径提供插件根和节点的作者默认布局。服务端登记和客户端导入共用 `plugins.json` schema v1 校验器;校验插件 ID、页面、模式、权限、文件归属、路径唯一性和包内文件大小,并将插件文件与普通皮肤素材分别缓存。客户端还会对 Wasm 入口执行固定导入/导出 ABI 预检。SHA-256 授权基础会绑定插件描述、入口、样式和全部素材;本机授权记录还会绑定皮肤/插件版本、API 版本和权限策略版本。摘要只能发现已授权内容被替换,不能证明发布者身份。WebClient 有本地授权对话框和 Wasm 运行生命周期;目前支持安全 UI 输出、可信 UI 事件回调、插件专属 CSS、按清单权限过滤的公开数据投影(单份最多 48 KiB)和首版单动作宿主桥。支持的数据读取权限包括 `session.status.read`、`session.channels.read`、`session.members.read`、`chat.channel.read`、`favorites.read`、`servers.quickList.read`、`audio.status.read`、`voice.whisper.status.read`、`voice.screenShare.status.read` 和 `voice.screenShare.read`,另支持 `ui.surface.replace`。`ui.input.read` 单独控制插件是否能收到用户在插件自有输入框中输入或被浏览器自动填入的值;未获授权时仍可收到事件类型,但不会收到文本或勾选值。密码、文件和隐藏输入始终拒绝。宿主动作仅可由可信 UI 事件触发,按清单权限、动作参数和会话状态再次校验;生产构建也有全局 worker 上限。跨浏览器验证和独立安全审查仍待完成。
```json
{
"schemaVersion": 4,
"packageType": "open-skin",
"id": "community.example-plugin-skin",
"name": "Example plugin skin",
"version": "1.0.0",
"author": "Example author",
"license": "MIT",
"entry": "skin.css",
"plugins": "plugins.json",
"minAppVersion": "0.2.7-preview"
}
```
`plugins.json` 顶层 `schemaVersion` 当前为 `1`,并包含 1–64 个插件。每个插件声明 `id`、`name`、`version`、`apiVersion: 1`、`page`(`home` 或 `voice`)、`mode`(`widget` 或 `surface`)、必需的 `entry`、可选的 `mount`、`runtime`、`style`、素材路径数组 `assets` 和 `permissions`。入口扩展名 `.js` 默认对应 `javascript`,`.wasm` 默认对应 `wasm`;显式 `runtime` 必须与入口扩展名一致。入口及样式必须位于 `plugins/<id>/`;素材必须位于该插件自己的 `assets/` 子目录,只能是本地图片或 woff2 字体。插件不能共享文件;同一公开页面最多有一个 `surface`,且必须申请 `ui.surface.replace`。surface 不能声明 `mount`;widget 可选声明一个与 page 相符的宿主槽位。未指定时放在页面级插件宿主中。`ui.input.read` 是单独的输入值读取权限,授权提示会说明浏览器自动填入的值也可能被读取;不得让用户在皮肤输入框中输入密码或其他秘密。其余权限只能从 `src/shared/skin-plugin.ts` 的现有权限表中选择。
`plugins.json` 不超过 256 KiB;每个入口 JS 或 Wasm 不超过 256 KiB,每个样式 CSS 不超过 512 KiB;每个插件最多声明 32 个素材。客户端导入会拒绝不符合固定内存、导入、导出和 Wasm 模块结构限制的入口。皮肤包整体仍受通用 ZIP 文件数、展开大小、图像和字体限额约束。v1–v3 不接受插件代码。v4 JavaScript 仍只校验、缓存,不执行。生产 Wasm 仅在用户显式授权、摘要匹配时通过有界解释器启动一次性任务;它已支持上述权限化只读投影、安全 UI 更新和首版宿主动作桥。动作由可信 UI 事件引发、由宿主按插件权限和会话状态复核;浏览器瞬时手势传递尚未验证。数据变化会触发一轮新的有界执行。不要将有 DOM 的 iframe 当作网络沙箱:sandbox 不阻止 iframe 自己导航,`navigate-to` 也不能作为跨浏览器安全保证。完整运行时还需补充作者工具、端到端验证和独立审查,不可退回固定原生控件目录。
widget 的可选 `mount` 只接受这些公开锚点:`home.header.after`、`home.content.before`、`home.content.after`、`home.footer.before`、`voice.server-rail.before`、`voice.server-rail.after`、`voice.header.before`、`voice.header.after`、`voice.activity.before`、`voice.activity.after`、`voice.chat.before`、`voice.chat.after`、`voice.channel-panel.before`、`voice.channel-panel.after`、`voice.audio-dock.before`、`voice.audio-dock.after`、`voice.mobile-nav.before`、`voice.mobile-nav.after` 和 `voice.workspace.overlay`。它们提供初始语义位置;作者仍可用插件 CSS 和本地布局编辑器自由调整位置、尺寸、显隐、安全外观及同级顺序。surface 替换内置页面时,如果声明的槽位不存在,插件会回退到页面级宿主,避免 UI 丢失。专用的插件挂载管理界面仍未实现。布局权限只覆盖当前皮肤中实际渲染的插件节点,不能越过自身节点调整其他插件或宿主恢复控件。生产 v4 宿主已按 descriptor 管理当前页 widget/surface、授权、输出、事件循环、样式和清理。
## 首页内容和文案
`content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例:
@@ -121,16 +274,26 @@ assets/brand.woff2 # 可选:自带字体
下列名称来自当前前端模板。对新功能,作者可以先用通用 `control` 部件;后续新增稳定部件会更新本目录。
服务器和频道密码弹窗共用 `auth.password.backdrop`、`auth.password.dialog`、`auth.password.decoration`、`auth.password.eyebrow`、`auth.password.title`、`auth.password.lead`、`auth.password.form`、`auth.password.label`、`auth.password.field`、`auth.password.field-icon`、`auth.password.error` 和 `auth.password.actions`。
服务器和频道密码弹窗共用 `auth.password.backdrop`、`auth.password.dialog`、`auth.password.close`、`auth.password.close-icon`、`auth.password.decoration`、`auth.password.eyebrow`、`auth.password.title`、`auth.password.lead`、`auth.password.form`、`auth.password.label`、`auth.password.field`、`auth.password.field-icon`、`auth.password.input`、`auth.password.error`、`auth.password.actions`、`auth.password.cancel`、`auth.password.submit`、`auth.password.spinner` 和 `auth.password.submit-icon`。
| 页面区域 | `data-ws-part` |
| --- | --- |
| 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` |
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.favorite-toggle`、`home.identity`、`home.identity-actions`、`home.identity-import.open`、`home.identity-export.button`、`home.identity-import-dialog`、`home.identity-import.header`、`home.identity-import.close`、`home.identity-import.textarea`、`home.identity-import.drop-zone`、`home.identity-import.file-button`、`home.identity-import.error`、`home.identity-import.security`、`home.identity-import.footer`、`home.identity-import.cancel`、`home.identity-import.submit`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.mobile-more`、`voice.mobile-nav` |
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.server-history.item`、`home.server-history.select`、`home.server-history.favorite-toggle`、`home.favorite-toggle`、`home.identity`、`home.identity-actions`、`home.identity-provider.button`、`home.identity-provider.label`、`home.identity-import.open`、`home.identity-export.button`、`home.identity-import-dialog`、`home.identity-import.header`、`home.identity-import.close`、`home.identity-import.textarea`、`home.identity-import.drop-zone`、`home.identity-import.file-button`、`home.identity-import.error`、`home.identity-import.security`、`home.identity-import.footer`、`home.identity-import.cancel`、`home.identity-import.submit`、`home.server-announcement`、`home.server-announcement.title`、`home.server-announcement.body`、`home.social-links`、`home.connection-status`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.action-trigger`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.mic-status`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.audio-settings.device-select`、`voice.audio-settings.device-select-trigger`、`voice.audio-settings.device-select-chevron`、`voice.audio-settings.device-select-menu`、`voice.audio-settings.device-select-option`、`voice.mobile-more`、`voice.mobile-nav` |
| KOOK 频道树与服务器切换 | `voice.server-switcher`、`voice.server-switcher.trigger`、`voice.server-switcher.menu`、`voice.server-switcher.item`、`voice.server-switcher.icon`、`voice.server-switcher.label`、`voice.server-switcher.current`、`voice.server-switcher.empty`、`voice.channel-tree.list`、`voice.channel-tree.empty`、`voice.channel-tree.node`、`voice.channel-tree.line`、`voice.channel-tree.expander`、`voice.channel-tree.row`、`voice.channel-tree.icon`、`voice.channel-tree.join-hint`、`voice.channel-tree.name`、`voice.channel-tree.count`、`voice.channel-tree.branch`、`voice.channel-tree.member`、`voice.channel-tree.avatar`、`voice.channel-tree.member-name`、`voice.channel-tree.member-muted`、`voice.channel-tree.member-screen-share`、`voice.channel-tree.member-speaking`、`voice.channel-tree.member-away` |
| 快速服务器 | `voice.favorite-servers.rail`、`voice.favorite-servers.rail.list`、`voice.favorite-servers.rail.item`、`voice.favorite-servers.server`、`voice.favorite-servers.avatar`、`voice.favorite-servers.tooltip`、`voice.favorite-servers.favorite-toggle`、`voice.favorite-servers.add`、`voice.favorite-servers.strip`、`voice.favorite-servers.strip.item`、`voice.favorite-servers.strip.server`、`voice.favorite-servers.strip.favorite-toggle`、`voice.favorite-servers.strip.add`、`voice.favorite-servers.switch-status`、`voice.favorite-servers.current-toggle`、`voice.favorite-servers.dialog-backdrop`、`voice.favorite-servers.dialog`、`voice.favorite-servers.dialog.header`、`voice.favorite-servers.dialog.close`、`voice.favorite-servers.dialog.form`、`voice.favorite-servers.dialog.field`、`voice.favorite-servers.dialog.input`、`voice.favorite-servers.dialog.target`、`voice.favorite-servers.dialog.hint`、`voice.favorite-servers.dialog.actions`、`voice.favorite-servers.dialog.cancel`、`voice.favorite-servers.dialog.submit` |
| 聊天与菜单 | `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` |
`voice.member.avatar` 是语音活动区头像;`voice.member-row.avatar` 是右侧成员树头像。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
`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`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
`voice.channel-tree`、`voice.server-switcher`、`voice.server-header` 和 `voice.server-banner` 是 WebSpeak 可信宿主控件。频道树按 TeamSpeak 返回的层级展示语音频道与成员;展开按钮只改变本地显示,双击频道或聚焦后按 Enter 才加入频道。服务器栏布局让频道成员保持可见,折叠按钮只收起子频道。成员头像和语音状态只在宿主渲染的频道树中出现,不会传给皮肤插件。服务器头部在宿主中展示状态并按频道名筛选;切换入口只列出本机收藏和最近连接,可用不透明本地标识触发既有连接流程;地址、密码和身份材料不会传给皮肤组件。服务器欢迎区需 `session.status.read`,从 TeamSpeak `serverinfo` 读取横幅 URL 和欢迎语;没有可用内容时隐藏。欢迎语作为纯文本渲染;`voice.server-banner.image`、`voice.server-banner.welcome`、`voice.server-banner.icon`、`voice.server-banner.title` 与 `voice.server-banner.body` 可由布局编辑器调整。
首页快速连接和语音工作区的服务器栏共用同一列表:收藏项排在前面,最近连接补在后面;地址相同的收藏与历史只显示一项。每项的星标按钮可在两个位置收藏或取消收藏,取消收藏后若该服务器仍在最近连接中,它会留在列表的最近连接位置。皮肤可通过 `data-ws-state="favorite|recent"` 区分首页条目,通过 `data-ws-server-kind="favorite|recent"` 区分语音栏条目。
首页身份选项支持导入 TeamSpeak `.ini` 或身份字段,并可导出为 TeamSpeak `.ini`;导入弹窗解析身份的过程在浏览器本地完成。自定义皮肤可以分别调整身份操作按钮、粘贴区、拖放区域、安全提示和弹窗按钮,但不得隐藏或弱化权限继承与私钥安全提示。
@@ -182,11 +345,11 @@ assets/brand.woff2 # 可选:自带字体
### 固定布局与交互边界
皮肤校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的 CSS 声明,包括 `display`、`position`、`inset`、`z-index`、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件、字号、行高、字距、大小写转换和换行方式等。也不能通过 `all` 重置组件或用伪元素生成/替换文字。动画可以用于颜色、阴影、滤镜等装饰效果,但关键帧同样不能动画化布局属性。
以下 CSS 限制适用于 v1 和 v2:校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的声明,包括 display、position、inset、z-index、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件和字号等。v2 的位置和尺寸只从经过 schema 校验的 layout.json 生效。v3 为支持自由布局而允许这些声明,但仍限制皮肤根作用域、公开钩子、危险值和外部资源;只通过 CSS 隔离不能阻止皮肤作者遮挡控件。
因此,皮肤可以把成员头像绘制成角色徽章、给屏幕播放器加主题边框和背景、换首页美术素材,但不能移动播放器、压缩文字、扩大/缩小成员卡片、把锚定浮层改成模态弹窗,或挪动按钮的点击区域。用 `background-position` / `background-size` 只调整图片在既有区域中的裁切,不改变组件盒子。轮廓或内阴影可作为不参与排版的描边。
因此,v1/v2 CSS 可以更换艺术素材、颜色和表面风格,但不能重排组件。v3 可以用 CSS 重新安排界面和组件盒子,也能隐藏普通界面部分;基础组件由宿主继续创建,宿主的恢复和权限 UI 位于皮肤作用域外。所有版本都应确保焦点、文字、键盘和触屏操作可用。
外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也受同一限制,不能用来重排组件。上线前仍需预览桌面与窄屏、所有五种语言、日夜基础主题、键盘焦点、减少动效偏好,并确认浮层和必要控件保持在原位、文字未被裁切。
v1/v2 外观可以因窄屏而更换图片裁切或装饰,但 @media 规则也受固定布局限制。v2 应在布局数据中分别设置桌面、平板和手机配置;v3 可用媒体查询构建响应式 CSS。上线前仍需预览各设备尺寸、所有五种语言、键盘焦点、减少动效偏好,并确认必要控件可用、文字未被裁切。
## 安全边界和限制
@@ -198,7 +361,7 @@ assets/brand.woff2 # 可选:自带字体
| 解压总大小 | 50 MiB |
| ZIP 条目数 | 128 |
| 单个 CSS 文件 | 512 KiB |
| `content.json` | 256 KiB |
| `content.json` / `components.json` | 256 KiB |
| 单张图片(包括预览) | 16 MiB |
| 单个 WOFF2 字体 | 4 MiB |
| 每实例皮肤数 | 50 |
@@ -206,7 +369,7 @@ assets/brand.woff2 # 可选:自带字体
压缩包路径穿越、重复/冲突路径、符号链接、异常 ZIP 元数据和本地文件头/目录不一致都会被拒绝。仅允许受支持的 CSS at-rule:`@media`、`@supports`、`@container`、具名 `@layer`、`@font-face` 和 keyframes。`@import`、脚本、HTML、外部网络资源会被拒绝;`!important` 可用于皮肤作用域内的样式。字体 `local()` 也会拒绝,避免绕过包内字体来源。
必要操作控件(加入/退出、麦克风、设置、菜单、屏幕共享退出、音量、全屏等)及其布局容器不能被隐藏或整体重置。只有下列明确标记为可选的装饰部件,才允许通过不改变排版盒子的透明度效果淡出:
v1/v2 校验器会阻止隐藏必要操作控件和其容器。v3 可改变显示状态,因此皮肤开发者必须保留语音操作路径;授权界面、皮肤选择和恢复入口由宿主在皮肤作用域之外提供。以下选择器是旧格式对可选装饰部件的透明度白名单:
```css
[data-ws-part="home.hero.eyebrow"]
@@ -229,23 +392,34 @@ assets/brand.woff2 # 可选:自带字体
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
皮肤可以重画控制外观,但不能重新布置或阻断加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等必要操作。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、日夜基础主题、键盘焦点与减少动效设置。
皮肤可以重画控制外观。v1/v2 不能重新布置必要操作;v3 可以,因此须人工实测加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等操作的可达性。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、键盘焦点与减少动效设置。
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
## 制作与验收
1. 复制 `docs/examples/illusia-voice/`,先修改 `manifest.json` 的唯一 `id`、名称、作者、版本和授权。ILLUSIA 是完整的美术参考,不是必须沿用的角色或配色。
2. 只使用本目录公开的 `data-ws-part`、`data-ws-page`、状态属性和包内静态资源。不要依赖 Vue 内部 class。
3. 使用本地资源编写 `skin.css`;需要改首页文字或公开翻译时补充 `content.json`。
4. 在包根目录生成 ZIP,再改扩展名为 `.wskin`。PowerShell 示例:
1. 选择最接近目标的 `docs/examples/` 示例,复制其皮肤源码目录,并修改 `manifest.json` 的唯一 `id`、名称、作者、版本和授权。ILLUSIA 是美术参考,不要求沿用它的角色或配色。
2. 先查本文件和系统规格中已经发布的公开钩子、数据、控件和动作。不要依赖 Vue 内部 class、未公开的数据路径或某个实例的本地文件。
3. 将皮肤的页面/组件结构、样式、文案、布局及所有资源放在包目录中:CSS/图片/字体写入 `skin.css` 和 `assets/`,可选多语言文案写入 `content.json`,声明式组件写入 `components.json`,作者默认布局写入 `layout.json`,当前支持的插件逻辑和资源放进 v4 `plugins/`。运行时动态数据使用公开上下文;TeamSpeak 行为使用已发布的宿主动作。
4. 皮肤任务中不要修改 WebSpeak 核心客户端、服务端、共享协议或宿主控件。若没有足够的通用公开接口,先写明需要的数据/动作、权限和兼容性,再将它作为独立的平台工作处理;不要给某款皮肤增加专用核心分支。
5. 在包根目录生成 ZIP,再改扩展名为 `.wskin`,只包含 manifest 声明的文件。PowerShell 示例:
```powershell
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\illusia-voice.zip -Force
Rename-Item .\illusia-voice.zip illusia-voice.wskin
```
5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置,确认组件位置、尺寸、排列与未启用皮肤时一致。
6. 检查至少一个窄屏尺寸和桌面尺寸,并检查焦点可见、对比度、动效偏好;确认没有第三方素材授权问题。
6. 使用皮肤导入器验证生成的 `.wskin`,再在 `/admin/skins` 导入这个确切文件。用访客浏览器分别检查连接首页、语音页和 `/demo`;测试自定义图片、交互控件、会话状态、成员、聊天、屏幕共享及设置。v1/v2 检查固定布局;v2 检查作者默认布局和用户本地覆盖;v3/v4 检查授权拒绝/撤销、数据边界和失效恢复。
7. 检查窄屏与桌面、所有支持的语言、长文案、键盘焦点、对比度和减少动效偏好,并确认素材可再分发。若声称跨实例可移植,应在两个兼容版本的实例导入同一份 `.wskin`,记录并比较文件 SHA-256;不要为第二个实例复制核心代码改动。
当前自动化回归涵盖 ZIP/清单验证、资源路径、CSS 隔离与拒绝规则、文案结构和服务端皮肤目录读写。视觉排版、内容遮挡和浏览器间表现仍须人工预览。
自绘成员列表时,`session.members` 可读取 `screenSharing` 与 `screenShareStreamId`;这两个成员字段和 `screenShare.streams` 一样要求 `voice.screenShare.read`。用 `member.screenSharing` 显示共享标记,再将 `member.screenShareStreamId` 绑定到 `voice.joinScreenShare`(还需 `voice.screenShare.control`)即可让用户观看。未声明/未获共享读取权限的皮肤不会收到这两个字段;整页替换皮肤仍须在自己的成员列表中绘制标记或观看入口。
## 本轮实现问题记录
- 整页替换必须是用户明确批准的能力;仅安装皮肤不能隐藏普通首页或语音页。schema v2 surface 应声明 `ui.surface.replace`,并验证拒绝授权和撤销后普通界面会恢复。
- surface 上的“恢复内置皮肤”操作必须调用无条件的内置皮肤切换路径;用于“皮肤加载失败”提示的回退函数会在正常情况下直接返回。
- 自定义服务器栏需要用 `servers.quickList` 同时显示收藏与最近连接;只能把标签、类型、当前标记和随机令牌交给组件,切换时再由宿主解析本地目标。
- 最近连接和默认收藏名可能直接是服务器地址;组件上下文会在投影阶段将这种标签改为通用名称,不能改为暴露原始地址。
- KOOK 登录后的前两个用户授权语音房间已在 IAB 中读取。记录的仅为语音界面布局关系;没有保存服务器/房间标识、成员名称或聊天内容。完整的发现、运营及管理页面不属于皮肤范围,也没有检查。
+130
View File
@@ -0,0 +1,130 @@
# WebSpeak 皮肤与运行时核心耦合跟踪
## 目标与判定标准
持续检查 WebSpeak 运行时核心中是否存在“只是为了让 KAAK 正常运行,而不是皮肤系统普适能力”的代码。按用户给出的定义,这类皮肤专属行为若必须改动运行核心才能工作,就记为耦合。此文件用于逐次记录扫描范围、证据、结论、处理状态和下次检查位置。
皮肤 UI、布局和专属展示应由 `.wskin` 包及已发布的通用皮肤 API 表达。仅仅因为目前只有 KAAK 使用某项中性 API,并不足以认定它是 KAAK 专属;需要结合 API 的实现、用途和包内调用证据判断。
## 扫描边界
- 运行时核心:`src/**`、`web/src/**` 中会参与服务端或浏览器运行的代码。
- 皮肤声明与样式:`docs/examples/**`、`.wskin`、皮肤目录中的 CSS/组件 JSON。它们用于判断消费者和需求来源,不计为核心耦合点。
- 测试、目录清单和打包脚本不计为运行时行为;若其中只有 KAAK 的回归断言,作为证据记录即可。
- 扫描时同时检查显式 `KAAK/kaak` 分支、仅由 KAAK 消费的宿主组件/布局分支,以及由 KAAK 使用但可能具备普遍价值的新增 API。
## 当前扫描记录
日期:2026-10-12
分支:`dev`
检查点:第四轮从候选项续扫;已核对 KAAK 3.1.28—3.1.86 的运行时改动节点,确认当前 21 项宿主 widget 注册表与实现完全匹配,并逐一对比示例消费者。KAAK 密码文案 skin-ID 分支、MyTS 占位按钮、`room-panel` 宿主分支、音频设置私有结构和首页 `kaak-home-*` 运行时样式钩子为已确认的核心耦合;前四者为显式功能/结构适配,首页钩子是 KAAK 命名 DOM 依赖。聊天/音频动作、`stateScope` 与 resetKey 具有通用 schema/权限语义,不按单一消费者认定为专属。`server-password` 是适用于任意皮肤的通用语义状态,列为低风险文档/兼容性监视项;其余私有 Vue class 依赖集中于非交互结构,作为皮肤包兼容性风险和通用 API 覆盖缺口跟踪。runtime Wasm plugin host 未发现 KAAK 专用路径,KAAK 包当前也未声明 runtime plugins。
### 扫描耦合级别总表
本表汇总已确认耦合、宿主私有 DOM 兼容风险和经审阅的低级别候选;下方逐次扫描记录继续保留为证据日志。“高(已解除)”保留最初发现级别并标明当前已去耦;“低(监视)”表示目前证据倾向于通用皮肤能力或尚未确认是 KAAK 专属,不计入已确认的核心专属耦合;兼容性风险行描述的是 KAAK 样式依赖宿主私有 DOM,不等同于 KAAK 专属运行逻辑。重复出现的部件已合并,避免重复计数。
| 位置 | 证据与判定 | 级别 |
|---|---|---|
| `web/src/views/WebClient.vue`;历史 `c6eeb49` | 原分支按 `BUILTIN_KAAK_SKIN_ID` 覆写密码弹窗按钮。现改为通用消息键 `passwordDialogConfirm`,KAAK 在自己的 `content.json` 提供多语言文案,其他皮肤回退宿主默认翻译;无皮肤 ID 判断。 | 高(已解除) |
| `src/shared/skin-plugin.ts`;`web/src/views/WebClient.vue`;历史 `458f95c`;`web/src/services/identity-provider.ts` | 原 `home.myts-login` 升级为需要 provider ID/名称的通用 `home.identity-provider`。宿主统一分发登录请求,应用代码可注册适配器;KAAK 只声明 `myts`,当前仍诚实提示开发中,没有声称已实现认证。 | 高(已解除) |
| `web/src/views/WebClient.vue`;`docs/examples/kaak-voice/skin.css` | 首页宿主 widget 现在只输出通用语义部件(公告标题/正文、社交链接、连接状态和身份入口)。KAAK 的专属定位、颜色和样式选择器留在皮肤包,核心不再输出 `kaak-home-*` 或 `kaak-myts-*` DOM 类。 | 高(已解除) |
| `src/shared/skin-plugin.ts`;`web/src/views/WebClient.vue`;`web/src/components/web-client/AudioDock.vue`;历史 `21c008d`;`docs/examples/kaak-voice/components.json` | 移除 `room-panel` 布局值和宿主桌面/移动专用分支。KAAK 在声明树中绘制自己的桌面控制条,噪声抑制、伴奏状态与动作通过通用权限化音频 API 提供;通用 `voice.audio-controls` 保留原生默认表现,不再接受 KAAK 布局选项。 | 高(已解除) |
| `web/src/components/web-client/AudioSettingsDialog.vue:27,35,80,89,91,105,107,164,184,186,200,202`;`docs/examples/kaak-voice/skin.css:2895,2962,2973,3031,3039,3319,3322`;历史 `2a80ade`;`docs/KAAK-CLONE-WORKLOG.zh-CN.md:302-307` | KAAK 视觉需求驱动核心弹窗加入 `.settings-audio-card`、`.settings-form-row`、`.settings-form-control` 等分组结构;KAAK 样式依赖这些未公开的内部类,默认样式和其他示例没有消费者。工作日志的通用复用意图尚未形成公开部件合同。 | 中 |
| `web/src/components/web-client/VoiceServerHeader.vue`、`VoiceChannelTree.vue` / `VoiceChannelTreeItem.vue`、`MemberActionsMenu.vue`、`ChatPanel.vue`、`AudioDock.vue`(默认布局)、性能面板;`docs/examples/kaak-voice/skin.css`;`web/src/services/skin-runtime.ts:170-190` | KAAK 当前样式仍依赖这些通用宿主控件的私有 DOM 类/层级,例如头部标题与搜索、频道成员标记、菜单细节、聊天作者/时间、默认音频坞细节和性能次级文字;其中部分非交互节点没有稳定 `data-ws-part`。静态交叉扫描统计到 54 个当前命中的非交互无专属 part class;该总数包含上一行已单独指出的音频设置结构选择器,不能与上一行相加;排除了已单列的 `kaak-home-*` 专属钩子。这是皮肤包对核心模板的兼容性/API 覆盖风险,不是 KAAK 专属运行分支。可由父/子公开 part 表达的横幅 copy、共享波形颜色、频道分支样式不计入此项。 | 中(兼容性风险) |
| `src/shared/skin-plugin.ts:76,481-482`;`web/src/views/WebClient.vue:1918`;`web/src/components/web-client/VoiceChannelTree.vue:58`、`VoiceChannelTreeItem.vue:52,242,272`;`docs/SKIN_DEVELOPMENT.md:167`;历史 `96d2eba` | `server-sidebar` 目前由 KAAK 首先/唯一消费,但它作为任意频道树可选布局写入通用文档,控制成员展示和折叠,没有 KAAK ID 或专属数据路径;先列为低级别监视,不认定为专属耦合。`96d2eba` 引入服务器头部/侧栏,不是 `room-panel` 的来源。 | 低(监视) |
| `src/shared/skin-plugin.ts:40-65`;`web/src/views/WebClient.vue:1784-1936,2031`;`docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md:27`、`docs/SKIN_DEVELOPMENT.md:165` | `home.connection-status`、`home.server-announcement`、`home.social-links`、`voice.server-header`、`voice.server-banner`、`voice.channel-tree`、`voice.member-cards`、`voice.performance-panel` 目前只在 KAAK 示例找到消费者,但功能语义由通用连接状态、管理端公告、全站链接及服务器/频道/成员/性能数据驱动,控件 ID 已公开且无 KAAK 分支;公告/社交的 KAAK 类名耦合已单独列为高风险。`voice.server-switcher` 没有示例消费者,故不列入。 | 低(监视) |
| `src/shared/skin-plugin.ts:69-77,480-489`;`web/src/views/WebClient.vue:1918`;`docs/SKIN_DEVELOPMENT.md:165`;`docs/KAAK-CLONE-WORKLOG.zh-CN.md:351,511,521` | `memberActions` 与 `memberDragDrop` 当前只有 KAAK 包启用,但公开文档将其定义为通用可选能力,菜单和移动操作复用宿主既有流程;没有 KAAK 专属分支。保留监视,不能只凭唯一消费者升级为专属耦合。 | 低(监视) |
| `web/src/components/web-client/ServerPasswordDialog.vue:5,11`;`docs/examples/kaak-voice/skin.css:4078-4305`;`docs/SKIN_DEVELOPMENT.md:271`;历史 `458f95c` | `data-ws-state="server-password"` 目前只被 KAAK 用来区分浅色服务器密码弹窗,但它表达服务器/频道凭据的通用语义,机制适用于任意皮肤且无 KAAK ID 判断。精确状态值文档覆盖较少,作为低级别兼容/文档监视项,不算已确认的 KAAK 专属逻辑。 | 低(监视) |
### 本次续扫(2026-10-12)
- 公开规格检索区分了 CSS 部件 `voice.chat.status`(`docs/SKIN_DEVELOPMENT.md:288`)与运行时投影 `chat.status`:目前没有找到 `chat.status.panelOpen/tab/tabLabel`、`chat.togglePanel`、`audio.openSettings` / `audio.settings.open`、组件 `stateScope` 或 `room-panel` 的公开合同。当前 KAAK 包实际绑定 `chat.status.panelOpen` 与 `chat.status.tabLabel`;`chat.status.tab` 虽被通用上下文允许,但没有被此包引用。规格第 27 行只列出了宿主 widget ID,未描述这些字段、动作和布局值。
- `chat.status` 的字段由 `src/shared/skin-runtime-plugin-context.ts` 在 `chat.channel.read` 权限下白名单投影;`chat.togglePanel` 同样需要该权限,并调用普通聊天 composable 的开合状态;`audio.openSettings` 受 `audio.settings.open` 权限控制,宿主只打开可信音频设置对话框。实现没有 KAAK ID 判断,语义适用于自定义聊天/音频界面,因此不计为耦合;公开文档缺少这些字段和动作的说明,作为文档缺口记录。
- `stateScope` 只接受已公开的标量上下文路径,并通过同一路径权限检查;`ui.toggleState.resetKey` 只重置 schema 声明的布尔本地状态。两者由宿主通用机制实现,没有 KAAK ID 分支或 KAAK 专用数据路径,因此不计为耦合;公开文档对这些字段的说明仍不足。
- `home.social-links` 固定输出 WebSpeak 官方 GitHub、全站 QQ 群和 `/admin` 管理入口。QQ 地址在这次加入 KAAK widget 之前已用于默认首页社区弹窗;widget ID 也在公开宿主控件清单中,故其链接语义按通用站点导航排除。KAAK 的 `kaak-home-social-links` DOM 类和对应 CSS 仍属于上方记录的 KAAK 呈现耦合。
- `room-panel` 首次在 `21c008d` 以 KAAK 控制坞布局加入 schema 和宿主模板;当前唯一消费者、无公开合同且不能由已公开的皮肤动作重建其降噪按钮,现从候选提升为高风险耦合。后续若发现它已被定义为跨皮肤产品能力,再用正式合同证据复核。
- 重新按当前源码匹配宿主控件:注册表 21 项,`WebClient.vue` 实现 21 项,集合完全相同。内置示例中 KAAK 独占消费者包括首页状态/公告/社交/MyTS widget,以及语音服务器头部、服务器横幅、频道树、成员卡和性能面板;多个皮肤共用连接表单、皮肤/语言切换、聊天面板、音频控件、共享播放器等;`voice.server-switcher` 和 `voice.channel-panel` 暂无示例消费者。此计数只涵盖仓库内置示例。
- 对 `src/**` 与 `web/src/**` 再次检索字面量 `kaak`:运行路径仍集中在两个密码对话框的 KAAK ID 文案分支、KAAK 首页 widget 的 DOM 类名,以及内置皮肤目录元数据;首页 DOM 类名已列为确认耦合,其他候选仍结合消费者差异和结构分支判断。
- 逐项检查了 KAAK 独占的服务器头部、服务器横幅、频道树、成员卡和性能面板:宿主分别传入通用服务器标签/连接状态/收藏列表、公开 TeamSpeak 欢迎信息、公开频道树和加入频道动作、成员/共享状态、性能指标;实现没有按皮肤 ID 分支。它们仍是“目前只在内置 KAAK 示例使用”的监视项,而不是仅凭这一点升级为耦合。
- 历史提交 `458f95c feat: refine KAAK navigation and join experience` 首次把 `home.connection-status`、`home.myts-login` 和相应 KAAK 样式/翻译放入核心。工作日志明确要求 MyTS 只做入口外观并提示“开发中”,这支持将 MyTS 实现列为确认耦合;连接状态值来自通用错误/初始化状态,因此其功能语义按通用能力排除,KAAK DOM 钩子另列为确认耦合。`home.social-links` 使用产品全局链接,按通用导航排除;它在当前未提交差异中首次出现,未找到历史提交。
- 交叉核对未提交的运行时 diff(`src/**`、`web/src/**` 共 22 个改动文件)后,新增 KAAK 专属运行路径仍是本轮首页 widget/DOM 钩子;`WebClient.vue` 的 KAAK ID 分支继续只用于密码按钮文案。其余新增逻辑涉及 TeamSpeak 域名解析/安全校验、快速服务器匹配与中断切换、通用聊天状态/动作、成员显示/拖动及组件本地状态,没有发现 KAAK ID 条件或 KAAK 专用数据流。`skin-catalog.ts` 的 KAAK ID 只负责内置皮肤注册和包地址解析,作为目录机制排除。
- 在 `src/**`、`web/src/**` 重查运行时代码的 `KAAK/kaak` 标识后,除内置目录注册外,当前命中仍只有 `WebClient.vue` 的密码对话框 skin-ID 条件及 KAAK 首页 widget 类名/占位按钮;其他命中均位于 KAAK 包断言、目录测试或包验证中,不构成运行分支。通用 widget 的唯一 KAAK 消费仍只作为消费者差异记录。
- `git log -S'home.social-links'` 未找到历史提交,因为该 widget 仍处于当前未提交差异;`qqJoinUrl` 本身则早已服务于默认首页社区弹窗。此次归类依据当前运行语义与公开 widget ID,不把未提交差异伪称为已有提交历史。
- 版本缺口核对:`HEAD:docs/examples/kaak-voice/manifest.json` 是 `3.1.86`,工作树为 `3.1.106`,工作日志也止于 `3.1.86`;相关 KAAK 皮肤文件的 Git 历史在 `HEAD` 之后没有提交。因此 3.1.87—3.1.105 不是可逐提交追溯的已提交阶段,本轮以当前 `.wskin` 源文件与核心差异为依据,不推断缺失版本各自的修改内容。
- 当前 KAAK 组件文件差异增加了公告/社交通用 widget、声明式移动房间工具栏,并将聊天面板状态和开合动作接入公开 `chat.status` / `chat.togglePanel` API;这些移动布局仍在包内定义。它依赖的 `room-panel` 桌面控制坞分支仍是唯一已确认的相关专用布局耦合,其他 widget 的 KAAK DOM 类另列。
- 对照 `c6eeb49`、`458f95c` 与 `21c008d` 的提交补丁,三处高风险分支均能追溯到相应 KAAK 需求:skin-ID 密码按钮文案、无登录能力的 MyTS 首页占位,以及在 `room-panel` 桌面模板中加入语音设置入口和独立降噪切换按钮、在移动模板中加入对应设置/降噪入口。前两项是皮肤视觉专属;后一项把某一皮肤的控件组合直接加进核心。当前移动模板还在该布局分支中单独放置伴奏入口,详见本轮接口核验。
- 将历史筛选扩展为大小写无关的所有 `KAAK` 提交标题后,补核了先前过滤条件漏掉的 `17fb27b`、`53324ef`、`3476d47`、`a3bf476`、`83902e0` 及早期皮肤系统提交。服务器名称/图标被整理为受权限保护的 `servers.quickList` 公共投影;`auth.password.*` 钩子同时用于服务器与频道弹窗;频道成员操作复用同一个可选宿主菜单;频道容量源自 TeamSpeak 并进入公开 `session.channels`;权限差异随通用 widget 选项计算。这些改动由 KAAK 需求触发或首先消费,但当前实现均以通用权限、schema、数据投影或稳定部件形式供所有皮肤使用,未发现 KAAK ID 条件或专属数据路径。
- 历史提交 `2a80ade` 将音频设置中设备/音量字段重排为通用语义分组;工作日志明确为“通用音频设置控件”分组,功能本身不含 KAAK 分支。KAAK 样式当前依赖其中未公开的 Vue class,且示例目录中只有 KAAK 使用这些 class,因此仍记为结构兼容性风险,不把通用分组本身误升为 KAAK 专属运行行为。`8e580e7` 新增的设备选择器则提供了显式 `voice.audio-settings.device-select.*` 部件和通用键盘交互,属于可复用能力。
- `13f4dda` 历史上曾在皮肤布局编辑运行时强制 44px 触控尺寸;KAAK 工作日志记录该默认值随后已移除。当前 `skin-layout` 实现和布局 CSS 中均无 44px 强制规则,因此不属于现行耦合。
- 逐项核对完整 `skinPluginWidgets` 宿主映射后,核心选项分支只有 `room-panel`、`server-sidebar`、`screenShare`、`memberActions` 与 `memberDragDrop`,另有针对所有皮肤通用的视口分支。`server-sidebar`、屏幕共享隐藏选项、成员动作与拖动均有通用合同/文档;仅 `room-panel` 同时只由 KAAK 使用、无公开合同且附带专有控件组合,支持其高风险分类。
- 检查了完整 surface 渲染路径:`SkinPluginOutlet` 依据已授权组件的 `page` / `mode` 选择和抑制 surface,`WebClient.vue` 仅根据通用 `surface-change` 布尔值隐藏默认首页/语音壳;渲染器没有 KAAK ID 或专属组件名判断。KAAK、Harbor、Open Voice Surface 都声明了 `mode: "surface"`,因此整页替换路径属于跨皮肤能力。该 outlet 还在替换式语音表面通用注入服务器加号,不是 KAAK 专属行为。
- 续审剩余宿主模板与对话框状态后,没有发现新的 KAAK skin-ID 条件或其他隐藏布局分支;已存在的 `room-panel` 是唯一确认的 KAAK-only 选项分支。另确认 `ServerPasswordDialog.vue` 的 `data-ws-state="server-password"` 由 `458f95c` 加入,KAAK 3.1.83 样式据此区分浅色服务器密码弹窗和深色频道密码弹窗;这是没有 skin-ID 判断、适用于任意皮肤的语义状态,精确值只被 KAAK 使用且公开文档未列出,作为低风险文档/兼容性监视项。全仓搜索没有发现该状态值的其他运行时消费者。
- 扫描 KAAK CSS class 选择器并与 Vue 模板交叉核对:187 个不同选择器中,149 个与宿主 Vue class 相交;其中 73 个没有任何匹配宿主节点携带静态 `data-ws-part`,其余部分选择器有对应公开部件。由于运行时会给交互元素动态补通用 `control`,73 只是静态 class 统计,不代表缺失 API 数。开发规范明示 Vue class 不是稳定接口;将残留的私有 class 依赖作为包兼容性耦合风险,与核心是否含 KAAK 专用逻辑分开判定。
- 复查通用 `control` 的运行时覆盖:`skin-runtime.ts:170-190` 在所有 `.ws-skin-root` 下标记按钮、链接、输入、选择框、文本框、button/menuitem role 和可拖动元素,并通过 child-list observer 处理之后插入的节点。WebClient 页面根确实含 `.ws-skin-root`,KAAK 所用宿主控件位于其内,因此其按钮/输入可使用动态 `[data-ws-part="control"][data-ws-control-kind]`;非交互元素仍不会获得此部件。对当前 KAAK widget 命中的模板作标签分类,54 个 class 名仅出现在非交互且没有专属 part 的节点上,这是比“73 个静态缺 part”更准确的待审范围。
- 将内部 class 命中与当前 KAAK `components.json` 实际声明的 widget 交叉后,确认依赖落在当前使用的连接表单/语言与皮肤选择器、音频坞、频道树、聊天、成员卡、性能面板、共享播放器、服务器头部与横幅等宿主控件;并非全是旧默认壳的死选择器。缺少同节点公开部件的类集中在音频设置/坞细节、成员操作菜单、服务器头部细项、聊天元信息和少量状态图形。移动控制栏的旧类不据此算入当前 KAAK surface 依赖,避免误把默认壳隐藏时不渲染的选择器计为活依赖。
- 手工核对代表性缺口:`AudioSettingsDialog.vue` 仅在对话框根和设备选择器暴露公开 parts,KAAK 对其余约 30 个内部类做了细节样式;`VoiceServerHeader.vue` 的名称、状态标签、搜索和分隔区共 9 个 KAAK 命中都没有公开 part;`MemberActionsMenu.vue` 公开了菜单根、标题和移动子菜单,但关闭、个人音量、子菜单触发/箭头及空状态仍无单独 part。`AudioDock.vue` 的 KAAK 降噪/伴奏/控制组合依赖 `room-panel` 的专用实现,已计入高风险项,不重复列为单独候选。
- 继续逐项检查了频道树、聊天、共享/性能和横幅内部节点:频道树分支内容/成员列表、未静音麦克风图标、“你”标记没有直接 part;聊天 tab 标题附属文字、消息作者/时间元信息没有直接 part,但发送按钮有运行时通用 `control`;成员屏幕共享波形属于 live-indicator 子结构、性能面板的 `voice-audio-details` 和服务器横幅 copy wrapper 没有直接 part,标题/正文则各有公开 part。这些 class 被 KAAK 当前组件样式使用,属于非交互宿主结构的包到核心模板依赖;其中横幅文案自身已有 title/body 部件,不需要把这个既有展示再误判为专用横幅功能耦合。
- 逐类复核样式职责后,54 个候选并非都需要新部件:`.screen-share-wave` 只着色,可由现有 `voice.member.live-indicator` 继承颜色;`.ws-voice-server-banner-copy` 只设 `min-width: 0`,标题/正文已有独立公开部件;频道分支的边框/间距可主要放在现有 `voice.channel-tree.branch`。这些是可由已发布父/子部件表达的样式,不应被统计成必须新增 hook。仍有实质合同缺口的区域包括 `VoiceServerHeader.vue`(内部没有任何 `data-ws-part`)、`AudioSettingsDialog.vue` 多层布局/分组、聊天作者/时间元信息,以及频道树未静音麦克风和“你”标记;这些规则用类名或 DOM 层级才能区分。`memberActions` 菜单已有根/标题/移动面板部件,关闭、音量标签、子菜单行等细项需单独评估;控制按钮和输入本身已有动态 `control` 部件。
- 对上述剩余结构复核具体 CSS 用法:服务器头部整块的标题行、连接标签、搜索框与分隔线都靠私有 Vue class;音频设置的公开合同只有对话框根和设备选择器,KAAK 还依靠私有 class 排版分组、状态条和测试区域;聊天作者/时间虽可由消息体部件作为祖先限定,但当前皮肤需要区分作者、自身消息和时间,稳定子部件更直接;频道树“你”和活动麦克风缺少语义部件。成员菜单已有根、标题和移动子菜单,其它操作项按钮会动态获得通用 `control`,但体积/排列依赖类名,若需单项级主题则还缺通用菜单项语义。以上归类为皮肤包依赖宿主私有结构的兼容性风险/API 覆盖不足,不是新增的 KAAK 专用运行时分支;应优先补稳定的通用部件合同,避免把当前 Vue class 当兼容接口。
- 重新核对音频设置结构的起源:`2a80ade` 的确在 KAAK 专属布局提交中直接改了核心 DOM。新类在默认全局 CSS 和公开 part 表中都没有消费者,仓库示例也只有 KAAK 样式依赖;工作日志的“通用语义”说明复用意图,却没有形成系统合同。因此将其从待确认候选升级为中风险核心结构耦合,不把它误记为 skin-ID 条件分支。
- 重新审查 `96d2eba` 引入的 `voice.server-header` 与 `server-sidebar`:服务器头部组合通用连接状态、服务器快切列表和频道搜索;侧栏布局只改变通用频道树的成员展示与折叠方式。两者虽由 KAAK 首次提出且目前只有 KAAK 示例使用,但接口已公开、使用通用会话数据/现有连接操作,也没有 KAAK ID 分支;与 `room-panel` 将 KAAK 专属控制排布写入核心的情况不同,继续列为低风险通用能力。头部内部私有 class 的皮肤兼容风险仍按上方 API 覆盖缺口单独跟踪。
- 以当前 `dev` 工作树(`HEAD c994722`)重新检索生产运行代码的 `KAAK/kaak/MyTS/myts` 标识和布局条件:品牌标识命中仍只在内置目录注册、MyTS 占位 widget、首页 `kaak-home-*` DOM 类以及两个密码确认文案 skin-ID 条件;布局路径中 `room-panel` 仍是唯一含 KAAK 专属控件组合且无公开合同的分支,`server-sidebar` 则有通用文档合同。没有发现本次续审中新出现的 KAAK 专用运行分支;后续只在运行时文件出现新改动时重查,不重复当前完整字面搜索。
- 反查现有替代接口:`SkinPluginAction` / `ACTIONS` 仅提供麦克风、扬声器、音量和打开设置等动作,没有降噪切换动作;`21c008d` 与当前 `AudioDock.vue` 都证明 `room-panel` 会在宿主桌面/移动控件里注入专用降噪操作(移动布局还单独放置语音设置与伴奏入口)。密码弹窗虽有通用 `submitLabel` 组件属性,但它只由 `WebClient.vue` 按 KAAK ID 赋值;皮肤 schema/部件公开表没有提交文案配置。两者均缺少可由当前皮肤包独立表达的通用替代能力,支持现有高风险分类。
- 按用户关注点重新逐段审阅当前未提交的 `WebClient.vue` diff:服务器目标相等判断/连接中断、服务器显示名投影、`chat.status` 与 `chat.togglePanel`、`audio.openSettings` 都是与 skin ID 无关的通用连接或权限 API;新增的公告与社交 widget 功能也使用全站通用数据。该文件中确属 KAAK 呈现耦合的新增代码是 `kaak-home-*` 私有 DOM class,另有已单列的密码文案 skin-ID 条件和 MyTS 占位 widget;没有发现其他只为 KAAK 加入的隐藏分支。
- 按恢复点再次交叉搜索音频设置分组类:`settings-audio-card`、`settings-form-row`、`settings-form-control` 和 `settings-range-form-row` 仅命中 `AudioSettingsDialog.vue` 与 KAAK CSS;默认 `web-client.css` 和其它示例没有消费者,公开 part 文档只列 `voice.audio-settings` 根与设备选择器子部件。当前没有新的公开合同或跨皮肤证据替代它们,中风险结构耦合分类维持不变。
- 续审服务器头部内部结构:KAAK CSS 当前有 9 组选择器依赖 `VoiceServerHeader.vue` 的私有 class;默认全局样式和其它示例没有命中,组件内部也没有 `data-ws-part`。但整个 `voice.server-header` 控件作为通用宿主能力公开,行为只组合通用服务器状态、快切列表和频道过滤;因此其功能仍按低风险通用能力处理,内部 class 依赖计入皮肤兼容性/API 覆盖缺口,不另升为 KAAK 专用功能分支。
- 续审 `server-sidebar` 的频道成员模板:KAAK 样式使用的成员、头像、成员名、静音状态已有通用 parts;成员列表容器、本人标记、未静音麦克风图标和分支内容容器没有专属 part。`96d2eba` 把这些节点放在公开的 `voice.channel-tree` 通用 `server-sidebar` 布局分支中;功能不按 KAAK 专属分支统计,缺失的结构锚点继续归入私有 class 兼容/API 覆盖缺口。
- 校正聊天样式依赖的有效范围:当前 KAAK `components.json` 渲染 `voice.chat-panel`;旧 CSS 中 `kaak-workspace.chat-message-author`、`chat-message-time`、`chat-message-text` 等自定义消息部件在组件树里没有对应节点,不计为当前耦合。现行 ChatPanel 的作者/时间元信息由 KAAK 在公开 `voice.chat.message-body` 部件下通过 `.message-meta strong` 与 `time` 后代选择器样式化;这仍是非交互子结构的兼容性依赖,但可与已失效的旧选择器区分。
- 续审成员菜单:KAAK 通过公开可选 `memberActions` 启用通用音量、私聊、戳一戳、悄悄话、复制昵称和移动成员操作;`3476d47` 虽从 KAAK 需求起步,但不含 skin-ID 行为分支,菜单根、标题和移动面板都有公开 parts。关闭按钮、音量行、移动菜单触发器/箭头和空状态仍靠私有 class;可操作控件有通用 `control`,因此这是细节样式合同缺口,不认定为 KAAK 专属运行行为。
- 续审性能面板与成员共享细节:`.voice-audio-details` 在 `0a4fff6 feat: report live voice status...` 的通用性能组件中已存在,并非 KAAK 需求引入;KAAK 仅通过这个无专属 part 的 class 控制次级文字样式。性能面板根、面板、路由、指标、状态和 WebRTC 区域均有公开 parts。成员共享提示的 `.screen-share-live-indicator` 本身带 `voice.member.live-indicator` part;内部 `.screen-share-wave` 子节点只作装饰且 KAAK 只改颜色,可继承父部件的颜色。以上不升级为专属运行逻辑,分别保留私有结构兼容风险与可由父 part 表达的样式备注。
- 续审默认音频坞内部选择器:KAAK 会用 `.desktop-audio-dock-copy`、`.desktop-audio-dock-actions`、`.dock-slider-heading` 等内部 class 细调布局/文字;当前公开 parts 已覆盖音频坞、麦克风/扬声器区及各自弹出面板,滑杆也会获得通用 `control`。这些默认结构来自通用桌面音频控件和伴奏功能提交(`1c80791`、`0986c65`),不是 KAAK 专用改动;它们仍是内部 DOM 兼容风险。`.desktop-audio-dock-room-panel`、专用语音设置/降噪按钮则另按 `21c008d` 高风险分支记录,不与默认结构混算。
- 检查 Wasm runtime plugin host、manifest 校验、审批摘要和 action 转发:KAAK 3.1.106 清单没有 `plugins.json`/runtime plugin 声明;宿主以 `skinId` 隔离各皮肤的本地授权、按组件声明权限校验 action,并以通用 `page`/`mode` 控制生命周期与 surface,没有 KAAK 标识或 KAAK 专用路径,因此不列为耦合。
- 分发工件核验:当前清单版本为 `3.1.106`;示例与 `web/public/skins/kaak-voice.wskin` 两个 `.wskin` 的 SHA-256 相同。包内只有 `manifest.json`、`components.json`、`content.json`、`skin.css` 四项,且各项字节哈希都与 `docs/examples/kaak-voice/` 源文件匹配;本次审查所依据的 KAAK CSS/组件不是只存在于示例目录的未分发内容,包内也没有隐藏 JS/Wasm 插件资产。
- 首页公告卡片此前已按要求铺满左半栏并同步至 KAAK 包(`3.1.106`);用户要求冻结横幅 UI,本轮续审期间未改动横幅或运行实现。
### 历史改动交叉核对
本轮读取 `docs/KAAK-CLONE-WORKLOG.zh-CN.md` 中 3.1.28—3.1.86 的运行时相关节点,并用当前源代码和组件包核对其结论:
- `options.screenShare`、性能面板开合交互、音频设备选择与菜单定位、公开布局部件注册均描述为跨皮肤能力;它们没有 KAAK ID 分支,KAAK 只通过包配置或 CSS 消费,暂不列为耦合。
- 第一方 `docs/examples` 的宿主控件映射已逐项统计:`home.connection-form`、两个 app switcher、`voice.audio-controls` 和 `voice.screen-share-player` 被多个皮肤使用;`voice.screen-share-start` 由 KAAK/Harbor 使用,`voice.chat-panel` 由 KAAK/Open Voice Surface 使用。`home.connection-status`、`home.server-announcement`、`home.social-links`、`home.myts-login`、`voice.server-header`、`voice.server-banner`、`voice.channel-tree`、`voice.member-cards`、`voice.performance-panel` 当前只在 KAAK 示例使用;`voice.server-switcher` 当前没有示例消费者。这里的“只在 KAAK 使用”仅指仓库内置示例,不能推断外部皮肤包的使用情况。
- 服务器导航加号的记录明确要求任意皮肤、任意连接模式可用,宿主同时注入普通导航与替换式皮肤轨道;这是通用功能,不列为 KAAK 专属。
- 屏幕共享成员数据/标记已由 Open Voice Surface、Harbor 与 KAAK 共用;服务器横幅读取的是 TeamSpeak 握手公开数据,宿主控件和数据路径没有 KAAK skin-ID 条件,暂不列为耦合。
- 服务器头部、服务器横幅、频道树、成员卡、性能卡等 widget 虽然目前多由 KAAK 首先或唯一消费,但它们作为固定宿主能力写入公开皮肤 API;结合通用组件实现,本轮记录为低风险监视项,而非已确认专属分支。
- 工作日志中首页 myts 入口及密码按钮文案是当前可确认的 KAAK 专属需求;密码按钮分支、MyTS 占位控件和 KAAK 首页 DOM 钩子已列在“已确认的核心耦合”。聊天上下文/动作与频道状态作用域具备通用权限/schema 实现,按通用 API 排除;`room-panel` 根据最早提交和核心模板分支证据列为高风险耦合。
- 历史提交 `9f11d11` 为 KAAK 的逐频道聊天开合首次加入 `stateScope`;工作日志明确把它做成任意公开标量路径可用的通用作用域,因此不按当前单一消费者认定为耦合,但公开规格缺项仍需记录。`room-panel` 的首次实现实际在更早的 `21c008d`;`96d2eba` 随后引入的是 `voice.server-header` 与频道树 `server-sidebar`。两者已在开发文档中作为通用宿主能力公开;结合本轮对数据/操作来源和当前模板分支的复核,不列为高风险耦合,服务器头部内部 class 的兼容风险仍单独跟踪。
- `voice.server-header`、频道树的 `server-sidebar` 展示以及头像/成员行扩展分别出现在 KAAK 相关提交 `96d2eba`、`b13bdf1` 中;它们由显式 widget ID 或通用 `layout` 参数启用,没有发现按 KAAK 皮肤 ID 分支。按目前证据继续记为通用 API 的首个消费者,而非确认耦合。
- `chat.togglePanel`、`audio.openSettings` 的核心 action 枚举/权限映射和 `chat.status` 投影在当前工作树可见;提交历史搜索未定位到其引入提交。实现使用通用宿主动作和显式权限,无 KAAK 专属分支,因此归入通用 API;公开规格条目及非 KAAK 示例仍缺失。
### 已排除项
- `web/src/services/skin-catalog.ts:6,47-60,77` 中 KAAK ID、目录名称和包 URL 是内置皮肤发现/打包注册,不会因 KAAK 的视觉或行为要求改变运行核心执行路径,当前不算耦合。
- `src/shared/skin-plugin.test.ts`、`web/src/services/skin-pack.test.ts` 中 KAAK 专属断言仅是测试证据,不会进入运行时。
- `voice.screenShare.*` 等已被 Harbor、Open Voice Surface 等皮肤共同使用的能力不属于 KAAK 专属;本轮搜索确认这些 widget 能力有多个皮肤消费者。
- `voice.screen-share-start` 与默认 `voice.audio-controls` 均由 Harbor、KAAK 的组件包使用;通用控件本身不算 KAAK 独占。嵌套在 `voice.audio-controls` 内的 `room-panel` 特殊分支仍单独计为高风险耦合。
- 工作日志记录的 `options.screenShare`、共享成员状态投影、通用服务器导航加号、服务器横幅数据读取及设备选择器交互,都有跨皮肤 API/消费者或明确的全局适用范围;本轮没有发现对应的 KAAK-only 运行时分支。
- `memberActions`、`memberDragDrop` 在公开开发文档中作为通用可选能力描述;目前 KAAK 是唯一消费者,但单一消费者本身不足以证明代码只服务 KAAK。
- `home.server-announcement` 提供本地化管理端欢迎语,`home.connection-status` 显示通用连接/初始化错误状态;两者语义适用于任意首页且作为通用 widget ID 写入公开规格,不单独计为 KAAK 行为耦合。它们当前使用的 KAAK 命名 DOM 钩子已在确认耦合项中单列。
- `home.social-links` 输出 WebSpeak 官方 GitHub、全站 QQ 群与管理员入口;`qqJoinUrl` 也用于默认首页的社区弹窗,且该 widget ID 在公开规格中注册,因此按通用站点导航排除其功能语义。其 KAAK 命名 DOM 类和皮肤 CSS 依赖仍计在上方确认耦合项中。
- `web/src/components/web-client/ChatPanel.vue` 新增的 `data-ws-chat-*` 属性在当前所有 `docs/examples` 皮肤样式/组件中都没有命中;本轮没有证据证明这些钩子是 KAAK 运行所需,暂不计为 KAAK 耦合。
- `chat.status`、`chat.togglePanel`、`audio.openSettings`、组件 `stateScope` 与 `ui.toggleState.resetKey` 均由通用白名单、权限或 schema 状态机制处理,未发现 KAAK ID 分支;作为通用运行时 API 排除出耦合项,单独保留公开文档缺项。
- 本次公告卡片宽度调整位于 `docs/examples/kaak-voice/skin.css` 并重新打包到 KAAK `.wskin`,没有增加运行时核心分支。
- 本次从 `c994722` 基线继续核查当前工作树的运行时代码差异:没有新提交;新增/变更的核心文件涉及服务器目标解析、skin plugin schema/context/outlet、WebClient、聊天/成员/连接 composable、快速服务器服务和成员状态工具。新增的 `chat.status`、`chat.togglePanel`、`audio.openSettings`、`ui.toggleState.resetKey` 由通用权限和 schema 白名单表达;`SkinPluginOutlet` 的状态刷新也对所有皮肤一致生效。没有发现新的皮肤 ID 分支。
- `WebClient.vue` 当前差异中的快速服务器目标比较、连接中断后切换、服务端名称回退、聊天状态投影和音频设置动作均适用于通用工作区;现存 `options.layout === "room-panel"` 仍是此前确认的 KAAK-only 核心分支,没有新增计数。首页公告/社交 widget 的语义可供任意首页使用,但核心输出 `kaak-home-*` 类名仍属于已登记的高风险项,不重复计数。
- 其他本轮检查的增量:`memberPresenceKey` 将已在频道内的成员统一显示为在线/离开/发言,避免不可能的“状态未知”;成员拖动对输入控件的保护、快速服务器按规范化 TeamSpeak 地址匹配,以及 SRV/DNS 安全解析均不检查皮肤 ID,行为适用于所有皮肤/连接用户,未发现 KAAK 专属数据路径。测试、翻译、目录版本和皮肤包更新不构成运行时分支。
- 对已确认的核心分支做精确定位回查:运行时代码中 `BUILTIN_KAAK_SKIN_ID` 只用于 `WebClient.vue` 两个密码对话框的按钮文案;`room-panel` 只出现在 schema 值校验、`AudioDock.vue` 布局和 WebClient 桌面/移动控件分支;MyTS 是单一占位 widget;KAAK 首页私有类集中在公告、社交链接、状态与 MyTS 节点。以上均与已登记的四项高风险耦合重合,没有发现额外的运行时命中。
- 本轮完成当前状态收尾核验:全量检索生产 `src/**`、`web/src/**` 后,KAAK/MyTS 字面量仅落在两个密码文案条件、首页私有类/MyTS 占位、内置目录注册/包 URL 和对应翻译;布局值命中仅有 KAAK-only `room-panel` 与已有通用合同的 `server-sidebar`。测试与包名不参与运行逻辑。此结果与已登记清单一致,作为当前审计基线;后续有新运行时差异时再增量续查。
- 逐项提取当前 KAAK `components.json` 的 widget、option、数据路径和 action:两个 surface 使用的宿主控件都在注册表内;`screenShare`、`memberActions`、`memberDragDrop`、`server-sidebar` 有通用文档,`room-panel` 是唯一未公开且在核心绑定专属控件组合的布局值。实际依赖的未充分公开合同是 `chat.status.panelOpen/tabLabel`、`chat.togglePanel`、`audio.openSettings` / `audio.settings.open`、`stateScope` 和 `ui.toggleState.resetKey`;其实现都是通用权限/schema/状态机制,没有 KAAK 判断。它们是文档覆盖不足,不另计核心专属代码。宿主控件清单在系统规格中完整,开发手册的简短清单遗漏部分首页 widget,但不影响实现是否通用的判定。
- 验证实际皮肤包而非只看源目录:`docs/examples/kaak-voice.wskin` 与 `web/public/skins/kaak-voice.wskin` 内的 `manifest.json`、`components.json`、`skin.css`、`content.json` 均与对应源文件一致;两包均没有 `.js`、`.mjs` 或 `.wasm` 可执行条目。KAAK 的自定义布局行为来自声明式组件/公开动作,未藏在额外脚本里;前述核心耦合仍是由宿主硬编码功能/类名产生。
### 高等级处理(2026-10-12)
- 密码确认文案:两个宿主密码对话框统一读取通用 `passwordDialogConfirm` 消息;KAAK 在包内多语言覆盖,其他皮肤使用宿主语言字典,不再按内置皮肤 ID 分支。
- MyTS 入口:通用 `home.identity-provider` 接收受校验的 provider ID 和显示名;宿主应用分发层提供注册/调用适配器接口。KAAK 包只请求 `myts`,尚无 MyTS 适配器,因而仍显示开发中提示。
- 首页呈现:核心只输出公告、社交链接、连接状态和身份入口的通用 `data-ws-part`;首页专属排版留在 KAAK CSS。
- 音频控制台:移除未公开的 `room-panel` 选项及宿主布局分支;KAAK 声明自己的桌面控制条,通过通用音频状态、降噪和伴奏动作调用宿主既有功能。
- KAAK 皮肤包升级至 `3.1.107`,示例归档与内置公开归档重新打包并保持一致。
## 下次恢复位置
恢复基线:分支 `dev`、`HEAD c994722`;工作树 KAAK 包为 `3.1.107`。原 4 项高等级问题均已处理:密码文案改为包级消息覆盖,MyTS 入口转为通用身份提供方分发接口,`room-panel` 控件排布由 KAAK 声明树拥有,KAAK 首页不再依赖核心输出的私有类名。仍有 1 项中等级音频设置对话框私有 DOM 结构耦合,低级别监视项继续保留。下一轮从未处理的中等级开始;只检查自此工作树状态之后新增或改变的运行时文件及其皮肤依赖,不重复已解除的高等级项和横幅 UI 审查。
+4 -7
View File
@@ -1,14 +1,11 @@
# ILLUSIA风
ILLUSIA风 is a visual-only `.wskin` example built from the local artwork in `illusia-voice/assets/`. It styles the WebSpeak home page, voice workspace, screen-share player, and `/demo` with bright glass surfaces and cyan accents. The homepage skin follows the supplied reference art for the translucent navigation, matching glass skin and language selectors, an illustrated animated ILLUSIA skin option, a floating mascot with a visibly pulsing cyan waveform and expanding halo in the join card, a softly animated cyan aurora inspired by the visitor badge, three feature tiles, character visitor badge, mascot-accented join action, and full-width curved footer. The ambient waveform and halo slow down when reduced motion is enabled instead of disappearing. The voice-room skin uses the resting chibi illustration as the message-empty backdrop and places the main character illustration on the dedicated non-interactive artwork layer so it can rest over the edge of member cards or a live screen-share player without moving or blocking their controls.
ILLUSIA 风格 is a schema v3 open-skin example built from the local artwork in [illusia-voice/assets](./illusia-voice/assets/). Version 2.0.2 keeps its existing light-glass CSS and current-channel card, adds matching visual treatment for the host member-card screen-share status and watch action, and uses a black letterbox background for the fixed WebSpeak screen-share player. The package still uses WebSpeak's base translations and contains no executable skin code.
This package intentionally omits `content.json`: the existing WebSpeak translations supply every label and message, including the current and total visitor counts. A skin may optionally add localized copy overrides, but missing locales and fields continue to use WebSpeak's base content. Its CSS is visual-only: WebSpeak retains its component positions, dimensions, text flow, and interactions. In the voice room, the main illustration and headset use separate, non-interactive foreground layers with restrained perspective and shadows; the chat's empty state includes a CSS-drawn speech-bubble ornament, while its translated copy remains visible. The footer wave is a pre-rendered transparent asset sampled from the example's original curve, so it decorates the existing footer instead of introducing another layout element.
The new voice-page component is defined in [components.json](./illusia-voice/components.json). It reads only the current public channel name through session.status.read and uses a local mascot image for a compact, non-interactive glass badge. The component needs the user's local approval before it renders; that approval is scoped to this skin version and can be revoked from the host access control. It cannot switch channels, read favorites, access a server address, or control audio.
The package source is in [`illusia-voice/`](illusia-voice/). To build it from the repository root:
The CSS continues to style the WebSpeak home page, voice workspace, screen-share player and /demo with cyan accents and original art. The homepage includes translucent navigation and selectors, animated mascot details, feature tiles, a visitor badge, a join action and a curved footer. The voice workspace includes the shared quick-server list, channel/member views, chat empty state, screen-share art and audio controls. The shared member cards detect active screen shares and show a themed live badge and watch button. The mobile view keeps WebSpeak's responsive host navigation while applying ILLUSIA colors and artwork.
```powershell
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\docs\examples\illusia-voice.zip -Force
Rename-Item .\docs\examples\illusia-voice.zip illusia-voice.wskin -Force
```
The distributable package and the copy served from web/public/skins are built from the source folder. After changing source files, run `npm run skin:illusia:build` to recreate both copies. Run the package import test to confirm both copies stay byte-identical and valid.
Use only artwork you have permission to redistribute when publishing a skin to other WebSpeak instances.
+48
View File
@@ -0,0 +1,48 @@
# KAAK voice skin
The participant stage uses larger profile portraits (104px on desktop, reduced for narrow layouts). A live speaking state adds a pulsing accent ring and a visible waveform marker, including when participant names are hidden while chat is open. The ring and speaking status use KAAK's shared green accent.
The server sidebar can show the connected TeamSpeak virtual server's configured host-banner image and welcome message between the server header and channel tree. Both fields come from live server information; the card disappears when neither is configured, and a missing or failed banner image does not hide the welcome text. Welcome content is rendered as plain text.
The server sidebar can show the connected TeamSpeak virtual server's configured host-banner image and welcome message between the server header and channel tree. Both fields come from live server information; the card disappears when neither is configured, and a missing or failed banner image does not hide the welcome text. Welcome content is rendered as plain text.
The voice-channel sidebar follows KOOK's observed typography: 16px/700 server title, 12px/700 group title, 14px/700 channel title, and 12px/400 low-contrast member count.
Chat visibility is kept separately for each active TeamSpeak channel, so collapsing one room does not collapse the next room. TeamSpeak does not expose KOOK's music-channel category; a new channel therefore starts expanded until the user changes its chat visibility.
While the WebSpeak performance card is sampling, its refresh icon spins to show the busy state; the animation is disabled when reduced motion is requested.
KAAK is a schema v3 open-skin package with full connection and voice-workspace surfaces. Its desktop voice page follows KOOK's proportions: an 86px server rail with 58px icons and 18px vertical spacing, a 290px channel pane, a 40px top bar, a central participant stage, right-side chat attached to the current voice channel, and a lower-left voice dock. The server rail uses KOOK's rounded-square silhouette, a 2px green active outline and left-edge marker, with neutral fallback tiles and the muted purple active tile from the reference. The identity tile stays pinned at the bottom with a 54px circular monogram and connection-aware online dot; the server list scrolls when the window is short. The host provides a stable color-tone value derived only from the privacy-safe label, but the rail keeps the KOOK neutral tile treatment rather than exposing those tones. The KOOK voice room is the point-to-point visual reference: composition, member presentation, styling, and motion should be compared directly, rather than treating matching component types or approximate placement as sufficient. The left tree contains the TeamSpeak voice channels only; KOOK's separate text-channel group is outside this pass because TeamSpeak has no equivalent channel type. The current voice channel's text chat remains on the right. Closing it hides the entire panel, expands the participant stage, and leaves a reopen button in the stage heading; this happens without leaving the voice room. Its header uses the `#` channel mark and an unobtrusive close control; the composer sits at the bottom edge. Messages use author monograms, a separate identity/time line, and readable message text. The central stage uses WebSpeak's reusable member-card widget so available TeamSpeak profile avatars appear inside KAAK's participant tiles; the tiles use a wide 1.82:1 layout with a responsive grid to match KOOK's participant presentation. Member names stay hidden at rest while chat is open and fade upward into the lower-left label on hover; they remain visible while chat is collapsed. KAAK's CSS adds hover depth and a smoothly transitioning speaking ring driven by live voice state. Active screen shares appear on member cards with a live badge and a themed watch action; the share player remains a WebSpeak host component. The dock retains WebSpeak's trusted connection-quality, audio, and disconnect controls. Input/output volume buttons open hover or keyboard-focus panels with live numeric levels; sliders use a skin-colored progress track, a distinct thumb, and visible focus feedback. Audio input and output devices use a reusable keyboard-accessible picker with a scrollable option list, selected/highlighted states, and an animated chevron; KAAK styles the trigger and open list. The connection surface, voice workspace, and audio settings share KOOK's PingFang SC-first font stack; audio settings use 16px/600 section headings and observed 14px/400 field labels. Audio sliders use a 16px thumb with hover/focus feedback. The performance card opens with a short entrance motion and readable network/audio metrics. No real device, volume, or microphone state is changed during visual checks. The roster shows connected TeamSpeak clients only; it does not invent an offline list. Channel selection is single-click; joining is double-click. The narrow layout keeps the host's mobile controls available while retaining readable member tiles.
The single TeamSpeak voice-channel group in the left tree collapses and expands with a short two-way height and fade transition like KOOK's voice group; the separate KOOK text-channel group remains outside this pass. A first click selects a channel and reveals a brief “双击加入” hint; the hint disappears on the active room. The current voice-room heading keeps the channel name and live member count visible above the participant stage while the attached chat is expanded, matching KOOK's room view. Member cards expose WebSpeak's trusted member-actions menu from a small hover or keyboard-focus control; desktop cards also open it on right-click, and touch layouts keep the control visible. KAAK gives the host menu KOOK's compact dark panel, separated volume section, and highlighted action rows while keeping WebSpeak's own individual-volume slider and member actions; it does not add KOOK menu actions or skin-side audio logic.
The design target is the voice-client portion of KOOK, as requested by the project owner. It does not include discovery, companion/party, event, store, advertising, administrator, or other service-operator pages. It does not add a KOOK account flow, direct messages, server administration, or channels absent from the connected TeamSpeak server. The voice performance card also closes on outside click or Escape; Escape returns focus to its trigger, and its entrance/exit motion respects reduced-motion preferences.
The device picker now follows the public KOOK style geometry: a 40px trigger with 12px corners, a menu with 12px corners and 8px inset, and 32px rows with 2px gaps and 8px corners. Hover and selected rows use distinct low-contrast fills. The shared host measures the rendered menu before applying viewport limits, so skin-defined padding and row spacing stay visible without a KAAK-specific placement path. KAAK uses KOOK's dark-theme brand green (`#6cbf00`, `#7ac51a` hover) for speaker, slider, and control highlights. The performance trigger, metric values, volume readouts, audio settings icons, and sliders reuse the same accent tokens. Volume sliders use a 4px track, a 16px white thumb with a 2px brand-green border, and a 3px hover/focus halo without extra hover scaling.
The audio settings surface now follows the observed KOOK form proportions: a 660px dark card, 16px corners, 72px field rows, and a two-column label/control layout. Device and volume controls keep their WebSpeak behavior; only their shared form grouping and KAAK skin presentation changed. The layout stacks fields on narrow screens. KOOK's settings typography remains PingFang SC-first, with a 32px/600 title, 16px/600 section headings, and 14px/400 field labels.
The existing WebSpeak noise-suppression switch is available in the audio settings on desktop and mobile, matching its placement in KOOK's voice settings. It remains the browser's current noise-suppression control; KAAK does not claim to reproduce KOOK's branded processing modes.
## Reference access note
The owner authorized inspection of the first two voice rooms in the KOOK server. Both rooms were entered and viewed; the microphone remained off and no message was sent. The in-room view confirmed a single large participant tile in the center, a separate right-side panel for the active voice channel's text chat, a narrow server rail, grouped voice channels, and a compact voice-control dock near the lower left. The chat was empty, so no message contents were recorded. Server/room identifiers and member names were not recorded.
## Components and permissions
The connection page and voice workspace are full-page declarative surfaces in [components.json](./kaak-voice/components.json). The voice surface requests only the capabilities it uses: visible server shortcuts, channel and member data, cached profile-avatar display inside the trusted member-card widget, channel joining, channel chat, voice status, microphone/output controls, whisper controls, disconnect, and screen-share status/read/control. Its member-card widget explicitly enables share status and watch actions; the KAAK dock uses the host's screen-share control. The performance panel hides only share transport metrics. The host renders trusted connection, language, skin, and audio controls. KAAK 3.1.78 keeps the shared-screen player inside the central voice-stage column with an explicit responsive height, so the player cannot collapse when the host applies its inline video sizing; member cards scroll in the remaining area. The full source image remains visible with black letterboxing. Server and channel password prompts use the compact dark KAAK dialog style while retaining WebSpeak's trusted password, error, cancel, and retry behavior. It rechecks permissions and connection state when each action runs; approval is local to this skin version and can be revoked from the host access control.
The server header uses the live, privacy-filtered TeamSpeak server label and a trusted `voice.server-switcher` menu backed by favorites and recent connections. Its click handler reuses WebSpeak's existing connection flow with an opaque local ID; addresses and credentials never enter skin data. The left panel uses the trusted `voice.channel-tree` widget to retain TeamSpeak channel nesting, member counts and capacity, available avatars, and mute/speaking/away states. Expanding a branch is local UI state, a single click selects a channel, and double-click joins it. With `memberActions` enabled, right-clicking another member row opens WebSpeak's existing host-owned action menu. With `memberDragDrop` enabled, another member can be dragged onto a different channel row; the member row and target channel receive visual feedback, and the host reuses its existing move-client operation. Both options default off for other skins. The skin does not add KOOK's separate text-channel list.
On desktop, right-clicking another member row in the channel tree or member card opens WebSpeak's existing host-owned member actions menu. Member cards also retain their accessible action button; keyboard activation remains anchored to that button, and touch layouts keep it available. The menu's actions come from WebSpeak and are unchanged by the skin.
Member cards are rendered by WebSpeak's trusted `voice.member-cards` widget. It displays an already available TeamSpeak profile avatar, or the host-generated nickname initial when no avatar is available; image bytes stay in the host and are not exposed in the skin's data context or Wasm runtime. The skin does not receive server addresses, passwords, identity keys, raw audio, private messages, or arbitrary network/storage APIs. Its markup is data-only; it contains no executable JavaScript or Wasm. The `/demo` page uses synthetic data and does not connect to TeamSpeak.
## Files
- Source package: [kaak-voice](./kaak-voice/)
- Component schema: [components.json](./kaak-voice/components.json)
- Distributable archive: [kaak-voice.wskin](./kaak-voice.wskin)
- Shared format and safety rules: [SKIN_DEVELOPMENT.md](../SKIN_DEVELOPMENT.md)
KAAK is included in the public skin selector and its `.wskin` archive is also available as a standalone package. After changing the source, run `npm run skin:kaak:build` to rebuild both copies, then run the package tests and verify the connection page, approval, denial, revoke, desktop, and narrow-screen paths in the local browser. The connected voice surface can be verified when a TeamSpeak session is available.
+10
View File
@@ -0,0 +1,10 @@
# Open Voice Surface scaffold
This importable schema v3 surface package exercises complete public home and voice pages using only declarative nodes and WebSpeak-owned controls. It includes server switching, channel navigation, visible members, per-member screen-share status and a watch action, chat, audio, whisper, connection controls, and the built-in language and skin selectors. It contains no discovery, events, shop, companion, advertising, or administration pages.
This is an implementation scaffold for testing the open-skin format, not a pixel-matched KOOK skin. The visual reference was read in the in-app browser in the first two user-authorized voice rooms. The separate [KAAK voice sample](./KAAK-VOICE.md) records the voice-only layout findings and applies them to the channel and member sidebars. No server/room identifiers, member names, or chat contents were retained. Discovery, companion shop, events, ads, and operator/admin pages are outside the sample's scope.
- Source: [open-voice-surface](./open-voice-surface/)
- Importable package: [open-voice-surface.wskin](./open-voice-surface.wskin)
- Shared component and permission rules: [skin development guide](../SKIN_DEVELOPMENT.md)
- Architecture and safety boundaries: [open skin spec](../OPEN_SKIN_SYSTEM_SPEC.zh-CN.md)
Binary file not shown.
@@ -0,0 +1,9 @@
# Harbor Voice Workspace
这是一个 KOOK 语音工作区风格的完整皮肤测试包,参考范围只限语音客户端:服务器快捷栏、频道列表、中央聊天、成员列表和底部语音控制。没有复用 KOOK 的图片、标志、广告或站点文案,也没有加入发现、陪玩、派对、商城、活动通知、排行榜或管理后台。
皮肤使用 `components.json` 的完整声明式 surface 自己构建频道树、聊天消息与输入框、成员状态和悄悄话控制;底部音频区嵌入 WebSpeak 的可信音频控件,继续使用现有麦克风/扬声器开关和音频设置(包括麦克风灵敏度)。样例隐藏与语音布局无关的伴奏开关;断开和频道控制仍由 WebSpeak 校验并执行。频道缩进直接映射 TeamSpeak 公开树深度;频道单击只改变皮肤本地选中态,双击才请求 TeamSpeak 切换频道。语音成员列表显示公开的说话、静音和离开状态。消息、频道和成员数据由权限筛选后提供。屏幕共享启动保留一个可自行排版和换肤的可信宿主按钮,以保留浏览器要求的真实用户手势;视频流和设备 API 不交给皮肤代码。皮肤不读取服务器地址、账号凭据或连接密钥,也不包含可执行 JavaScript/Wasm;这个样例用于验证 v3 surface 的可定制界面和交互,v4 Wasm 插件运行时另由运行时测试覆盖。
桌面布局保留四个区域:服务器快捷栏、频道树、聊天区和成员区;服务器栏底部展示当前 TeamSpeak 昵称,连接后语音控制坞固定在频道栏底部。昵称项只呈现当前会话身份,不模拟 KOOK 账号或资料运营功能。窄屏下服务器栏保持可用,频道项转为横向滚动,成员与语音控制各自占一行,基础连接控制不被隐藏。
`manifest.json`、`components.json` 与 `skin.css` 是可编辑源码。根目录的 `../harbor-voice.wskin` 是源码打包后的本地导入包;源码修改后运行 `npm run skin:harbor:build` 重新打包,再在测试实例的皮肤管理页导入验证。当前没有加入公共皮肤目录或发布到服务器。
+480
View File
@@ -0,0 +1,480 @@
{
"schemaVersion": 3,
"components": [
{
"id": "harbor-home",
"name": "Harbor connection home",
"page": "home",
"mode": "surface",
"accessibleName": "WebSpeak connection page",
"permissions": ["ui.surface.replace"],
"actions": {},
"root": {
"tag": "main",
"part": "home",
"children": [
{
"tag": "header",
"part": "home-header",
"children": [
{ "tag": "span", "part": "brand-mark", "children": [{ "text": "W" }] },
{ "tag": "span", "part": "brand-name", "children": [{ "text": "WEBSPEAK" }] },
{ "widget": "app.language-switcher", "part": "language" },
{ "widget": "app.skin-switcher", "part": "skin" }
]
},
{
"tag": "section",
"part": "connection-card",
"children": [
{ "tag": "p", "part": "eyebrow", "children": [{ "text": "VOICE CLIENT" }] },
{ "tag": "h1", "part": "title", "children": [{ "text": "Connect with your community" }] },
{ "tag": "p", "part": "description", "children": [{ "text": "Choose a TeamSpeak server and return to your voice channels." }] },
{ "widget": "home.connection-form", "part": "connection-form" }
]
},
{
"tag": "footer",
"part": "home-footer",
"children": [{ "text": "Your connection and identity stay under WebSpeak's control." }]
}
]
}
},
{
"id": "harbor-workspace",
"name": "Harbor voice workspace",
"page": "voice",
"mode": "surface",
"accessibleName": "WebSpeak voice workspace",
"permissions": [
"ui.surface.replace",
"session.status.read",
"session.channels.read",
"session.members.read",
"session.channel.join",
"servers.quickList.read",
"servers.quickList.switch",
"chat.channel.read",
"chat.channel.send",
"audio.status.read",
"audio.microphone.control",
"audio.output.control",
"voice.whisper.status.read",
"voice.whisper.control",
"voice.disconnect",
"voice.screenShare.read",
"voice.screenShare.control"
],
"actions": {
"switch-server": {
"type": "quickServers.switch",
"args": { "quickServerId": "{{server.id}}" }
},
"select-channel": {
"type": "ui.setState",
"args": { "key": "selectedchannel", "value": "{{channel.id}}" }
},
"join-channel": {
"type": "voice.joinChannel",
"args": { "channelId": "{{channel.id}}" }
},
"send-message": {
"type": "chat.sendMessage",
"args": { "text": "{{state.message}}" }
},
"disconnect": { "type": "voice.disconnect", "args": {} },
"whisper-on": { "type": "voice.setWhisperActive", "args": { "active": true } },
"whisper-off": { "type": "voice.setWhisperActive", "args": { "active": false } },
"watch-screen-share": {
"type": "voice.joinScreenShare",
"args": { "streamId": "{{member.screenShareStreamId}}" }
},
"watch-channel-member-screen-share": {
"type": "voice.joinScreenShare",
"args": { "streamId": "{{voicemember.screenShareStreamId}}" }
}
},
"state": { "selectedchannel": "", "message": "" },
"root": {
"tag": "main",
"part": "workspace",
"children": [
{
"tag": "header",
"part": "topbar",
"children": [
{ "tag": "span", "part": "brand-mark", "children": [{ "text": "W" }] },
{ "tag": "span", "part": "brand-name", "children": [{ "text": "WEBSPEAK" }] },
{ "tag": "span", "part": "server-title", "children": [{ "text": "{{session.status.serverLabel}}" }] },
{ "widget": "app.language-switcher", "part": "language" },
{ "widget": "app.skin-switcher", "part": "skin" }
]
},
{
"tag": "nav",
"part": "server-rail",
"attributes": { "aria-label": "Favorite and recent servers" },
"children": [
{
"tag": "div",
"part": "quick-server-item",
"repeat": { "path": "servers.quickList", "as": "server" },
"children": [
{
"tag": "button",
"part": "quick-server",
"attributes": {
"type": "button",
"aria-current": "{{server.current}}",
"aria-label": "Switch to {{server.label}}"
},
"events": { "click": "switch-server" },
"children": [
{ "tag": "span", "part": "server-monogram", "children": [{ "text": "{{server.label}}" }] },
{
"tag": "span",
"part": "server-kind",
"when": { "path": "server.favorite", "equals": true },
"children": [{ "text": "Saved" }]
},
{
"tag": "span",
"part": "server-kind",
"when": { "path": "server.kind", "equals": "recent" },
"children": [{ "text": "Recent" }]
}
]
}
]
}
]
},
{
"tag": "aside",
"part": "channel-panel",
"attributes": { "aria-label": "Server channels" },
"children": [
{
"tag": "header",
"part": "server-summary",
"children": [
{ "tag": "strong", "part": "server-name", "children": [{ "text": "{{session.status.serverLabel}}" }] },
{ "tag": "small", "part": "server-subtitle", "children": [{ "text": "VOICE CHANNELS" }] }
]
},
{
"tag": "nav",
"part": "channel-list",
"attributes": { "aria-label": "Channels" },
"children": [
{ "tag": "h2", "part": "section-label", "children": [{ "text": "CHANNELS" }] },
{
"tag": "div",
"part": "channel-item",
"repeat": { "path": "session.channels", "as": "channel" },
"children": [
{
"tag": "button",
"part": "channel-row",
"attributes": {
"type": "button",
"aria-current": "{{channel.current}}",
"aria-label": "Double-click to join {{channel.name}}",
"data-depth": "{{channel.depth}}"
},
"events": { "click": "select-channel", "dblclick": "join-channel" },
"children": [
{ "tag": "span", "part": "channel-glyph", "children": [{ "text": "◉" }] },
{ "tag": "span", "part": "channel-name", "children": [{ "text": "{{channel.name}}" }] },
{ "tag": "small", "part": "channel-count", "children": [{ "text": "{{channel.memberCount}}" }] },
{
"tag": "span",
"part": "selected-channel-indicator",
"when": { "path": "state.selectedchannel", "equals": "{{channel.id}}" },
"attributes": { "aria-label": "Selected" }
}
]
},
{
"tag": "ul",
"part": "channel-voice-members",
"when": { "path": "channel.current", "equals": true },
"attributes": { "aria-label": "Members connected to this channel" },
"children": [
{
"tag": "li",
"part": "channel-voice-member",
"repeat": { "path": "channel.members", "as": "voicemember" },
"children": [
{ "tag": "span", "part": "channel-member-avatar", "children": [{ "text": "{{voicemember.name}}" }] },
{ "tag": "span", "part": "channel-member-name", "children": [{ "text": "{{voicemember.name}}" }] },
{
"tag": "span",
"part": "channel-member-muted",
"when": { "path": "voicemember.status", "equals": "muted" },
"attributes": { "aria-label": "Microphone muted" },
"children": [{ "text": "MIC OFF" }]
},
{
"tag": "span",
"part": "channel-member-away",
"when": { "path": "voicemember.status", "equals": "away" },
"attributes": { "aria-label": "Away" },
"children": [{ "text": "AWAY" }]
},
{
"tag": "span",
"part": "channel-member-state",
"when": { "path": "voicemember.self", "equals": true },
"children": [{ "text": "YOU" }]
},
{
"tag": "span",
"part": "channel-member-state",
"when": { "path": "voicemember.speaking", "equals": true },
"attributes": { "aria-label": "Speaking" },
"children": [{ "text": "●" }]
},
{
"tag": "div",
"part": "channel-member-screen-share",
"when": { "path": "voicemember.screenSharing", "equals": true },
"children": [
{ "tag": "span", "part": "channel-member-screen-share-live", "children": [{ "text": "SHARING" }] },
{
"tag": "button",
"part": "channel-member-screen-share-watch",
"when": { "path": "voicemember.self", "equals": false },
"attributes": { "type": "button", "aria-label": "Watch {{voicemember.name}}'s screen" },
"events": { "click": "watch-channel-member-screen-share" },
"children": [{ "text": "WATCH" }]
}
]
}
]
}
]
}
]
}
]
}
]
},
{
"tag": "section",
"part": "conversation",
"attributes": { "aria-label": "Current channel conversation" },
"children": [
{
"tag": "header",
"part": "conversation-heading",
"children": [
{ "tag": "span", "part": "conversation-glyph", "children": [{ "text": "◉" }] },
{ "tag": "h1", "part": "channel-title", "children": [{ "text": "{{session.status.channelName}}" }] },
{
"tag": "span",
"part": "connection-state",
"when": { "path": "session.status.connected", "equals": true },
"children": [{ "text": "CONNECTED" }]
}
]
},
{
"tag": "div",
"part": "chat",
"children": [
{
"tag": "div",
"part": "chat-message-list",
"attributes": { "aria-label": "Current channel messages", "role": "log", "aria-live": "polite" },
"children": [
{
"tag": "p",
"part": "chat-empty",
"when": { "path": "chat.messages", "empty": true },
"children": [{ "text": "No messages yet. Say hello to the channel." }]
},
{
"tag": "article",
"part": "chat-message",
"repeat": { "path": "chat.messages", "as": "message" },
"children": [
{
"tag": "header",
"part": "chat-message-heading",
"children": [
{ "tag": "strong", "part": "chat-message-author", "children": [{ "text": "{{message.author}}" }] },
{ "tag": "time", "part": "chat-message-time", "children": [{ "text": "{{message.time}}" }] }
]
},
{ "tag": "p", "part": "chat-message-text", "children": [{ "text": "{{message.text}}" }] }
]
}
]
},
{
"tag": "form",
"part": "chat-composer",
"events": { "submit": "send-message" },
"children": [
{
"tag": "input",
"part": "chat-input",
"bindValue": "message",
"attributes": {
"type": "text",
"maxlength": 1000,
"autocomplete": "off",
"placeholder": "Message this channel",
"aria-label": "Message this channel"
}
},
{
"tag": "button",
"part": "chat-send",
"attributes": { "type": "submit", "aria-label": "Send message" },
"children": [{ "text": "Send" }]
}
]
}
]
},
{ "widget": "voice.screen-share-player", "part": "screen-player" }
]
},
{
"tag": "aside",
"part": "members-panel",
"attributes": { "aria-label": "Members in this channel" },
"children": [
{
"tag": "header",
"part": "members-heading",
"children": [
{ "tag": "h2", "part": "section-label", "children": [{ "text": "MEMBERS" }] }
]
},
{
"tag": "ul",
"part": "member-list",
"children": [
{
"tag": "li",
"part": "member-row",
"repeat": { "path": "session.members", "as": "member" },
"children": [
{ "tag": "span", "part": "member-avatar", "children": [{ "text": "{{member.name}}" }] },
{ "tag": "span", "part": "member-name", "children": [{ "text": "{{member.name}}" }] },
{
"tag": "span",
"part": "speaking-indicator",
"when": { "path": "member.speaking", "equals": true },
"attributes": { "aria-label": "Speaking" },
"children": [{ "text": "SPEAKING" }]
},
{
"tag": "span",
"part": "member-muted-state",
"when": { "path": "member.status", "equals": "muted" },
"attributes": { "aria-label": "Microphone muted" },
"children": [{ "text": "MIC OFF" }]
},
{
"tag": "span",
"part": "member-away-state",
"when": { "path": "member.status", "equals": "away" },
"attributes": { "aria-label": "Away" },
"children": [{ "text": "AWAY" }]
},
{
"tag": "div",
"part": "member-screen-share",
"when": { "path": "member.screenSharing", "equals": true },
"children": [
{ "tag": "span", "part": "member-screen-share-live", "children": [{ "text": "SHARING" }] },
{
"tag": "button",
"part": "member-screen-share-watch",
"when": { "path": "member.self", "equals": false },
"attributes": { "type": "button", "aria-label": "Watch {{member.name}}'s screen" },
"events": { "click": "watch-screen-share" },
"children": [{ "text": "WATCH" }]
}
]
}
]
}
]
},
{
"tag": "div",
"part": "whisper-controls",
"children": [
{
"tag": "button",
"part": "whisper-start",
"when": { "path": "whisper.status.active", "equals": false },
"attributes": { "type": "button", "aria-label": "Start whisper" },
"events": { "click": "whisper-on" },
"children": [{ "text": "Whisper" }]
},
{
"tag": "button",
"part": "whisper-stop",
"when": { "path": "whisper.status.active", "equals": true },
"attributes": { "type": "button", "aria-label": "Stop whisper" },
"events": { "click": "whisper-off" },
"children": [{ "text": "Whisper on" }]
}
]
}
]
},
{
"tag": "footer",
"part": "voice-dock",
"attributes": { "aria-label": "Voice controls" },
"children": [
{
"tag": "div",
"part": "voice-dock-heading",
"children": [
{ "tag": "span", "part": "connection-indicator", "children": [{ "text": "●" }] },
{ "tag": "strong", "part": "voice-channel-name", "children": [{ "text": "{{session.status.channelName}}" }] },
{ "tag": "span", "part": "voice-dock-caption", "children": [{ "text": "VOICE CONNECTED" }] }
]
},
{
"tag": "div",
"part": "voice-dock-actions",
"children": [
{ "widget": "voice.screen-share-start", "part": "screen-share-start" },
{ "widget": "voice.audio-controls", "part": "audio-controls" },
{
"tag": "button",
"part": "disconnect-control",
"attributes": { "type": "button", "aria-label": "Disconnect voice" },
"events": { "click": "disconnect" },
"children": [{ "text": "Leave" }]
}
]
}
]
},
{
"tag": "div",
"part": "identity-entry",
"when": { "path": "session.status.userName" },
"attributes": { "role": "group", "aria-label": "Current TeamSpeak identity" },
"children": [
{ "tag": "span", "part": "identity-monogram", "children": [{ "text": "TS" }] },
{ "tag": "span", "part": "identity-name", "children": [{ "text": "{{session.status.userName}}" }] }
]
}
]
}
}
]
}
+13
View File
@@ -0,0 +1,13 @@
{
"schemaVersion": 3,
"packageType": "open-skin",
"id": "community.harbor-voice",
"name": "Harbor Voice Workspace",
"version": "1.1.1",
"author": "WebSpeak Project",
"license": "AGPL-3.0-only",
"description": "A KOOK-inspired dark voice workspace using only WebSpeak host controls and public session data.",
"entry": "skin.css",
"components": "components.json",
"minAppVersion": "0.2.7-preview"
}
+946
View File
@@ -0,0 +1,946 @@
:root {
color-scheme: dark;
--skin-harbor-bg: #17181b;
--skin-harbor-rail: #141518;
--skin-harbor-panel: #1d1e22;
--skin-harbor-raised: #292a2f;
--skin-harbor-hover: #303137;
--skin-harbor-border: #303136;
--skin-harbor-text: #f0f1f3;
--skin-harbor-muted: #a0a2a8;
--skin-harbor-dim: #777a82;
--skin-harbor-accent: #58c877;
--skin-harbor-danger: #e36b6b;
--skin-harbor-radius: 9px;
}
[data-ws-plugin-part="harbor-home"] {
display: grid;
grid-template-rows: auto 1fr auto;
justify-items: center;
min-height: 100dvh;
gap: 28px;
padding: clamp(16px, 4vw, 42px);
color: var(--skin-harbor-text);
background:
radial-gradient(ellipse at 50% 44%, #25272b 0, transparent 58%),
var(--skin-harbor-bg);
}
[data-ws-plugin-part="harbor-home.home-header"] {
display: flex;
align-items: center;
gap: 11px;
width: min(100%, 1080px);
}
[data-ws-plugin-part="harbor-home.brand-mark"],
[data-ws-plugin-part="harbor-workspace.brand-mark"] {
display: grid;
place-items: center;
flex: 0 0 34px;
width: 34px;
height: 34px;
border-radius: 50%;
color: #101512;
background: var(--skin-harbor-accent);
font-size: 14px;
font-weight: 900;
}
[data-ws-plugin-part="harbor-home.brand-name"],
[data-ws-plugin-part="harbor-workspace.brand-name"] {
color: var(--skin-harbor-text);
font-size: 12px;
font-weight: 850;
letter-spacing: .1em;
}
[data-ws-plugin-part="harbor-home.language"] { margin-left: auto; }
[data-ws-plugin-part="harbor-home.connection-card"] {
align-self: center;
width: min(100%, 510px);
padding: clamp(22px, 5vw, 40px);
border: 1px solid var(--skin-harbor-border);
border-radius: 16px;
background: color-mix(in srgb, var(--skin-harbor-panel) 96%, transparent);
box-shadow: 0 24px 70px #0007;
}
[data-ws-plugin-part="harbor-home.eyebrow"] {
color: var(--skin-harbor-accent);
font-size: 10px;
font-weight: 800;
letter-spacing: .14em;
}
[data-ws-plugin-part="harbor-home.title"] {
margin: 12px 0 8px;
font-size: clamp(26px, 5vw, 38px);
letter-spacing: -.04em;
}
[data-ws-plugin-part="harbor-home.description"],
[data-ws-plugin-part="harbor-home.home-footer"] {
color: var(--skin-harbor-muted);
line-height: 1.6;
}
[data-ws-plugin-part="harbor-home.home-footer"] {
width: min(100%, 1080px);
font-size: 12px;
}
[data-ws-plugin-part="harbor-home"] .join-card {
color: var(--skin-harbor-text);
background: transparent;
border-color: var(--skin-harbor-border);
box-shadow: none;
}
[data-ws-plugin-part="harbor-home"] .field-wrap,
[data-ws-plugin-part="harbor-home"] .settings-select {
color: var(--skin-harbor-muted);
background: var(--skin-harbor-raised);
border-color: var(--skin-harbor-border);
}
[data-ws-plugin-part="harbor-home"] .field-wrap input,
[data-ws-plugin-part="harbor-home"] .settings-select {
color: var(--skin-harbor-text);
}
[data-ws-plugin-part="harbor-workspace"] {
display: grid;
grid-template-columns: 68px 276px minmax(340px, 1fr) 244px;
grid-template-rows: 54px minmax(0, 1fr);
width: 100%;
height: 100dvh;
min-height: 560px;
overflow: hidden;
color: var(--skin-harbor-text);
background: var(--skin-harbor-bg);
font-family: Inter, "Segoe UI", system-ui, sans-serif;
}
[data-ws-plugin-part="harbor-workspace"],
[data-ws-plugin-part="harbor-workspace"] * {
scrollbar-color: #4a4c51 transparent;
scrollbar-width: thin;
}
[data-ws-plugin-part="harbor-workspace"] *::-webkit-scrollbar { width: 6px; height: 6px; }
[data-ws-plugin-part="harbor-workspace"] *::-webkit-scrollbar-thumb { background: #4a4c51; border-radius: 6px; }
[data-ws-plugin-part="harbor-workspace.topbar"] {
z-index: 2;
grid-column: 1 / -1;
grid-row: 1;
display: flex;
align-items: center;
gap: 11px;
min-width: 0;
padding: 0 14px;
border-bottom: 1px solid var(--skin-harbor-border);
background: var(--skin-harbor-rail);
}
[data-ws-plugin-part="harbor-workspace.server-title"] {
overflow: hidden;
margin-right: auto;
color: var(--skin-harbor-muted);
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace.server-rail"] {
grid-column: 1;
grid-row: 2;
display: flex;
flex-direction: column;
align-items: center;
gap: 9px;
min-height: 0;
overflow-y: auto;
padding: 13px 7px;
background: var(--skin-harbor-rail);
border-right: 1px solid #ffffff08;
}
[data-ws-plugin-part="harbor-workspace.quick-server"] {
display: grid;
justify-items: center;
gap: 3px;
width: 52px;
min-height: 54px;
padding: 4px;
border: 0;
border-radius: 13px;
color: var(--skin-harbor-muted);
background: transparent;
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace.quick-server"]:hover,
[data-ws-plugin-part="harbor-workspace.quick-server"]:focus-visible {
color: var(--skin-harbor-text);
background: var(--skin-harbor-raised);
}
[data-ws-plugin-part="harbor-workspace.quick-server"][aria-current="true"] {
color: var(--skin-harbor-text);
background: var(--skin-harbor-raised);
box-shadow: inset 3px 0 var(--skin-harbor-accent);
}
[data-ws-plugin-part="harbor-workspace.server-monogram"] {
display: grid;
place-items: center;
width: 40px;
height: 40px;
overflow: hidden;
border: 1px solid #ffffff12;
border-radius: 13px;
color: var(--skin-harbor-text);
background: linear-gradient(145deg, #383a40, #222429);
font-size: 11px;
font-weight: 800;
text-align: center;
}
[data-ws-plugin-part="harbor-workspace.server-kind"] {
color: var(--skin-harbor-dim);
font-size: 8px;
line-height: 1;
}
[data-ws-plugin-part="harbor-workspace.identity-entry"] {
display: grid;
justify-items: center;
gap: 4px;
width: 100%;
margin-top: auto;
padding: 9px 1px 1px;
border-top: 1px solid var(--skin-harbor-border);
}
[data-ws-plugin-part="harbor-workspace.identity-monogram"] {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border: 1px solid #ffffff18;
border-radius: 50%;
color: var(--skin-harbor-text);
background: linear-gradient(145deg, #4a4c53, #292a30);
font-size: 10px;
font-weight: 850;
}
[data-ws-plugin-part="harbor-workspace.identity-name"] {
display: block;
max-width: 100%;
overflow: hidden;
color: var(--skin-harbor-muted);
font-size: 8px;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace.channel-panel"] {
z-index: 1;
grid-column: 2;
grid-row: 2;
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
overflow: auto;
padding: 12px 9px 118px;
border-right: 1px solid var(--skin-harbor-border);
background: var(--skin-harbor-panel);
}
[data-ws-plugin-part="harbor-workspace.server-summary"] {
display: flex;
flex-direction: column;
gap: 4px;
min-height: 49px;
padding: 3px 9px 13px;
border-bottom: 1px solid #ffffff0b;
}
[data-ws-plugin-part="harbor-workspace.server-name"] {
overflow: hidden;
color: var(--skin-harbor-text);
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace.server-subtitle"],
[data-ws-plugin-part="harbor-workspace.section-label"] {
color: var(--skin-harbor-dim);
font-size: 10px;
font-weight: 800;
letter-spacing: .08em;
}
[data-ws-plugin-part="harbor-workspace.channel-list"] {
display: flex;
flex-direction: column;
gap: 2px;
min-height: 0;
padding-top: 13px;
}
[data-ws-plugin-part="harbor-workspace.section-label"] { margin: 0 8px 7px; }
[data-ws-plugin-part="harbor-workspace.channel-row"] {
position: relative;
display: flex;
align-items: center;
gap: 9px;
width: 100%;
min-height: 38px;
padding: 6px 9px;
border: 0;
border-radius: 6px;
color: var(--skin-harbor-muted);
background: transparent;
text-align: left;
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace.selected-channel-indicator"] {
position: absolute;
inset: 0;
border: 1px solid var(--skin-harbor-accent);
border-radius: inherit;
pointer-events: none;
}
[data-ws-plugin-part="harbor-workspace.channel-row"]:hover,
[data-ws-plugin-part="harbor-workspace.channel-row"][aria-current="true"] {
color: var(--skin-harbor-text);
background: var(--skin-harbor-raised);
}
[data-ws-plugin-part="harbor-workspace.channel-row"][aria-current="true"] {
box-shadow: inset 2px 0 var(--skin-harbor-accent);
}
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="1"] { padding-inline-start: 19px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="2"] { padding-inline-start: 29px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="3"] { padding-inline-start: 39px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="4"] { padding-inline-start: 49px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="5"] { padding-inline-start: 59px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="6"] { padding-inline-start: 69px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="7"] { padding-inline-start: 79px; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="8"] { padding-inline-start: 89px; }
[data-ws-plugin-part="harbor-workspace.channel-glyph"] {
display: grid;
place-items: center;
width: 18px;
color: var(--skin-harbor-dim);
font-size: 13px;
}
[data-ws-plugin-part="harbor-workspace.channel-name"] {
min-width: 0;
flex: 1;
overflow: hidden;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace.channel-count"] {
color: var(--skin-harbor-dim);
font-size: 10px;
}
[data-ws-plugin-part="harbor-workspace.channel-voice-members"] {
display: grid;
gap: 1px;
margin: 0 0 6px 29px;
padding: 2px 0 3px;
list-style: none;
}
[data-ws-plugin-part="harbor-workspace.channel-voice-member"] {
display: grid;
grid-template-columns: 18px minmax(0, 1fr) auto auto;
align-items: center;
gap: 5px;
min-height: 21px;
color: var(--skin-harbor-muted);
font-size: 10px;
}
[data-ws-plugin-part="harbor-workspace.channel-member-avatar"] {
display: grid;
place-items: center;
width: 16px;
height: 16px;
overflow: hidden;
border-radius: 50%;
color: var(--skin-harbor-text);
background: #393b41;
font-size: 7px;
font-weight: 800;
}
[data-ws-plugin-part="harbor-workspace.channel-member-name"] {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace.channel-member-state"] {
color: var(--skin-harbor-accent);
font-size: 8px;
font-weight: 800;
}
[data-ws-plugin-part="harbor-workspace.channel-member-muted"],
[data-ws-plugin-part="harbor-workspace.member-muted-state"] {
color: var(--skin-harbor-danger);
font-size: 8px;
font-weight: 800;
}
[data-ws-plugin-part="harbor-workspace.channel-member-away"],
[data-ws-plugin-part="harbor-workspace.member-away-state"] {
color: var(--skin-harbor-dim);
font-size: 8px;
font-weight: 800;
}
[data-ws-plugin-part="harbor-workspace.channel-member-screen-share"] {
grid-column: 2 / -1;
display: flex;
align-items: center;
gap: 6px;
color: var(--skin-harbor-accent);
font-size: 8px;
font-weight: 800;
}
[data-ws-plugin-part="harbor-workspace.channel-member-screen-share-watch"],
[data-ws-plugin-part="harbor-workspace.member-screen-share-watch"] {
min-height: 28px;
padding: 0 8px;
border: 1px solid #7ed95755;
border-radius: 5px;
color: var(--skin-harbor-text);
background: var(--skin-harbor-raised);
font-size: 9px;
font-weight: 800;
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace.channel-member-screen-share-watch"]:hover,
[data-ws-plugin-part="harbor-workspace.member-screen-share-watch"]:hover {
color: var(--skin-harbor-accent);
background: #313238;
}
[data-ws-plugin-part="harbor-workspace.conversation"] {
grid-column: 3;
grid-row: 2;
display: grid;
grid-template-rows: 48px minmax(0, 1fr) auto;
gap: 10px;
min-width: 0;
min-height: 0;
padding: 0 17px 12px;
background: var(--skin-harbor-bg);
}
[data-ws-plugin-part="harbor-workspace.conversation-heading"] {
display: flex;
align-items: center;
gap: 9px;
min-width: 0;
border-bottom: 1px solid var(--skin-harbor-border);
}
[data-ws-plugin-part="harbor-workspace.conversation-glyph"] {
color: var(--skin-harbor-muted);
font-size: 15px;
}
[data-ws-plugin-part="harbor-workspace.channel-title"] {
min-width: 0;
margin: 0 auto 0 0;
overflow: hidden;
font-size: 14px;
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace.connection-state"] {
color: var(--skin-harbor-accent);
font-size: 9px;
font-weight: 800;
letter-spacing: .06em;
}
[data-ws-plugin-part="harbor-workspace"] [data-ws-part="voice.chat"] {
min-width: 0;
min-height: 0;
color: var(--skin-harbor-text);
background: transparent;
border-color: transparent;
}
[data-ws-plugin-part="harbor-workspace.chat"] {
display: grid;
grid-template-rows: minmax(0, 1fr) auto;
min-width: 0;
min-height: 0;
overflow: hidden;
color: var(--skin-harbor-text);
}
[data-ws-plugin-part="harbor-workspace.chat-message-list"] {
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: 14px;
min-height: 0;
overflow: auto;
padding: 8px 4px 16px;
}
[data-ws-plugin-part="harbor-workspace.chat-empty"] {
align-self: center;
margin: auto;
color: var(--skin-harbor-muted);
font-size: 13px;
}
[data-ws-plugin-part="harbor-workspace.chat-message"] { min-width: 0; }
[data-ws-plugin-part="harbor-workspace.chat-message-heading"] { display: flex; align-items: baseline; gap: 8px; }
[data-ws-plugin-part="harbor-workspace.chat-message-author"] { color: var(--skin-harbor-text); font-size: 12px; }
[data-ws-plugin-part="harbor-workspace.chat-message-time"] { color: var(--skin-harbor-dim); font-size: 10px; }
[data-ws-plugin-part="harbor-workspace.chat-message-text"] { margin: 3px 0 0; color: var(--skin-harbor-muted); font-size: 13px; overflow-wrap: anywhere; white-space: pre-wrap; }
[data-ws-plugin-part="harbor-workspace.chat-composer"] {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
padding: 8px;
border: 1px solid var(--skin-harbor-border);
border-radius: 9px;
background: var(--skin-harbor-panel);
}
[data-ws-plugin-part="harbor-workspace.chat-input"] {
flex: 1;
min-width: 0;
height: 38px;
padding: 0 10px;
border: 0;
outline: 0;
color: var(--skin-harbor-text);
background: transparent;
}
[data-ws-plugin-part="harbor-workspace.chat-send"] {
min-width: 54px;
min-height: 36px;
border: 0;
border-radius: 7px;
color: #111;
background: var(--skin-harbor-accent);
font-weight: 700;
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace"] .chat-panel { min-height: 0; background: transparent; }
[data-ws-plugin-part="harbor-workspace"] .chat-heading { border-color: var(--skin-harbor-border); }
[data-ws-plugin-part="harbor-workspace"] .message-bubble { color: var(--skin-harbor-text); background: var(--skin-harbor-panel); }
[data-ws-plugin-part="harbor-workspace"] .message-composer { border-color: var(--skin-harbor-border); background: var(--skin-harbor-panel); }
[data-ws-plugin-part="harbor-workspace"] .message-composer input { color: var(--skin-harbor-text); }
[data-ws-plugin-part="harbor-workspace.members-panel"] {
grid-column: 4;
grid-row: 2;
min-width: 0;
min-height: 0;
overflow: auto;
padding: 16px 11px 118px;
border-left: 1px solid var(--skin-harbor-border);
background: var(--skin-harbor-panel);
}
[data-ws-plugin-part="harbor-workspace.members-heading"] {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 30px;
}
[data-ws-plugin-part="harbor-workspace.members-heading"] .section-label { margin: 0; }
[data-ws-plugin-part="harbor-workspace.member-total"] { color: var(--skin-harbor-dim); font-size: 11px; }
[data-ws-plugin-part="harbor-workspace.member-list"] {
display: grid;
gap: 3px;
margin: 8px 0 16px;
padding: 0;
list-style: none;
}
[data-ws-plugin-part="harbor-workspace.member-row"] {
display: grid;
grid-template-columns: 32px minmax(0, 1fr);
align-items: center;
column-gap: 8px;
min-height: 42px;
padding: 4px 5px;
border-radius: 6px;
color: var(--skin-harbor-muted);
font-size: 12px;
}
[data-ws-plugin-part="harbor-workspace.member-row"]:hover { background: var(--skin-harbor-raised); }
[data-ws-plugin-part="harbor-workspace.member-avatar"] {
grid-row: span 2;
display: grid;
place-items: center;
width: 30px;
height: 30px;
overflow: hidden;
border-radius: 50%;
color: var(--skin-harbor-text);
background: #393b41;
font-size: 10px;
font-weight: 700;
}
[data-ws-plugin-part="harbor-workspace.member-name"] {
min-width: 0;
overflow: hidden;
color: var(--skin-harbor-text);
text-overflow: ellipsis;
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace.speaking-indicator"] {
color: var(--skin-harbor-accent);
font-size: 8px;
font-weight: 800;
letter-spacing: .05em;
}
[data-ws-plugin-part="harbor-workspace.member-muted-state"],
[data-ws-plugin-part="harbor-workspace.member-away-state"],
[data-ws-plugin-part="harbor-workspace.speaking-indicator"] { grid-column: 2 / -1; }
[data-ws-plugin-part="harbor-workspace.member-screen-share"] {
grid-column: 2 / -1;
display: flex;
align-items: center;
gap: 6px;
color: var(--skin-harbor-accent);
font-size: 8px;
font-weight: 800;
}
[data-ws-plugin-part="harbor-workspace.voice-dock"] {
z-index: 4;
grid-column: 2;
grid-row: 2;
align-self: end;
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 6px 8px;
min-width: 0;
padding: 9px;
border: 1px solid var(--skin-harbor-border);
border-radius: 10px;
background: #222328;
box-shadow: 0 8px 20px #0005;
}
[data-ws-plugin-part="harbor-workspace.voice-dock-heading"] {
grid-column: 1 / -1;
display: grid;
grid-template-columns: 10px minmax(0, 1fr);
align-items: center;
gap: 2px 7px;
}
[data-ws-plugin-part="harbor-workspace.voice-dock-actions"] {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 4px;
min-width: 0;
}
[data-ws-plugin-part="harbor-workspace.connection-indicator"] {
grid-row: span 2;
color: var(--skin-harbor-accent);
font-size: 9px;
}
[data-ws-plugin-part="harbor-workspace.voice-channel-name"] {
overflow: hidden;
color: var(--skin-harbor-text);
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace.voice-dock-caption"] {
color: var(--skin-harbor-dim);
font-size: 8px;
letter-spacing: .05em;
}
[data-ws-plugin-part="harbor-workspace.audio-controls"] {
display: flex;
align-items: center;
gap: 4px;
min-width: 0;
}
[data-ws-plugin-part="harbor-workspace.microphone-control"],
[data-ws-plugin-part="harbor-workspace.output-control"],
[data-ws-plugin-part="harbor-workspace.disconnect-control"],
[data-ws-plugin-part="harbor-workspace.whisper-start"],
[data-ws-plugin-part="harbor-workspace.whisper-stop"] {
min-width: 38px;
min-height: 38px;
padding: 0 8px;
border: 1px solid var(--skin-harbor-border);
border-radius: 7px;
color: var(--skin-harbor-muted);
background: var(--skin-harbor-raised);
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace.microphone-control"][aria-pressed="true"],
[data-ws-plugin-part="harbor-workspace.output-control"][aria-pressed="true"] { color: var(--skin-harbor-danger); }
[data-ws-plugin-part="harbor-workspace.disconnect-control"] { color: var(--skin-harbor-danger); }
[data-ws-plugin-part="harbor-workspace.output-volume"] { width: 72px; accent-color: var(--skin-harbor-accent); }
[data-ws-plugin-part="harbor-workspace.whisper-controls"] { display: flex; gap: 6px; margin-top: 12px; }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] { flex: 0 0 auto; }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button {
display: grid;
place-items: center;
width: 34px;
height: 34px;
padding: 0;
border: 1px solid var(--skin-harbor-border);
border-radius: 7px;
color: var(--skin-harbor-muted);
background: var(--skin-harbor-raised);
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button:hover:not(:disabled),
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button:focus-visible { color: var(--skin-harbor-accent); }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button:disabled { opacity: .45; cursor: not-allowed; }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button span {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
[data-ws-plugin-part="harbor-workspace"] .desktop-audio-dock {
min-width: 0;
margin: 0;
padding: 4px;
border: 0;
border-radius: 7px;
background: transparent;
box-shadow: none;
}
[data-ws-plugin-part="harbor-workspace"] .desktop-audio-dock-copy { display: none; }
[data-ws-plugin-part="harbor-workspace"] .desktop-audio-dock-actions { gap: 2px; }
[data-ws-plugin-part="harbor-workspace"] .dock-audio-button { width: 34px; height: 34px; color: var(--skin-harbor-muted); }
[data-ws-plugin-part="harbor-workspace"] .dock-audio-button:hover,
[data-ws-plugin-part="harbor-workspace"] .dock-audio-button:focus-visible { color: var(--skin-harbor-accent); background: var(--skin-harbor-raised); border-color: var(--skin-harbor-border); }
[data-ws-plugin-part="harbor-workspace.audio-controls"] .accompaniment-toggle { display: none; }
[data-ws-plugin-part="harbor-workspace.disconnect-control"] {
display: grid;
align-content: center;
}
[data-ws-plugin-part="harbor-workspace"] .ws-plugin-disconnect-control {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border: 0;
border-radius: 8px;
color: var(--skin-harbor-danger);
background: var(--skin-harbor-raised);
cursor: pointer;
}
[data-ws-plugin-part="harbor-workspace"] .ws-plugin-disconnect-control:hover { background: #3a292b; }
[data-ws-plugin-part="harbor-workspace"] button:focus-visible,
[data-ws-plugin-part="harbor-home"] button:focus-visible,
[data-ws-plugin-part="harbor-home"] input:focus-visible {
outline: 2px solid var(--skin-harbor-accent);
outline-offset: 2px;
}
@media (max-width: 1060px) {
[data-ws-plugin-part="harbor-workspace"] {
grid-template-columns: 60px 236px minmax(300px, 1fr) 204px;
}
}
@media (max-width: 820px) {
[data-ws-plugin-part="harbor-workspace"] {
grid-template-columns: 56px minmax(0, 1fr);
grid-template-rows: 50px 126px minmax(220px, 1fr) 82px 74px;
height: 100dvh;
min-height: 540px;
}
[data-ws-plugin-part="harbor-workspace.topbar"] { padding: 0 8px; gap: 7px; }
[data-ws-plugin-part="harbor-workspace.brand-mark"] { flex-basis: 28px; width: 28px; height: 28px; }
[data-ws-plugin-part="harbor-workspace.brand-name"] { font-size: 10px; }
[data-ws-plugin-part="harbor-workspace.server-title"] { font-size: 10px; }
[data-ws-plugin-part="harbor-workspace.server-rail"] { grid-column: 1; grid-row: 2 / 6; padding: 8px 3px; }
[data-ws-plugin-part="harbor-workspace.quick-server"] { width: 48px; min-height: 48px; }
[data-ws-plugin-part="harbor-workspace.server-monogram"] { width: 36px; height: 36px; }
[data-ws-plugin-part="harbor-workspace.identity-monogram"] { width: 34px; height: 34px; }
[data-ws-plugin-part="harbor-workspace.channel-panel"] {
grid-column: 2;
grid-row: 2;
display: grid;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: 30px minmax(0, 1fr);
gap: 4px;
overflow: hidden;
padding: 5px 8px;
border-right: 0;
border-bottom: 1px solid var(--skin-harbor-border);
}
[data-ws-plugin-part="harbor-workspace.server-summary"] {
min-height: 0;
flex-direction: row;
align-items: center;
gap: 8px;
padding: 0 2px;
border: 0;
}
[data-ws-plugin-part="harbor-workspace.server-name"] { max-width: 60%; font-size: 11px; }
[data-ws-plugin-part="harbor-workspace.server-subtitle"],
[data-ws-plugin-part="harbor-workspace.channel-list"] > [data-ws-plugin-part="harbor-workspace.section-label"] { display: none; }
[data-ws-plugin-part="harbor-workspace.channel-list"] {
flex-direction: row;
gap: 5px;
overflow: auto hidden;
padding: 0;
}
[data-ws-plugin-part="harbor-workspace.channel-item"] { flex: 0 0 auto; }
[data-ws-plugin-part="harbor-workspace.channel-row"] { width: max-content; min-width: 116px; min-height: 42px; margin: 0; }
[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth] { padding-inline-start: 9px; }
[data-ws-plugin-part="harbor-workspace.channel-voice-members"] { display: none; }
[data-ws-plugin-part="harbor-workspace.conversation"] {
grid-column: 2;
grid-row: 3;
grid-template-rows: 40px minmax(0, 1fr) auto;
gap: 6px;
padding: 0 8px 6px;
}
[data-ws-plugin-part="harbor-workspace.members-panel"] {
grid-column: 2;
grid-row: 4;
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: 7px;
overflow: hidden;
padding: 5px 8px;
border-top: 1px solid var(--skin-harbor-border);
border-left: 0;
}
[data-ws-plugin-part="harbor-workspace.members-heading"] { gap: 5px; }
[data-ws-plugin-part="harbor-workspace.members-heading"] .section-label { max-width: 60px; font-size: 8px; }
[data-ws-plugin-part="harbor-workspace.member-list"] {
display: flex;
gap: 5px;
min-width: 0;
overflow: auto hidden;
margin: 0;
}
[data-ws-plugin-part="harbor-workspace.member-row"] { flex: 0 0 auto; grid-template-columns: 28px auto; min-height: 38px; padding: 2px 4px; }
[data-ws-plugin-part="harbor-workspace.member-avatar"] { width: 26px; height: 26px; }
[data-ws-plugin-part="harbor-workspace.speaking-indicator"] { display: none; }
[data-ws-plugin-part="harbor-workspace.member-muted-state"],
[data-ws-plugin-part="harbor-workspace.member-away-state"] { display: none; }
[data-ws-plugin-part="harbor-workspace.voice-dock"] {
grid-column: 2;
grid-row: 5;
align-self: stretch;
grid-template-columns: minmax(0, 1fr) auto;
grid-template-rows: minmax(0, 1fr);
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 0;
border-right: 0;
border-bottom: 0;
}
[data-ws-plugin-part="harbor-workspace.voice-dock-heading"] { grid-column: auto; grid-row: auto; }
[data-ws-plugin-part="harbor-workspace.voice-dock-actions"] { grid-column: 2; grid-row: 1; justify-content: flex-end; gap: 3px; }
[data-ws-plugin-part="harbor-workspace.voice-dock-caption"] { display: none; }
[data-ws-plugin-part="harbor-workspace.disconnect-control"] { grid-column: 2; grid-row: 1; }
[data-ws-plugin-part="harbor-workspace.audio-controls"] .mobile-voice-controls { display: flex; gap: 4px; }
[data-ws-plugin-part="harbor-workspace.audio-controls"] .mobile-voice-toggle { min-width: 44px; min-height: 44px; border-radius: 7px; color: var(--skin-harbor-muted); background: var(--skin-harbor-raised); }
[data-ws-plugin-part="harbor-workspace.microphone-control"],
[data-ws-plugin-part="harbor-workspace.output-control"],
[data-ws-plugin-part="harbor-workspace.disconnect-control"] { min-width: 42px; min-height: 44px; }
[data-ws-plugin-part="harbor-workspace.output-volume"] { width: 58px; }
[data-ws-plugin-part="harbor-workspace.screen-share-start"] button { width: 42px; height: 44px; }
}
@media (max-width: 460px) {
[data-ws-plugin-part="harbor-workspace"] { grid-template-columns: 50px minmax(0, 1fr); }
[data-ws-plugin-part="harbor-workspace.server-rail"] { padding-inline: 1px; }
[data-ws-plugin-part="harbor-workspace.quick-server"] { width: 44px; }
[data-ws-plugin-part="harbor-workspace.identity-name"] { max-width: 43px; }
[data-ws-plugin-part="harbor-workspace.topbar"] { padding-inline: 5px; }
[data-ws-plugin-part="harbor-workspace.brand-name"] { display: none; }
[data-ws-plugin-part="harbor-workspace.server-title"] { max-width: 100px; }
[data-ws-plugin-part="harbor-workspace.channel-panel"] { grid-column: 2; }
[data-ws-plugin-part="harbor-workspace.conversation"] { grid-column: 2; }
[data-ws-plugin-part="harbor-workspace.members-panel"] { grid-column: 2; }
[data-ws-plugin-part="harbor-workspace.voice-dock"] { grid-column: 2; }
}
@media (prefers-reduced-motion: reduce) {
[data-ws-plugin-part="harbor-home"] *,
[data-ws-plugin-part="harbor-workspace"] * {
scroll-behavior: auto;
animation-duration: .01ms;
animation-iteration-count: 1;
transition-duration: .01ms;
}
}
Binary file not shown.
@@ -0,0 +1,31 @@
{
"schemaVersion": 1,
"components": [
{
"id": "illusia-now-playing",
"name": "ILLUSIA 当前频道 / current channel",
"page": "voice",
"accessibleName": "当前语音频道 / Current voice channel",
"permissions": ["session.status.read"],
"actions": {},
"root": {
"tag": "aside",
"part": "room-card",
"className": "illusia-now-playing",
"attributes": { "role": "status" },
"children": [
{
"tag": "small",
"part": "eyebrow",
"children": [{ "text": "ILLUSIA · 当前频道 / NOW IN" }]
},
{
"tag": "strong",
"part": "channel-name",
"children": [{ "text": "{{session.status.channelName}}" }]
}
]
}
}
]
}
+6 -4
View File
@@ -1,12 +1,14 @@
{
"schemaVersion": 1,
"schemaVersion": 3,
"packageType": "open-skin",
"id": "community.illusia-voice",
"name": "ILLUSIA风",
"version": "1.0.27",
"version": "2.0.2",
"author": "WebSpeak Project",
"license": "All rights reserved",
"description": "A bright original-character art skin for the home, voice room, and demo pages.",
"description": "A bright original-character art skin with a safe declarative live-channel badge.",
"entry": "skin.css",
"components": "components.json",
"preview": "assets/background-composite.webp",
"minAppVersion": "0.2.6"
"minAppVersion": "0.2.7-preview"
}
+249 -2
View File
@@ -271,6 +271,57 @@
}
}
/* Open-skin compatibility sample: a small, non-interactive live-channel card. */
[data-ws-page="voice"] .ws-plugin-component[data-ws-plugin-part="illusia-now-playing"] {
position: fixed;
z-index: 5;
top: 66px;
right: 18px;
display: grid;
gap: 3px;
width: min(236px, calc(100vw - 36px));
min-height: 58px;
padding: 10px 56px 10px 14px;
overflow: hidden;
color: #15545b;
border: 1px solid rgba(71, 201, 212, .52);
border-radius: 17px;
background-image: linear-gradient(110deg, rgba(255, 255, 255, .95), rgba(219, 249, 250, .8)), url("assets/banner-mascot-blob.webp");
background-repeat: no-repeat;
background-position: center, right 8px center;
background-size: auto, 42px 42px;
box-shadow: 0 12px 30px rgba(7, 55, 65, .16), inset 0 1px rgba(255, 255, 255, .9);
backdrop-filter: blur(12px);
pointer-events: none;
}
[data-ws-page="voice"] [data-ws-plugin-part="illusia-now-playing.eyebrow"] {
color: #168f99;
font-size: 9px;
font-weight: 800;
letter-spacing: .08em;
}
[data-ws-page="voice"] [data-ws-plugin-part="illusia-now-playing.channel-name"] {
overflow: hidden;
color: #173f48;
font-size: 13px;
font-weight: 750;
text-overflow: ellipsis;
white-space: nowrap;
}
@media (max-width: 740px) {
[data-ws-page="voice"] .ws-plugin-component[data-ws-plugin-part="illusia-now-playing"] {
top: 62px;
right: 10px;
width: min(218px, calc(100vw - 20px));
min-height: 52px;
padding-block: 8px;
border-radius: 14px;
}
}
[data-ws-part="home.join-title"] {
color: var(--skin-illusia-ink);
}
@@ -840,11 +891,12 @@
[data-ws-part="voice.screen-player.stage"] {
border-radius: 22px;
background: radial-gradient(ellipse at 50% 38%, rgba(248, 255, 255, .98), rgba(220, 246, 250, .92) 58%, rgba(202, 237, 244, .9));
background: #000;
}
[data-ws-part="voice.screen-player.video"] {
background: #e5f4f8;
object-fit: contain;
background: #000;
}
[data-ws-part="voice.screen-player.placeholder"] {
@@ -891,6 +943,201 @@
box-shadow: 0 0 0 2px rgba(255, 255, 255, .94), 0 0 0 4px rgba(71, 201, 212, .72);
}
/* Home quick servers use the same light glass language as the voice switcher. */
[data-ws-part="home.server-history.group"] {
color: var(--skin-illusia-muted);
}
[data-ws-part="home.server-history.item"] {
color: var(--skin-illusia-ink);
border-color: rgba(104, 183, 198, .42);
border-radius: 9px;
background: linear-gradient(145deg, rgba(255, 255, 255, .94), rgba(220, 245, 249, .84));
box-shadow: 0 3px 10px rgba(37, 122, 143, .08), inset 0 1px 0 rgba(255, 255, 255, .9);
}
[data-ws-part="home.server-history.select"] {
color: var(--skin-illusia-ink);
}
[data-ws-part="home.server-history.select"]:hover {
color: var(--skin-illusia-teal);
background: rgba(71, 201, 212, .12);
}
[data-ws-part="home.server-history.favorite-toggle"] {
color: var(--skin-illusia-muted);
border-color: rgba(104, 183, 198, .32);
}
[data-ws-part="home.server-history.favorite-toggle"][data-ws-state="saved"] {
color: #b47a09;
background: rgba(255, 245, 205, .62);
}
/* Favorite-server navigation shares the voice room's light glass appearance. */
[data-ws-part="voice.favorite-servers.rail"],
[data-ws-part="voice.favorite-servers.strip"] {
color: var(--skin-illusia-ink);
background: linear-gradient(180deg, rgba(248, 254, 255, .92), rgba(225, 246, 250, .86));
border-color: rgba(112, 190, 204, .38);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .84);
backdrop-filter: blur(16px);
}
[data-ws-part="voice.favorite-servers.server"],
[data-ws-part="voice.favorite-servers.strip.server"],
[data-ws-part="voice.favorite-servers.add"],
[data-ws-part="voice.favorite-servers.strip.add"] {
color: var(--skin-illusia-ink);
border-color: rgba(104, 183, 198, .4);
background: linear-gradient(145deg, rgba(255, 255, 255, .96), rgba(220, 245, 249, .88));
box-shadow: 0 5px 16px rgba(37, 122, 143, .12), inset 0 1px 0 rgba(255, 255, 255, .92);
}
[data-ws-part="voice.favorite-servers.server"][data-ws-state="current"],
[data-ws-part="voice.favorite-servers.strip.server"][data-ws-state="current"] {
border-color: rgba(15, 151, 157, .72);
background: linear-gradient(145deg, rgba(220, 255, 249, .98), rgba(178, 239, 239, .94));
box-shadow: 0 0 0 2px rgba(26, 180, 180, .18), 0 8px 20px rgba(27, 143, 157, .18);
}
[data-ws-part="voice.favorite-servers.server"]:hover,
[data-ws-part="voice.favorite-servers.server"]:focus-visible,
[data-ws-part="voice.favorite-servers.strip.server"]:hover,
[data-ws-part="voice.favorite-servers.strip.server"]:focus-visible,
[data-ws-part="voice.favorite-servers.add"]:focus-visible,
[data-ws-part="voice.favorite-servers.strip.add"]:focus-visible {
border-color: rgba(12, 151, 159, .8);
box-shadow: 0 0 0 3px rgba(35, 183, 188, .22), 0 8px 20px rgba(27, 143, 157, .16);
}
[data-ws-part="voice.favorite-servers.avatar"] {
outline: 1px solid rgba(255, 255, 255, .82);
box-shadow: inset 0 0 0 1px rgba(20, 103, 119, .12), 0 3px 9px rgba(28, 104, 125, .16);
}
[data-ws-part="voice.favorite-servers.tooltip"] {
color: var(--skin-illusia-ink);
border-color: rgba(107, 189, 202, .48);
background: linear-gradient(145deg, rgba(255, 255, 255, .98), rgba(230, 249, 251, .96));
box-shadow: 0 10px 26px rgba(25, 94, 115, .2), inset 0 1px 0 #fff;
}
[data-ws-part="voice.favorite-servers.favorite-toggle"],
[data-ws-part="voice.favorite-servers.strip.favorite-toggle"] {
color: var(--skin-illusia-muted);
border-color: rgba(255, 255, 255, .96);
background: linear-gradient(145deg, rgba(255, 255, 255, .98), rgba(221, 246, 249, .94));
box-shadow: 0 2px 7px rgba(26, 82, 94, .22);
}
[data-ws-part="voice.favorite-servers.favorite-toggle"][data-ws-state="saved"],
[data-ws-part="voice.favorite-servers.strip.favorite-toggle"][data-ws-state="saved"] {
color: #a87405;
background: linear-gradient(145deg, rgba(255, 245, 205, .98), rgba(255, 255, 255, .96));
}
[data-ws-part="voice.favorite-servers.switch-status"] {
color: var(--skin-illusia-ink);
border-color: rgba(53, 172, 180, .42);
background: linear-gradient(105deg, rgba(224, 250, 250, .96), rgba(250, 255, 255, .94));
box-shadow: 0 8px 20px rgba(34, 120, 139, .1), inset 0 1px 0 #fff;
}
[data-ws-part="voice.favorite-servers.switch-status"][data-ws-state="failed"] {
border-color: rgba(190, 91, 105, .42);
background: linear-gradient(105deg, rgba(255, 239, 241, .98), rgba(255, 251, 251, .96));
}
[data-ws-part="voice.favorite-servers.current-toggle"][data-ws-state="saved"] {
color: #b47a09;
background: linear-gradient(145deg, rgba(255, 245, 205, .96), rgba(255, 255, 255, .94));
box-shadow: inset 0 0 0 1px rgba(224, 166, 47, .24);
}
[data-ws-part="voice.favorite-servers.dialog"] {
color: var(--skin-illusia-ink);
border-color: rgba(112, 190, 204, .52);
background: linear-gradient(145deg, rgba(255, 255, 255, .99), rgba(226, 246, 250, .98));
box-shadow: 0 24px 70px rgba(16, 72, 91, .3), inset 0 1px 0 #fff;
}
[data-ws-part="voice.favorite-servers.dialog-backdrop"] {
background: rgba(16, 54, 62, .48);
backdrop-filter: blur(7px);
}
[data-ws-part="voice.favorite-servers.dialog.header"] {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.favorite-servers.dialog.close"] {
color: var(--skin-illusia-ink);
border-color: rgba(112, 190, 204, .4);
background: linear-gradient(145deg, #fff, #e7f6f9);
}
[data-ws-part="voice.favorite-servers.dialog.field"] {
color: var(--skin-illusia-ink);
}
[data-ws-part="voice.favorite-servers.dialog.hint"] {
color: #547782;
}
[data-ws-part="voice.favorite-servers.dialog.input"] {
color: var(--skin-illusia-ink);
border-color: rgba(108, 174, 189, .48);
background: rgba(248, 254, 255, .96);
box-shadow: inset 0 1px 3px rgba(34, 104, 125, .08);
}
[data-ws-part="voice.favorite-servers.dialog.input"]:focus-visible {
border-color: rgba(11, 148, 154, .84);
box-shadow: 0 0 0 3px rgba(34, 183, 185, .2), inset 0 1px 3px rgba(34, 104, 125, .08);
}
[data-ws-part="voice.favorite-servers.dialog.submit"] {
color: #fff;
border-color: rgba(7, 121, 130, .86);
background: linear-gradient(110deg, #0a9997, #08717e);
box-shadow: 0 7px 16px rgba(10, 116, 130, .22), inset 0 1px 0 rgba(255, 255, 255, .24);
}
[data-ws-part="voice.favorite-servers.dialog.cancel"] {
color: var(--skin-illusia-ink);
border-color: rgba(116, 179, 192, .4);
background: linear-gradient(145deg, #fff, #eaf7f9);
}
/* Shared voice roster: give live screen-share status and watch actions an ILLUSIA treatment. */
[data-ws-part="voice.member.live-indicator"] {
color: #075b65;
border-color: rgba(34, 156, 167, .48);
background: rgba(250, 255, 255, .98);
box-shadow: 0 5px 16px rgba(27, 119, 137, .2), inset 0 1px 0 #fff;
}
[data-ws-part="voice.member.live-indicator"]::before {
background: #25c18a;
box-shadow: 0 0 0 3px rgba(37, 193, 138, .16);
}
[data-ws-part="voice.member.live-indicator"] .screen-share-wave { color: #078b98; }
[data-ws-part="voice.member.share-actions"] .screen-share-card-button {
color: #075e68;
border-color: rgba(34, 156, 167, .42);
background: linear-gradient(120deg, #f6ffff, #dff7f5);
box-shadow: 0 4px 12px rgba(30, 150, 163, .12), inset 0 1px 0 #fff;
}
[data-ws-part="voice.member.share-actions"] .screen-share-card-button:hover {
background: linear-gradient(120deg, #fff, #c9f0ec);
}
[data-ws-part="voice.member.share-actions"] .screen-share-card-button.viewing {
color: #fff;
border-color: #087e86;
background: linear-gradient(110deg, #0a9997, #08717e);
}
/* The demo keeps its original controls, labels, and interactions. */
[data-ws-page="demo"] {
color: var(--skin-illusia-ink);
Binary file not shown.
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
{
"defaultLocale": "zh-CN",
"locales": {
"zh-CN": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "确定" } },
"en": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "Confirm" } },
"de": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "Bestätigen" } },
"ru": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "Подтвердить" } },
"ja": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "確定" } }
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"schemaVersion": 3,
"packageType": "open-skin",
"id": "community.kaak-voice",
"name": "KAAK",
"version": "3.1.108",
"author": "WebSpeak Project",
"license": "AGPL-3.0-only",
"description": "A KOOK-inspired WebSpeak skin with a split-screen connection home, searchable server header, TeamSpeak banner, nested channel members, unified chat with local history, and a compact audio dock.",
"entry": "skin.css",
"components": "components.json",
"content": "content.json",
"minAppVersion": "0.2.7-preview"
}
File diff suppressed because it is too large. Load diff
Binary file not shown.
@@ -0,0 +1,240 @@
{
"schemaVersion": 3,
"components": [
{
"id": "open-voice-home",
"name": "Open voice connection page",
"page": "home",
"mode": "surface",
"accessibleName": "WebSpeak connection page",
"permissions": ["ui.surface.replace"],
"actions": {},
"root": {
"tag": "main",
"part": "home",
"children": [
{
"tag": "header",
"part": "home-header",
"children": [
{ "tag": "span", "part": "brand-mark", "children": [{ "text": "W" }] },
{ "tag": "span", "part": "brand-name", "children": [{ "text": "VOICE SPACE" }] },
{ "widget": "app.language-switcher", "part": "language" },
{ "widget": "app.skin-switcher", "part": "skin" }
]
},
{
"tag": "section",
"part": "connection-card",
"children": [
{ "tag": "p", "part": "eyebrow", "children": [{ "text": "TEAM SPEAK · VOICE CLIENT" }] },
{ "tag": "h1", "part": "title", "children": [{ "text": "Connect with your people" }] },
{ "tag": "p", "part": "description", "children": [{ "text": "Join a voice server and continue where your community meets." }] },
{ "widget": "home.connection-form", "part": "connection-form" }
]
},
{
"tag": "footer",
"part": "home-footer",
"children": [{ "text": "Your connection and identity remain managed by WebSpeak." }]
}
]
}
},
{
"id": "open-voice-workspace",
"name": "Open voice workspace",
"page": "voice",
"mode": "surface",
"accessibleName": "WebSpeak voice workspace",
"permissions": [
"ui.surface.replace",
"session.status.read",
"servers.quickList.read",
"servers.quickList.switch",
"session.channels.read",
"session.members.read",
"session.channel.join",
"chat.channel.read",
"chat.channel.send",
"audio.status.read",
"audio.microphone.control",
"audio.output.control",
"voice.whisper.status.read",
"voice.whisper.control",
"voice.disconnect",
"voice.screenShare.read",
"voice.screenShare.control"
],
"actions": {
"switch-server": {
"type": "quickServers.switch",
"args": { "quickServerId": "{{server.id}}" }
},
"join-channel": {
"type": "voice.joinChannel",
"args": { "channelId": "{{channel.id}}" }
},
"watch-screen-share": {
"type": "voice.joinScreenShare",
"args": { "streamId": "{{member.screenShareStreamId}}" }
}
},
"root": {
"tag": "main",
"part": "workspace",
"children": [
{
"tag": "header",
"part": "workspace-header",
"children": [
{ "tag": "span", "part": "brand-mark", "children": [{ "text": "W" }] },
{ "tag": "strong", "part": "server-title", "children": [{ "text": "{{session.status.channelName}}" }] },
{ "widget": "app.language-switcher", "part": "language" },
{ "widget": "app.skin-switcher", "part": "skin" }
]
},
{
"tag": "nav",
"part": "quick-rail",
"attributes": { "aria-label": "Favorite and recent servers" },
"children": [
{
"tag": "div",
"part": "quick-server-item",
"repeat": { "path": "servers.quickList", "as": "server" },
"children": [
{
"tag": "button",
"part": "quick-server",
"attributes": {
"type": "button",
"aria-current": "{{server.current}}",
"aria-label": "Switch to {{server.label}}"
},
"events": { "click": "switch-server" },
"children": [
{ "tag": "span", "part": "server-monogram", "children": [{ "text": "{{server.label}}" }] },
{
"tag": "small",
"part": "server-kind",
"when": { "path": "server.favorite", "equals": true },
"children": [{ "text": "Favorite" }]
},
{
"tag": "small",
"part": "server-kind",
"when": { "path": "server.kind", "equals": "recent" },
"children": [{ "text": "Recent" }]
}
]
}
]
}
]
},
{
"tag": "nav",
"part": "channels",
"attributes": { "aria-label": "Voice channels" },
"children": [
{ "tag": "h2", "part": "section-title", "children": [{ "text": "VOICE CHANNELS" }] },
{
"tag": "div",
"part": "channel-item",
"repeat": { "path": "session.channels", "as": "channel" },
"children": [
{
"tag": "button",
"part": "channel-row",
"attributes": {
"type": "button",
"aria-current": "{{channel.current}}",
"aria-label": "Join {{channel.name}}"
},
"events": { "dblclick": "join-channel", "keydown": "join-channel" },
"children": [
{ "tag": "span", "part": "channel-glyph", "children": [{ "text": "◖" }] },
{ "tag": "span", "part": "channel-name", "children": [{ "text": "{{channel.name}}" }] },
{ "tag": "small", "part": "channel-count", "children": [{ "text": "{{channel.memberCount}}" }] }
]
}
]
}
]
},
{
"tag": "section",
"part": "conversation",
"children": [
{
"tag": "header",
"part": "conversation-heading",
"children": [
{ "tag": "h1", "part": "channel-title", "children": [{ "text": "{{session.status.channelName}}" }] },
{ "tag": "span", "part": "connection-state", "children": [{ "text": "Connected" }] }
]
},
{ "widget": "voice.chat-panel", "part": "chat" },
{ "widget": "voice.screen-share-player", "part": "screen-share" }
]
},
{
"tag": "aside",
"part": "members-and-controls",
"children": [
{ "tag": "h2", "part": "section-title", "children": [{ "text": "IN THIS CHANNEL" }] },
{
"tag": "ul",
"part": "member-list",
"children": [
{
"tag": "li",
"part": "member-row",
"repeat": { "path": "session.members", "as": "member" },
"children": [
{ "tag": "span", "part": "member-avatar", "children": [{ "text": "{{member.name}}" }] },
{ "tag": "span", "part": "member-name", "children": [{ "text": "{{member.name}}" }] },
{
"tag": "small",
"part": "speaking-indicator",
"when": { "path": "member.speaking", "equals": true },
"attributes": { "aria-label": "Speaking" },
"children": [{ "text": "Speaking" }]
},
{
"tag": "div",
"part": "member-screen-share",
"when": { "path": "member.screenSharing", "equals": true },
"children": [
{
"tag": "span",
"part": "member-screen-share-live",
"attributes": { "role": "status" },
"children": [{ "text": "Sharing screen" }]
},
{
"tag": "button",
"part": "member-screen-share-watch",
"when": { "path": "member.self", "equals": false },
"attributes": { "type": "button", "aria-label": "Watch {{member.name}}'s screen" },
"events": { "click": "watch-screen-share" },
"children": [{ "text": "Watch" }]
}
]
}
]
}
]
},
{ "widget": "voice.whisper-controls", "part": "whisper" },
{ "widget": "voice.audio-controls", "part": "audio" },
{ "widget": "voice.connection-controls", "part": "connection" },
{ "widget": "voice.disconnect-control", "part": "disconnect" }
]
}
]
}
}
]
}
@@ -0,0 +1,13 @@
{
"schemaVersion": 3,
"packageType": "open-skin",
"id": "community.open-voice-surface",
"name": "Open Voice Surface",
"version": "1.0.1",
"author": "WebSpeak Project",
"license": "AGPL-3.0-only",
"description": "A complete, script-free public voice client surface scaffold.",
"entry": "skin.css",
"components": "components.json",
"minAppVersion": "0.2.7-preview"
}
+313
View File
@@ -0,0 +1,313 @@
:root {
color-scheme: dark;
--skin-voice-bg: #111318;
--skin-voice-panel: #191c24;
--skin-voice-raised: #222631;
--skin-voice-text: #f0f1f5;
--skin-voice-muted: #969baa;
--skin-voice-accent: #8e7bff;
--skin-voice-live: #62d5a7;
}
[data-ws-plugin-part="open-voice-home"] {
min-height: 100vh;
display: grid;
grid-template-rows: auto 1fr auto;
justify-items: center;
gap: 32px;
padding: clamp(18px, 5vw, 56px);
color: var(--skin-voice-text);
background: radial-gradient(ellipse at 50% 42%, #25253c 0, var(--skin-voice-bg) 66%);
}
[data-ws-plugin-part="open-voice-home.home-header"] {
display: flex;
align-items: center;
gap: 12px;
width: min(100%, 1080px);
}
[data-ws-plugin-part="open-voice-home.brand-mark"],
[data-ws-plugin-part="open-voice-workspace.brand-mark"] {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border-radius: 14px;
color: white;
background: var(--skin-voice-accent);
font-weight: 800;
}
[data-ws-plugin-part="open-voice-home.brand-name"] {
margin-right: auto;
font-size: 13px;
font-weight: 800;
letter-spacing: .14em;
}
[data-ws-plugin-part="open-voice-home.connection-card"] {
align-self: center;
width: min(100%, 520px);
padding: clamp(22px, 5vw, 42px);
border: 1px solid #ffffff17;
border-radius: 24px;
background: color-mix(in srgb, var(--skin-voice-panel) 94%, transparent);
box-shadow: 0 28px 90px #0008;
}
[data-ws-plugin-part="open-voice-home.eyebrow"],
[data-ws-plugin-part="open-voice-workspace.section-title"] {
color: var(--skin-voice-muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .14em;
}
[data-ws-plugin-part="open-voice-home.title"] {
margin: 10px 0;
font-size: clamp(27px, 5vw, 40px);
letter-spacing: -.04em;
}
[data-ws-plugin-part="open-voice-home.description"],
[data-ws-plugin-part="open-voice-home.home-footer"] {
color: var(--skin-voice-muted);
line-height: 1.6;
}
[data-ws-plugin-part="open-voice-workspace"] {
display: grid;
grid-template-columns: 72px 228px minmax(320px, 1fr) 252px;
grid-template-rows: 62px minmax(0, 1fr);
width: 100%;
min-height: 100vh;
color: var(--skin-voice-text);
background: var(--skin-voice-bg);
}
[data-ws-plugin-part="open-voice-workspace.workspace-header"] {
grid-column: 1 / -1;
display: flex;
align-items: center;
gap: 14px;
padding: 0 18px;
border-bottom: 1px solid #ffffff12;
background: #171920;
}
[data-ws-plugin-part="open-voice-workspace.server-title"] { margin-right: auto; }
[data-ws-plugin-part="open-voice-workspace.quick-rail"] {
grid-column: 1;
grid-row: 2;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
overflow-y: auto;
padding: 14px 8px;
background: #171920;
}
[data-ws-plugin-part="open-voice-workspace.quick-server"] {
display: grid;
justify-items: center;
gap: 4px;
width: 52px;
min-height: 58px;
padding: 5px;
border: 0;
border-radius: 16px;
color: var(--skin-voice-muted);
background: transparent;
cursor: pointer;
}
[data-ws-plugin-part="open-voice-workspace.quick-server"][aria-current="true"] {
color: white;
background: var(--skin-voice-accent);
}
[data-ws-plugin-part="open-voice-workspace.server-monogram"] {
display: grid;
place-items: center;
width: 36px;
height: 36px;
overflow: hidden;
border-radius: 12px;
background: #ffffff18;
font-size: 11px;
font-weight: 800;
}
[data-ws-plugin-part="open-voice-workspace.server-kind"] { font-size: 8px; }
[data-ws-plugin-part="open-voice-workspace.channels"],
[data-ws-plugin-part="open-voice-workspace.members-and-controls"] {
min-height: 0;
overflow: auto;
padding: 18px 12px;
background: var(--skin-voice-panel);
}
[data-ws-plugin-part="open-voice-workspace.channels"] { grid-column: 2; grid-row: 2; }
[data-ws-plugin-part="open-voice-workspace.members-and-controls"] { grid-column: 4; grid-row: 2; }
[data-ws-plugin-part="open-voice-workspace.channel-row"] {
display: flex;
align-items: center;
gap: 9px;
width: 100%;
margin-top: 4px;
padding: 9px 10px;
border: 0;
border-radius: 8px;
color: var(--skin-voice-muted);
background: transparent;
text-align: left;
cursor: pointer;
}
[data-ws-plugin-part="open-voice-workspace.channel-row"][aria-current="true"] {
color: var(--skin-voice-text);
background: var(--skin-voice-raised);
}
[data-ws-plugin-part="open-voice-workspace.channel-name"] { flex: 1; }
[data-ws-plugin-part="open-voice-workspace.channel-count"] { font-size: 11px; }
[data-ws-plugin-part="open-voice-workspace.conversation"] {
grid-column: 3;
grid-row: 2;
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
min-width: 0;
min-height: 0;
padding: 18px;
gap: 12px;
}
[data-ws-plugin-part="open-voice-workspace.conversation-heading"] {
display: flex;
align-items: center;
gap: 12px;
min-height: 46px;
border-bottom: 1px solid #ffffff12;
}
[data-ws-plugin-part="open-voice-workspace.channel-title"] { margin-right: auto; }
[data-ws-plugin-part="open-voice-workspace.connection-state"] { color: var(--skin-voice-live); font-size: 12px; }
[data-ws-plugin-part="open-voice-workspace.member-list"] {
display: grid;
gap: 8px;
margin: 12px 0 20px;
padding: 0;
list-style: none;
}
[data-ws-plugin-part="open-voice-workspace.member-row"] {
display: grid;
grid-template-columns: 34px minmax(0, 1fr);
align-items: center;
column-gap: 10px;
color: var(--skin-voice-text);
font-size: 12px;
}
[data-ws-plugin-part="open-voice-workspace.member-avatar"] {
grid-row: span 2;
display: grid;
place-items: center;
width: 34px;
height: 34px;
overflow: hidden;
border-radius: 50%;
color: white;
background: var(--skin-voice-raised);
font-weight: 700;
}
[data-ws-plugin-part="open-voice-workspace.speaking-indicator"] { color: var(--skin-voice-live); font-size: 10px; }
[data-ws-plugin-part="open-voice-workspace.member-screen-share"] {
grid-column: 2;
display: flex;
align-items: center;
gap: 8px;
color: var(--skin-voice-live);
font-size: 10px;
}
[data-ws-plugin-part="open-voice-workspace.member-screen-share-watch"] {
min-height: 32px;
padding: 0 10px;
border: 1px solid color-mix(in srgb, var(--skin-voice-live) 50%, transparent);
border-radius: 7px;
color: var(--skin-voice-text);
background: var(--skin-voice-raised);
cursor: pointer;
}
[data-ws-plugin-part="open-voice-workspace"] [data-ws-part="voice.chat"],
[data-ws-plugin-part="open-voice-workspace"] [data-ws-part="voice.audio-controls"],
[data-ws-plugin-part="open-voice-workspace"] [data-ws-part="voice.connection-controls"],
[data-ws-plugin-part="open-voice-workspace"] [data-ws-part="voice.disconnect-control"],
[data-ws-plugin-part="open-voice-workspace"] [data-ws-part="voice.whisper-controls"],
[data-ws-plugin-part="open-voice-workspace"] [data-ws-part="voice.screen-player"] {
border-radius: 12px;
color: var(--skin-voice-text);
background-color: var(--skin-voice-panel);
}
[data-ws-plugin-part="open-voice-workspace"] button:focus-visible {
outline: 2px solid var(--skin-voice-accent);
outline-offset: 2px;
}
@media (max-width: 800px) {
[data-ws-plugin-part="open-voice-workspace"] {
grid-template-columns: 58px minmax(0, 1fr);
grid-template-rows: 56px minmax(320px, 1fr) auto;
min-height: 100dvh;
}
[data-ws-plugin-part="open-voice-workspace.workspace-header"] { padding: 0 10px; }
[data-ws-plugin-part="open-voice-workspace.quick-rail"] { grid-column: 1; grid-row: 2; }
[data-ws-plugin-part="open-voice-workspace.channels"] {
grid-column: 1 / -1;
grid-row: 3;
display: flex;
gap: 6px;
overflow-x: auto;
overflow-y: hidden;
padding: 8px;
}
[data-ws-plugin-part="open-voice-workspace.section-title"] { display: none; }
[data-ws-plugin-part="open-voice-workspace.channel-row"] { width: max-content; min-width: 130px; margin: 0; }
[data-ws-plugin-part="open-voice-workspace.conversation"] {
grid-column: 2;
grid-row: 2;
padding: 10px;
}
[data-ws-plugin-part="open-voice-workspace.members-and-controls"] {
grid-column: 1 / -1;
grid-row: 4;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
padding: 8px;
}
[data-ws-plugin-part="open-voice-workspace.member-list"] { grid-column: 1 / -1; }
}
@media (prefers-reduced-motion: reduce) {
[data-ws-plugin-part="open-voice-workspace"] *,
[data-ws-plugin-part="open-voice-home"] * {
scroll-behavior: auto;
animation-duration: .01ms;
animation-iteration-count: 1;
transition-duration: .01ms;
}
}
+27 -13
View File
@@ -1,26 +1,40 @@
# WebSpeak 0.2.6
本版本相对于 [0.2.5 正式版](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) 更新。
本版本以 [0.2.5 正式版](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) 为基线。除了用户可见功能和问题修复,0.2.6 还完成了覆盖 TeamSpeak 网关、共享协议、语音工作区与管理页面的大范围工程结构重构。
## 问题修复与功能
## 工程结构重构
- **已修复 [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10)**:Docker/Compose 环境下短主机名的本地 DNS 解析回退;云端昵称发现加入超时和直接连接回退,避免外部发现服务不可用时阻塞连接。HTTPS 部署的健康检查也会根据证书配置选择 HTTPS。
- **已实现 [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9)**:导入 TeamSpeak 3 身份 INI 或身份字符串、导出 WebSpeak/TeamSpeak 兼容身份,并在本地校验格式和密钥一致性。
- **已修复 [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6)**:静音同步遇到服务端频率限制时有限重试;会话切换或重连后,旧请求不会覆盖当前麦克风状态。
- **已修复 [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7)**:TS6 屏幕共享清理等待服务器确认,携带清理原因并对频率限制有限重试,避免本地提前显示清理成功。
- **已实现 [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) 请求的配置入口**:管理员可设置公网媒体地址、IPv6 候选和语音 STUN,以适配反向代理或 TCP 隧道后的 UDP 媒体路径。直接媒体仍要求 UDP 可达,STUN 不提供中继。
- 修复 [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) 所报告的问题:新 WebSpeak 会话会发现已经开始的 TS6 原生屏幕共享,并将发现过程按服务器协调。PR 本身没有合并。
- 改善语音稳定性:隔离重连前后的音频帧、播放回调、目录事件和性能统计;保留连续 Opus 编码状态,只协商受支持的音频参数;切换麦克风或伴奏设置时尽量保留正在工作的采集链路。
- 改善移动端布局和语音控制,增加语音会话期间的屏幕常亮行为;梳理管理后台状态请求和语音工作区组件边界。
- **服务端语音网关:** 将原本集中在语音桥接中的工作拆分为 TeamSpeak 命令、会话事件、会话音频、语音协议和屏幕共享协调模块;客户端命令、服务端消息、音频与屏幕共享协议抽取为共享契约。
- **前端语音与管理:** 将大型 Vue 页面拆分为语音工作区、成员、聊天、音频、身份和屏幕共享组件;把连接、聊天、成员、身份、性能及屏幕共享逻辑放入职责明确的 composables 和服务。
- **管理后台与样式:** 将管理操作、服务器设置和皮肤管理拆分为独立组件与状态模块;分离管理页和语音客户端样式,并补充移动端样式层。
- **生命周期与测试:** SDK 事件、目录同步、头像传输、音频资源、屏幕共享及异步请求绑定到所属会话或页面。重连、切页或组件卸载时,旧操作不能再覆盖当前状态。新增的单元和集成测试覆盖这些边界与竞态。
## 功能与问题修复
- **[#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10):** 修复 Docker/Compose 中短主机名的 DNS 回退;云端昵称发现增加超时和直接连接回退;HTTPS 部署的健康检查按证书配置使用 HTTPS。
- **[#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9):** 支持从 TeamSpeak 3 身份 INI 或身份字符串导入,转换并导出 WebSpeak/TeamSpeak 兼容身份;在本地校验格式和密钥一致性。
- **[#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6):** 静音同步遭遇服务端频率限制时有限重试;切换会话或重连后,旧请求不能覆盖当前麦克风状态。
- **[#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7):** TS6 屏幕共享清理等待服务器确认、携带清理原因,并对频率限制有限重试,避免本地先显示清理成功。
- **[#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12):** 管理员可配置公网媒体地址、IPv6 候选和语音 STUN,供反向代理或 TCP 隧道后的媒体路径使用。STUN 只发现地址,不中继音频;直接媒体仍要求客户端能访问 UDP/IPv6 路径。
- **[PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13):** 修复新 WebSpeak 会话漏掉既有 TS6 原生屏幕共享的问题;由重构后的服务器级协调器实现发现与同步。
- **语音与 WebRTC:** 隔离重连前后的音频帧、播放回调、SDK/目录事件和性能统计;保留连续 Opus 编码状态,只协商当前网关支持的参数;切换麦克风或伴奏设置时尽可能保留正在工作的采集链路,闭麦时伴奏仍可播放。
- **移动端:** 优化窄屏布局和语音控制;语音会话期间保持屏幕常亮。
## 发布包与架构
- Windows:`windows-x64.zip`。
- Linux:`linux-x64.tar.gz`、`linux-arm64.tar.gz`。
- Docker:同一镜像标签提供 `linux/amd64` 和 `linux/arm64`。
- Android:分别提供 `arm64-v8a`、`armeabi-v7a`、`x86_64` APK。APK 使用 Android debug 签名,适合手动安装和测试,不是 Google Play 发布包。Android 端的真实 TeamSpeak 连接、双向语音和后台行为仍需真机验收。
- `SHA256SUMS.txt` 列出本次附件的 SHA-256,可用于下载后校验。
- Android:`arm64-v8a`、`armeabi-v7a`、`x86_64` 三种 APK。APK 使用 Android debug 签名,适合手动安装和测试,不是 Google Play 发布包。
- `SHA256SUMS.txt` 提供 Release 附件的 SHA-256 校验值。
Windows ARM64 未纳入本次发布:当前 `@discordjs/opus` 原生依赖不支持该构建目标。Android 已构建并提供安装包,但 Android 真机 TeamSpeak 连接、双向语音和后台行为仍需单独验收。
## 验证
发布流程运行完整自动化测试和前后端构建;Windows x64、Linux x64/ARM64 发布包均启动内置健康检查,Android 流程构建三种 ABI 的 APK。Windows ARM64 未纳入本次发布:当前 `@discordjs/opus` 上游只声明支持 Windows x64,ARM64 源码构建在 MSVC 下失败。自动化构建成功不等于真实 TeamSpeak 服务器或 Android 真机媒体链路已经验收。
GitHub Actions 发布流程通过自动化测试、类型检查和前后端构建;Docker 镜像执行启动检查,Windows x64 与 Linux x64/ARM64 发布包执行内置健康检查,Android 流程构建三种 ABI 的 APK。自动化构建通过不代表已完成真实 TeamSpeak 服务器互通或 Android 真机媒体验收。
## 近期合并的 PR 贡献者
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) 改进浏览器端报错翻译与提示;[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) 修正缩放、浮动布局和首页脚注。
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
+100 -5
View File
@@ -1,18 +1,21 @@
{
"name": "webspeak-webclient",
"version": "0.2.6",
"version": "0.2.7-preview",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.2.6",
"version": "0.2.7-preview",
"license": "AGPL-3.0-only",
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#758a0d7d9120b0f5777d9451fb6b134f0b606f65",
"express": "^5.2.1",
"pino": "^10.3.1",
"postcss": "^8.5.29",
"postcss-selector-parser": "^7.1.6",
"postcss-value-parser": "^4.2.0",
"werift": "0.24.4",
"ws": "^8.20.0"
},
@@ -62,8 +65,8 @@
}
},
"node_modules/@echosixhiya/teamspeak-client": {
"version": "0.2.4",
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
"version": "0.2.5",
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#758a0d7d9120b0f5777d9451fb6b134f0b606f65",
"license": "MIT",
"dependencies": {
"@noble/curves": "^2.0.1"
@@ -1198,6 +1201,18 @@
"node": ">=6.6.0"
}
},
"node_modules/cssesc": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
"integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
"license": "MIT",
"bin": {
"cssesc": "bin/cssesc"
},
"engines": {
"node": ">=4"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -1901,6 +1916,24 @@
"multicast-dns": "cli.js"
}
},
"node_modules/nanoid": {
"version": "3.3.20",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
"integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/negotiator": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
@@ -2046,6 +2079,12 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC"
},
"node_modules/pino": {
"version": "10.3.1",
"resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz",
@@ -2083,6 +2122,53 @@
"integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",
"license": "MIT"
},
"node_modules/postcss": {
"version": "8.5.29",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz",
"integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.19",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.2"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/postcss-selector-parser": {
"version": "7.1.6",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz",
"integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==",
"license": "MIT",
"dependencies": {
"cssesc": "^3.0.0",
"util-deprecate": "^1.0.2"
},
"engines": {
"node": ">=4"
}
},
"node_modules/postcss-value-parser": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
"license": "MIT"
},
"node_modules/process-warning": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",
@@ -2427,6 +2513,15 @@
"atomic-sleep": "^1.0.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
+55 -47
View File
@@ -1,47 +1,55 @@
{
"name": "webspeak-webclient",
"version": "0.2.6",
"private": true,
"license": "AGPL-3.0-only",
"type": "module",
"description": "Server-side browser gateway for TeamSpeak — deploy on your server, users join from any browser",
"engines": {
"node": ">=22.5.0"
},
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test src/admin/skin-registry.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 src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.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/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/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-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/member-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/identity-import.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts",
"verify": "npm test && npm run build && npm run web:build",
"start": "node dist/index.js",
"web:dev": "cd web && npx vite --host",
"web:build": "npm --prefix web run build",
"android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs",
"android:sync": "npm run android:prepare && cd web && npx cap sync android",
"prepare:sdk": "node scripts/prepare-sdk.mjs",
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
"acceleration:relay": "node dist/relay.js"
},
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
"express": "^5.2.1",
"pino": "^10.3.1",
"werift": "0.24.4",
"ws": "^8.20.0"
},
"devDependencies": {
"@types/express": "^5.0.3",
"@types/node": "^22.15.0",
"@types/ws": "^8.18.1",
"tsx": "^4.21.0",
"typescript": "^6.0.2"
},
"overrides": {
"body-parser": "^2.3.0",
"esbuild": "^0.28.2",
"tar": "^7.5.22"
}
}
{
"name": "webspeak-webclient",
"version": "0.2.7-preview",
"private": true,
"license": "AGPL-3.0-only",
"type": "module",
"description": "Server-side browser gateway for TeamSpeak — deploy on your server, users join from any browser",
"engines": {
"node": ">=22.5.0"
},
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.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 src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.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-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-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-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",
"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",
"skin:kaak:build": "node web/scripts/build-kaak-voice-skin.mjs",
"skin:illusia:build": "node web/scripts/build-illusia-voice-skin.mjs",
"start": "node dist/index.js",
"web:dev": "cd web && npx vite --host",
"web:build": "npm --prefix web run build",
"skin:wasm:build": "node scripts/build-skin-wasm-interpreter.mjs",
"android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs",
"android:sync": "npm run android:prepare && cd web && npx cap sync android",
"prepare:sdk": "node scripts/prepare-sdk.mjs",
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
"acceleration:relay": "node dist/relay.js"
},
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#758a0d7d9120b0f5777d9451fb6b134f0b606f65",
"express": "^5.2.1",
"pino": "^10.3.1",
"postcss": "^8.5.29",
"postcss-selector-parser": "^7.1.6",
"postcss-value-parser": "^4.2.0",
"werift": "0.24.4",
"ws": "^8.20.0"
},
"devDependencies": {
"@types/express": "^5.0.3",
"@types/node": "^22.15.0",
"@types/ws": "^8.18.1",
"tsx": "^4.21.0",
"typescript": "^6.0.2"
},
"overrides": {
"body-parser": "^2.3.0",
"esbuild": "^0.28.2",
"tar": "^7.5.22"
}
}
+32
View File
@@ -0,0 +1,32 @@
import { copyFile, mkdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const interpreterRoot = path.join(repositoryRoot, "web", "skin-wasm-interpreter");
const sourceArtifact = path.join(interpreterRoot, "target", "wasm32-unknown-unknown", "release", "webspeak_skin_wasm_interpreter.wasm");
const publicDirectory = path.join(repositoryRoot, "web", "public");
const publicArtifact = path.join(publicDirectory, "skin-wasm-interpreter.wasm");
const rustFlags = "-C link-arg=--max-memory=67108864 -C panic=abort";
const result = spawnSync("cargo", ["build", "--locked", "--release", "--target", "wasm32-unknown-unknown"], {
cwd: interpreterRoot,
env: { ...process.env, RUSTFLAGS: rustFlags },
stdio: "inherit",
});
if (result.error) throw result.error;
if (result.status !== 0) process.exit(result.status ?? 1);
const artifactInfo = await stat(sourceArtifact);
if (artifactInfo.size < 8 || artifactInfo.size > 8 * 1024 * 1024) {
throw new Error(`The Wasmi interpreter artifact has an unexpected size: ${artifactInfo.size} bytes.`);
}
const header = await readFile(sourceArtifact, { encoding: null, flag: "r" });
if (header[0] !== 0 || header[1] !== 0x61 || header[2] !== 0x73 || header[3] !== 0x6d) {
throw new Error("The Wasmi interpreter build did not produce a WebAssembly module.");
}
await mkdir(publicDirectory, { recursive: true });
await copyFile(sourceArtifact, publicArtifact);
console.log(`Built bounded Wasmi interpreter (${artifactInfo.size} bytes) at web/public/skin-wasm-interpreter.wasm.`);
+39 -16
View File
@@ -5,7 +5,9 @@ import { createHash, randomBytes } from "node:crypto";
import { existsSync } from "node:fs";
import type { Logger } from "../logger.js";
import { loadConfig } from "../config.js";
import { formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { DEFAULT_TEAM_SPEAK_PORT, formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget, type TeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
import { resolveTeamSpeakTarget, TeamSpeakAliasLookupError } from "../server/teamspeak-alias.js";
import { type AccessMode, type ManagedInviteRecord, type PersistedRelayNode, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
@@ -18,7 +20,7 @@ import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
export interface ConnectionPolicy {
defaultTarget: TeamSpeakTarget;
defaultTarget: string;
serverPassword: string;
accessMode: AccessMode;
}
@@ -98,14 +100,14 @@ export class AdminService {
welcomeTextEn: welcomeTexts.en,
welcomeTexts,
accessMode: settings.accessMode,
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
target: settingsTarget(settings),
};
}
getAdminSettings(): AdminSettings {
const settings = this.database.getSettings();
return {
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
target: settingsTarget(settings),
hasPassword: Boolean(settings.tsPasswordEncrypted),
accessMode: settings.accessMode,
siteName: settings.siteName,
@@ -168,7 +170,7 @@ export class AdminService {
const current = this.database.getSettings();
const relayNodes = input.relayNodes === undefined ? undefined : this.normalizeRelayNodes(input.relayNodes);
const settings = this.normalizeSettings(input, current, relayNodes);
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort;
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort || current.tsTarget !== settings.tsTarget;
this.database.updateSettings(settings);
if (relayNodes !== undefined) {
this.database.replaceRelayNodes(relayNodes);
@@ -187,7 +189,7 @@ export class AdminService {
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Stored TeamSpeak password could not be decrypted");
}
return {
defaultTarget: { host: settings.tsHost, port: settings.tsPort },
defaultTarget: settingsTarget(settings),
serverPassword,
accessMode: settings.accessMode,
};
@@ -196,11 +198,12 @@ export class AdminService {
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<{ ok: boolean; checkType: "network" | "protocol"; passwordVerified: boolean; latencyMs: number; serverName: string | null; requiresPassword: boolean; packetLossPercent?: number; attempts?: number; successfulAttempts?: number; errorCode?: string }> {
let target: TeamSpeakTarget;
try {
target = parseTeamSpeakTarget(targetText);
parseTeamSpeakConnectionTarget(targetText);
} catch {
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
}
try {
target = await resolveTeamSpeakTarget(targetText);
// The admin connection test must not create a temporary TeamSpeak
// client: that client becomes visible in the target channel. Use the
// WebSpeak host's ICMP route measurement instead. The injected probe is
@@ -239,7 +242,9 @@ export class AdminService {
} catch (error: unknown) {
const probeError = error instanceof TeamSpeakProbeError
? error
: new TeamSpeakProbeError("INTERNAL_ERROR", "Connection test failed", error);
: error instanceof TeamSpeakAliasLookupError
? new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak server nickname could not be resolved", error)
: new TeamSpeakProbeError("INTERNAL_ERROR", "Connection test failed", error);
if (persistResult) {
this.database.recordConnectionTest({ protocol: null, latencyMs: null, error: probeError.code });
this.database.addAudit("CONNECTION_TEST_FAILED", { code: probeError.code });
@@ -257,7 +262,7 @@ export class AdminService {
uptimeSeconds: Math.max(0, Math.floor((Date.now() - startedAt) / 1000)),
},
teamSpeak: {
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
target: settingsTarget(settings),
status: settings.lastTestError ? "unreachable" : settings.lastTestAt ? "reachable" : "unknown",
lastTestAt: settings.lastTestAt,
latencyMs: settings.lastTestLatencyMs,
@@ -285,6 +290,7 @@ export class AdminService {
tokenHash: hashInviteToken(token),
targetHost: settings.tsHost,
targetPort: settings.tsPort,
targetText: settings.tsTarget,
serverPasswordEncrypted: settings.tsPasswordEncrypted,
channel,
expiresAt: new Date(Date.now() + input.expiresInHours * 60 * 60 * 1000).toISOString(),
@@ -305,7 +311,17 @@ export class AdminService {
return revoked;
}
consumeManagedInvite(token: string): { target: TeamSpeakTarget; serverPassword: string; channel: string } | null {
getManagedInvite(token: string): { target: string; channel: string } | null {
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return null;
const record = this.database.getManagedInvite(hashInviteToken(token));
if (!record) return null;
return {
target: record.targetText ?? formatTeamSpeakTarget({ host: record.targetHost, port: record.targetPort }),
channel: record.channel,
};
}
consumeManagedInvite(token: string): { target: string; serverPassword: string; channel: string } | null {
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return null;
const record = this.database.consumeManagedInvite(hashInviteToken(token));
if (!record) return null;
@@ -316,7 +332,7 @@ export class AdminService {
this.logger.error({ err: error instanceof Error ? error.message : String(error), inviteId: record.id }, "Managed invite password could not be decrypted");
}
this.database.addAudit("INVITE_CONSUMED", { id: record.id });
return { target: { host: record.targetHost, port: record.targetPort }, serverPassword, channel: record.channel };
return { target: record.targetText ?? formatTeamSpeakTarget({ host: record.targetHost, port: record.targetPort }), serverPassword, channel: record.channel };
}
dismissLegacyImportNotice(): void {
@@ -324,9 +340,9 @@ export class AdminService {
}
private normalizeSettings(input: AdminSettingsInput, current: ReturnType<WebSpeakDatabase["getSettings"]>, relayNodes?: PersistedRelayNode[]): SettingsUpdate {
let target: TeamSpeakTarget;
let target: TeamSpeakConnectionTarget;
try {
target = parseTeamSpeakTarget(input.target);
target = parseTeamSpeakConnectionTarget(input.target);
} catch {
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
}
@@ -430,8 +446,9 @@ export class AdminService {
welcomeTextRu,
welcomeTextJa,
accessMode: input.accessMode,
tsHost: target.host,
tsPort: target.port,
tsHost: target.kind === "nickname" ? target.name : target.target.host,
tsPort: target.kind === "nickname" ? target.port ?? DEFAULT_TEAM_SPEAK_PORT : target.target.port,
tsTarget: target.kind === "nickname" ? formatTeamSpeakConnectionTarget(target) : null,
tsPasswordEncrypted: encryptedPassword,
webRtcEnabled: input.webRtcEnabled,
webRtcPublicHost, webRtcIpv6Enabled, webRtcStunServer,
@@ -528,7 +545,7 @@ export class AdminService {
const exhausted = record.maxUses > 0 && record.useCount >= record.maxUses;
return {
id: record.id,
target: formatTeamSpeakTarget({ host: record.targetHost, port: record.targetPort }),
target: record.targetText ?? formatTeamSpeakTarget({ host: record.targetHost, port: record.targetPort }),
channel: record.channel,
expiresAt: record.expiresAt,
maxUses: record.maxUses,
@@ -550,6 +567,7 @@ export class AdminService {
accessMode: settings.accessMode,
tsHost: settings.tsHost,
tsPort: settings.tsPort,
tsTarget: settings.tsTarget,
tsPasswordEncrypted: settings.tsPasswordEncrypted,
webRtcEnabled: settings.webRtcEnabled,
webRtcPublicHost: settings.webRtcPublicHost,
@@ -581,6 +599,7 @@ export class AdminService {
accessMode: current.accessMode,
tsHost: legacy.tsHost,
tsPort: legacy.tsPort,
tsTarget: legacy.tsTarget ?? null,
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
webRtcEnabled: current.webRtcEnabled,
webRtcPublicHost: current.webRtcPublicHost,
@@ -607,6 +626,10 @@ function hashInviteToken(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
function settingsTarget(settings: { tsHost: string; tsPort: number; tsTarget?: string | null }): string {
return settings.tsTarget ?? formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort });
}
function formatRelayTarget(host: string, port: number): string {
return `${host.includes(":") ? `[${host}]` : host}#${port}`;
}
+271 -4
View File
@@ -5,7 +5,7 @@ import path from "node:path";
import test from "node:test";
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
const manifest = {
const manifest = {
schemaVersion: 1,
id: "sample-skin",
name: "Sample skin",
@@ -26,7 +26,7 @@ test("skin registry validates, lists, replaces, serves, and removes packages", a
assert.equal(await registry.readArchive("sample-skin"), null);
const firstArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifest))],
["skin.css", Buffer.from(".voice-card { background: url(assets/background.png); }")],
["skin.css", Buffer.from('[data-ws-part="voice.member"] { background: url(assets/background.png); }')],
["content.json", Buffer.from(JSON.stringify({ defaultLocale: "en", locales: { en: { home: { title: "Hello" } } } }))],
["assets/background.png", Buffer.from([1, 2, 3, 4])],
["assets/preview.png", Buffer.from([5, 6, 7, 8])],
@@ -45,7 +45,7 @@ test("skin registry validates, lists, replaces, serves, and removes packages", a
const replacement = { ...manifest, version: "2.0.0", content: undefined, preview: undefined };
const secondArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify(replacement))],
["skin.css", Buffer.from(".voice-card { border-radius: 0; }")],
["skin.css", Buffer.from('[data-ws-part="voice.member"] { border-radius: 0; }')],
]);
const second = await registry.save(secondArchive, "sample-skin");
assert.equal(second.version, "2.0.0");
@@ -87,13 +87,280 @@ test("custom skins can be enabled, disabled, and selected as the instance defaul
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
});
test("server accepts validated declarative v2 layouts and rejects permissions or unregistered components", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v2-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
const manifestV2 = {
...manifest,
schemaVersion: 2,
packageType: "layout-skin",
permissions: [],
layout: "layout.json",
content: undefined,
preview: undefined,
};
const layout = {
schemaVersion: 1,
pages: { home: { desktop: { "home.header": { x: 24, visible: true, background: "#123456" } } } },
};
const archive = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifestV2))],
["skin.css", Buffer.from('[data-ws-part="home.header"] { color: teal; }')],
["layout.json", Buffer.from(JSON.stringify(layout))],
]);
const saved = await registry.save(archive, "sample-skin");
assert.equal(saved.id, "sample-skin");
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
const permissionsArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifestV2, permissions: ["network.fetch"] }))],
["skin.css", Buffer.from("")],
["layout.json", Buffer.from(JSON.stringify(layout))],
]);
await assert.rejects(registry.save(permissionsArchive, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PERMISSION_INVALID");
const unknownManifestField = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifestV2, capabilities: ["network.fetch"] }))],
["skin.css", Buffer.from('[data-ws-part="home.header"] { color: teal; }')],
["layout.json", Buffer.from(JSON.stringify({ schemaVersion: 1, pages: {} }))],
]);
await assert.rejects(registry.save(unknownManifestField, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_MANIFEST_INVALID");
const unknownComponentArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifestV2))],
["skin.css", Buffer.from('[data-ws-part="voice.member"] { color: teal; }')],
["layout.json", Buffer.from(JSON.stringify({ schemaVersion: 1, pages: { home: { desktop: { "home.unknown": { x: 1 } } } } }))],
]);
await assert.rejects(registry.save(unknownComponentArchive, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_LAYOUT_INVALID");
});
test("server accepts v3 declarative components and rejects unapproved capability declarations", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v3-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
const manifestV3 = {
...manifest,
schemaVersion: 3,
packageType: "open-skin",
content: undefined,
preview: undefined,
components: "components.json",
};
const components = {
schemaVersion: 1,
components: [{
id: "channels",
name: "Channels",
page: "voice",
accessibleName: "TeamSpeak channels",
permissions: ["session.channels.read", "session.channel.join"],
actions: { join: { type: "voice.joinChannel", args: { channelId: "{{channel.id}}" } } },
root: { tag: "nav", repeat: { path: "session.channels", as: "channel" }, children: [{ tag: "button", events: { dblclick: "join" }, children: [{ text: "{{channel.name}}" }] }] },
}],
};
const archive = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifestV3))],
["skin.css", Buffer.from('[data-ws-part="voice.channel-group"] { display: none; }')],
["components.json", Buffer.from(JSON.stringify(components))],
]);
const saved = await registry.save(archive, "sample-skin");
assert.equal(saved.id, "sample-skin");
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
const unapproved = structuredClone(components) as typeof components;
unapproved.components[0].permissions = ["network.fetch"];
const unsafeArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifestV3))],
["skin.css", Buffer.from("[data-ws-part=app] { color: red; }")],
["components.json", Buffer.from(JSON.stringify(unapproved))],
]);
await assert.rejects(registry.save(unsafeArchive, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PLUGIN_INVALID");
});
test("server accepts a v3 open visual skin without a components document", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v3-visual-only-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
const archive = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, schemaVersion: 3, packageType: "open-skin", content: undefined, preview: undefined }))],
["skin.css", Buffer.from('[data-ws-part="app"] { position: fixed; }')],
]);
const saved = await registry.save(archive, "sample-skin");
assert.equal(saved.id, "sample-skin");
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
});
test("server applies the browser CSS scope and package-only resource policy to every stylesheet", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-css-policy-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
const unsafeLegacySelector = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
["skin.css", Buffer.from(".private-class { color: teal; }")],
]);
await assert.rejects(registry.save(unsafeLegacySelector, "sample-skin"), (error: unknown) =>
error instanceof SkinRegistryError && error.code === "SKIN_CSS_SELECTOR");
const remoteSkinCss = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
["skin.css", Buffer.from('[data-ws-part="app"] { background-image: url("https://example.invalid/track.png"); }')],
]);
await assert.rejects(registry.save(remoteSkinCss, "sample-skin"), (error: unknown) =>
error instanceof SkinRegistryError && error.code === "SKIN_EXTERNAL_RESOURCE");
const manifestV4 = {
...manifest,
schemaVersion: 4,
packageType: "open-skin",
content: undefined,
preview: undefined,
plugins: "plugins.json",
};
const plugins = {
schemaVersion: 1,
plugins: [{
id: "voice-toolbar",
name: "Voice toolbar",
version: "1.0.0",
apiVersion: 1,
page: "voice",
mode: "widget",
entry: "plugins/voice-toolbar/index.js",
style: "plugins/voice-toolbar/style.css",
assets: [],
permissions: [],
}],
};
const remotePluginCss = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifestV4))],
["skin.css", Buffer.from('[data-ws-part="app"] { color: teal; }')],
["plugins.json", Buffer.from(JSON.stringify(plugins))],
["plugins/voice-toolbar/index.js", Buffer.from("export {}; ")],
["plugins/voice-toolbar/style.css", Buffer.from('.toolbar { background-image: u\\72l("https://example.invalid/track.png"); }')],
]);
await assert.rejects(registry.save(remotePluginCss, "sample-skin"), (error: unknown) =>
error instanceof SkinRegistryError && error.code === "SKIN_EXTERNAL_RESOURCE");
});
test("server validates v4 plugin manifests and package files without executing author code", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-v4-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
const manifestV4 = {
...manifest,
schemaVersion: 4,
packageType: "open-skin",
content: undefined,
preview: undefined,
plugins: "plugins.json",
};
const plugins = {
schemaVersion: 1,
plugins: [{
id: "voice-toolbar",
name: "Voice toolbar",
version: "1.0.0",
apiVersion: 1,
page: "voice",
mode: "widget",
entry: "plugins/voice-toolbar/index.js",
style: "plugins/voice-toolbar/style.css",
assets: ["plugins/voice-toolbar/assets/icon.png"],
permissions: ["session.channels.read"],
}],
};
const archive = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifestV4))],
["skin.css", Buffer.from('[data-ws-part="app"] { position: fixed; }')],
["plugins.json", Buffer.from(JSON.stringify(plugins))],
["plugins/voice-toolbar/index.js", Buffer.from("export const render = () => document.createElement('button');")],
["plugins/voice-toolbar/style.css", Buffer.from(".toolbar { color: teal; }")],
["plugins/voice-toolbar/assets/icon.png", Buffer.from([1, 2, 3, 4])],
]);
const saved = await registry.save(archive, "sample-skin");
assert.equal(saved.id, "sample-skin");
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
const layout = {
schemaVersion: 1,
pages: { voice: { desktop: { "skin.voice.runtime_plugin_root_voice-toolbar": { order: 2, visible: true } } } },
};
const archiveWithLayout = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifestV4, layout: "layout.json" }))],
["skin.css", Buffer.from('[data-ws-part="app"] { position: fixed; }')],
["plugins.json", Buffer.from(JSON.stringify(plugins))],
["plugins/voice-toolbar/index.js", Buffer.from("export const render = () => document.createElement('button');")],
["plugins/voice-toolbar/style.css", Buffer.from(".toolbar { color: teal; }")],
["plugins/voice-toolbar/assets/icon.png", Buffer.from([1, 2, 3, 4])],
["layout.json", Buffer.from(JSON.stringify(layout))],
]);
const layoutSaved = await registry.save(archiveWithLayout, "sample-skin");
assert.equal(layoutSaved.id, "sample-skin");
assert.deepEqual(await registry.readArchive("sample-skin"), archiveWithLayout);
const invalidLayoutArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify({ ...manifestV4, layout: "layout.json" }))],
["skin.css", Buffer.from('[data-ws-part="app"] { position: fixed; }')],
["plugins.json", Buffer.from(JSON.stringify(plugins))],
["plugins/voice-toolbar/index.js", Buffer.from("export {}; ")],
["plugins/voice-toolbar/style.css", Buffer.from(".toolbar { color: teal; }")],
["plugins/voice-toolbar/assets/icon.png", Buffer.from([1, 2, 3, 4])],
["layout.json", Buffer.from(JSON.stringify({ schemaVersion: 1, pages: { voice: { desktop: { "voice.not-registered": { order: 2 } } } } }))],
]);
await assert.rejects(registry.save(invalidLayoutArchive, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_LAYOUT_INVALID");
const wasmPlugins = {
schemaVersion: 1,
plugins: [{
id: "bounded-widget",
name: "Bounded widget",
version: "1.0.0",
apiVersion: 1,
runtime: "wasm",
page: "voice",
mode: "widget",
entry: "plugins/bounded-widget/index.wasm",
assets: [],
permissions: [],
}],
};
const wasmManifest = { ...manifestV4, id: "wasm-skin" };
const wasmArchive = createZip([
["manifest.json", Buffer.from(JSON.stringify(wasmManifest))],
["skin.css", Buffer.from('[data-ws-part="app"] { position: fixed; }')],
["plugins.json", Buffer.from(JSON.stringify(wasmPlugins))],
["plugins/bounded-widget/index.wasm", Buffer.from([0, 97, 115, 109, 1, 0, 0, 0])],
]);
const wasmSaved = await registry.save(wasmArchive, "wasm-skin");
assert.equal(wasmSaved.id, "wasm-skin");
assert.deepEqual(await registry.readArchive("wasm-skin"), wasmArchive);
const missingEntry = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifestV4))],
["skin.css", Buffer.from("[data-ws-part=app] { color: teal; }")],
["plugins.json", Buffer.from(JSON.stringify(plugins))],
]);
await assert.rejects(registry.save(missingEntry, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_RUNTIME_PLUGIN_FILE_MISSING");
const unlistedScript = createZip([
["manifest.json", Buffer.from(JSON.stringify(manifestV4))],
["skin.css", Buffer.from("[data-ws-part=app] { color: teal; }")],
["plugins.json", Buffer.from(JSON.stringify(plugins))],
["plugins/voice-toolbar/index.js", Buffer.from("export {};")],
["plugins/voice-toolbar/style.css", Buffer.from(".toolbar { color: teal; }")],
["plugins/voice-toolbar/assets/icon.png", Buffer.from([1, 2, 3, 4])],
["plugins/other/rogue.js", Buffer.from("export {};")],
]);
await assert.rejects(registry.save(unlistedScript, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_FILE_UNSUPPORTED");
});
test("skin registry rejects path traversal and mismatched local ZIP headers", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-invalid-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const registry = new SkinRegistry(directory);
const goodFiles: Array<[string, Buffer]> = [
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
["skin.css", Buffer.from(".voice-card { color: teal; }")],
["skin.css", Buffer.from('[data-ws-part="voice.member"] { color: teal; }')],
];
await assert.rejects(registry.save(createZip([["../escape.png", Buffer.from([1])], ...goodFiles]), "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PATH_INVALID");
+130 -7
View File
@@ -1,4 +1,15 @@
import type { SkinCatalogEntry as SharedSkinCatalogEntry } from "../shared/skin-catalog.js";
import { compileSkinCss, SkinCssValidationError, type SkinCssSchemaVersion } from "../shared/skin-css.js";
import { parseSkinLayoutJson } from "../shared/skin-layout.js";
import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../shared/skin-plugin.js";
import {
listSkinRuntimePluginFilePaths,
parseSkinRuntimePluginJson,
SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES,
SKIN_RUNTIME_PLUGIN_SOURCE_LIMIT_BYTES,
SKIN_RUNTIME_PLUGIN_STYLE_LIMIT_BYTES,
type SkinRuntimePluginDocument,
} from "../shared/skin-runtime-plugins.js";
import { randomBytes } from "node:crypto";
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
@@ -40,8 +51,13 @@ interface SkinArchiveEntry {
}
type ParsedSkinManifest = Omit<SkinCatalogEntry, "installedAt" | "previewUrl" | "previewMimeType" | "enabled"> & {
schemaVersion: 1 | 2 | 3 | 4;
packageType?: "layout-skin" | "open-skin";
entry: string;
layout?: string;
content?: string;
components?: string;
plugins?: string;
preview?: string;
};
@@ -217,17 +233,71 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa
if (expectedId && manifest.id !== expectedId) throw new SkinRegistryError("The skin ID does not match the upload target.", "SKIN_ID_MISMATCH");
const cssBytes = fileBytes.get(manifest.entry);
if (!cssBytes || !cssBytes.byteLength || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinRegistryError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE");
decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8.");
const cssSource = decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8.");
let runtimePlugins: SkinRuntimePluginDocument | undefined;
if (manifest.plugins) {
const pluginsBytes = fileBytes.get(manifest.plugins);
if (!pluginsBytes || pluginsBytes.byteLength > SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES) {
throw new SkinRegistryError("plugins.json is missing or exceeds 256 KiB.", "SKIN_RUNTIME_PLUGIN_SIZE");
}
try { runtimePlugins = parseSkinRuntimePluginJson(decodeUtf8(pluginsBytes, "plugins.json is not valid UTF-8.")); }
catch (error) { throw new SkinRegistryError("plugins.json is invalid: " + (error instanceof Error ? error.message : "unknown plugin error"), "SKIN_RUNTIME_PLUGIN_INVALID"); }
}
const runtimePluginPaths = runtimePlugins ? listSkinRuntimePluginFilePaths(runtimePlugins) : [];
const runtimePluginPathSet = new Set(runtimePluginPaths.map((packagePath) => packagePath.toLowerCase()));
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview]
.filter((packagePath): packagePath is string => Boolean(packagePath)).map((packagePath) => packagePath.toLowerCase());
if (runtimePluginPaths.some((packagePath) => manifestPathSet.includes(packagePath))) {
throw new SkinRegistryError("Plugin files cannot reuse skin manifest, CSS, content, component, or preview paths.", "SKIN_RUNTIME_PLUGIN_FILE_DUPLICATE");
}
for (const pluginPath of runtimePluginPaths) {
const data = fileBytes.get(pluginPath);
if (!data) throw new SkinRegistryError(`A declared plugin file is missing: ${pluginPath}`, "SKIN_RUNTIME_PLUGIN_FILE_MISSING");
const lowerPath = pluginPath.toLowerCase();
if (lowerPath.endsWith(".js")) {
if (data.byteLength > SKIN_RUNTIME_PLUGIN_SOURCE_LIMIT_BYTES) throw new SkinRegistryError("Plugin entry files must be smaller than 256 KiB.", "SKIN_RUNTIME_PLUGIN_SOURCE_SIZE");
decodeUtf8(data, "Plugin entry files must contain valid UTF-8.");
} else if (lowerPath.endsWith(".wasm")) {
if (data.byteLength > SKIN_RUNTIME_PLUGIN_SOURCE_LIMIT_BYTES) throw new SkinRegistryError("Wasm plugin entry files must be smaller than 256 KiB.", "SKIN_RUNTIME_PLUGIN_SOURCE_SIZE");
} else if (lowerPath.endsWith(".css")) {
if (data.byteLength > SKIN_RUNTIME_PLUGIN_STYLE_LIMIT_BYTES) throw new SkinRegistryError("Plugin style files must be smaller than 512 KiB.", "SKIN_RUNTIME_PLUGIN_STYLE_SIZE");
decodeUtf8(data, "Plugin style files must contain valid UTF-8.");
} else {
const mimeType = imageMime(pluginPath) ?? (lowerPath.endsWith(".woff2") ? "font/woff2" : null);
if (!mimeType) throw new SkinRegistryError(`Unsupported plugin asset: ${pluginPath}`, "SKIN_RUNTIME_PLUGIN_ASSET_INVALID");
if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Plugin images must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
if (mimeType.startsWith("font/") && data.byteLength > MAX_FONT_BYTES) throw new SkinRegistryError("Plugin fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
}
}
let previewBytes: Buffer | undefined;
let previewMime: string | undefined;
for (const [packagePath, data] of fileBytes) {
if (["manifest.json", manifest.entry, manifest.content, manifest.preview].includes(packagePath)) continue;
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview].includes(packagePath)
|| runtimePluginPathSet.has(packagePath.toLowerCase())) continue;
const mimeType = imageMime(packagePath) ?? (packagePath.toLowerCase().endsWith(".woff2") ? "font/woff2" : null);
if (!mimeType) throw new SkinRegistryError(`Unsupported package file: ${packagePath}`, "SKIN_FILE_UNSUPPORTED");
if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
if (mimeType.startsWith("font/") && data.byteLength > MAX_FONT_BYTES) throw new SkinRegistryError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
}
const cssAssets = new Set([...fileBytes.keys()].filter((packagePath) =>
imageMime(packagePath) !== null || packagePath.toLowerCase().endsWith(".woff2")));
validateSkinCss(cssSource, manifest.id, cssAssets, manifest.schemaVersion);
for (const plugin of runtimePlugins?.plugins ?? []) {
if (!plugin.style) continue;
const styleBytes = fileBytes.get(plugin.style);
if (!styleBytes) throw new SkinRegistryError(`A declared plugin style is missing: ${plugin.style}`, "SKIN_RUNTIME_PLUGIN_FILE_MISSING");
const pluginCssAssets = new Set([...cssAssets].filter((packagePath) =>
packagePath.startsWith("assets/") || packagePath.startsWith(`plugins/${plugin.id}/assets/`)));
validateSkinCss(
decodeUtf8(styleBytes, "Plugin style files must contain valid UTF-8."),
manifest.id,
pluginCssAssets,
manifest.schemaVersion,
plugin.id,
);
}
if (manifest.content) {
const content = fileBytes.get(manifest.content);
if (!content || content.byteLength > MAX_CONTENT_BYTES) throw new SkinRegistryError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE");
@@ -235,6 +305,22 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa
try { JSON.parse(content.toString("utf8")); }
catch { throw new SkinRegistryError("content.json is not valid JSON.", "SKIN_CONTENT_INVALID"); }
}
if (manifest.layout) {
const layout = fileBytes.get(manifest.layout);
if (!layout || layout.byteLength > 128 * 1024) throw new SkinRegistryError("layout.json is missing or exceeds 128 KiB.", "SKIN_LAYOUT_SIZE");
try { parseSkinLayoutJson(decodeUtf8(layout, "layout.json is not valid UTF-8.")); }
catch (error) { throw new SkinRegistryError("layout.json is invalid: " + (error instanceof Error ? error.message : "unknown layout error"), "SKIN_LAYOUT_INVALID"); }
}
if (manifest.components) {
const components = fileBytes.get(manifest.components);
if (!components || components.byteLength > MAX_CONTENT_BYTES) throw new SkinRegistryError("components.json is missing or exceeds 256 KiB.", "SKIN_PLUGIN_SIZE");
let document: SkinPluginDocument;
try { document = parseSkinPluginJson(decodeUtf8(components, "components.json is not valid UTF-8.")); }
catch (error) { throw new SkinRegistryError("components.json is invalid: " + (error instanceof Error ? error.message : "unknown plugin error"), "SKIN_PLUGIN_INVALID"); }
for (const assetPath of listSkinPluginAssetPaths(document)) {
if (!fileBytes.has(assetPath) || !imageMime(assetPath)) throw new SkinRegistryError(`Component image asset is missing or unsupported: ${assetPath}`, "SKIN_PLUGIN_ASSET_INVALID");
}
}
if (manifest.preview) {
previewBytes = fileBytes.get(manifest.preview);
previewMime = imageMime(manifest.preview) ?? undefined;
@@ -243,6 +329,22 @@ function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: Pa
return { manifest, ...(previewBytes ? { previewBytes, previewMime } : {}) };
}
function validateSkinCss(
source: string,
skinId: string,
assets: Set<string>,
schemaVersion: SkinCssSchemaVersion,
pluginId?: string,
): void {
try { compileSkinCss(source, skinId, assets, schemaVersion, pluginId); }
catch (error) {
const cssError = error instanceof SkinCssValidationError
? error
: new SkinCssValidationError(error instanceof Error ? error.message : "The CSS file is invalid.", "SKIN_CSS_INVALID");
throw new SkinRegistryError(cssError.message, cssError.code);
}
}
function inspectArchive(bytes: Buffer): SkinArchiveEntry[] {
if (bytes.byteLength < 22 || bytes.byteLength > MAX_ARCHIVE_BYTES) throw new SkinRegistryError("A skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE");
const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff);
@@ -366,25 +468,46 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
catch { throw new SkinRegistryError("manifest.json must contain valid JSON.", "SKIN_MANIFEST_INVALID"); }
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinRegistryError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
const value = raw as Record<string, unknown>;
const schemaVersion = value.schemaVersion;
if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
if (schemaVersion >= 2) {
const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]);
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); }
if (schemaVersion === 4) fields.add("plugins");
const unknown = Object.keys(value).find((key) => !fields.has(key));
if (unknown) throw new SkinRegistryError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID");
}
const read = (key: string, max: number): string => {
const item = value[key];
if (typeof item !== "string" || !item.trim() || item.length > max) throw new SkinRegistryError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
return item.trim();
};
const id = read("id", 80);
if (value.schemaVersion !== 1 || !isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
if (!isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
if (schemaVersion === 2 && (value.packageType !== "layout-skin" || !Array.isArray(value.permissions) || value.permissions.length !== 0)) {
throw new SkinRegistryError("Layout skin packages must declare the layout-skin type and no executable permissions.", "SKIN_PERMISSION_INVALID");
}
if (schemaVersion === 3 && value.packageType !== "open-skin") throw new SkinRegistryError("Version 3 skin packages must declare the open-skin type.", "SKIN_MANIFEST_INVALID");
if (schemaVersion === 4 && value.packageType !== "open-skin") throw new SkinRegistryError("Version 4 skin packages must declare the open-skin type.", "SKIN_MANIFEST_INVALID");
if (schemaVersion === 1 && (value.layout !== undefined || value.packageType !== undefined || value.permissions !== undefined || value.components !== undefined || value.plugins !== undefined)) {
throw new SkinRegistryError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION");
}
const version = read("version", 32);
const minAppVersion = read("minAppVersion", 32);
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(minAppVersion)) throw new SkinRegistryError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
const entry = read("entry", 120);
const readOptional = (key: string, max: number): string | undefined => value[key] == null ? undefined : read(key, max);
const layout = schemaVersion === 2 ? read("layout", 120) : schemaVersion >= 3 ? readOptional("layout", 120) : undefined;
const content = readOptional("content", 120);
const components = schemaVersion >= 3 && value.components != null ? read("components", 120) : undefined;
const plugins = schemaVersion === 4 ? read("plugins", 120) : undefined;
const preview = readOptional("preview", 120);
for (const candidate of [entry, content, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID");
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
if (new Set(["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase())).size !== 2 + Number(Boolean(content)) + Number(Boolean(preview))) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
for (const candidate of [entry, layout, content, components, plugins, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID");
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (plugins && !plugins.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The CSS entry, layout, content, plugin, or preview path is invalid.", "SKIN_MANIFEST_INVALID");
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
const description = readOptional("description", 400);
return { id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(content ? { content } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
return { schemaVersion, ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : schemaVersion >= 3 ? { packageType: "open-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(components ? { components } : {}), ...(plugins ? { plugins } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
}
function singleRootPrefix(paths: string[]): string {
+18 -1
View File
@@ -3,12 +3,15 @@ import { dirname } from "node:path";
import {
DEFAULT_TEAM_SPEAK_PORT,
parseTeamSpeakTargetParts,
parseTeamSpeakPort,
} from "./domain/teamspeak-target.js";
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "./domain/teamspeak-connection-target.js";
/** The only TeamSpeak state still read from the legacy JSON config. */
export interface AppConfig {
tsHost: string;
tsPort: number;
tsTarget?: string;
tsServerPassword: string;
}
@@ -34,8 +37,21 @@ export function migrateConfig(input: unknown): AppConfig {
: defaults.tsHost;
const rawPort = input.tsPort === undefined ? undefined : input.tsPort;
let target;
let tsTarget: string | undefined;
try {
target = parseTeamSpeakTargetParts(rawHost, toPortValue(rawPort), defaults.tsPort);
const connection = /^[0-9a-f:]+$/i.test(rawHost) && rawHost.indexOf(":") !== rawHost.lastIndexOf(":") && input.tsTarget === undefined
? { kind: "address" as const, target: parseTeamSpeakTargetParts(rawHost, toPortValue(rawPort), defaults.tsPort) }
: parseTeamSpeakConnectionTarget(typeof input.tsTarget === "string" ? input.tsTarget : rawHost);
if (connection.kind === "nickname") {
const port = toPortValue(rawPort);
if (input.tsTarget === undefined && port !== undefined && String(port).trim()) {
connection.port = parseTeamSpeakPort(port);
}
target = { host: connection.name, port: connection.port ?? defaults.tsPort };
tsTarget = formatTeamSpeakConnectionTarget(connection);
} else {
target = parseTeamSpeakTargetParts(rawHost, toPortValue(rawPort), defaults.tsPort);
}
} catch {
target = { host: defaults.tsHost, port: defaults.tsPort };
}
@@ -43,6 +59,7 @@ export function migrateConfig(input: unknown): AppConfig {
return {
tsHost: target.host,
tsPort: target.port,
...(tsTarget ? { tsTarget } : {}),
tsServerPassword: typeof input.tsServerPassword === "string" ? input.tsServerPassword : defaults.tsServerPassword,
};
}
+74
View File
@@ -0,0 +1,74 @@
import {
InvalidTeamSpeakTargetError,
formatTeamSpeakTarget,
parseTeamSpeakTarget,
parseTeamSpeakPort,
type TeamSpeakTarget,
} from "./teamspeak-target.js";
export const TEAM_SPEAK_NICKNAME_LOOKUP = "https://named.myteamspeak.com/lookup";
export type TeamSpeakConnectionTarget =
| { kind: "address"; target: TeamSpeakTarget }
| { kind: "nickname"; name: string; port?: number; lookupOnly?: true };
/** Single-label names follow the TeamSpeak nickname convention; localhost stays local. */
export function parseTeamSpeakConnectionTarget(value: string): TeamSpeakConnectionTarget {
const input = value.trim();
if (!input) throw new InvalidTeamSpeakTargetError("TeamSpeak server address is required");
if (/^https?:\/\//i.test(input)) {
let url: URL;
try { url = new URL(input); }
catch { throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak nickname lookup URL"); }
if (url.origin !== "https://named.myteamspeak.com" || url.pathname !== "/lookup" || url.username || url.password) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak nickname lookup URL");
}
const names = url.searchParams.getAll("name");
if (names.length !== 1) throw new InvalidTeamSpeakTargetError("One TeamSpeak nickname is required");
// URLSearchParams decodes the query once, including form-encoded spaces.
const target = nicknameTarget(names[0]!, url.hash ? parseTeamSpeakPort(url.hash.slice(1)) : undefined);
// Keep an explicit registry lookup distinct from a local service name
// when the target is saved or split into the address and port fields.
if (/^[a-z0-9_-]+$/i.test(target.name)) target.lookupOnly = true;
return target;
}
if (input.startsWith("[") || input.indexOf(":") !== input.lastIndexOf(":")) {
return { kind: "address", target: parseTeamSpeakTarget(input) };
}
const separator = Math.max(input.indexOf("#"), input.indexOf(":"));
const host = (separator >= 0 ? input.slice(0, separator) : input).trim();
const port = separator >= 0 ? parseTeamSpeakPort(input.slice(separator + 1)) : undefined;
if (host.toLowerCase() === "localhost" || /^[a-z0-9._-]+\.[a-z0-9._-]*$/i.test(host)) {
return { kind: "address", target: parseTeamSpeakTarget(input) };
}
if (/[\/\\?#@\[\]:]/.test(host)) throw new InvalidTeamSpeakTargetError();
return nicknameTarget(host, port);
}
export function formatTeamSpeakConnectionTarget(target: TeamSpeakConnectionTarget): string {
if (target.kind === "address") return formatTeamSpeakTarget(target.target);
// A lookup URL preserves names that could otherwise be mistaken for a host or port.
if (target.lookupOnly || /[.\/\\?#@\[\]:]/.test(target.name) || target.name.toLowerCase() === "localhost") {
const url = createTeamSpeakNicknameLookup(target.name);
if (target.port !== undefined) url.hash = String(target.port);
return url.href;
}
return target.port === undefined ? target.name : `${target.name}:${target.port}`;
}
export function createTeamSpeakNicknameLookup(name: string): URL {
const url = new URL(TEAM_SPEAK_NICKNAME_LOOKUP);
url.searchParams.set("name", name);
return url;
}
function nicknameTarget(nameValue: string, port?: number): Extract<TeamSpeakConnectionTarget, { kind: "nickname" }> {
const name = nameValue.trim();
if (!name || name.length > 255 || /[\u0000-\u001f\u007f]/.test(name)) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server nickname");
}
return { kind: "nickname", name, ...(port === undefined ? {} : { port }) };
}
+5 -1
View File
@@ -89,11 +89,15 @@ function createTarget(hostValue: string, portValue: string | number): TeamSpeakT
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
}
return { host, port: parseTeamSpeakPort(portValue) };
}
export function parseTeamSpeakPort(portValue: string | number): number {
const portText = String(portValue).trim();
if (!/^\d+$/.test(portText)) throw new InvalidTeamSpeakTargetError("TeamSpeak port must be a number");
const port = Number(portText);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new InvalidTeamSpeakTargetError("TeamSpeak port must be between 1 and 65535");
}
return { host, port };
return port;
}
+35 -4
View File
@@ -6,7 +6,7 @@ import type { AdminCredential } from "../security/admin-password.js";
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
export const DATABASE_SCHEMA_VERSION = 8;
export const DATABASE_SCHEMA_VERSION = 9;
export type AccessMode = "fixed" | "open";
export interface PersistedSettings {
@@ -19,6 +19,7 @@ export interface PersistedSettings {
accessMode: AccessMode;
tsHost: string;
tsPort: number;
tsTarget: string | null;
tsPasswordEncrypted: string | null;
detectedProtocol: TeamSpeakProtocol | null;
lastTestAt: string | null;
@@ -49,6 +50,7 @@ export interface SettingsUpdate {
accessMode: AccessMode;
tsHost: string;
tsPort: number;
tsTarget?: string | null;
tsPasswordEncrypted: string | null;
webRtcEnabled: boolean;
webRtcPublicHost?: string;
@@ -80,6 +82,7 @@ export interface ManagedInviteRecord {
tokenHash: string;
targetHost: string;
targetPort: number;
targetText?: string | null;
serverPasswordEncrypted: string | null;
channel: string;
expiresAt: string;
@@ -94,6 +97,7 @@ interface ManagedInviteRow extends Record<string, unknown> {
token_hash: string;
target_host: string;
target_port: number;
target_text: string | null;
server_password_encrypted: string | null;
channel: string;
expires_at: string;
@@ -113,6 +117,7 @@ interface SettingsRow extends Record<string, unknown> {
access_mode: string;
ts_host: string;
ts_port: number;
ts_target: string | null;
ts_password_encrypted: string | null;
detected_protocol: string | null;
last_test_at: string | null;
@@ -210,6 +215,7 @@ export class WebSpeakDatabase {
accessMode: row.access_mode === "open" ? "open" : "fixed",
tsHost: row.ts_host,
tsPort: row.ts_port,
tsTarget: row.ts_target,
tsPasswordEncrypted: row.ts_password_encrypted,
detectedProtocol: row.detected_protocol === "ts3" || row.detected_protocol === "ts6" ? row.detected_protocol : null,
lastTestAt: row.last_test_at,
@@ -301,14 +307,15 @@ export class WebSpeakDatabase {
this.transaction(() => {
this.database.prepare(
`INSERT INTO managed_invites (
id, token_hash, target_host, target_port, server_password_encrypted,
id, token_hash, target_host, target_port, target_text, server_password_encrypted,
channel, expires_at, max_uses, use_count, created_at, revoked_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, NULL)`,
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, NULL)`,
).run(
record.id,
record.tokenHash,
record.targetHost,
record.targetPort,
record.targetText ?? null,
record.serverPasswordEncrypted,
record.channel,
record.expiresAt,
@@ -326,6 +333,18 @@ export class WebSpeakDatabase {
return rows.map(mapManagedInviteRow);
}
getManagedInvite(tokenHash: string, now = Date.now()): ManagedInviteRecord | null {
const nowIso = new Date(now).toISOString();
const row = this.database.prepare(
`SELECT * FROM managed_invites
WHERE token_hash = ?
AND revoked_at IS NULL
AND expires_at > ?
AND (max_uses = 0 OR use_count < max_uses)`,
).get(tokenHash, nowIso) as ManagedInviteRow | undefined;
return row ? mapManagedInviteRow(row) : null;
}
revokeManagedInvite(id: string): boolean {
const result = this.database.prepare(
"UPDATE managed_invites SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
@@ -597,13 +616,23 @@ export class WebSpeakDatabase {
`);
this.database.exec("PRAGMA user_version = 8");
});
version = 8;
}
if (version === 8) {
this.transaction(() => {
this.database.exec(`
ALTER TABLE settings ADD COLUMN ts_target TEXT;
ALTER TABLE managed_invites ADD COLUMN target_text TEXT;
`);
this.database.exec("PRAGMA user_version = 9");
});
}
}
private writeSettings(settings: SettingsUpdate, now: string): void {
this.database.prepare(
`UPDATE settings SET
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?,
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?, ts_target = ?,
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_public_host = ?, webrtc_ipv6_enabled = ?, webrtc_stun_server = ?, webrtc_udp_start = ?,
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
@@ -618,6 +647,7 @@ export class WebSpeakDatabase {
settings.accessMode,
settings.tsHost,
settings.tsPort,
settings.tsTarget ?? null,
settings.tsPasswordEncrypted,
settings.webRtcEnabled ? 1 : 0,
settings.webRtcPublicHost ?? "",
@@ -659,6 +689,7 @@ function mapManagedInviteRow(row: ManagedInviteRow): ManagedInviteRecord {
tokenHash: row.token_hash,
targetHost: row.target_host,
targetPort: row.target_port,
targetText: row.target_text,
serverPasswordEncrypted: row.server_password_encrypted,
channel: row.channel,
expiresAt: row.expires_at,
+69 -1
View File
@@ -1,6 +1,74 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isSafeOpenTargetForPrefill } from "./open-target-policy.js";
import {
isRestrictedAddress,
isSafeOpenTargetForPrefill,
resolveSafeOpenTarget,
TeamSpeakTargetResolutionError,
} from "./open-target-policy.js";
const resolved = (...addresses: string[]) => async () => addresses.map((address) => ({
address,
family: address.includes(":") ? 6 : 4,
}));
test("Mihomo fake-IP DNS answers remain connectable without allowing literal or mixed fake-IP targets", async () => {
const target = { host: "ts.twilightly.top", port: 9987 };
assert.equal(isRestrictedAddress("198.18.0.32"), true);
assert.deepEqual(await resolveSafeOpenTarget(target, { lookup: resolved("198.18.0.32"), resolveSrv: async () => [] }), {
host: "198.18.0.32",
port: 9987,
});
await assert.rejects(resolveSafeOpenTarget({ host: "198.18.0.32", port: 9987 }));
await assert.rejects(resolveSafeOpenTarget(target, { lookup: resolved("198.19.0.32"), resolveSrv: async () => [] }));
await assert.rejects(resolveSafeOpenTarget(target, { lookup: resolved("198.18.0.32", "192.168.1.10"), resolveSrv: async () => [] }));
await assert.rejects(resolveSafeOpenTarget(target, { lookup: resolved("198.18.0.32", "8.8.8.8"), resolveSrv: async () => [] }));
});
test("TeamSpeak SRV records resolve before the input hostname and pin the advertised endpoint", async () => {
const lookups: string[] = [];
const target = await resolveSafeOpenTarget({ host: "ts.twilightly.top", port: 9987 }, {
resolveSrv: async (service) => {
assert.equal(service, "_ts3._udp.ts.twilightly.top");
return [{ name: "routerstun.speedtest.twilightly.top.", port: 18967, priority: 0, weight: 5 }];
},
lookup: async (hostname) => {
lookups.push(hostname);
assert.equal(hostname, "routerstun.speedtest.twilightly.top");
return [{ address: "183.200.23.34", family: 4 }];
},
});
assert.deepEqual(target, { host: "183.200.23.34", port: 18967 });
assert.deepEqual(lookups, ["routerstun.speedtest.twilightly.top"]);
});
test("all TeamSpeak SRV destinations are checked and failed hostname resolution is classified", async () => {
await assert.rejects(resolveSafeOpenTarget({ host: "voice.example.com", port: 9987 }, {
resolveSrv: async () => [
{ name: "public.example.net", port: 18967, priority: 0, weight: 5 },
{ name: "private.example.net", port: 18967, priority: 0, weight: 5 },
],
lookup: async (hostname) => [{ address: hostname.startsWith("private") ? "10.0.0.8" : "8.8.8.8", family: 4 }],
}));
await assert.rejects(resolveSafeOpenTarget({ host: "missing.example.com", port: 9987 }, {
resolveSrv: async () => [],
lookup: async () => { throw Object.assign(new Error("no records"), { code: "ENOTFOUND" }); },
}), TeamSpeakTargetResolutionError);
});
test("open-mode hostname checks still pin public DNS results and block ordinary private answers", async () => {
assert.deepEqual(await resolveSafeOpenTarget({ host: "voice.example.com", port: 9987 }, {
lookup: resolved("8.8.8.8", "1.1.1.1"),
resolveSrv: async () => [],
}), { host: "8.8.8.8", port: 9987 });
await assert.rejects(resolveSafeOpenTarget({ host: "voice.example.com", port: 9987 }, {
lookup: resolved("8.8.8.8", "10.0.0.5"),
resolveSrv: async () => [],
}));
});
test("open-mode target prefill follows the same allow/deny result as the join policy", async () => {
assert.equal(await isSafeOpenTargetForPrefill({ host: "198.51.100.24", port: 9987 }, {
+73 -6
View File
@@ -1,6 +1,7 @@
import { isIP } from "node:net";
import { lookup } from "node:dns/promises";
import { lookup, resolveSrv } from "node:dns/promises";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
export class UnsafeTeamSpeakTargetError extends Error {
constructor(message = "This TeamSpeak target is not allowed in open mode") {
@@ -9,17 +10,77 @@ export class UnsafeTeamSpeakTargetError extends Error {
}
}
export class TeamSpeakTargetResolutionError extends Error {
constructor(message = "TeamSpeak target could not be resolved", options?: ErrorOptions) {
super(message, options);
this.name = "TeamSpeakTargetResolutionError";
}
}
/** Resolve and reject addresses that could turn a public gateway into an internal network probe. */
export async function assertSafeOpenTarget(target: TeamSpeakTarget): Promise<void> {
await resolveSafeOpenTarget(target);
}
export async function resolveSafeOpenTarget(target: TeamSpeakTarget): Promise<TeamSpeakTarget> {
type ResolvedAddress = { address: string; family: number };
type AddressLookup = (hostname: string) => Promise<ResolvedAddress[]>;
type TeamSpeakSrvRecord = { name: string; port: number; priority: number; weight: number };
type TeamSpeakSrvLookup = (service: string) => Promise<TeamSpeakSrvRecord[]>;
export async function resolveSafeOpenTarget(
target: TeamSpeakTarget,
options: { lookup?: AddressLookup; resolveSrv?: TeamSpeakSrvLookup } = {},
): Promise<TeamSpeakTarget> {
const addressLookup = options.lookup ?? ((hostname) => lookup(hostname, { all: true, verbatim: true }));
if (!isIP(target.host) && target.host.includes(".") && target.host !== "localhost") {
const srvLookup = options.resolveSrv ?? resolveSrv;
let srvRecords: TeamSpeakSrvRecord[] = [];
try {
srvRecords = await srvLookup(`_ts3._udp.${target.host}`);
} catch {
// No SRV record is normal; use the regular address lookup below.
}
if (srvRecords.length > 0) {
const srvTargets = srvRecords.map(({ name, port }) => {
const srvHost = name.replace(/\.$/, "");
if (!srvHost || !Number.isInteger(port) || port < 1 || port > 65535) {
throw new TeamSpeakTargetResolutionError("Invalid TeamSpeak SRV record");
}
try {
return parseTeamSpeakTarget(`${srvHost}:${port}`);
} catch (error: unknown) {
throw new TeamSpeakTargetResolutionError("Invalid TeamSpeak SRV record", { cause: error });
}
});
const safeTargets = await Promise.all(srvTargets.map((srvTarget) => resolveSafeAddress(srvTarget, addressLookup)));
// The SDK uses the first record returned by the system SRV resolver;
// keep that ordering while validating every advertised destination.
return safeTargets[0]!;
}
}
return resolveSafeAddress(target, addressLookup);
}
async function resolveSafeAddress(target: TeamSpeakTarget, addressLookup: AddressLookup): Promise<TeamSpeakTarget> {
const literalVersion = isIP(target.host);
const addresses = literalVersion
? [{ address: target.host, family: literalVersion }]
: await lookup(target.host, { all: true, verbatim: true });
if (!addresses.length || addresses.some(({ address }) => isRestrictedAddress(address))) {
let addresses: ResolvedAddress[];
try {
addresses = literalVersion
? [{ address: target.host, family: literalVersion }]
: await addressLookup(target.host);
} catch (error: unknown) {
throw new TeamSpeakTargetResolutionError(undefined, { cause: error });
}
// Mihomo's default fake-IP pool is 198.18.0.0/16, allowing its TUN to
// route the eventual socket by hostname. Accept this only for DNS names
// whose complete answer set is synthetic; literal and mixed answers remain
// blocked, preserving the open-mode SSRF boundary.
const mihomoFakeIpResolution = !literalVersion
&& addresses.length > 0
&& addresses.every(({ address }) => isMihomoFakeIpv4(address));
if (!addresses.length || (!mihomoFakeIpResolution && addresses.some(({ address }) => isRestrictedAddress(address)))) {
throw new UnsafeTeamSpeakTargetError();
}
// Use the address that was actually validated so a second DNS lookup cannot
@@ -68,6 +129,12 @@ export function isRestrictedAddress(address: string): boolean {
return false;
}
function isMihomoFakeIpv4(address: string): boolean {
if (isIP(address) !== 4) return false;
const [first, second] = address.split(".").map(Number);
return first === 198 && second === 18;
}
function isRestrictedIpv4(address: string): boolean {
const parts = address.split(".").map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return true;
+64
View File
@@ -0,0 +1,64 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
applyChannelCapacityNotification,
applyChannelPasswordProtectionNotification,
parseChannelCapacities,
parseChannelPasswordProtections,
} from "./channel-capacity.js";
test("channel capacity rows keep finite limits and distinguish unlimited channels", () => {
const capacities = parseChannelCapacities([
{ cid: "1", channel_maxclients: "10", channel_flag_maxclients_unlimited: "0" },
{ cid: "2", channel_maxclients: "0", channel_flag_maxclients_unlimited: "1" },
{ cid: "3", channel_maxclients: "65536", channel_flag_maxclients_unlimited: "0" },
{ cid: "4", channel_maxclients: "12" },
{ cid: "18446744073709551616", channel_maxclients: "4", channel_flag_maxclients_unlimited: "0" },
]);
assert.deepEqual(capacities.get(1n), { maxClients: 10, maxClientsLimited: true });
assert.deepEqual(capacities.get(2n), { maxClients: 0, maxClientsLimited: false });
assert.equal(capacities.has(3n), false);
assert.equal(capacities.has(4n), false);
assert.equal(capacities.size, 2);
});
test("channel capacity notifications merge edits and remove deleted channels", () => {
const capacities = new Map([[1n, { maxClients: 10, maxClientsLimited: true }]]);
applyChannelCapacityNotification("notifychanneledited", { cid: "1", channel_maxclients: "16" }, capacities);
assert.deepEqual(capacities.get(1n), { maxClients: 16, maxClientsLimited: true });
applyChannelCapacityNotification("notifychanneledited", { cid: "1", channel_flag_maxclients_unlimited: "1" }, capacities);
assert.deepEqual(capacities.get(1n), { maxClients: 16, maxClientsLimited: false });
applyChannelCapacityNotification("notifychannelcreated", {
cid: "2", channel_maxclients: "8", channel_flag_maxclients_unlimited: "0",
}, capacities);
assert.deepEqual(capacities.get(2n), { maxClients: 8, maxClientsLimited: true });
applyChannelCapacityNotification("notifychanneldeleted", { cid: "2" }, capacities);
assert.equal(capacities.has(2n), false);
});
test("channel password protection is parsed as a public boolean and tracks channel edits", () => {
const protections = parseChannelPasswordProtections([
{ cid: "1", channel_flag_password: "1" },
{ cid: "2", channel_flag_password: "0" },
{ cid: "3", channel_flag_password: "unknown" },
{ cid: "18446744073709551616", channel_flag_password: "1" },
]);
assert.deepEqual([...protections], [[1n, true], [2n, false]]);
assert.deepEqual(
applyChannelPasswordProtectionNotification("notifychanneledited", { cid: "1", channel_flag_password: "0" }, protections),
{ channelId: 1n, passwordProtected: false },
);
assert.deepEqual(
applyChannelPasswordProtectionNotification("notifychannelcreated", { cid: "4", channel_flag_password: "1" }, protections),
{ channelId: 4n, passwordProtected: true },
);
assert.equal(applyChannelPasswordProtectionNotification("notifychanneldeleted", { cid: "4" }, protections), null);
assert.equal(protections.has(4n), false);
assert.equal(protections.has(3n), false, "unknown flag values are not interpreted as unlocked");
});
+105
View File
@@ -0,0 +1,105 @@
export interface ChannelCapacity {
maxClients: number;
maxClientsLimited: boolean;
}
export interface ChannelPasswordProtection {
passwordProtected: boolean;
}
const UINT64_MAX = 18_446_744_073_709_551_615n;
function parseChannelId(value: string | undefined): bigint | null {
if (!value || !/^\d{1,20}$/.test(value)) return null;
try {
const id = BigInt(value);
return id > 0n && id <= UINT64_MAX ? id : null;
} catch {
return null;
}
}
export function parseChannelCapacity(row: Record<string, string>): ChannelCapacity | null {
const maxClientsRaw = row.channel_maxclients;
const unlimitedRaw = row.channel_flag_maxclients_unlimited;
if (!maxClientsRaw || !/^\d{1,5}$/.test(maxClientsRaw) || (unlimitedRaw !== "0" && unlimitedRaw !== "1")) return null;
const maxClients = Number(maxClientsRaw);
if (!Number.isSafeInteger(maxClients) || maxClients > 65_535) return null;
return { maxClients, maxClientsLimited: unlimitedRaw === "0" };
}
export function parseChannelCapacities(rows: readonly Record<string, string>[]): Map<bigint, ChannelCapacity> {
const capacities = new Map<bigint, ChannelCapacity>();
for (const row of rows) {
const id = parseChannelId(row.cid);
const capacity = parseChannelCapacity(row);
if (id !== null && capacity) capacities.set(id, capacity);
}
return capacities;
}
/** The password flag reveals whether a password is required, never the password itself. */
export function parseChannelPasswordProtection(row: Record<string, string>): boolean | null {
if (row.channel_flag_password === "1") return true;
if (row.channel_flag_password === "0") return false;
return null;
}
export function parseChannelPasswordProtections(rows: readonly Record<string, string>[]): Map<bigint, boolean> {
const protections = new Map<bigint, boolean>();
for (const row of rows) {
const id = parseChannelId(row.cid);
const passwordProtected = parseChannelPasswordProtection(row);
if (id !== null && passwordProtected !== null) protections.set(id, passwordProtected);
}
return protections;
}
/** Keep the password-required flag current as channels are created or edited. */
export function applyChannelPasswordProtectionNotification(
name: string,
params: Record<string, string>,
protections: Map<bigint, boolean>,
): { channelId: bigint; passwordProtected: boolean } | null {
const id = parseChannelId(params.cid);
if (id === null) return null;
if (name === "notifychanneldeleted") {
protections.delete(id);
return null;
}
if (name !== "notifychannelcreated" && name !== "notifychanneledited") return null;
const passwordProtected = parseChannelPasswordProtection(params);
if (passwordProtected === null) return null;
protections.set(id, passwordProtected);
return { channelId: id, passwordProtected };
}
/** Keep capacity metadata in step with TeamSpeak's incremental channel events. */
export function applyChannelCapacityNotification(
name: string,
params: Record<string, string>,
capacities: Map<bigint, ChannelCapacity>,
): void {
const id = parseChannelId(params.cid);
if (id === null) return;
if (name === "notifychanneldeleted") {
capacities.delete(id);
return;
}
if (name !== "notifychannelcreated" && name !== "notifychanneledited") return;
const current = name === "notifychanneledited" ? capacities.get(id) : undefined;
const maxClientsRaw = params.channel_maxclients;
const unlimitedRaw = params.channel_flag_maxclients_unlimited;
const maxClients = maxClientsRaw !== undefined && /^\d{1,5}$/.test(maxClientsRaw) && Number(maxClientsRaw) <= 65_535
? Number(maxClientsRaw)
: current?.maxClients;
const unlimited = unlimitedRaw === "0" || unlimitedRaw === "1"
? unlimitedRaw === "1"
: current ? !current.maxClientsLimited : undefined;
if (maxClients === undefined || unlimited === undefined) return;
capacities.set(id, { maxClients, maxClientsLimited: !unlimited });
}
+4 -1
View File
@@ -5,7 +5,7 @@ import { mapChannelTree, normalizeDirectorySnapshot } from "./directory-view.js"
import { parseServerMessage } from "../shared/server-messages.js";
const directory = (): TSDirectorySnapshot => ({
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }, { id: 18446744073709551615n, parentID: 1n, order: 1n, name: "Room", description: "" }],
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }, { id: 18446744073709551615n, parentID: 1n, order: 1n, name: "Room", description: "", maxClients: 10, maxClientsLimited: true, passwordProtected: true }],
clients: [{ id: 2, channelID: 1n, nickname: "Member", uid: "uid-2", type: 0, serverGroups: [], away: true, inputMuted: true }],
});
@@ -36,5 +36,8 @@ test("directory presentation survives JSON transport with large IDs, member flag
assert.equal(decoded.channels[0]?.members?.[0]?.inputMuted, true);
assert.equal(decoded.channels[0]?.members?.[0]?.away, true);
assert.equal(decoded.channels[0]?.members?.[0]?.avatar, "data:image/png;base64,test");
assert.equal(decoded.channels[1]?.maxClients, 10);
assert.equal(decoded.channels[1]?.maxClientsLimited, true);
assert.equal(decoded.channels[1]?.passwordProtected, true);
assert.deepEqual(decoded.channels[1]?.members, []);
});
+4
View File
@@ -8,6 +8,10 @@ export function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new
order: String(channel.order),
name: channel.name || "未命名频道",
description: channel.description || "",
...(typeof channel.maxClients === "number" && typeof channel.maxClientsLimited === "boolean"
? { maxClients: channel.maxClients, maxClientsLimited: channel.maxClientsLimited }
: {}),
...(typeof channel.passwordProtected === "boolean" ? { passwordProtected: channel.passwordProtected } : {}),
members: snapshot.clients
.filter((client) => client.channelID === channel.id)
.map((client) => {
+28 -17
View File
@@ -5,11 +5,13 @@ import { readFileSync } from "node:fs";
import path from "node:path";
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
import type { Logger } from "../logger.js";
import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-target.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
import { resolveTeamSpeakTarget, TeamSpeakAliasLookupError } from "./teamspeak-alias.js";
import { createAdminRouter } from "../admin/admin-router.js";
import type { AdminService } from "../admin/admin-service.js";
import { AdminSessionStore } from "../admin/admin-session.js";
import { isSafeOpenTargetForPrefill, resolveSafeOpenTarget } from "../security/open-target-policy.js";
import { isSafeOpenTargetForPrefill, resolveSafeOpenTarget, TeamSpeakTargetResolutionError } from "../security/open-target-policy.js";
import { identityFromString } from "@echosixhiya/teamspeak-client";
import { JoinRateLimiter } from "./join-rate-limit.js";
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
@@ -95,7 +97,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
let targetPrefillBlocked = false;
if (publicConfig.accessMode === "open" && target.trim()) {
try {
targetPrefillBlocked = !await isSafeOpenTargetForPrefill(parseTeamSpeakTarget(target));
targetPrefillBlocked = !await isSafeOpenTargetForPrefill(await resolveTeamSpeakTarget(target));
} catch {
targetPrefillBlocked = true;
}
@@ -181,13 +183,14 @@ export function createWebServer(options: WebServerOptions): WebServer {
}
const policy = options.adminService.getConnectionPolicy();
const managedInvite = inviteToken ? options.adminService.consumeManagedInvite(inviteToken) : null;
const managedInvite = inviteToken ? options.adminService.getManagedInvite(inviteToken) : null;
if (inviteToken && !managedInvite) {
response.status(400).json({ ok: false, code: "INVITE_INVALID" });
return;
}
let target = managedInvite?.target ?? policy.defaultTarget;
let serverPassword = managedInvite?.serverPassword ?? policy.serverPassword;
let targetText = managedInvite?.target ?? policy.defaultTarget;
let target: TeamSpeakTarget;
let serverPassword = policy.serverPassword;
const channel = requestedChannel || managedInvite?.channel || "";
const requestedRelayId = typeof body.accelerationRelayId === "string" ? body.accelerationRelayId.trim().slice(0, 110) : "";
const accelerationRequested = body.accelerated === true || Boolean(requestedRelayId);
@@ -200,16 +203,11 @@ export function createWebServer(options: WebServerOptions): WebServer {
response.status(400).json({ ok: false, code: "ACCELERATION_UNAVAILABLE" });
return;
}
if (!managedInvite) {
try {
try {
if (!managedInvite) {
if (policy.accessMode === "open" && typeof body.target === "string" && body.target.trim()) {
target = parseTeamSpeakTarget(body.target);
const isDefault = teamSpeakTargetKey(target) === teamSpeakTargetKey(policy.defaultTarget);
// Open mode must protect the gateway even when a user submits the
// same address configured as the administrator's default target.
// The default target only controls which server is prefilled; it is
// not a trust boundary and must not bypass SSRF protection.
target = await resolveSafeOpenTarget(target);
targetText = formatTeamSpeakConnectionTarget(parseTeamSpeakConnectionTarget(body.target));
const isDefault = targetText === policy.defaultTarget;
if (!isDefault) serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
else if (typeof body.serverPassword === "string" && body.serverPassword.trim()) serverPassword = body.serverPassword.slice(0, 512);
} else if (policy.accessMode === "fixed" && typeof body.serverPassword === "string" && body.serverPassword.trim()) {
@@ -218,10 +216,23 @@ export function createWebServer(options: WebServerOptions): WebServer {
// required. The target itself is never taken from this request.
serverPassword = body.serverPassword.slice(0, 512);
}
} catch {
response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" });
}
target = await resolveTeamSpeakTarget(targetText);
// Open-mode defaults are user targets too; validate the resolved address
// and pass that exact IP to the voice connection to prevent DNS rebinding.
if (!managedInvite && policy.accessMode === "open") target = await resolveSafeOpenTarget(target);
} catch (error) {
response.status(400).json({ ok: false, code: error instanceof TeamSpeakAliasLookupError || error instanceof TeamSpeakTargetResolutionError ? "HOST_NOT_FOUND" : "TARGET_NOT_ALLOWED" });
return;
}
if (inviteToken) {
const consumedInvite = options.adminService.consumeManagedInvite(inviteToken);
if (!consumedInvite) {
response.status(400).json({ ok: false, code: "INVITE_INVALID" });
return;
}
serverPassword = consumedInvite.serverPassword;
}
const ticket = options.voiceBridgeOptions.joinTickets.create({
+18
View File
@@ -98,6 +98,24 @@ test("channel changes preserve large identifiers and publish only actual create,
assert.equal(f.events.length, 0);
});
test("live channel password changes update and publish the lock state without a full tree refresh", t => {
const f = fixture(t);
f.client.emit("directorySnapshot", snapshot(member(1)));
f.coordinator.syncSelf(); f.phase.published = true;
f.client.emit("channelPasswordProtectionChanged", { channelId: 2n, passwordProtected: true });
assert.equal(f.state.channelTree.find(item => item.id === "2")?.passwordProtected, true);
let published = f.messages.at(-1);
assert.equal(published?.type, "channelList");
if (published?.type === "channelList") assert.equal(published.channels.find(item => item.id === "2")?.passwordProtected, true);
f.client.emit("channelPasswordProtectionChanged", { channelId: 2n, passwordProtected: false });
assert.equal(f.state.channelTree.find(item => item.id === "2")?.passwordProtected, false);
published = f.messages.at(-1);
assert.equal(published?.type, "channelList");
if (published?.type === "channelList") assert.equal(published.channels.find(item => item.id === "2")?.passwordProtected, false);
});
test("reset rejects backoff events and close detaches only owned listeners including captured callbacks", t => {
const f = fixture(t);
f.client.emit("directorySnapshot", snapshot(member(1), member(2)));
+9
View File
@@ -23,6 +23,7 @@ interface SdkEvents {
clientMoved: { id: number; targetChannelID?: bigint };
clientUpdated: TSDirectoryClient;
directoryClientsSnapshot: TSDirectoryClient[];
channelPasswordProtectionChanged: { channelId: bigint; passwordProtected: boolean };
rawNotification: TSRawNotification;
voiceData: TSVoiceData;
textMessage: TSChatMessage;
@@ -135,6 +136,14 @@ export class SessionEventCoordinator {
this.refresh();
this.publishDirectory();
});
this.listenDirectory("channelPasswordProtectionChanged", change => {
const channelId = String(change.channelId);
if (!state.channelTree.some(channel => channel.id === channelId)) return;
state.channelTree = state.channelTree.map(channel => channel.id === channelId
? { ...channel, passwordProtected: change.passwordProtected }
: channel);
this.publishDirectory();
});
this.listen("rawNotification", options.onNotification);
this.listen("voiceData", options.onVoice);
this.listen("textMessage", message => {
@@ -0,0 +1,164 @@
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { createServer } from "node:net";
import os from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import test from "node:test";
import { AdminService, type AdminSettingsInput } from "../admin/admin-service.js";
import { migrateConfig } from "../config.js";
import type { Logger } from "../logger.js";
import { WebSpeakDatabase } from "../persistence/database.js";
import { JoinTicketStore } from "./join-ticket.js";
import { createWebServer } from "./server.js";
const noop = () => {};
const logger: Logger = { debug: noop, info: noop, warn: noop, error: noop, child: () => logger };
const settings = (target: string, accessMode: "open" | "fixed" = "open"): AdminSettingsInput => ({
target, accessMode, siteName: "WebSpeak", welcomeText: "", webRtcEnabled: false,
serverPassword: "stored-password", passwordAction: "replace",
});
test("settings, tests, invites, and join tickets resolve nicknames through the gateway", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-alias-"));
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const service = new AdminService(database, Buffer.alloc(32, 1), logger, path.join(directory, "missing-config.json"), async (target) => {
assert.deepEqual(target, { host: "8.8.8.8", port: 10000 });
return { ok: true, protocol: "ts3", latencyMs: 1, serverName: "Test", requiresPassword: false };
});
await service.initialize();
let lookupBody = "8.8.8.8:10000";
let lookups = 0;
const realFetch = globalThis.fetch;
context.mock.method(globalThis, "fetch", ((input, options) => {
if (new URL(String(input)).origin === "https://named.myteamspeak.com") {
lookups += 1;
return Promise.resolve(new Response(lookupBody));
}
return realFetch(input, options);
}) as typeof fetch);
const port = await availablePort();
const origin = `http://127.0.0.1:${port}`;
const joinTickets = new JoinTicketStore();
const server = createWebServer({ port, adminService: service, voiceBridgeOptions: { joinTickets }, logger });
context.after(async () => {
await server.stop();
database.close();
await rm(directory, { recursive: true, force: true });
});
await server.start();
const join = async (input: Record<string, unknown>) => {
const response = await realFetch(`${origin}/api/join-ticket`, {
method: "POST", headers: { origin, "content-type": "application/json" },
body: JSON.stringify({ nickname: "Tester", ...input }),
});
const body = await response.json() as { code?: string; ticket?: string };
return { status: response.status, code: body.code, payload: body.ticket ? joinTickets.consume(body.ticket) : null };
};
service.updateSettings(settings("team eco"));
assert.equal(database.getSettings().tsTarget, "team eco");
assert.equal(service.getPublicConfig().target, "team eco");
assert.equal(service.getAdminSettings().target, "team eco");
const publicConfig = await (await realFetch(`${origin}/api/public-config`)).json() as { target: string; targetPrefillBlocked: boolean };
assert.equal(publicConfig.target, "team eco");
assert.equal(publicConfig.targetPrefillBlocked, false);
const first = await join({ target: "https://named.myteamspeak.com/lookup?name=team%20eco" });
assert.equal(first.status, 201);
assert.deepEqual(first.payload?.target, { host: "8.8.8.8", port: 10000 });
assert.equal(first.payload?.serverPassword, "stored-password");
assert.equal((await join({ target: "another guild" })).payload?.serverPassword, "");
assert.equal((await join({ target: "another guild:9987" })).payload?.target.port, 9987);
assert.equal((await service.testConnection("another guild", "", true)).ok, true);
lookupBody = "1.1.1.1:10001";
assert.deepEqual((await join({ target: "team eco" })).payload?.target, { host: "1.1.1.1", port: 10001 });
lookupBody = "127.0.0.1:9987";
const blockedConfig = await (await realFetch(`${origin}/api/public-config`)).json() as { target: string; targetPrefillBlocked: boolean };
assert.equal(blockedConfig.target, "");
assert.equal(blockedConfig.targetPrefillBlocked, true);
assert.equal((await join({ target: "team eco" })).code, "TARGET_NOT_ALLOWED");
assert.equal((await join({})).code, "TARGET_NOT_ALLOWED");
service.updateSettings(settings("team eco", "fixed"));
const fixed = await join({ target: "untrusted guild" });
assert.equal(fixed.status, 201);
assert.equal(fixed.payload?.target.host, "127.0.0.1");
const invite = service.createManagedInvite({ channel: "Lobby", expiresInHours: 1, maxUses: 0 });
assert.equal(invite.invite.target, "team eco");
service.updateSettings(settings("different guild:9987"));
lookupBody = "1.1.1.1:10001";
const invited = await join({ invite: invite.token, target: "ignored target" });
assert.equal(invited.status, 201);
assert.deepEqual(invited.payload?.target, { host: "1.1.1.1", port: 10001 });
assert.equal(invited.payload?.channel, "Lobby");
assert.equal(invited.payload?.serverPassword, "stored-password");
assert.equal(service.getConnectionPolicy().defaultTarget, "different guild:9987");
service.updateSettings(settings("retry guild", "fixed"));
const retryInvite = service.createManagedInvite({ channel: "Lobby", expiresInHours: 1, maxUses: 1 });
lookupBody = "";
assert.equal((await join({ invite: retryInvite.token })).code, "HOST_NOT_FOUND");
assert.equal(service.listManagedInvites().find((item) => item.id === retryInvite.invite.id)?.useCount, 0);
lookupBody = "1.1.1.1:10001";
const retriedInvite = await join({ invite: retryInvite.token });
assert.equal(retriedInvite.status, 201);
assert.deepEqual(retriedInvite.payload?.target, { host: "1.1.1.1", port: 10001 });
assert.equal(service.listManagedInvites().find((item) => item.id === retryInvite.invite.id)?.useCount, 1);
lookupBody = "";
assert.equal((await join({ target: "missing guild" })).code, "HOST_NOT_FOUND");
await assert.rejects(service.testConnection("missing guild", "", true), { code: "HOST_NOT_FOUND" });
assert.ok(lookups >= 9);
assert.throws(() => service.updateSettings({ ...settings("guild"), relaySettingsAction: "replace", relayTarget: "team eco" }));
service.updateSettings(settings("8.8.8.8#9988"));
assert.equal(database.getSettings().tsTarget, null);
const direct = await join({ target: "8.8.8.8:9988" });
assert.deepEqual(direct.payload?.target, { host: "8.8.8.8", port: 9988 });
assert.equal(direct.payload?.serverPassword, "stored-password");
});
test("schema 8 settings and invites survive the nickname migration", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-alias-migration-"));
context.after(() => rm(directory, { recursive: true, force: true }));
const file = path.join(directory, "webspeak.db");
const database = new WebSpeakDatabase(file);
database.createManagedInvite({
id: "legacy", tokenHash: "legacy-token", targetHost: "voice.example.com", targetPort: 9988,
channel: "", expiresAt: new Date(Date.now() + 3600000).toISOString(), maxUses: 0, serverPasswordEncrypted: null,
});
database.close();
const legacy = new DatabaseSync(file);
legacy.exec("ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; PRAGMA user_version = 8;");
legacy.close();
const migrated = new WebSpeakDatabase(file);
try {
assert.equal(migrated.schemaVersion, 9);
assert.equal(migrated.getSettings().tsHost, "127.0.0.1");
assert.equal(migrated.getSettings().tsTarget, null);
const invite = migrated.consumeManagedInvite("legacy-token");
assert.equal(invite?.targetHost, "voice.example.com");
assert.equal(invite?.targetPort, 9988);
assert.equal(invite?.targetText, null);
} finally { migrated.close(); }
});
test("legacy config imports nicknames without silently replacing them with localhost", () => {
assert.deepEqual(migrateConfig({ tsHost: "team eco" }), { tsHost: "team eco", tsPort: 9987, tsTarget: "team eco", tsServerPassword: "" });
assert.equal(migrateConfig({ tsHost: "another guild", tsPort: 9988 }).tsTarget, "another guild:9988");
assert.equal(migrateConfig({ tsHost: "abc:123" }).tsTarget, "abc:123");
assert.equal(migrateConfig({ tsHost: "https://named.myteamspeak.com/lookup?name=team%20eco" }).tsTarget, "team eco");
assert.equal(migrateConfig(migrateConfig({ tsHost: "team eco" })).tsTarget, "team eco");
assert.equal(migrateConfig({ tsHost: "voice.example.com", tsPort: 9988 }).tsHost, "voice.example.com");
assert.equal(migrateConfig({ tsHost: "::1", tsPort: 9988 }).tsHost, "::1");
});
async function availablePort(): Promise<number> {
const socket = createServer();
await new Promise<void>((resolve, reject) => { socket.once("error", reject); socket.listen(0, "127.0.0.1", resolve); });
const address = socket.address();
assert.ok(address && typeof address !== "string");
await new Promise<void>((resolve, reject) => socket.close((error) => error ? reject(error) : resolve()));
return address.port;
}
+112
View File
@@ -0,0 +1,112 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
import { parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
import { resolveTeamSpeakTarget as resolveTarget, TeamSpeakAliasLookupError } from "./teamspeak-alias.js";
const publicTarget = "8.8.8.8:10000";
const lookup = (body = publicTarget, status = 200): typeof fetch => async () => new Response(body, { status });
const resolveTeamSpeakTarget = (value: string, fetchLookup: typeof fetch) => resolveTarget(value, fetchLookup, async () => undefined);
test("private service names retain local discovery while explicit lookup URLs use the registry", async () => {
const noFetch: typeof fetch = async () => { throw new Error("Local services must not use cloud lookup"); };
assert.deepEqual(await resolveTarget("teamspeak:9988", noFetch, async () => "172.18.0.6"), { host: "172.18.0.6", port: 9988 });
const explicit = "https://named.myteamspeak.com/lookup?name=teamspeak";
const stored = formatTeamSpeakConnectionTarget(parseTeamSpeakConnectionTarget(explicit));
assert.equal(stored, explicit);
assert.deepEqual(await resolveTarget(stored, lookup(), async () => {
throw new Error("An explicit lookup URL must not use local discovery");
}), { host: "8.8.8.8", port: 10000 });
});
test("unrelated plain nicknames are encoded as one query parameter", async () => {
for (const name of ["team eco", "another guild", "Solo", "\u4e2d\u6587\u670d\u52a1\u5668", "A+B & 50%", "literal%20name"]) {
const fetchLookup: typeof fetch = async (input, options) => {
const url = new URL(String(input));
assert.equal(url.origin, "https://named.myteamspeak.com");
assert.equal(url.pathname, "/lookup");
assert.deepEqual([...url.searchParams], [["name", name]]);
assert.equal(options?.redirect, "error");
assert.ok(options?.signal instanceof AbortSignal);
return new Response(publicTarget);
};
assert.deepEqual(await resolveTeamSpeakTarget(name, fetchLookup), { host: "8.8.8.8", port: 10000 });
}
});
test("lookup URLs decode name exactly once and preserve reserved characters", async () => {
const examples = [
["team%20eco", "team eco"],
["A%2BB+%26+50%25", "A+B & 50%"],
["literal%2520name", "literal%20name"],
["%E4%B8%AD%E6%96%87", "\u4e2d\u6587"],
["dotted.name%3A12%23x%2Ftest", "dotted.name:12#x/test"],
];
for (const [encoded, name] of examples) {
const value = `https://named.myteamspeak.com/lookup?name=${encoded}`;
const parsed = parseTeamSpeakConnectionTarget(value);
assert.deepEqual(parsed, { kind: "nickname", name });
assert.deepEqual(parseTeamSpeakConnectionTarget(formatTeamSpeakConnectionTarget(parsed)), parsed);
await resolveTeamSpeakTarget(value, async (input) => {
assert.equal(new URL(String(input)).searchParams.get("name"), name);
return new Response(publicTarget);
});
}
});
test("lookup ports apply unless the user explicitly overrides them", async () => {
assert.equal((await resolveTeamSpeakTarget("guild", lookup())).port, 10000);
assert.equal((await resolveTeamSpeakTarget("guild:9987", lookup())).port, 9987);
assert.equal((await resolveTeamSpeakTarget("guild#12345", lookup())).port, 12345);
assert.equal((await resolveTeamSpeakTarget("https://named.myteamspeak.com/lookup?name=guild#9988", lookup())).port, 9988);
assert.equal((await resolveTeamSpeakTarget("guild", lookup("8.8.8.8"))).port, 9987);
assert.deepEqual(await resolveTeamSpeakTarget("guild", lookup("\n[2606:4700:4700::1111]:9988\r\n8.8.8.8")), { host: "2606:4700:4700::1111", port: 9988 });
});
test("ordinary targets retain their parser and do not call nickname lookup", async () => {
const unexpectedFetch: typeof fetch = async () => { throw new Error("Lookup should not run"); };
for (const value of ["8.8.8.8", "voice.example.com:9988", "voice.example.com#9988", "localhost", "[2606:4700:4700::1111]:9987"]) {
assert.deepEqual(await resolveTeamSpeakTarget(value, unexpectedFetch), parseTeamSpeakTarget(value));
}
assert.throws(() => parseTeamSpeakTarget("team eco"));
});
test("invalid inputs and failed or malformed lookups reject the connection", async () => {
for (const value of ["", " ", "x:0", "x:65536", "x:abc", "x#123#456", "a\nb", "x".repeat(256),
"https://example.com/lookup?name=guild", "http://named.myteamspeak.com/lookup?name=guild",
"https://named.myteamspeak.com/wrong?name=guild", "https://named.myteamspeak.com/lookup?name=",
"https://named.myteamspeak.com/lookup?name=a&name=b", "https://named.myteamspeak.com/lookup"]) {
assert.throws(() => parseTeamSpeakConnectionTarget(value), value);
}
for (const body of ["", "\n", "not found", "another-nickname", "8.8.8.8:0", "https://example.com", "x".repeat(4097)]) {
await assert.rejects(resolveTeamSpeakTarget("guild", lookup(body)), TeamSpeakAliasLookupError);
}
await assert.rejects(resolveTeamSpeakTarget("guild", lookup("error", 503)), TeamSpeakAliasLookupError);
await assert.rejects(resolveTeamSpeakTarget("guild", async () => { throw new Error("Network failed"); }), TeamSpeakAliasLookupError);
await assert.rejects(resolveTeamSpeakTarget("guild", async () => { throw new DOMException("Timed out", "TimeoutError"); }), TeamSpeakAliasLookupError);
});
test("open-target protection runs on the lookup result", async () => {
for (const address of ["127.0.0.1", "10.0.0.1", "192.168.1.1", "[::1]", "[fd00::1]"]) {
const target = await resolveTeamSpeakTarget("guild", lookup(address));
await assert.rejects(resolveSafeOpenTarget(target));
}
assert.deepEqual(await resolveSafeOpenTarget(await resolveTeamSpeakTarget("guild", lookup())), { host: "8.8.8.8", port: 10000 });
});
test("TeamSpeak nickname results continue through SRV discovery before open-mode validation", async () => {
const target = await resolveTarget("guild", lookup("ts.twilightly.top"), async () => undefined);
const safeTarget = await resolveSafeOpenTarget(target, {
resolveSrv: async (service) => {
assert.equal(service, "_ts3._udp.ts.twilightly.top");
return [{ name: "routerstun.speedtest.twilightly.top.", port: 18967, priority: 0, weight: 5 }];
},
lookup: async (hostname) => {
assert.equal(hostname, "routerstun.speedtest.twilightly.top");
return [{ address: "183.200.23.34", family: 4 }];
},
});
assert.deepEqual(safeTarget, { host: "183.200.23.34", port: 18967 });
});
+51
View File
@@ -0,0 +1,51 @@
import {
createTeamSpeakNicknameLookup,
parseTeamSpeakConnectionTarget,
} from "../domain/teamspeak-connection-target.js";
import { DEFAULT_TEAM_SPEAK_PORT, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { resolveLocalTeamSpeakAlias } from "./teamspeak-resolver.js";
export class TeamSpeakAliasLookupError extends Error {
constructor(message = "TeamSpeak server nickname could not be resolved", options?: ErrorOptions) {
super(message, options);
this.name = "TeamSpeakAliasLookupError";
}
}
/** Only the official HTTPS lookup runs before the open-target address checks. */
export async function resolveTeamSpeakTarget(
value: string,
fetchLookup: typeof fetch = fetch,
localLookup = resolveLocalTeamSpeakAlias,
): Promise<TeamSpeakTarget> {
const target = parseTeamSpeakConnectionTarget(value);
if (target.kind === "address") return target.target;
// An explicit lookup URL always requests a registered nickname. Ordinary
// short hostnames retain the local service discovery introduced in v0.2.6.
if (!target.lookupOnly) {
const localAddress = await localLookup(target.name);
if (localAddress) return { host: localAddress, port: target.port ?? DEFAULT_TEAM_SPEAK_PORT };
}
try {
const response = await fetchLookup(createTeamSpeakNicknameLookup(target.name), {
headers: { accept: "text/plain" },
redirect: "error",
signal: AbortSignal.timeout(5000),
});
if (!response.ok) throw new TeamSpeakAliasLookupError();
const body = await response.text();
if (body.length > 4096) throw new TeamSpeakAliasLookupError("Invalid TeamSpeak nickname lookup response");
const address = body.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
if (!address) throw new TeamSpeakAliasLookupError("TeamSpeak server nickname was not found");
const resolved = parseTeamSpeakTarget(address);
if (!resolved.host.includes(".") && !resolved.host.includes(":") && resolved.host !== "localhost") {
throw new TeamSpeakAliasLookupError("Invalid TeamSpeak nickname lookup response");
}
return { host: resolved.host, port: target.port ?? resolved.port };
} catch (error) {
if (error instanceof TeamSpeakAliasLookupError) throw error;
throw new TeamSpeakAliasLookupError(undefined, { cause: error });
}
}
+22 -11
View File
@@ -51,18 +51,11 @@ export class WebSpeakTeamSpeakResolver implements AddrResolver {
return this.resolveBase(address, signal);
}
const localAddresses = await raceWithTimeout(
Promise.resolve().then(() => this.localLookup(host)),
this.localAliasLookupTimeoutMs,
signal,
)
.catch((error: unknown) => {
if (signal?.aborted) throw signal.reason ?? error;
return null;
});
const localAddress = localAddresses?.find(({ address: candidate }) => isPrivateNetworkAddress(candidate));
const localAddress = await resolveLocalTeamSpeakAlias(host, {
lookup: this.localLookup, timeoutMs: this.localAliasLookupTimeoutMs, signal,
});
if (localAddress) {
return [directAddress(localAddress.address, port)];
return [directAddress(localAddress, port)];
}
const baseResults = await this.resolveBaseWithTimeout(address, signal);
@@ -91,6 +84,24 @@ export class WebSpeakTeamSpeakResolver implements AddrResolver {
}
}
/** Keep Docker/service names local before attempting public nickname discovery. */
export async function resolveLocalTeamSpeakAlias(
host: string,
options: { lookup?: LocalLookup; timeoutMs?: number; signal?: AbortSignal } = {},
): Promise<string | undefined> {
if (!/^[a-z0-9_-]+$/i.test(host)) return undefined;
const localLookup = options.lookup ?? ((name: string) => lookup(name, { all: true, verbatim: true }));
const addresses = await raceWithTimeout(
Promise.resolve().then(() => localLookup(host)),
options.timeoutMs ?? LOCAL_ALIAS_LOOKUP_TIMEOUT_MS,
options.signal,
).catch((error: unknown) => {
if (options.signal?.aborted) throw options.signal.reason ?? error;
return null;
});
return addresses?.find(({ address }) => isPrivateNetworkAddress(address))?.address;
}
function directAddress(host: string, port: number): ResolvedAddr {
return {
addr: formatTeamSpeakTarget({ host, port }),
+112 -2
View File
@@ -17,6 +17,10 @@ const transfer = { size: 6n };
class SdkStub extends EventEmitter {
inputCommands: string[] = [];
fileTransfers: Array<{ channelId: bigint; path: string; password: string }> = [];
serverInfo: { name: string; iconId: number | null; hostBannerGfxUrl: string | null; welcomeMessage: string } | null = {
name: "兄弟们的teamspeak", iconId: 123456, hostBannerGfxUrl: null, welcomeMessage: "",
};
inputUpdate = async (_command: string): Promise<void> => {};
async execCommand(command: string) { this.inputCommands.push(command); await this.inputUpdate(command); }
initialized = 0;
@@ -24,8 +28,15 @@ class SdkStub extends EventEmitter {
metadata = async () => rows;
transfer = async () => transfer;
download = async (destination: Writable) => { destination.write(Buffer.from("GIF89a")); };
execCommandWithResponse() { return this.metadata(); }
async fileTransferInitDownload() { this.initialized++; return this.transfer(); }
execCommandWithResponse(command = "") {
this.inputCommands.push(command);
return this.metadata();
}
async fileTransferInitDownload(channelId: bigint, path: string, password: string) {
this.initialized++;
this.fileTransfers.push({ channelId, path, password });
return this.transfer();
}
async downloadFileData(_host: string, _transfer: unknown, destination: Writable) { this.downloaded++; await this.download(destination); }
}
@@ -53,6 +64,50 @@ test("stream commands wait for server acknowledgement and propagate refusals", a
await assert.rejects(f.client.sendProtocolCommand("removeclientfromstream id=test"), /missing required parameter/);
});
test("server info uses the name and icon id captured by the SDK handshake", async () => {
const f = fixture();
assert.deepEqual(await f.client.getServerInfo(), { name: "兄弟们的teamspeak", iconId: 123456 });
assert.deepEqual(f.sdk.inputCommands, [], "server identity does not issue a ServerQuery-only command over the client session");
f.sdk.serverInfo = { name: "No icon", iconId: null, hostBannerGfxUrl: null, welcomeMessage: "" };
assert.deepEqual(await f.client.getServerInfo(), { name: "No icon", iconId: null });
});
test("server presentation reads bounded public banner and welcome fields", async () => {
const f = fixture();
f.sdk.serverInfo = {
name: "兄弟们的teamspeak",
iconId: 123456,
hostBannerGfxUrl: "https://assets.example.invalid/teamspeak/banner.png",
welcomeMessage: "欢迎来到服务器!\n请遵守频道规则。",
};
assert.deepEqual(await f.client.getServerPresentation(), {
bannerUrl: "https://assets.example.invalid/teamspeak/banner.png",
welcomeMessage: "欢迎来到服务器!\n请遵守频道规则。",
});
assert.deepEqual(f.sdk.inputCommands, [], "server presentation comes from the connection handshake without extra permissions");
f.sdk.serverInfo = {
name: "兄弟们的teamspeak",
iconId: null,
hostBannerGfxUrl: "javascript:alert(1)",
welcomeMessage: "x".repeat(5_000),
};
const sanitized = await f.client.getServerPresentation();
assert.equal(sanitized.bannerUrl, null);
assert.equal(sanitized.welcomeMessage.length, 4_096);
});
test("server icons use the TeamSpeak file transfer path and enforce the download limit", async () => {
const f = fixture();
assert.equal((await f.client.getServerIcon(123456))?.toString(), "GIF89a");
assert.deepEqual(f.sdk.fileTransfers, [{ channelId: 0n, path: "/icon_123456", password: "" }]);
assert.equal(f.sdk.downloaded, 1);
f.sdk.transfer = async () => ({ size: 128n * 1024n + 1n });
assert.equal(await f.client.getServerIcon(123456), null);
assert.equal(f.sdk.downloaded, 1);
});
test("stream cleanup flood retries back off and stop after two retries", async t => {
const f = fixture();
t.mock.timers.enable({ apis: ["setTimeout"] });
@@ -258,6 +313,61 @@ test("a current avatar download preserves its bytes and rejects a mismatched ide
assert.equal(f.sdk.downloaded, 1);
});
test("public channel metadata survives directory snapshots and follows channel edits", () => {
const f = fixture();
const snapshots: Array<{ channels: Array<{ id: bigint; maxClients?: number; maxClientsLimited?: boolean; passwordProtected?: boolean }>; clients: unknown[] }> = [];
f.client.on("directorySnapshot", snapshot => snapshots.push(snapshot));
f.sdk.emit("rawNotification", {
name: "notifychannelcreated",
params: { cid: "1", channel_maxclients: "10", channel_flag_maxclients_unlimited: "0", channel_flag_password: "1" },
});
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, 10);
assert.equal(snapshots.at(-1)?.channels[0]?.maxClientsLimited, true);
assert.equal(snapshots.at(-1)?.channels[0]?.passwordProtected, true);
f.sdk.emit("rawNotification", { name: "notifychanneledited", params: { cid: "1", channel_maxclients: "12" } });
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, 12);
assert.equal(snapshots.at(-1)?.channels[0]?.maxClientsLimited, true);
assert.equal(snapshots.at(-1)?.channels[0]?.passwordProtected, true, "partial edits retain the previously reported password flag");
f.sdk.emit("rawNotification", { name: "notifychanneledited", params: { cid: "1", channel_flag_password: "0" } });
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.passwordProtected, false);
f.sdk.emit("rawNotification", { name: "notifychanneldeleted", params: { cid: "1" } });
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, undefined);
assert.equal(snapshots.at(-1)?.channels[0]?.passwordProtected, undefined);
});
test("TeamSpeak SDK password flags pass through to the directory snapshot", () => {
const f = fixture();
let snapshot: { channels: Array<{ id: bigint; passwordProtected?: boolean }>; clients: unknown[] } | undefined;
f.client.on("directorySnapshot", value => { snapshot = value; });
f.sdk.emit("directorySnapshot", {
channels: [{ id: 2n, parentID: 0n, order: 0n, name: "msicbot", description: "", passwordProtected: true }],
clients: [],
});
assert.equal(snapshot?.channels[0]?.passwordProtected, true);
});
test("a retired SDK client's disconnect cannot invalidate a current avatar request", async () => {
const f = fixture();
const replacement = new SdkStub();
+137 -3
View File
@@ -20,6 +20,14 @@ import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKick
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { createAccelerationRelayClient, type AccelerationRelayClient, type AccelerationRelayOptions } from "./acceleration-relay.js";
import {
applyChannelCapacityNotification,
applyChannelPasswordProtectionNotification,
parseChannelCapacities,
parseChannelPasswordProtections,
type ChannelCapacity,
type ChannelPasswordProtection,
} from "./channel-capacity.js";
export interface TSClientOptions {
target: TeamSpeakTarget;
@@ -43,12 +51,26 @@ export interface TSClientAvatar {
data: Buffer;
}
export interface TSClientServerInfo {
name: string;
iconId: number | null;
}
export interface TSClientServerPresentation {
bannerUrl: string | null;
welcomeMessage: string;
}
// Keep enough room for avatars produced by the native client. The previous
// 120 KiB limit rejected the 134 KiB PNG used by the Shanghai test account,
// so every avatar silently fell back to its initial letter.
const MAX_CLIENT_AVATAR_BYTES = 256 * 1024;
const MAX_SERVER_ICON_BYTES = 128 * 1024;
const MAX_SERVER_BANNER_URL_LENGTH = 2_048;
const MAX_SERVER_WELCOME_MESSAGE_LENGTH = 4_096;
export type TSDirectorySnapshot = DirectorySnapshot;
export type TSDirectoryChannel = DirectorySnapshot["channels"][number] & Partial<ChannelCapacity> & Partial<ChannelPasswordProtection>;
export type TSDirectorySnapshot = Omit<DirectorySnapshot, "channels"> & { channels: TSDirectoryChannel[] };
export type TSDirectoryClient = DirectoryClientInfo;
export type TSRawNotification = RawNotification;
@@ -92,6 +114,8 @@ export class TSClient extends EventEmitter {
private inputStateQueue: Promise<void> = Promise.resolve();
private preferredChannelId = 0n;
private accelerationClient: AccelerationRelayClient | null = null;
private readonly channelCapacities = new Map<bigint, ChannelCapacity>();
private readonly channelPasswordProtection = new Map<bigint, boolean>();
// Reason id of the most recent self leave, kept so the SDK `kicked` event can
// tell a plain kick (4) from a kick with ban (5). The SDK only forwards the
// reason message to its `kicked` handler, not the reason id.
@@ -109,6 +133,8 @@ export class TSClient extends EventEmitter {
this.syncedInputMuted = null;
this.inputStateQueue = Promise.resolve();
this.selfLeaveReasonId = null;
this.channelCapacities.clear();
this.channelPasswordProtection.clear();
if (!this.adapter || !this.client) {
let transportTarget = this.options.target;
if (this.options.acceleration && !this.accelerationClient) {
@@ -163,7 +189,25 @@ export class TSClient extends EventEmitter {
tsListChannels(client),
tsListClients(client),
]);
this.emit("directorySnapshot", { channels, clients });
try {
// The high-level SDK directory type intentionally omits channel limit
// metadata. Its raw client-protocol rows still include the public
// maximum-client properties, so retain those without another SDK API.
// TeamSpeak only includes channel flag fields (including the public
// password-required bit) when the client asks for flags explicitly.
const rows = await client.execCommandWithResponse("channellist -flags", 5_000);
const capacities = parseChannelCapacities(rows);
for (const [id, capacity] of capacities) this.channelCapacities.set(id, capacity);
for (const [id, passwordProtected] of parseChannelPasswordProtections(rows)) {
this.channelPasswordProtection.set(id, passwordProtected);
}
} catch (error: unknown) {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not read TeamSpeak channel limits");
}
this.emit("directorySnapshot", {
channels: this.applyChannelMetadata(channels),
clients,
});
} catch (error: unknown) {
this.logger.warn({
failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE",
@@ -257,6 +301,59 @@ export class TSClient extends EventEmitter {
return { cacheKey, data };
}
/** Read the public virtual-server name and icon marker from the active session. */
async getServerInfo(): Promise<TSClientServerInfo> {
const client = this.client;
if (!client || !this.connected) throw new Error("TeamSpeak session is not ready");
const generation = this.connectionGeneration;
if (this.client !== client || !this.connected || this.connectionGeneration !== generation) {
throw new Error("TeamSpeak session changed while reading server information");
}
const info = client.serverInfo;
return info ? { name: info.name, iconId: info.iconId } : { name: "", iconId: null };
}
/** Read only the public banner and welcome message from the active virtual server. */
async getServerPresentation(): Promise<TSClientServerPresentation> {
const client = this.client;
if (!client || !this.connected) throw new Error("TeamSpeak session is not ready");
const generation = this.connectionGeneration;
const isCurrent = () => this.client === client && this.connected && this.connectionGeneration === generation;
const empty: TSClientServerPresentation = { bannerUrl: null, welcomeMessage: "" };
const info = client.serverInfo;
if (!isCurrent() || !info) return empty;
return {
bannerUrl: normalizeTeamSpeakBannerUrl(info.hostBannerGfxUrl),
welcomeMessage: normalizeTeamSpeakWelcomeMessage(info.welcomeMessage),
};
}
/** Download the public virtual-server icon using TeamSpeak's normal file-transfer port. */
async getServerIcon(iconId: number): Promise<Buffer | null> {
const client = this.client;
if (!client || !this.connected) throw new Error("TeamSpeak session is not ready");
if (!Number.isSafeInteger(iconId) || iconId === 0) return null;
const generation = this.connectionGeneration;
const isCurrent = () => this.client === client && this.connected && this.connectionGeneration === generation;
const transfer = await client.fileTransferInitDownload(0n, `/icon_${iconId}`, "");
if (!isCurrent()) return null;
const size = Number(transfer.size);
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_SERVER_ICON_BYTES) return null;
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer | string, _encoding, callback) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
callback();
},
});
await client.downloadFileData(this.options.target.host, transfer, destination);
if (!isCurrent()) return null;
const data = Buffer.concat(chunks);
if (data.length === 0 || data.length > MAX_SERVER_ICON_BYTES) return null;
return data;
}
private attachClientListeners(client: TS3FullClient): void {
client.on("voiceData", (data: VoiceData) => {
if (this.client !== client) return;
@@ -273,13 +370,20 @@ export class TSClient extends EventEmitter {
client.on("directorySnapshot", (snapshot) => {
if (this.client !== client) return;
this.emit("directorySnapshot", {
channels: snapshot.channels.slice(),
channels: this.applyChannelMetadata(snapshot.channels),
clients: snapshot.clients.slice(),
});
});
client.on("rawNotification", (notification: RawNotification) => {
if (this.client !== client) return;
applyChannelCapacityNotification(notification.name, notification.params, this.channelCapacities);
const protectionChange = applyChannelPasswordProtectionNotification(
notification.name,
notification.params,
this.channelPasswordProtection,
);
if (protectionChange) this.emit("channelPasswordProtectionChanged", protectionChange);
this.emit("rawNotification", {
name: notification.name,
params: { ...notification.params },
@@ -310,6 +414,8 @@ export class TSClient extends EventEmitter {
}
this.connected = false;
this.clientId = 0;
this.channelCapacities.clear();
this.channelPasswordProtection.clear();
this.emit("disconnected", err);
});
@@ -505,6 +611,34 @@ export class TSClient extends EventEmitter {
this.clientId = 0;
}
}
private applyChannelMetadata(channels: readonly TSDirectoryChannel[]): TSDirectoryChannel[] {
return channels.map((channel) => ({
...channel,
...this.channelCapacities.get(channel.id),
...(this.channelPasswordProtection.has(channel.id)
? { passwordProtected: this.channelPasswordProtection.get(channel.id)! }
: {}),
}));
}
}
function normalizeTeamSpeakBannerUrl(value: unknown): string | null {
if (typeof value !== "string") return null;
const candidate = value.trim();
if (!candidate || candidate.length > MAX_SERVER_BANNER_URL_LENGTH) return null;
try {
const url = new URL(candidate);
if ((url.protocol !== "https:" && url.protocol !== "http:") || url.username || url.password) return null;
return url.toString();
} catch {
return null;
}
}
function normalizeTeamSpeakWelcomeMessage(value: unknown): string {
if (typeof value !== "string") return "";
return value.replace(/\0/g, "").replace(/\r\n?/g, "\n").slice(0, MAX_SERVER_WELCOME_MESSAGE_LENGTH).trim();
}
function escapeTeamSpeakValue(value: string): string {
+47 -2
View File
@@ -20,11 +20,21 @@ class TeamSpeakStub extends EventEmitter {
sent: Buffer[] = [];
directory: TSDirectorySnapshot = { channels: [], clients: [] };
avatarRequest: (id: number, uid: string) => Promise<TSClientAvatar | null> = async () => null;
async connect() { this.disconnected = false; this.emit("directorySnapshot", this.directory); }
emitDirectorySnapshotOnConnect = true;
connectCalls = 0;
serverInfoCalls = 0;
serverPresentationCalls = 0;
async connect() { this.connectCalls++; this.disconnected = false; if (this.emitDirectorySnapshotOnConnect) this.emit("directorySnapshot", this.directory); }
async disconnect() { this.disconnected = true; }
getClientId() { return 1; }
getChannelId() { return 1n; }
isConnected() { return !this.disconnected; }
async getServerInfo() { this.serverInfoCalls++; return { name: "兄弟们的teamspeak", iconId: null }; }
async getServerPresentation() {
this.serverPresentationCalls++;
return { bannerUrl: "https://assets.example.invalid/teamspeak/banner.png", welcomeMessage: "欢迎来到服务器!\n请遵守频道规则。" };
}
async getServerIcon() { return null; }
async sendProtocolCommand() {}
async setAccompanimentActive() {}
sendVoice(data: Buffer) { this.sent.push(data); this.emit("sent", data); }
@@ -36,6 +46,7 @@ async function fixture(t: TestContext, overrides: {
createTeamSpeakClient?: () => TSClient;
createEncoder?: () => Pick<OpusEncoder, "encode" | "dispose">;
configureSdk?: (sdk: TeamSpeakStub) => void;
waitForFirstMessage?: boolean;
} = {}) {
const sdk = new TeamSpeakStub();
overrides.configureSdk?.(sdk);
@@ -65,7 +76,7 @@ async function fixture(t: TestContext, overrides: {
await bridge.shutdown();
await new Promise<void>(resolve => server.close(() => resolve()));
});
await first;
if (overrides.waitForFirstMessage !== false) await first;
const entries = (bridge as unknown as { entries: Map<string, {
id: string; ws: WebSocket; audio: AudioFlowStats; webrtc: WebRtcAudioSession | null;
isAlive: boolean; avatarCache: Map<string, string | null>;
@@ -82,6 +93,40 @@ test("a TeamSpeak constructor failure releases the admitted gateway slot", { tim
assert.equal(f.bridge.getActiveCount(), 0);
});
test("server identity lookup waits until the directory sync publishes the connected state", { timeout: 5_000 }, async t => {
const f = await fixture(t, { waitForFirstMessage: false, configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; } });
while (!f.sdk.connectCalls) await nextTurn();
await nextTurn();
assert.equal(f.sdk.serverInfoCalls, 0);
const serverInfo = new Promise<Record<string, unknown>>(resolve => {
f.socket.on("message", (data, binary) => {
if (binary) return;
const message = JSON.parse(data.toString()) as Record<string, unknown>;
if (message.type === "serverInfo" && message.bannerUrl === null) resolve(message);
});
});
const serverPresentation = new Promise<Record<string, unknown>>(resolve => {
f.socket.on("message", (data, binary) => {
if (binary) return;
const message = JSON.parse(data.toString()) as Record<string, unknown>;
if (message.type === "serverInfo" && message.bannerUrl === "https://assets.example.invalid/teamspeak/banner.png") resolve(message);
});
});
f.sdk.emit("directorySnapshot", f.sdk.directory);
assert.deepEqual(await serverInfo, { type: "serverInfo", name: "兄弟们的teamspeak", icon: null, bannerUrl: null, welcomeMessage: "" });
assert.deepEqual(await serverPresentation, {
type: "serverInfo", name: "兄弟们的teamspeak", icon: null,
bannerUrl: "https://assets.example.invalid/teamspeak/banner.png", welcomeMessage: "欢迎来到服务器!\n请遵守频道规则。",
});
const publishedTypes = f.messages.filter(message => !message.binary).map(message => (JSON.parse(message.data.toString()) as { type: string }).type);
assert.ok(publishedTypes.indexOf("connected") >= 0);
assert.ok(publishedTypes.indexOf("serverInfo") > publishedTypes.indexOf("connected"));
assert.equal(f.sdk.serverInfoCalls, 1);
assert.equal(f.sdk.serverPresentationCalls, 1);
assert.ok(f.bridge.getActiveCount() > 0);
});
test("a codec disposal failure cannot abandon TeamSpeak or the browser socket", { timeout: 5_000 }, async t => {
const encoder = new OpusEncoder(48000, 1);
t.mock.method(encoder, "dispose", () => { throw new Error("Codec already disposed"); });
+30
View File
@@ -26,6 +26,7 @@ import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioSessionOpt
import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./acceleration-relay.js";
import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareIceServer } from "./screen-share.js";
import { OpusEncoder } from "./opus-codec.js";
import { avatarDataUrl } from "./directory-view.js";
const HEARTBEAT_INTERVAL_MS = 30_000;
function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>): string | undefined {
@@ -242,6 +243,7 @@ export class VoiceBridge {
}
let initialStateSent = false;
let serverInfoGeneration = 0;
let hasConnectedOnce = false;
let reconnectStartedAt = 0;
let reconnectAttempt = 0;
@@ -290,6 +292,7 @@ export class VoiceBridge {
sendJson({ type: "channelList", channels: entry!.channelTree });
if (wasReconnecting) sendJson({ type: "reconnected" });
events.scheduleAvatars();
void publishServerInfo();
};
const resetDirectoryForReconnect = () => {
@@ -299,6 +302,33 @@ export class VoiceBridge {
initialStateSent = false;
};
const publishServerInfo = async (): Promise<void> => {
const generation = ++serverInfoGeneration;
const isCurrent = () => generation === serverInfoGeneration
&& this.entries.get(entryId) === entry && session.state === "connected";
try {
const info = await tsClient.getServerInfo();
if (!isCurrent()) return;
const name = info.name.trim().slice(0, 256);
const publicInfo = { name, icon: null as string | null, bannerUrl: null as string | null, welcomeMessage: "" };
sendJson({ type: "serverInfo", ...publicInfo });
const [presentation, icon] = await Promise.all([
tsClient.getServerPresentation().catch((error: unknown) => {
if (isCurrent()) this.logger.debug({ entryId, err: error instanceof Error ? error.message : String(error) }, "TeamSpeak server presentation unavailable");
return { bannerUrl: null, welcomeMessage: "" };
}),
info.iconId ? tsClient.getServerIcon(info.iconId).catch(() => null) : Promise.resolve(null),
]);
if (!isCurrent()) return;
publicInfo.bannerUrl = presentation.bannerUrl;
publicInfo.welcomeMessage = presentation.welcomeMessage;
publicInfo.icon = icon ? avatarDataUrl(icon) : null;
sendJson({ type: "serverInfo", ...publicInfo });
} catch (error: unknown) {
if (isCurrent()) this.logger.debug({ entryId, err: error instanceof Error ? error.message : String(error) }, "TeamSpeak server icon unavailable");
}
};
const failReconnect = (normalized: ReturnType<typeof normalizeTeamSpeakError>) => {
if (entry!.reconnectTimer) {
clearTimeout(entry!.reconnectTimer);
+11 -1
View File
@@ -9,10 +9,14 @@ const stream = {
const event = { id: "event-1", kind: "joined", message: "Member joined", timestamp: 1_000 };
const samples: Record<ServerMessage["type"], ServerMessage> = {
connected: { type: "connected", tsClientId: 1, members: [{ id: 1, nickname: "Owner" }], serverEventLog: [event] },
serverInfo: {
type: "serverInfo", name: "兄弟们的teamspeak", icon: "data:image/png;base64,iVBORw0KGgo=",
bannerUrl: "https://assets.example.invalid/teamspeak/banner.png", welcomeMessage: "欢迎来到服务器!\n请遵守频道规则。",
},
memberEnter: { type: "memberEnter", id: 2, nickname: "Visitor", uid: "uid-2", isSelf: false },
memberLeave: { type: "memberLeave", id: 2 },
memberAvatar: { type: "memberAvatar", id: 2, avatar: "data:image/png;base64,test" },
channelList: { type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", members: [{ id: 1, nickname: "Owner" }] }] },
channelList: { type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", maxClients: 10, maxClientsLimited: true, passwordProtected: true, members: [{ id: 1, nickname: "Owner" }] }] },
chatMessage: { type: "chatMessage", scope: "channel", targetId: "1", invokerId: 2, message: "hello" },
pokeReceived: { type: "pokeReceived", invokerId: 2, message: "poke" },
serverEvent: { type: "serverEvent", event },
@@ -60,7 +64,13 @@ test("malformed nested directory and event data is rejected before client state
{ type: "connected", tsClientId: 1, members: [null] },
{ type: "connected", tsClientId: 1, members: [{ id: "1", nickname: "bad id" }] },
{ type: "connected", tsClientId: 1, serverEventLog: [{ id: "incomplete" }] },
{ type: "serverInfo", name: "TeamSpeak", icon: "https://example.com/icon.png" },
{ type: "serverInfo", name: "TeamSpeak", bannerUrl: "javascript:alert(1)" },
{ type: "serverInfo", name: "TeamSpeak", welcomeMessage: "x".repeat(4_097) },
{ type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", members: [{}] }] },
{ type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", maxClients: 10 }] },
{ type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", maxClients: 65536, maxClientsLimited: true }] },
{ type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", passwordProtected: "yes" }] },
{ type: "memberEnter", id: 65536, nickname: "bad id" },
{ type: "memberEnter", id: 1, nickname: "bad flag", inputMuted: "false" },
{ type: "serverEvent", event: { ...event, timestamp: Infinity } },
+19
View File
@@ -13,6 +13,7 @@ type ChatFields = { invokerId?: number; invokerName?: string; message: string; t
/** Public JSON messages. Internal sockets, SDK clients and media objects stay out. */
export type ServerMessage =
| Message<"connected", { tsClientId: number; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webRtcStunServer?: string; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
| Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }>
| Message<"memberEnter", ChannelMember>
| Message<"memberLeave", { id: number }>
| Message<"memberAvatar", { id: number; uid?: string; avatar?: string }>
@@ -50,6 +51,15 @@ const identifier = (value: unknown): value is string => text(value) && value.len
const channelId = (value: unknown): value is string | number => (text(value) && /^\d{1,20}$/.test(value)) || (finite(value) && Number.isSafeInteger(value) && value >= 0);
const optional = (value: unknown, check: (value: unknown) => boolean): boolean => value === undefined || check(value);
const arrayOf = (value: unknown, check: (value: unknown) => boolean): boolean => Array.isArray(value) && value.every(check);
const safeHttpUrl = (value: unknown): boolean => {
if (!text(value) || value.length > 2_048) return false;
try {
const url = new URL(value);
return (url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password;
} catch {
return false;
}
};
function member(value: unknown): value is ChannelMember {
return isRecord(value) && clientId(value.id) && text(value.nickname)
@@ -60,6 +70,10 @@ function member(value: unknown): value is ChannelMember {
function channel(value: unknown): value is ChannelInfo {
return isRecord(value) && text(value.id) && channelId(value.id) && text(value.parentID) && channelId(value.parentID)
&& text(value.name) && optional(value.order, text) && optional(value.description, text)
&& optional(value.maxClients, maximum => finite(maximum) && Number.isInteger(maximum) && maximum >= 0 && maximum <= 65_535)
&& optional(value.maxClientsLimited, boolean)
&& optional(value.passwordProtected, boolean)
&& (value.maxClients === undefined) === (value.maxClientsLimited === undefined)
&& optional(value.members, members => arrayOf(members, member));
}
@@ -112,6 +126,11 @@ const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> =
connected: m => clientId(m.tsClientId) && optional(m.members, v => arrayOf(v, member)) && optional(m.serverEventLog, v => arrayOf(v, event))
&& optional(m.identity, v => text(v) && v.length <= 8192) && optional(m.webrtcAvailable, boolean) && optional(m.webRtcStunServer, v => normalizeVoiceStunServer(v) !== null)
&& optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean),
serverInfo: m => text(m.name) && m.name.length <= 256
&& optional(m.icon, v => v === null || (text(v) && v.length <= 180_000
&& /^data:image\/(?:png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(v)))
&& optional(m.bannerUrl, v => v === null || safeHttpUrl(v))
&& optional(m.welcomeMessage, v => text(v) && v.length <= 4_096),
memberEnter: member,
memberLeave: m => clientId(m.id),
memberAvatar: m => clientId(m.id) && optional(m.uid, text) && optional(m.avatar, text),
+380
View File
@@ -0,0 +1,380 @@
import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss";
import selectorParser from "postcss-selector-parser";
import valueParser from "postcss-value-parser";
export type SkinCssSchemaVersion = 1 | 2 | 3 | 4;
export type SkinCssAssets = Readonly<Record<string, unknown>> | Map<string, unknown> | Set<string>;
const MAX_CSS_BYTES = 512 * 1024;
export class SkinCssValidationError extends Error {
constructor(message: string, readonly code: string) {
super(message);
this.name = "SkinCssValidationError";
}
}
function hasSkinCssAsset(assets: SkinCssAssets, path: string): boolean {
if (assets instanceof Set) return assets.has(path);
if (assets instanceof Map) return assets.has(path);
return Object.prototype.hasOwnProperty.call(assets, path) && Boolean(assets[path]);
}
const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "layer", "font-face", "keyframes", "-webkit-keyframes"]);
const LAYOUT_AFFECTING_PROPERTIES = new Set([
"all", "display", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline",
"width", "height", "min-width", "min-height", "max-width", "max-height", "inline-size", "block-size",
"min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio", "box-sizing",
"gap", "row-gap", "column-gap", "grid", "flex", "order", "float", "clear", "overflow", "overflow-x",
"overflow-y", "overflow-block", "overflow-inline", "overscroll-behavior", "z-index", "visibility",
"pointer-events", "clip", "clip-path", "mask", "mask-image", "transform", "transform-origin", "transform-style", "translate", "scale", "rotate",
"perspective", "perspective-origin", "contain", "content-visibility", "container", "container-name",
"container-type", "contain-intrinsic-size", "resize", "columns", "column-count", "column-width", "scrollbar-width", "font",
"font-size", "line-height", "letter-spacing", "word-spacing", "white-space", "word-break", "overflow-wrap", "word-wrap",
"text-wrap", "text-overflow", "text-indent", "text-transform", "text-combine-upright", "text-autospace", "text-spacing-trim",
"line-clamp", "tab-size", "hyphens", "line-break", "text-size-adjust", "initial-letter", "shape-outside", "baseline-shift",
"box-orient", "box-direction", "box-lines", "ruby-position", "caption-side", "table-layout", "border-collapse", "border-spacing",
"writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content",
"position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope",
]);
const OPTIONAL_VISUAL_PARTS = new Set([
"home.hero.eyebrow",
"home.gateway-status",
"home.features",
"home.feature",
"home.visitors",
"home.join-card.waveform",
"home.join-card.sonar",
"voice.activity-heading",
"voice.member.avatar",
"voice.member.live-indicator",
"voice.member-row.avatar",
"voice.screen-player.viewer-avatar",
"voice.screen-player.live",
"demo.badge",
"demo.wave",
"demo.avatar",
"demo.member-status",
"demo.note",
]);
export function compileSkinCss(source: string, id: string, assets: SkinCssAssets, schemaVersion: SkinCssSchemaVersion, pluginId?: string): { css: string; warnings: string[] } {
const size = new TextEncoder().encode(source).byteLength;
if (!size || size > MAX_CSS_BYTES) throw new SkinCssValidationError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
let root: postcss.Root;
try { root = postcss.parse(source, { from: undefined }); }
catch (error) { throw new SkinCssValidationError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); }
const skinScope = `.ws-skin-root[data-ws-skin="${id}"]`;
const scope = pluginId
? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]`
: skinScope;
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`;
const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone());
const warnings = new Set<string>();
const keyframeNames = new Map<string, string>();
const fontFamilyNames = new Map<string, string>();
const hideableRules = new WeakSet<Rule>();
let nodeCount = 0;
root.walk((node) => {
nodeCount += 1;
if (nodeCount > 12000) throw new SkinCssValidationError("The CSS file contains too many rules.", "SKIN_CSS_COMPLEXITY");
});
root.walkAtRules((rule: AtRule) => {
const name = rule.name.toLowerCase();
if (!ALLOWED_AT_RULES.has(name)) throw rule.error(`The @${rule.name} rule is not allowed in a skin package.`);
if (name.endsWith("keyframes")) {
const keyframeName = rule.params.trim();
if (!/^[-_a-z][-_a-z0-9]*$/i.test(keyframeName)) throw rule.error("Keyframe names must be simple CSS identifiers.");
keyframeNames.set(keyframeName, `${namespace}-${keyframeName}`);
rule.params = `${namespace}-${keyframeName}`;
} else if (name === "layer") {
const layers = rule.params.split(",").map((layer) => layer.trim());
if (!layers.length || layers.some((layer) => !layer || !layer.split(".").every((part) => /^[-_a-z][-_a-z0-9]*$/i.test(part)))) {
throw rule.error("Skin CSS must use named @layer values so layer names can be isolated.");
}
rule.params = layers.map((layer) => `${namespace}-${layer.split(".").join(`.${namespace}-`)}`).join(", ");
} else if (name === "font-face") {
if (/\blocal\s*\(/i.test(decodeCssEscapes(rule.toString()))) throw rule.error("@font-face local() is not allowed; include a WOFF2 file in the package.");
const family = rule.nodes?.find((node): node is Declaration => node.type === "decl" && node.prop.toLowerCase() === "font-family");
if (!family) throw rule.error("Each @font-face rule must declare font-family.");
const originalFamily = parseSingleFontFamily(family.value);
const scopedFamily = `${namespace}-${originalFamily.replace(/[^a-z0-9_-]/gi, "-")}`;
fontFamilyNames.set(originalFamily.toLowerCase(), scopedFamily);
family.value = `"${scopedFamily}"`;
}
});
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
if (rule.parent?.type === "rule") throw rule.error("Nested style rules are not supported; use flat selectors.");
if (!pluginId && !selectorUsesPublicHook(rule.selector, schemaVersion >= 3)) {
throw new SkinCssValidationError(rule.error("Skin selectors must use :root, [data-ws-page], [data-ws-part], or [data-ws-plugin-part] so they stay attached to WebSpeak's stable visual interface.").message, "SKIN_CSS_SELECTOR");
}
if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule);
try {
rule.selector = selectorParser((selectors) => {
selectors.each((selector) => {
const text = selector.toString().trim();
if (!text) throw new SkinCssValidationError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinCssValidationError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/^:root\b/.test(text)) {
selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone());
return;
}
selector.prepend(selectorParser.combinator({ value: " " }));
for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone());
});
}).processSync(rule.selector);
} catch (error) {
if (error instanceof SkinCssValidationError) throw error;
throw rule.error(`A CSS selector is invalid: ${(error as Error).message}`);
}
});
const referencedKeyframes = new Set<string>();
const nonOptionalKeyframes = new Set<string>();
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
const optionalTarget = hideableRules.has(rule);
rule.walkDecls((declaration: Declaration) => {
const property = declaration.prop.toLowerCase();
if (property !== "animation" && property !== "animation-name") return;
const value = declaration.value;
if (/\b(?:var|attr)\s*\(|\\/i.test(value)) {
keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name));
return;
}
for (const name of keyframeNames.keys()) {
if (!referencesCssIdentifier(value, name)) continue;
referencedKeyframes.add(name);
if (!optionalTarget) nonOptionalKeyframes.add(name);
}
});
});
const optionalOnlyKeyframes = new Set([...referencedKeyframes]
.filter((name) => !nonOptionalKeyframes.has(name))
.map((name) => keyframeNames.get(name)!));
root.walkDecls((declaration: Declaration) => {
const property = decodeCssEscapes(declaration.prop).toLowerCase();
const value = declaration.value.trim();
const decodedValue = decodeCssEscapes(value);
const owningRule = findOwningRule(declaration);
const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null;
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
throw declaration.error(pluginId
? `Custom plugin variables must use --plugin-${pluginId}- or --skin- prefixes.`
: "Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
}
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.");
}
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(decodedValue)) {
throw declaration.error("Executable CSS values are not allowed.");
}
const compactValue = decodeCssEscapes(valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("")).toLowerCase();
if (schemaVersion < 3 && ["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(decodedValue)) {
if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
}
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));
if (removesVisual && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
}
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(decodedValue))
|| (property === "clip-path" && /inset\(\s*50%/i.test(decodedValue))
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(decodedValue));
if (visuallyRemoves && !canHideTarget && schemaVersion < 3) {
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
}
if (schemaVersion >= 3 && removesVisual) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${decodedValue}`) || (property === "position" && decodedValue === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile.");
const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames);
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
if (!hasSkinCssAsset(assets, assetPath)) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`);
return `wskin-asset:${encodeURIComponent(assetPath)}`;
});
});
return { css: root.toString(), warnings: [...warnings] };
}
export function rewriteSkinCssAssets(css: string, resolve: (path: string) => string): string {
const root = postcss.parse(css, { from: undefined });
root.walkDecls((declaration) => {
declaration.value = rewriteAssetUrls(declaration.value, resolve);
});
return root.toString();
}
function targetsOnlyOptionalVisualParts(selector: string): boolean {
try {
const parsed = selectorParser().astSync(selector);
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
if (item.nodes.length !== 1 || item.nodes[0].type !== "attribute") return false;
const attribute = item.nodes[0];
if (attribute.attribute.toLowerCase() !== "data-ws-part" || attribute.operator !== "=") return false;
const part = (attribute.value ?? "").replace(/^['"]|['"]$/g, "");
return OPTIONAL_VISUAL_PARTS.has(part);
});
} catch {
return false;
}
}
function selectorUsesPublicHook(selector: string, allowCustomClasses = false): boolean {
try {
const parsed = selectorParser().astSync(selector);
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
let scoped = false;
let usesPrivateName = false;
item.walk((node) => {
if (node.type === "attribute" && ["data-ws-part", "data-ws-page", ...(allowCustomClasses ? ["data-ws-plugin-part"] : [])].includes(node.attribute.toLowerCase())) scoped = true;
if (node.type === "pseudo" && node.value.toLowerCase() === ":root") scoped = true;
if (!allowCustomClasses && (node.type === "class" || node.type === "id")) usesPrivateName = true;
});
return scoped && !usesPrivateName;
});
} catch {
return false;
}
}
function isLayoutAffectingProperty(property: string): boolean {
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true;
if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true;
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true;
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
}
function findOwningRule(node: Node): Rule | null {
let parent = node.parent;
while (parent && parent.type !== "root") {
if (parent.type === "rule") return parent as Rule;
parent = parent.parent;
}
return null;
}
function findKeyframesRule(rule: Rule): AtRule | null {
let parent = rule.parent;
while (parent && parent.type !== "root") {
if (parent.type === "atrule" && /(?:^|-)?keyframes$/i.test(parent.name)) return parent as AtRule;
parent = parent.parent;
}
return null;
}
function referencesCssIdentifier(value: string, identifier: string): boolean {
const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value);
}
export function rewriteAssetUrls(value: string, resolve: (path: string) => string): string {
const parsed = valueParser(value);
const resolvePackageAsset = (rawValue: string): string => {
const raw = decodeCssEscapes(rawValue.trim());
if (!raw || raw.startsWith("#")) throw new SkinCssValidationError("CSS images and fonts must point to assets inside this skin package.", "SKIN_EXTERNAL_RESOURCE");
const isInternalMarker = raw.startsWith("wskin-asset:");
if (!isInternalMarker && /^(?:data:|blob:|https?:|\/\/|file:|javascript:)/i.test(raw)) throw new SkinCssValidationError("Only relative paths to assets inside this skin package are allowed in url().", "SKIN_EXTERNAL_RESOURCE");
let path: string;
try { path = isInternalMarker ? decodeURIComponent(raw.slice("wskin-asset:".length)) : normalizeAssetPath(raw); }
catch { throw new SkinCssValidationError("A skin asset reference is invalid.", "SKIN_ASSET_PATH"); }
return resolve(path);
};
const visit = (nodes: typeof parsed.nodes, inImageSet = false): void => {
for (const node of nodes) {
const functionName = node.type === "function" ? decodeCssEscapes(node.value).toLowerCase() : "";
if (node.type === "function" && functionName === "url") {
const raw = valueParser.stringify(node.nodes).trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/, "$1$2").trim();
node.nodes = [{ type: "string", quote: '"', value: resolvePackageAsset(raw), sourceIndex: 0, sourceEndIndex: 0, unclosed: undefined }];
node.before = "";
node.after = "";
continue;
}
if (node.type === "function" && (functionName === "image-set" || functionName === "-webkit-image-set")) {
for (const child of node.nodes) {
if (child.type === "string") child.value = resolvePackageAsset(child.value);
else if (child.type === "function") visit([child]);
}
continue;
}
if (node.type === "function") visit(node.nodes, inImageSet);
else if (inImageSet && node.type === "string") node.value = resolvePackageAsset(node.value);
}
};
visit(parsed.nodes);
return parsed.toString();
}
function decodeCssEscapes(value: string): string {
return value.replace(/\\([\da-f]{1,6})(?:[\t\n\f\r ]|\r\n)?|\\([^\da-f\r\n\f])/gi, (match, hexadecimal: string | undefined, escaped: string | undefined) => {
if (hexadecimal) {
const codePoint = Number.parseInt(hexadecimal, 16);
if (!codePoint || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) return "\ufffd";
return String.fromCodePoint(codePoint);
}
return escaped ?? match;
});
}
function parseSingleFontFamily(value: string): string {
const parsed = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment");
if (parsed.length !== 1 || (parsed[0].type !== "string" && parsed[0].type !== "word") || !parsed[0].value.trim()) {
throw new SkinCssValidationError("@font-face must declare exactly one font family.", "SKIN_FONT_FAMILY");
}
return parsed[0].value.trim();
}
function rewriteScopedNames(value: string, property: string, keyframes: Map<string, string>, fontFamilies: Map<string, string>): string {
const parsed = valueParser(value);
if (["animation", "animation-name", "font", "font-family"].includes(property)) {
parsed.walk((node) => {
if (node.type !== "word" && node.type !== "string") return;
const keyframe = keyframes.get(node.value);
if (keyframe) node.value = keyframe;
const family = fontFamilies.get(node.value.toLowerCase());
if (family) node.value = family;
});
}
return parsed.toString();
}
function normalizeAssetPath(raw: string): string {
let path = raw.split(/[?#]/, 1)[0];
try { path = decodeURIComponent(path); } catch { throw new SkinCssValidationError("An asset URL contains invalid encoding.", "SKIN_ASSET_PATH"); }
if (path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[a-z]:/i.test(path)) throw new SkinCssValidationError("An asset URL must be a relative package path.", "SKIN_ASSET_PATH");
const segments: string[] = [];
for (const segment of path.split("/")) {
if (!segment || segment === ".") continue;
if (segment === "..") {
if (!segments.length) throw new SkinCssValidationError("An asset URL cannot leave the skin package.", "SKIN_ASSET_PATH");
segments.pop();
} else {
segments.push(segment);
}
}
if (!segments.length) throw new SkinCssValidationError("An asset URL must point to a package file.", "SKIN_ASSET_PATH");
return segments.join("/");
}
function hasKeyframesAncestor(rule: Rule): boolean {
let parent = rule.parent;
while (parent && parent.type !== "root") {
if (parent.type === "atrule" && /keyframes$/i.test(parent.name)) return true;
parent = parent.parent;
}
return false;
}
+129
View File
@@ -0,0 +1,129 @@
import {
projectSkinRuntimePluginContext,
SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS,
} from "./skin-runtime-plugin-context.js";
export const SKIN_EXTENSION_UI_INPUT_SCHEMA_VERSION = 1 as const;
export const SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES = 64 * 1024;
export const SKIN_EXTENSION_UI_STATE_KEY_LIMIT = 64;
export const SKIN_EXTENSION_UI_EVENT_NAMES = Object.freeze([
"click", "dblclick", "change", "input", "submit", "keydown", "keyup", "contextmenu", "focus", "blur",
"pointerdown", "pointerup", "pointerenter", "pointerleave", "dragstart", "dragover", "drop",
] as const);
export type SkinExtensionUiEventName = typeof SKIN_EXTENSION_UI_EVENT_NAMES[number];
export type SkinExtensionUiScalar = string | number | boolean;
export interface SkinExtensionUiEventInput {
componentId: string;
handlerId: string;
eventName: SkinExtensionUiEventName;
key?: string;
value?: string;
checked?: boolean;
}
export interface SkinExtensionUiInput {
schemaVersion: typeof SKIN_EXTENSION_UI_INPUT_SCHEMA_VERSION;
state: Record<string, SkinExtensionUiScalar>;
event: SkinExtensionUiEventInput | null;
/** Host-projected public application data; permissions are enforced before this is populated. */
data?: Record<string, unknown>;
}
export class SkinExtensionUiInputError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinExtensionUiInputError";
}
}
function fail(message: string): never {
throw new SkinExtensionUiInputError("SKIN_EXTENSION_UI_INPUT_INVALID", message);
}
function isRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function cleanState(value: unknown): Record<string, SkinExtensionUiScalar> {
if (!isRecord(value) || Object.keys(value).length > SKIN_EXTENSION_UI_STATE_KEY_LIMIT) {
return fail("UI state must be a bounded scalar object.");
}
const state: Record<string, SkinExtensionUiScalar> = Object.create(null) as Record<string, SkinExtensionUiScalar>;
for (const [key, entry] of Object.entries(value)) {
if (!/^[a-z][a-zA-Z0-9_.-]{0,63}$/.test(key)
|| (typeof entry !== "string" && typeof entry !== "number" && typeof entry !== "boolean")
|| (typeof entry === "string" && entry.length > 1_024)
|| (typeof entry === "number" && (!Number.isFinite(entry) || Math.abs(entry) > 1_000_000_000))) {
return fail("UI state contains an invalid key or scalar value.");
}
state[key] = entry;
}
return state;
}
function cleanEvent(value: unknown): SkinExtensionUiEventInput | null {
if (value === null) return null;
if (!isRecord(value)) return fail("A UI event must be an object or null.");
const allowed = ["componentId", "handlerId", "eventName", "key", "value", "checked"];
if (Object.keys(value).some((key) => !allowed.includes(key))) return fail("A UI event contains an unsupported field.");
const slug = (entry: unknown): entry is string => typeof entry === "string" && /^[a-z][a-z0-9-]{0,63}$/.test(entry);
if (!slug(value.componentId) || !slug(value.handlerId)
|| typeof value.eventName !== "string"
|| !(SKIN_EXTENSION_UI_EVENT_NAMES as readonly string[]).includes(value.eventName)) {
return fail("A UI event has an invalid component, handler, or event name.");
}
const event: SkinExtensionUiEventInput = {
componentId: value.componentId,
handlerId: value.handlerId,
eventName: value.eventName as SkinExtensionUiEventName,
};
if (value.key !== undefined) {
if (typeof value.key !== "string" || !value.key || value.key.length > 32 || /[\u0000-\u001f]/.test(value.key)) {
return fail("A UI event key is invalid.");
}
if (event.eventName !== "keydown" && event.eventName !== "keyup") return fail("Only keyboard events may carry a key.");
event.key = value.key;
}
if (value.value !== undefined) {
if (typeof value.value !== "string" || value.value.length > 2_048) return fail("A UI event value exceeds its limit.");
if (event.eventName !== "input" && event.eventName !== "change") return fail("Only input and change events may carry a value.");
event.value = value.value;
}
if (value.checked !== undefined) {
if (typeof value.checked !== "boolean") return fail("A UI event checked value must be boolean.");
if (event.eventName !== "input" && event.eventName !== "change") return fail("Only input and change events may carry a checked value.");
event.checked = value.checked;
}
return event;
}
/** Validates bounded local UI state, one safe event, and a host-projected data snapshot. */
export function parseSkinExtensionUiInput(input: unknown): SkinExtensionUiInput {
let value = input;
if (typeof input === "string") {
if (new TextEncoder().encode(input).byteLength > SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES) {
return fail("UI input exceeds its 64 KiB limit.");
}
try { value = JSON.parse(input); }
catch { return fail("UI input must be valid JSON."); }
}
if (!isRecord(value) || Object.keys(value).some((key) => !["schemaVersion", "state", "event", "data"].includes(key))
|| value.schemaVersion !== SKIN_EXTENSION_UI_INPUT_SCHEMA_VERSION) {
return fail("UI input uses an unsupported schema or contains unsupported fields.");
}
if (value.data !== undefined && !isRecord(value.data)) return fail("UI data must be a bounded object.");
const parsed = {
schemaVersion: SKIN_EXTENSION_UI_INPUT_SCHEMA_VERSION,
state: cleanState(value.state),
event: cleanEvent(value.event),
...(value.data === undefined ? {} : { data: projectSkinRuntimePluginContext(SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS, value.data) }),
} satisfies SkinExtensionUiInput;
if (new TextEncoder().encode(JSON.stringify(parsed)).byteLength > SKIN_EXTENSION_UI_INPUT_LIMIT_BYTES) {
return fail("UI input exceeds its 64 KiB limit.");
}
return parsed;
}
+307
View File
@@ -0,0 +1,307 @@
import {
SKIN_PLUGIN_PERMISSIONS,
SKIN_PLUGIN_HOST_WIDGETS,
missingSkinPluginWidgetPermission,
parseSkinPluginRuntimeAction,
SKIN_PLUGIN_NODE_LIMIT,
SKIN_PLUGIN_TREE_DEPTH_LIMIT,
parseSkinPluginDocument,
type SkinPluginAction,
type SkinPluginActionDefinition,
type SkinPluginComponent,
type SkinPluginDocument,
type SkinPluginNode,
type SkinPluginHostWidget,
type SkinPluginPermission,
} from "./skin-plugin.js";
import { parseSkinExtensionUiInput, SKIN_EXTENSION_UI_EVENT_NAMES } from "./skin-extension-ui-input.js";
export const SKIN_EXTENSION_UI_OUTPUT_LIMIT_BYTES = 256 * 1024;
const LOCAL_UI_ACTIONS = new Set<SkinPluginAction>(["ui.setState", "ui.toggleState"]);
const GENERATED_COMPONENT_LIMIT = 64;
const GENERATED_RUNTIME_HOST_WIDGETS = new Set<SkinPluginHostWidget>(["voice.screen-share-start"]);
const GENERATED_CHILD_LIMIT = 256;
const GENERATED_ATTRIBUTE_LIMIT = 64;
const GENERATED_BLOCKED_ELEMENTS = new Set([
"animate", "animatemotion", "animatetransform", "applet", "base", "embed", "fencedframe", "foreignobject", "frame", "frameset",
"iframe", "link", "math", "meta", "noembed", "noframes", "object", "plaintext", "portal", "script", "set", "style", "template", "webview", "xmp",
]);
const GENERATED_VOID_ELEMENTS = new Set([
"br", "col", "hr", "img", "input", "line", "path", "polygon", "polyline", "rect", "stop", "use", "wbr",
]);
const GENERATED_BLOCKED_ATTRIBUTES = new Set([
"action", "archive", "background", "code", "codebase", "data", "download", "form", "formaction", "formmethod", "formenctype",
"formtarget", "is", "manifest", "ping", "poster", "profile", "src", "srcdoc", "srcset", "style", "target", "xlink:href",
"autofocus", "autoplay", "command", "commandfor", "http-equiv", "nonce", "popover", "popovertarget", "popovertargetaction", "slot", "xml:base",
]);
export class SkinExtensionUiOutputError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinExtensionUiOutputError";
}
}
function fail(code: string, message: string): never {
throw new SkinExtensionUiOutputError(code, message);
}
function assertLocalUiNode(node: SkinPluginNode): void {
if (node.widget) fail("SKIN_EXTENSION_UI_WIDGET_UNSUPPORTED", "Extension UI output cannot embed privileged host widgets.");
node.children?.forEach(assertLocalUiNode);
}
function rejectExtensionHostWidgets(node: unknown): void {
if (!isRecord(node)) return;
if (node.widget !== undefined) fail("SKIN_EXTENSION_UI_WIDGET_UNSUPPORTED", "Extension UI output cannot embed privileged host widgets.");
if (Array.isArray(node.children)) node.children.forEach(rejectExtensionHostWidgets);
}
function isRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function boundedText(value: unknown, maximum: number, code: string, field: string): string {
if (typeof value !== "string" || !value.trim() || value.trim() !== value || value.length > maximum) {
fail(code, `${field} must be bounded non-empty text.`);
}
return value;
}
function onlyKeys(value: Record<string, unknown>, allowed: readonly string[], context: string): void {
if (Object.keys(value).some((key) => !allowed.includes(key))) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", `${context} has an unsupported field.`);
}
function generatedNode(
input: unknown,
depth: number,
count: { value: number },
allowEvents: boolean,
page: "home" | "voice",
permissions: readonly SkinPluginPermission[],
): SkinPluginNode {
count.value += 1;
if (count.value > SKIN_PLUGIN_NODE_LIMIT || depth > SKIN_PLUGIN_TREE_DEPTH_LIMIT || !isRecord(input)) {
fail("SKIN_EXTENSION_UI_COMPLEXITY_LIMIT", "The generated UI tree exceeds its node or depth limit.");
}
onlyKeys(input, ["widget", "tag", "text", "part", "className", "attributes", "asset", "children", ...(allowEvents ? ["events"] : [])], "A generated UI node");
const hasWidget = input.widget !== undefined;
const hasTag = input.tag !== undefined;
const hasText = input.text !== undefined;
if (Number(hasWidget) + Number(hasTag) + Number(hasText) !== 1) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "A generated node must contain exactly one widget, tag, or text.");
const node: SkinPluginNode = {};
if (hasWidget) {
if (typeof input.widget !== "string" || !SKIN_PLUGIN_HOST_WIDGETS.includes(input.widget as SkinPluginHostWidget)
|| !GENERATED_RUNTIME_HOST_WIDGETS.has(input.widget as SkinPluginHostWidget)) {
fail("SKIN_EXTENSION_UI_WIDGET_UNSUPPORTED", "The generated UI requested a host widget that is not available to runtime plugins.");
}
if (page !== "voice") fail("SKIN_EXTENSION_UI_WIDGET_UNSUPPORTED", "The screen-share host widget is available only on the voice page.");
const widget = input.widget as SkinPluginHostWidget;
const requiredPermission = missingSkinPluginWidgetPermission(widget, permissions);
if (requiredPermission) {
fail("SKIN_EXTENSION_UI_PERMISSION_MISSING", `The ${widget} widget requires ${requiredPermission}.`);
}
onlyKeys(input, ["widget", "part", "className"], "A generated host widget node");
node.widget = widget;
if (input.part !== undefined) {
const part = boundedText(input.part, 64, "SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "node.part");
if (!/^[a-z][a-z0-9-]*$/.test(part)) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "A generated part uses an invalid name.");
node.part = part;
}
if (input.className !== undefined) {
if (typeof input.className !== "string" || input.className.length > 512 || /[<>\u0000-\u001f]/.test(input.className)) {
fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Generated class names must be bounded plain text.");
}
node.className = input.className;
}
return node;
}
if (hasText) {
if (typeof input.text !== "string" || input.text.length > 8_192) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Generated text exceeds its limit.");
node.text = input.text;
}
if (hasTag) {
const tag = boundedText(input.tag, 64, "SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "node.tag");
if (!/^[A-Za-z][A-Za-z0-9-]*$/.test(tag) || GENERATED_BLOCKED_ELEMENTS.has(tag.toLowerCase())) {
fail("SKIN_EXTENSION_UI_ELEMENT_INVALID", `The generated element '${tag}' is invalid or has active browser capabilities.`);
}
node.tag = tag;
}
if (input.part !== undefined) {
const part = boundedText(input.part, 64, "SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "node.part");
if (!/^[a-z][a-z0-9-]*$/.test(part)) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "A generated part uses an invalid name.");
node.part = part;
}
if (input.className !== undefined) {
if (typeof input.className !== "string" || input.className.length > 512 || /[<>\u0000-\u001f]/.test(input.className)) {
fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Generated class names must be bounded plain text.");
}
node.className = input.className;
}
if (input.attributes !== undefined) {
if (!isRecord(input.attributes) || Object.keys(input.attributes).length > GENERATED_ATTRIBUTE_LIMIT) {
fail("SKIN_EXTENSION_UI_ATTRIBUTE_INVALID", "Generated attributes must be a bounded object.");
}
const attributes: Record<string, string | number | boolean> = Object.create(null) as Record<string, string | number | boolean>;
for (const [key, value] of Object.entries(input.attributes)) {
if (key !== key.toLowerCase() || !/^[a-z][a-z0-9:_-]{0,63}$/.test(key) || key.startsWith("on")
|| key.startsWith("data-ws-") || GENERATED_BLOCKED_ATTRIBUTES.has(key)) {
fail("SKIN_EXTENSION_UI_ATTRIBUTE_INVALID", `The generated attribute '${key}' is not allowed.`);
}
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
fail("SKIN_EXTENSION_UI_ATTRIBUTE_INVALID", "Generated attribute values must be scalar.");
}
if (typeof value === "string" && value.length > 4_096) fail("SKIN_EXTENSION_UI_ATTRIBUTE_INVALID", "A generated attribute exceeds its size limit.");
if (key === "href" && (typeof value !== "string" || !/^#[A-Za-z][A-Za-z0-9_.:-]{0,127}$/.test(value))) {
fail("SKIN_EXTENSION_UI_ATTRIBUTE_INVALID", "Generated links may only target a same-document fragment.");
}
if (["fill", "stroke", "clip-path", "filter", "mask", "marker-start", "marker-mid", "marker-end"].includes(key)
&& typeof value === "string" && /url\s*\(|javascript\s*:/i.test(value)) {
fail("SKIN_EXTENSION_UI_ATTRIBUTE_INVALID", "SVG attributes cannot load external or executable resources.");
}
attributes[key] = value;
}
node.attributes = attributes;
if (node.tag === "input" && typeof attributes.type === "string"
&& ["password", "file", "hidden"].includes(attributes.type.toLowerCase())) {
fail("SKIN_EXTENSION_UI_ATTRIBUTE_INVALID", "Generated input controls cannot collect password, file, or hidden values.");
}
}
if (input.asset !== undefined) {
const asset = boundedText(input.asset, 120, "SKIN_EXTENSION_UI_ASSET_INVALID", "node.asset");
if (node.tag !== "img" || !/^assets\/[A-Za-z0-9._/-]+$/.test(asset) || asset.split("/").some((part) => !part || part === "." || part === "..")) {
fail("SKIN_EXTENSION_UI_ASSET_INVALID", "Generated image assets must use safe package-relative paths.");
}
node.asset = asset;
}
if (input.events !== undefined) {
if (!allowEvents || !isRecord(input.events) || Object.keys(input.events).length > SKIN_EXTENSION_UI_EVENT_NAMES.length) {
fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Generated event callbacks are supported only by UI output schema 5.");
}
const events: NonNullable<SkinPluginNode["events"]> = {};
for (const [eventName, handlerId] of Object.entries(input.events)) {
if (!(SKIN_EXTENSION_UI_EVENT_NAMES as readonly string[]).includes(eventName)
|| typeof handlerId !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(handlerId)) {
fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "A generated callback uses an unsupported event or handler ID.");
}
events[eventName as keyof typeof events] = handlerId;
}
node.events = events;
}
if (input.children !== undefined) {
if (!Array.isArray(input.children) || input.children.length > GENERATED_CHILD_LIMIT) {
fail("SKIN_EXTENSION_UI_COMPLEXITY_LIMIT", "A generated node has too many children.");
}
if (node.tag && GENERATED_VOID_ELEMENTS.has(node.tag) && input.children.length > 0) {
fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Void generated elements cannot contain children.");
}
node.children = input.children.map((child) => generatedNode(child, depth + 1, count, allowEvents, page, permissions));
}
return node;
}
function parseGeneratedDocument(
input: Record<string, unknown>,
allowEvents: boolean,
allowRequest = false,
permissions: readonly SkinPluginPermission[] = [],
): SkinPluginDocument {
onlyKeys(input, ["schemaVersion", "components", ...(allowRequest ? ["request"] : [])], "Generated UI document");
if (!Array.isArray(input.components) || input.components.length < 1 || input.components.length > GENERATED_COMPONENT_LIMIT) {
fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "The generated document has an unsupported component count.");
}
const ids = new Set<string>();
const components: SkinPluginComponent[] = input.components.map((raw, index) => {
if (!isRecord(raw)) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", `Generated component ${index} must be an object.`);
onlyKeys(raw, ["id", "name", "page", "accessibleName", "root", ...(allowEvents ? ["state"] : [])], "Generated component");
const id = boundedText(raw.id, 64, "SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "component.id");
if (!/^[a-z][a-z0-9-]*$/.test(id) || ids.has(id)) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Generated component IDs must be unique lowercase slugs.");
ids.add(id);
const name = boundedText(raw.name, 80, "SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "component.name");
const accessibleName = boundedText(raw.accessibleName, 120, "SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "component.accessibleName");
if (raw.page !== "home" && raw.page !== "voice") fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Generated components may target only the public home or voice page.");
const root = generatedNode(raw.root, 1, { value: 0 }, allowEvents, raw.page, permissions);
if (!root.tag) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "A generated component root must be an element.");
const state = allowEvents
? parseSkinExtensionUiInput({ schemaVersion: 1, state: raw.state ?? {}, event: null }).state
: undefined;
return {
id, name, page: raw.page, accessibleName, permissions: [], actions: Object.create(null) as Record<string, never>, root,
...(state ? { state } : {}),
...(allowEvents ? { runtimeCallbacks: true } : {}),
};
});
return { schemaVersion: 3, components };
}
function parseOutputInput(source: string): Record<string, unknown> {
if (typeof source !== "string" || !source.length) {
fail("SKIN_EXTENSION_UI_OUTPUT_INVALID", "Extension UI output must be a non-empty JSON string.");
}
if (new TextEncoder().encode(source).byteLength > SKIN_EXTENSION_UI_OUTPUT_LIMIT_BYTES) {
fail("SKIN_EXTENSION_UI_OUTPUT_SIZE", "Extension UI output exceeds the 256 KiB UTF-8 limit.");
}
let input: unknown;
try { input = JSON.parse(source); }
catch { fail("SKIN_EXTENSION_UI_OUTPUT_JSON", "Extension UI output must contain valid JSON."); }
if (!isRecord(input)) fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Extension UI output must be an object.");
return input;
}
/** Parse a single host action effect from schema 6 output and require its permission in the plugin manifest. */
export function parseSkinExtensionUiActionRequest(
source: string,
permissions: readonly SkinPluginPermission[],
): SkinPluginActionDefinition | null {
const input = parseOutputInput(source);
if (input.schemaVersion !== 6 || input.request === undefined) return null;
try { return parseSkinPluginRuntimeAction(input.request, permissions); }
catch { fail("SKIN_EXTENSION_UI_ACTION_INVALID", "The requested host action is malformed or lacks an approved plugin permission."); }
}
/** Parses bounded Wasm output. Schema 5 adds trusted callbacks; schema 6 adds one permission-checked host action effect. */
export function parseSkinExtensionUiOutput(
source: string,
options: { permissions?: readonly SkinPluginPermission[] } = {},
): SkinPluginDocument {
const input = parseOutputInput(source);
const permissions = options.permissions ?? [];
if (input.schemaVersion === 4) return parseGeneratedDocument(input, false, false, permissions);
if (input.schemaVersion === 5) return parseGeneratedDocument(input, true, false, permissions);
if (input.schemaVersion === 6) {
const document = parseGeneratedDocument(input, true, true, permissions);
if (input.request !== undefined) {
try { parseSkinPluginRuntimeAction(input.request, Object.keys(SKIN_PLUGIN_PERMISSIONS) as SkinPluginPermission[]); }
catch { fail("SKIN_EXTENSION_UI_ACTION_INVALID", "The generated host action request is malformed."); }
}
return document;
}
if (input.schemaVersion === 3 && Array.isArray(input.components)) {
for (const rawComponent of input.components) {
if (isRecord(rawComponent)) rejectExtensionHostWidgets(rawComponent.root);
}
}
let document: SkinPluginDocument;
try { document = parseSkinPluginDocument(input); }
catch { fail("SKIN_EXTENSION_UI_OUTPUT_SCHEMA", "Extension UI output does not match the safe component schema."); }
if (document.schemaVersion !== 3) {
fail("SKIN_EXTENSION_UI_SCHEMA_UNSUPPORTED", "Extension UI output requires components schema version 3.");
}
for (const component of document.components) {
if (component.page === "demo" || component.mode === "surface" || component.permissions.length > 0) {
fail("SKIN_EXTENSION_UI_CAPABILITY_UNSUPPORTED", "Extension UI output cannot request skin permissions or replace a page.");
}
if (Object.values(component.actions).some((action) => !LOCAL_UI_ACTIONS.has(action.type))) {
fail("SKIN_EXTENSION_UI_ACTION_UNSUPPORTED", "Extension UI output can only update its own local UI state.");
}
assertLocalUiNode(component.root);
}
return document;
}
+245
View File
@@ -0,0 +1,245 @@
export const SKIN_EXTENSION_MANIFEST_SCHEMA_VERSION = 1 as const;
export const SKIN_EXTENSION_API_VERSION = 1 as const;
export const SKIN_EXTENSION_MESSAGE_CHANNEL = "webspeak.skin-extension" as const;
export const SKIN_EXTENSION_PERMISSION_DEFINITIONS = Object.freeze({
"session.status.read": Object.freeze({
policyVersion: 1,
risk: "low",
description: "Read a minimal snapshot of the current voice session status.",
}),
} as const);
export type SkinExtensionPermissionId = keyof typeof SKIN_EXTENSION_PERMISSION_DEFINITIONS;
export interface SkinExtensionManifest {
schemaVersion: typeof SKIN_EXTENSION_MANIFEST_SCHEMA_VERSION;
packageType: "extension";
id: string;
name: string;
version: string;
apiVersion: typeof SKIN_EXTENSION_API_VERSION;
permissions: readonly SkinExtensionPermissionId[];
}
export type SkinExtensionPermissionVersions = Readonly<Partial<Record<SkinExtensionPermissionId, number>>>;
/** A host-created approval record. Package contents can request permissions but cannot create this record. */
export interface SkinExtensionApproval {
pluginId: string;
apiVersion: number;
permissions: SkinExtensionPermissionVersions;
}
export interface SkinExtensionUpgradeConsentDelta {
addedPermissions: SkinExtensionPermissionId[];
changedMeaningPermissions: SkinExtensionPermissionId[];
removedPermissions: SkinExtensionPermissionId[];
apiVersionChanged: boolean;
requiresConsent: boolean;
}
export interface SkinExtensionSessionStatus {
connected: boolean;
channelName: string | null;
memberCount: number;
}
export interface SkinExtensionRequestMessage {
channel: typeof SKIN_EXTENSION_MESSAGE_CHANNEL;
apiVersion: typeof SKIN_EXTENSION_API_VERSION;
nonce: string;
id: string;
type: "request";
permission: SkinExtensionPermissionId;
payload: Record<string, never>;
}
export class SkinExtensionValidationError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinExtensionValidationError";
}
}
const MANIFEST_FIELDS = new Set(["schemaVersion", "packageType", "id", "name", "version", "apiVersion", "permissions"]);
const PLUGIN_ID_PATTERN = /^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
const SEMVER_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
const KNOWN_PERMISSIONS = new Set<string>(Object.keys(SKIN_EXTENSION_PERMISSION_DEFINITIONS));
function isPlainRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function boundedString(value: unknown, field: string, maximumLength: number): string {
if (typeof value !== "string" || value.length === 0 || value.length > maximumLength || value.trim() !== value) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", `Invalid ${field}.`);
}
return value;
}
export function parseSkinExtensionManifest(input: unknown): SkinExtensionManifest {
if (!isPlainRecord(input)) throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", "The extension manifest must be an object.");
if (Object.keys(input).some((key) => !MANIFEST_FIELDS.has(key))) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_UNKNOWN_FIELD", "The extension manifest contains an unsupported field.");
}
if (input.schemaVersion !== SKIN_EXTENSION_MANIFEST_SCHEMA_VERSION || input.packageType !== "extension") {
throw new SkinExtensionValidationError("SKIN_EXTENSION_SCHEMA_UNSUPPORTED", "The extension package schema is not supported.");
}
const id = boundedString(input.id, "id", 100);
if (!PLUGIN_ID_PATTERN.test(id)) throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", "The extension id must use lowercase letters, numbers, dots, or hyphens.");
const name = boundedString(input.name, "name", 120);
const version = boundedString(input.version, "version", 64);
if (!SEMVER_PATTERN.test(version)) throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", "The extension version must use semantic version syntax.");
if (input.apiVersion !== SKIN_EXTENSION_API_VERSION) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_API_UNSUPPORTED", "The extension API version is not supported.");
}
if (!Array.isArray(input.permissions) || input.permissions.length > 8) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_MANIFEST_INVALID", "The extension permissions must be a small array.");
}
const permissions: SkinExtensionPermissionId[] = [];
for (const permission of input.permissions) {
if (typeof permission !== "string" || !KNOWN_PERMISSIONS.has(permission)) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_PERMISSION_UNKNOWN", "The extension requests an unsupported permission.");
}
if (permissions.includes(permission as SkinExtensionPermissionId)) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_PERMISSION_DUPLICATE", "The extension requests a permission more than once.");
}
permissions.push(permission as SkinExtensionPermissionId);
}
return Object.freeze({
schemaVersion: SKIN_EXTENSION_MANIFEST_SCHEMA_VERSION,
packageType: "extension",
id,
name,
version,
apiVersion: SKIN_EXTENSION_API_VERSION,
permissions: Object.freeze(permissions),
});
}
/** Called only by a future host approval flow after the user approves the exact capabilities. */
export function createSkinExtensionApproval(manifest: SkinExtensionManifest): SkinExtensionApproval {
const permissions: Partial<Record<SkinExtensionPermissionId, number>> = {};
for (const permission of manifest.permissions) {
permissions[permission] = SKIN_EXTENSION_PERMISSION_DEFINITIONS[permission].policyVersion;
}
return Object.freeze({
pluginId: manifest.id,
apiVersion: manifest.apiVersion,
permissions: Object.freeze(permissions),
});
}
export function parseSkinExtensionApproval(input: unknown): SkinExtensionApproval {
if (!isPlainRecord(input) || Object.keys(input).some((key) => !["pluginId", "apiVersion", "permissions"].includes(key))) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_APPROVAL_INVALID", "The extension approval record is invalid.");
}
const pluginId = boundedString(input.pluginId, "approval.pluginId", 100);
if (!PLUGIN_ID_PATTERN.test(pluginId) || input.apiVersion !== SKIN_EXTENSION_API_VERSION || !isPlainRecord(input.permissions)) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_APPROVAL_INVALID", "The extension approval record is invalid.");
}
const permissions: Partial<Record<SkinExtensionPermissionId, number>> = {};
for (const [permission, policyVersion] of Object.entries(input.permissions)) {
if (!KNOWN_PERMISSIONS.has(permission) || !Number.isSafeInteger(policyVersion) || (policyVersion as number) < 1) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_APPROVAL_INVALID", "The extension approval record contains an unsupported grant.");
}
permissions[permission as SkinExtensionPermissionId] = policyVersion as number;
}
return Object.freeze({
pluginId,
apiVersion: SKIN_EXTENSION_API_VERSION,
permissions: Object.freeze(permissions),
});
}
export function getSkinExtensionUpgradeConsentDelta(
previousApproval: SkinExtensionApproval,
nextManifest: SkinExtensionManifest,
): SkinExtensionUpgradeConsentDelta {
if (previousApproval.pluginId !== nextManifest.id) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_ID_CHANGED", "An approval cannot be reused for a different extension id.");
}
const addedPermissions = nextManifest.permissions.filter((permission) => previousApproval.permissions[permission] === undefined);
const changedMeaningPermissions = nextManifest.permissions.filter((permission) => {
const grantedPolicyVersion = previousApproval.permissions[permission];
return grantedPolicyVersion !== undefined
&& grantedPolicyVersion !== SKIN_EXTENSION_PERMISSION_DEFINITIONS[permission].policyVersion;
});
const removedPermissions = Object.keys(previousApproval.permissions)
.filter((permission): permission is SkinExtensionPermissionId => KNOWN_PERMISSIONS.has(permission))
.filter((permission) => !nextManifest.permissions.includes(permission));
const apiVersionChanged = previousApproval.apiVersion !== nextManifest.apiVersion;
return {
addedPermissions,
changedMeaningPermissions,
removedPermissions,
apiVersionChanged,
requiresConsent: addedPermissions.length > 0 || changedMeaningPermissions.length > 0 || apiVersionChanged,
};
}
export function isSkinExtensionPermissionApproved(
approval: SkinExtensionApproval,
pluginId: string,
permission: SkinExtensionPermissionId,
): boolean {
return approval.pluginId === pluginId
&& approval.permissions[permission] === SKIN_EXTENSION_PERMISSION_DEFINITIONS[permission].policyVersion;
}
export function isSkinExtensionBootstrapHello(
event: { source: unknown; origin: string; data: unknown; ports: readonly unknown[] },
expectedSource: unknown,
expectedNonce: string,
): boolean {
if (event.source !== expectedSource || event.origin !== "null" || event.ports.length !== 1 || !isPlainRecord(event.data)) return false;
const data = event.data;
return Object.keys(data).length === 4
&& data.channel === SKIN_EXTENSION_MESSAGE_CHANNEL
&& data.type === "hello"
&& data.apiVersion === SKIN_EXTENSION_API_VERSION
&& data.nonce === expectedNonce;
}
export function parseSkinExtensionRequestMessage(value: unknown, expectedNonce: string): SkinExtensionRequestMessage | null {
if (!isPlainRecord(value) || !isPlainRecord(value.payload)) return null;
const expectedFields = ["channel", "apiVersion", "nonce", "id", "type", "permission", "payload"];
if (Object.keys(value).length !== expectedFields.length || expectedFields.some((field) => !(field in value))) return null;
if (Object.keys(value.payload).length !== 0) return null;
if (value.channel !== SKIN_EXTENSION_MESSAGE_CHANNEL || value.apiVersion !== SKIN_EXTENSION_API_VERSION
|| value.nonce !== expectedNonce || value.type !== "request") return null;
if (typeof value.id !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(value.id)) return null;
if (typeof value.permission !== "string" || !KNOWN_PERMISSIONS.has(value.permission)) return null;
return value as unknown as SkinExtensionRequestMessage;
}
/** Copies only the low-sensitivity fields registered for the prototype capability. */
export function sanitizeSkinExtensionSessionStatus(value: unknown): SkinExtensionSessionStatus {
if (!isPlainRecord(value) || typeof value.connected !== "boolean") {
throw new SkinExtensionValidationError("SKIN_EXTENSION_STATUS_INVALID", "The host session status is invalid.");
}
const channelName = value.channelName;
const memberCount = value.memberCount;
if (channelName !== null && typeof channelName !== "string") {
throw new SkinExtensionValidationError("SKIN_EXTENSION_STATUS_INVALID", "The host session status is invalid.");
}
if (!Number.isSafeInteger(memberCount) || (memberCount as number) < 0 || (memberCount as number) > 10000) {
throw new SkinExtensionValidationError("SKIN_EXTENSION_STATUS_INVALID", "The host session status is invalid.");
}
const safeChannelName = typeof channelName === "string"
? channelName.slice(0, 120).replace(/[\u0000-\u001f\u007f]/g, " ")
: null;
return Object.freeze({
connected: value.connected,
channelName: safeChannelName,
memberCount: memberCount as number,
});
}
+212
View File
@@ -0,0 +1,212 @@
import assert from "node:assert/strict";
import { readFile, readdir } from "node:fs/promises";
import test from "node:test";
import {
getSkinLayoutComponents,
getSkinLayoutComponent,
parseSkinLayoutJson,
SKIN_LAYOUT_COMPONENTS,
validateSkinLayout,
canEditSkinLayoutComponent,
} from "./skin-layout.js";
async function vueSources(directory: URL): Promise<string[]> {
const files = (await readdir(directory, { recursive: true })).filter((file) => file.endsWith(".vue"));
return Promise.all(files.map((file) => readFile(new URL(file.replaceAll("\\", "/"), directory), "utf8")));
}
test("the stable layout registry covers public skin hooks and excludes the admin console", async () => {
const [webClient, demo, sharedComponents, skinSwitcher, languageSwitcher, admin, adminComponents] = await Promise.all([
readFile(new URL("../../web/src/views/WebClient.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/views/DemoView.vue", import.meta.url), "utf8"),
vueSources(new URL("../../web/src/components/web-client/", import.meta.url)),
readFile(new URL("../../web/src/components/SkinSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/components/LanguageSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../../web/src/views/AdminView.vue", import.meta.url), "utf8"),
vueSources(new URL("../../web/src/components/admin/", import.meta.url)),
]);
const publicSource = [webClient, demo, ...sharedComponents, skinSwitcher, languageSwitcher].join("\n");
const publicParts = new Set([...publicSource.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
const interactiveParts = new Set<string>();
for (const match of publicSource.matchAll(/<[A-Za-z][\w.-]*\b[^>]*>/gs)) {
const attributes = match[0];
const part = attributes.match(/\bdata-ws-part="([^"]+)"/)?.[1];
if (!part) continue;
const isNativeControl = /^<(?:button|a|input|select|textarea)\b/i.test(attributes);
const hasButtonRole = /\brole="button"/.test(attributes);
const keyboardAction = /@keydown\.(?:enter|space)\b/.test(attributes);
// Native HTML drag gestures are desktop-only and do not make a row a 44px touch control.
if (isNativeControl || hasButtonRole || keyboardAction) interactiveParts.add(part);
}
const registered = new Set(SKIN_LAYOUT_COMPONENTS.map((component) => component.selectorPart));
for (const part of publicParts) assert.ok(registered.has(part), "Unregistered public layout hook: " + part);
const micStatus = getSkinLayoutComponent("voice.member.mic-status", "voice");
assert.equal(micStatus?.category, "core");
assert.equal(micStatus?.editable, true);
assert.ok(micStatus?.layoutModes.includes("visibility"));
assert.equal(getSkinLayoutComponent("voice.server-banner", "voice")?.editable, true);
for (const part of interactiveParts) {
const component = SKIN_LAYOUT_COMPONENTS.find((entry) => entry.id === part);
assert.ok(component, "Interactive public hook must have its own component metadata: " + part);
assert.ok(component.minTouchTarget >= 44, "Interactive public hook needs a 44px touch target: " + part);
assert.ok(component.minWidth >= 44 && component.minHeight >= 44, "Interactive public hook needs bounded minimum dimensions: " + part);
assert.ok(component.minScale >= 1, "Interactive public hook must not scale below its natural hit target: " + part);
}
assert.match(publicSource, /data-ws-part="demo\.voice-card"[\s\S]*?role="button"[\s\S]*?tabindex="0"[\s\S]*?@keydown\.enter[\s\S]*?@keydown\.space/);
assert.doesNotMatch([admin, ...adminComponents].join("\n"), /ws-skin-root|data-ws-page=/);
assert.ok(SKIN_LAYOUT_COMPONENTS.every((component) => !component.id.startsWith("admin.")));
});
test("valid layouts accept only bounded positions and safe visual tokens", () => {
const layout = validateSkinLayout({
schemaVersion: 1,
pages: {
home: {
desktop: {
"home.header": { x: -120, y: 40, scale: 1.25, order: -2, visible: true, foreground: "#aabbcc", radius: 16 },
"control.button": { background: "#010203", border: "#ffffff" },
},
mobile: { "home.join-card": { x: 8, scale: 0.9 } },
tablet: { "home.join-card": { width: 720, height: 460 } },
},
},
});
assert.equal(layout.pages.home?.desktop?.["home.header"]?.x, -120);
assert.equal(layout.pages.home?.desktop?.["home.header"]?.foreground, "#aabbcc");
assert.equal(layout.pages.home?.desktop?.["home.header"]?.order, -2);
assert.equal(layout.pages.home?.tablet?.["home.join-card"]?.width, 720);
assert.equal(getSkinLayoutComponents("home").some((component) => component.id === "home.join-card"), true);
assert.equal(getSkinLayoutComponents("voice").some((component) => component.id === "home.join-card"), false);
});
test("skin-authored component roots and nodes become independently editable layout parts", () => {
const maxRuntimeNodeId = `skin.voice.runtime_plugin_${"p".repeat(64)}__${"c".repeat(64)}.control-node-root-0`;
const dynamicIds = [
"skin.voice.toolbar",
"skin.voice.toolbar.node-root",
"skin.voice.toolbar.part-chat-list",
"skin.voice.toolbar.control-node-root-0",
"skin.voice.runtime_plugin_root_voice-toolbar",
"skin.voice.runtime_plugin_voice-surface__voice-ui",
"skin.voice.runtime_plugin_voice-surface__voice-ui.node-root",
"skin.voice.runtime_plugin_voice-surface__voice-ui.part-chat-list",
"skin.voice.runtime_plugin_voice-surface__voice-ui.control-part-join",
maxRuntimeNodeId,
];
const components = getSkinLayoutComponents("voice", dynamicIds);
assert.deepEqual(components.filter((component) => dynamicIds.includes(component.id)).map((component) => component.id), dynamicIds);
assert.ok(dynamicIds.every((id) => getSkinLayoutComponent(id, "voice")?.editable));
assert.equal(getSkinLayoutComponent("skin.home.toolbar", "voice"), undefined);
assert.equal(getSkinLayoutComponent("skin.voice.toolbar.node-root-onclick", "voice"), undefined);
const layout = validateSkinLayout({
schemaVersion: 1,
pages: { voice: { desktop: {
"skin.voice.toolbar": { x: 18, y: 12, visible: true },
"skin.voice.toolbar.node-root": { width: 720 },
"skin.voice.toolbar.part-chat-list": { visible: false },
"skin.voice.toolbar.control-node-root-0": { scale: 1, width: 60, height: 48 },
"skin.voice.runtime_plugin_root_voice-toolbar": { order: 2 },
"skin.voice.runtime_plugin_voice-surface__voice-ui": { width: 800 },
"skin.voice.runtime_plugin_voice-surface__voice-ui.part-chat-list": { visible: false },
"skin.voice.runtime_plugin_voice-surface__voice-ui.control-part-join": { width: 60, height: 48 },
} } },
});
assert.equal(layout.pages.voice?.desktop?.["skin.voice.toolbar.part-chat-list"]?.visible, false);
assert.equal(layout.pages.voice?.desktop?.["skin.voice.runtime_plugin_root_voice-toolbar"]?.order, 2);
assert.equal(layout.pages.voice?.desktop?.["skin.voice.runtime_plugin_voice-surface__voice-ui"]?.width, 800);
assert.equal(layout.pages.voice?.desktop?.["skin.voice.runtime_plugin_voice-surface__voice-ui.part-chat-list"]?.visible, false);
assert.equal(getSkinLayoutComponent("skin.voice.runtime_plugin_voice-surface__voice-ui.control-part-join")?.minTouchTarget, 44);
assert.equal(getSkinLayoutComponent(maxRuntimeNodeId)?.minTouchTarget, 44);
assert.equal(getSkinLayoutComponent("skin.voice.toolbar.control-node-root-0")?.minTouchTarget, 44);
assert.ok(getSkinLayoutComponent("skin.voice.toolbar.control-node-root-0")!.minScale >= 1);
assert.throws(() => validateSkinLayout({
schemaVersion: 1,
pages: { voice: { desktop: { "skin.home.toolbar": { x: 0 } } } },
}));
assert.throws(() => validateSkinLayout({
schemaVersion: 1,
pages: { voice: { desktop: { "skin.voice.toolbar.control-node-root-0": { scale: 0.8 } } } },
}));
});
test("layout validation fails closed for unknown pages, components, trusted notices, fields, and values", () => {
const invalidValues: unknown[] = [
{ schemaVersion: 2, pages: {} },
{ schemaVersion: 1, pages: { admin: { desktop: {} } } },
{ schemaVersion: 1, pages: { home: { desktop: { "home.not-registered": { x: 0 } } } } },
{ schemaVersion: 1, pages: { home: { desktop: { "home.security-note": { visible: false } } } } },
{ schemaVersion: 1, pages: { home: { desktop: { "home.security-note": { order: -1 } } } } },
{ schemaVersion: 1, pages: { home: { desktop: { app: { visible: false } } } } },
{ schemaVersion: 1, pages: { home: { desktop: { "home.header": { position: "fixed" } } } } },
{ schemaVersion: 1, pages: { home: { desktop: { "home.header": { x: 2001 } } } } },
{ schemaVersion: 1, pages: { home: { desktop: { "home.header": { order: 101 } } } } },
{ schemaVersion: 1, pages: { home: { desktop: { "home.header": { width: 8 } } } } },
{ schemaVersion: 1, pages: { home: { desktop: { "voice.connection-status": { visible: false } } } } },
{ schemaVersion: 1, pages: { home: { desktop: { "home.header": { background: "url(https://example.invalid)" } } } } },
];
for (const invalid of invalidValues) assert.throws(() => validateSkinLayout(invalid));
});
test("registered components carry accessibility, responsive, purpose, and data-scope metadata", () => {
assert.ok(SKIN_LAYOUT_COMPONENTS.length > 100);
for (const component of SKIN_LAYOUT_COMPONENTS) {
assert.ok(component.name.length > 0);
assert.notEqual(component.name, component.id, "registry names must be readable metadata rather than the ID repeated");
assert.ok(component.purpose.length > 0);
assert.ok(["core", "optional", "trusted-chrome"].includes(component.category));
if (component.editable) {
assert.deepEqual(component.allowedContainers, ["app"]);
assert.deepEqual(component.layoutModes, ["position", "size", "visibility", "appearance", "order"]);
assert.ok(component.minWidth > 0 && component.maxWidth >= component.minWidth);
assert.ok(component.minHeight > 0 && component.maxHeight >= component.minHeight);
assert.ok(component.minScale > 0 && component.maxScale >= component.minScale);
assert.ok(component.allowedStyleTokens.length > 0);
} else {
assert.deepEqual(component.allowedContainers, []);
assert.deepEqual(component.layoutModes, []);
assert.deepEqual(component.allowedStyleTokens, []);
}
assert.equal(component.keyboardBehavior, "host-native");
assert.equal(component.focusOrder, "host-dom");
assert.equal(component.accessibleNamePolicy, "preserve-host-name");
assert.ok(component.narrowScreenBehavior.length > 0);
assert.ok(component.dataSensitivity.length > 0);
}
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.connect")?.minTouchTarget, 44);
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.range")?.minTouchTarget, 44);
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "control.checkbox")?.minTouchTarget, 44);
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.feature")?.category, "optional");
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.security-note")?.category, "trusted-chrome");
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "home.identity-import.security")?.dataSensitivity, "identity");
assert.equal(SKIN_LAYOUT_COMPONENTS.find((component) => component.id === "demo.voice-card")?.minTouchTarget, 44);
});
test("trusted host components cannot be changed through a nested generic control", () => {
assert.equal(canEditSkinLayoutComponent("control.button", "home", ["home.form"]), true);
assert.equal(canEditSkinLayoutComponent("control.button", "home", ["home.identity-import.security"]), false);
assert.equal(canEditSkinLayoutComponent("control.button", "voice", ["voice.screen-share-error"]), false);
assert.equal(canEditSkinLayoutComponent("home.security-note", "home"), false);
});
test("touch controls cannot be shrunk below their registered hit-target bounds", () => {
assert.throws(() => validateSkinLayout({
schemaVersion: 1,
pages: { home: { desktop: { "home.connect": { scale: 0.75 } } } },
}));
assert.throws(() => validateSkinLayout({
schemaVersion: 1,
pages: { home: { desktop: { "control.button": { width: 20 } } } },
}));
assert.equal(validateSkinLayout({
schemaVersion: 1,
pages: { home: { desktop: { "home.feature": { width: 20, scale: 0.5 } } } },
}).pages.home?.desktop?.["home.feature"]?.width, 20);
});
test("layout JSON parsing rejects malformed and oversized documents", () => {
assert.throws(() => parseSkinLayoutJson("{"));
assert.throws(() => parseSkinLayoutJson(" ".repeat(128 * 1024 + 1)));
assert.deepEqual(parseSkinLayoutJson('{"schemaVersion":1,"pages":{}}'), { schemaVersion: 1, pages: {} });
});
+653
View File
@@ -0,0 +1,653 @@
export type SkinLayoutPage = "home" | "voice" | "demo";
export type SkinLayoutProfile = "desktop" | "tablet" | "mobile";
export interface SkinLayoutPlacement {
visible?: boolean;
x?: number;
y?: number;
scale?: number;
order?: number;
width?: number;
height?: number;
foreground?: string;
background?: string;
border?: string;
radius?: number;
}
export interface SkinLayoutDocument {
schemaVersion: 1;
pages: Partial<Record<SkinLayoutPage, Partial<Record<SkinLayoutProfile, Record<string, SkinLayoutPlacement>>>>>;
}
export interface SkinLayoutComponent {
id: string;
page: SkinLayoutPage | "common";
selectorPart: string;
controlKind?: string;
name: string;
purpose: "host-shell" | "host-action" | "session-content" | "identity-content" | "page-content" | "decoration" | "trusted-status";
category: "core" | "optional" | "trusted-chrome";
allowedContainers: readonly string[];
layoutModes: readonly ("position" | "size" | "visibility" | "appearance" | "order")[];
dataSensitivity: "none" | "public" | "session" | "identity";
keyboardBehavior: "host-native";
focusOrder: "host-dom";
accessibleNamePolicy: "preserve-host-name";
narrowScreenBehavior: "host-responsive" | "decorative" | "trusted-fixed";
minWidth: number;
minHeight: number;
maxWidth: number;
maxHeight: number;
minScale: number;
maxScale: number;
minTouchTarget: number;
allowedStyleTokens: readonly ("foreground" | "background" | "border" | "radius")[];
editable: boolean;
}
const AUTH_PASSWORD_PART_IDS = [
"auth.password.backdrop",
"auth.password.dialog",
"auth.password.decoration",
"auth.password.eyebrow",
"auth.password.title",
"auth.password.lead",
"auth.password.form",
"auth.password.label",
"auth.password.field",
"auth.password.field-icon",
"auth.password.error",
"auth.password.actions",
] as const;
const PUBLIC_PART_IDS = new Set<string>([
"app",
"app.toast",
...AUTH_PASSWORD_PART_IDS,
"control",
"demo.action.poke",
"demo.action.reconnect",
"demo.action.speaking",
"demo.actions",
"demo.actions.heading",
"demo.avatar",
"demo.badge",
"demo.brand",
"demo.channel",
"demo.channel.members",
"demo.channel.select",
"demo.channels",
"demo.channels.heading",
"demo.chat.composer",
"demo.chat.empty",
"demo.chat.heading",
"demo.chat.input",
"demo.chat.message",
"demo.chat.messages",
"demo.chat.send",
"demo.chat.tab",
"demo.chat.tabs",
"demo.header",
"demo.header-tools",
"demo.hero",
"demo.hero.description",
"demo.hero.online",
"demo.hero.title",
"demo.home-link",
"demo.language-switcher",
"demo.layout",
"demo.live",
"demo.main",
"demo.member-name",
"demo.member-status",
"demo.note",
"demo.poke-notification",
"demo.poke.dismiss",
"demo.reconnect",
"demo.reconnect.restore",
"demo.skin-switcher",
"demo.user",
"demo.voice-card",
"demo.voice-grid",
"demo.voice-heading",
"demo.wave",
"home",
"home.brand",
"home.community-dialog",
"home.connect",
"home.content",
"home.favorite-toggle",
"home.feature",
"home.features",
"home.field",
"home.field-label",
"home.footer",
"home.form",
"home.gateway-status",
"home.header",
"home.header-tools",
"home.hero",
"home.hero.description",
"home.hero.eyebrow",
"home.hero.title",
"home.identity",
"home.identity-actions",
"home.identity-export.button",
"home.identity-import-dialog",
"home.identity-import.cancel",
"home.identity-import.close",
"home.identity-import.drop-zone",
"home.identity-import.error",
"home.identity-import.file-button",
"home.identity-import.footer",
"home.identity-import.header",
"home.identity-import.open",
"home.identity-import.security",
"home.identity-import.submit",
"home.identity-import.textarea",
"home.join-card",
"home.join-card.sonar",
"home.join-card.waveform",
"home.join-description",
"home.join-title",
"home.notice",
"home.relay-choice",
"home.relay-choice.copy",
"home.security-note",
"home.server-history",
"home.server-history.favorite-toggle",
"home.server-history.group",
"home.server-history.item",
"home.server-history.select",
"home.server-target",
"home.visitors",
"language.menu",
"language.option",
"language.trigger",
"skin.menu",
"skin.option",
"skin.trigger",
"voice.activity",
"voice.activity-heading",
"voice.activity.artwork",
"voice.audio-dock",
"voice.audio-dock.microphone",
"voice.audio-dock.microphone-panel",
"voice.audio-dock.output",
"voice.audio-dock.output-panel",
"voice.audio-settings",
"voice.audio-settings.device-select",
"voice.audio-settings.device-select-trigger",
"voice.audio-settings.device-select-chevron",
"voice.audio-settings.device-select-menu",
"voice.audio-settings.device-select-option",
"voice.audio-status",
"voice.breadcrumbs",
"voice.channel-group",
"voice.channel-group.heading",
"voice.channel-group.members",
"voice.channel-tree.avatar",
"voice.channel-tree.branch",
"voice.channel-tree.count",
"voice.channel-tree.empty",
"voice.channel-tree.expander",
"voice.channel-tree.icon",
"voice.channel-tree.join-hint",
"voice.channel-tree.line",
"voice.channel-tree.list",
"voice.channel-tree.member",
"voice.channel-tree.member-away",
"voice.channel-tree.member-muted",
"voice.channel-tree.member-name",
"voice.channel-tree.member-screen-share",
"voice.channel-tree.member-speaking",
"voice.channel-tree.name",
"voice.channel-tree.node",
"voice.channel-tree.row",
"voice.server-switcher",
"voice.server-banner",
"voice.server-banner.body",
"voice.server-banner.icon",
"voice.server-banner.image",
"voice.server-banner.title",
"voice.server-banner.welcome",
"voice.server-switcher.current",
"voice.server-switcher.empty",
"voice.server-switcher.icon",
"voice.server-switcher.item",
"voice.server-switcher.label",
"voice.server-switcher.menu",
"voice.server-switcher.trigger",
"voice.chat",
"voice.chat.composer",
"voice.chat.empty",
"voice.chat.event",
"voice.chat.heading",
"voice.chat.message",
"voice.chat.message-avatar",
"voice.chat.message-body",
"voice.chat.message-bubble",
"voice.chat.messages",
"voice.chat.status",
"voice.chat.tab",
"voice.chat.tabs",
"voice.connection-status",
"voice.content",
"voice.context-menu",
"voice.context-menu-backdrop",
"voice.context-menu.header",
"voice.context-menu.move-submenu",
"voice.favorite-servers.add",
"voice.favorite-servers.avatar",
"voice.favorite-servers.current-toggle",
"voice.favorite-servers.dialog",
"voice.favorite-servers.dialog-backdrop",
"voice.favorite-servers.dialog.actions",
"voice.favorite-servers.dialog.cancel",
"voice.favorite-servers.dialog.close",
"voice.favorite-servers.dialog.field",
"voice.favorite-servers.dialog.form",
"voice.favorite-servers.dialog.header",
"voice.favorite-servers.dialog.hint",
"voice.favorite-servers.dialog.input",
"voice.favorite-servers.dialog.submit",
"voice.favorite-servers.dialog.target",
"voice.favorite-servers.favorite-toggle",
"voice.favorite-servers.rail",
"voice.favorite-servers.rail.item",
"voice.favorite-servers.rail.list",
"voice.favorite-servers.server",
"voice.favorite-servers.strip",
"voice.favorite-servers.strip.add",
"voice.favorite-servers.strip.favorite-toggle",
"voice.favorite-servers.strip.item",
"voice.favorite-servers.strip.server",
"voice.favorite-servers.switch-status",
"voice.favorite-servers.tooltip",
"voice.header",
"voice.header-actions",
"voice.member",
"voice.member-panel",
"voice.member-panel.channels",
"voice.member-panel.heading",
"voice.member-panel.search",
"voice.member-row",
"voice.member-row.avatar",
"voice.member-row.copy",
"voice.member-row.flags",
"voice.member-row.volume",
"voice.member.action-trigger",
"voice.member.avatar",
"voice.member.avatar-wrap",
"voice.member.live-indicator",
"voice.member.mic-status",
"voice.member.name",
"voice.member.share-actions",
"voice.member.status",
"voice.member.stop-share",
"voice.members",
"voice.members.empty",
"voice.mobile-more",
"voice.mobile-nav",
"voice.performance",
"voice.performance.metrics",
"voice.performance.panel",
"voice.performance.route",
"voice.performance.status",
"voice.performance.webrtc-stats",
"voice.poke",
"voice.screen-player",
"voice.screen-player.controls",
"voice.screen-player.exit",
"voice.screen-player.fullscreen",
"voice.screen-player.live",
"voice.screen-player.placeholder",
"voice.screen-player.source",
"voice.screen-player.stage",
"voice.screen-player.video",
"voice.screen-player.viewer-avatar",
"voice.screen-player.viewers",
"voice.screen-player.volume",
"voice.screen-share-error",
"voice.screen-share-settings",
"voice.screen-share-settings.actions",
"voice.screen-share-settings.fields",
"voice.screen-share-settings.heading",
"voice.screen-share-settings.note",
"voice.scroll",
"voice.shell",
"voice.whisper-strip",
"voice.workspace",
]);
const CONTROL_KINDS = ["button", "link", "input", "checkbox", "range", "select", "textarea", "menuitem", "draggable"] as const;
const TRUSTED_PART_IDS = new Set([
...AUTH_PASSWORD_PART_IDS,
"app",
"app.toast",
"home.security-note",
"home.identity-import.security",
"voice.connection-status",
"voice.screen-share-error",
]);
const DECORATIVE_PART_IDS = new Set([
"demo.avatar", "demo.badge", "demo.note", "demo.poke-notification", "demo.wave",
"home.feature", "home.features", "home.footer", "home.hero.eyebrow", "home.join-card.sonar",
"home.join-card.waveform", "home.visitors", "voice.activity.artwork", "voice.member.avatar-wrap",
"voice.member.live-indicator", "voice.performance.metrics", "voice.performance.webrtc-stats",
"voice.screen-player.viewer-avatar",
]);
const SHELL_PART_IDS = new Set([
"app", "home", "home.content", "home.form", "home.header", "voice.shell", "voice.workspace",
"voice.content", "demo.layout", "demo.main",
]);
const ACTION_PART_IDS = new Set([
"control", "home.connect", "home.favorite-toggle", "home.identity-actions", "home.identity-export.button",
"home.identity-import.cancel", "home.identity-import.close", "home.identity-import.file-button",
"home.identity-import.open", "home.identity-import.submit", "home.relay-choice.copy",
"home.server-history.favorite-toggle", "home.server-history.select", "language.trigger", "language.menu",
"language.option", "skin.trigger", "skin.menu", "skin.option", "voice.audio-dock.microphone",
"voice.audio-dock.output", "voice.audio-settings.device-select-trigger", "voice.context-menu", "voice.favorite-servers.add",
"voice.favorite-servers.current-toggle", "voice.favorite-servers.dialog.cancel",
"voice.favorite-servers.dialog.close", "voice.favorite-servers.dialog.submit",
"voice.favorite-servers.favorite-toggle", "voice.favorite-servers.strip.add",
"voice.favorite-servers.strip.favorite-toggle", "voice.member-row.copy", "voice.member-row.volume",
"voice.member.action-trigger", "voice.member.share-actions", "voice.member.stop-share", "voice.member.stop-share",
"voice.mobile-more", "voice.mobile-nav", "voice.poke", "voice.screen-player.controls",
"voice.screen-player.exit", "voice.screen-player.fullscreen", "voice.screen-player.volume",
"demo.action.poke", "demo.action.reconnect", "demo.action.speaking", "demo.channel.select",
"demo.chat.send", "demo.chat.tab", "demo.home-link", "demo.poke.dismiss", "demo.reconnect.restore",
"voice.channel-group.heading", "voice.chat.tab", "voice.favorite-servers.server",
"voice.favorite-servers.strip.server", "demo.voice-card", "home.identity-import.drop-zone",
"voice.channel-group", "voice.member-row", "voice.server-switcher.trigger", "voice.server-switcher.item",
"voice.channel-tree.expander", "voice.channel-tree.row", "demo.skin-switcher", "demo.language-switcher",
]);
const INTERACTIVE_PART_IDS = new Set([
"demo.action.poke", "demo.action.reconnect", "demo.action.speaking", "demo.channel.select",
"demo.chat.input", "demo.chat.send", "demo.chat.tab", "demo.home-link", "demo.poke.dismiss",
"demo.reconnect.restore", "home.connect", "home.favorite-toggle", "home.identity-export.button",
"home.identity-import.cancel", "home.identity-import.close", "home.identity-import.file-button",
"home.identity-import.open", "home.identity-import.submit", "home.identity-import.textarea",
"home.server-history.favorite-toggle", "home.server-history.select", "language.option",
"language.trigger", "skin.option", "skin.trigger", "voice.channel-group.heading", "voice.chat.tab",
"voice.favorite-servers.add", "voice.favorite-servers.current-toggle", "voice.favorite-servers.dialog.cancel",
"voice.favorite-servers.dialog.close", "voice.favorite-servers.dialog.input", "voice.favorite-servers.dialog.submit",
"voice.favorite-servers.favorite-toggle", "voice.favorite-servers.server", "voice.favorite-servers.strip.add",
"voice.favorite-servers.strip.favorite-toggle", "voice.favorite-servers.strip.server", "voice.member.action-trigger", "voice.member.stop-share",
"voice.server-switcher.trigger", "voice.server-switcher.item", "voice.channel-tree.expander", "voice.channel-tree.row",
"voice.audio-settings.device-select-trigger",
"voice.screen-player.exit", "voice.screen-player.fullscreen", "demo.voice-card",
"home.identity-import.drop-zone", "voice.channel-group", "voice.member-row", "demo.skin-switcher",
"demo.language-switcher",
]);
const IDENTITY_PART_IDS = new Set([
"home.identity", "home.identity-actions", "home.identity-export.button", "home.identity-import-dialog",
"home.identity-import.cancel", "home.identity-import.close", "home.identity-import.drop-zone",
"home.identity-import.error", "home.identity-import.file-button", "home.identity-import.footer",
"home.identity-import.header", "home.identity-import.open", "home.identity-import.submit",
"home.identity-import.textarea", "home.identity-import.security",
]);
const COMMON_PART_IDS = new Set([
...AUTH_PASSWORD_PART_IDS,
"app", "app.toast", "control", "skin.trigger", "skin.menu", "skin.option",
"language.trigger", "language.menu", "language.option",
]);
function pageOfPart(id: string): SkinLayoutPage | "common" | null {
if (COMMON_PART_IDS.has(id)) return "common";
if (id === "home" || id.startsWith("home.")) return "home";
if (id.startsWith("voice.")) return "voice";
if (id.startsWith("demo.")) return "demo";
return null;
}
const LAYOUT_MODES = ["position", "size", "visibility", "appearance", "order"] as const;
const STYLE_TOKENS = ["foreground", "background", "border", "radius"] as const;
const COMPONENT_NAME_PARTS: Record<string, string> = {
action: "Action", actions: "Actions", activity: "Activity", add: "Add", app: "Application", artwork: "Artwork",
audio: "Audio", avatar: "Avatar", backdrop: "Backdrop", badge: "Badge", body: "Body", brand: "Brand",
breadcrumbs: "Breadcrumbs", bubble: "Bubble", button: "Button", cancel: "Cancel", card: "Card",
channel: "Channel", channels: "Channels", chat: "Chat", checkbox: "Checkbox", choice: "Choice", close: "Close",
community: "Community", composer: "Composer", connect: "Connect", connection: "Connection", content: "Content",
context: "Context", control: "Control", controls: "Controls", copy: "Copy", current: "Current", demo: "Demo",
description: "Description", dialog: "Dialog", dismiss: "Dismiss", dock: "Dock", draggable: "Draggable",
drop: "Drop", empty: "Empty state", error: "Error", event: "Event", exit: "Exit", export: "Export",
eyebrow: "Eyebrow", favorite: "Favorite", feature: "Feature", features: "Features", field: "Field", fields: "Fields",
file: "File", flags: "Flags", footer: "Footer", form: "Form", fullscreen: "Fullscreen", gateway: "Gateway",
grid: "Grid", group: "Group", header: "Header", heading: "Heading", hero: "Hero", hint: "Hint", history: "History",
home: "Home page", identity: "Identity", import: "Import", indicator: "Indicator", input: "Input", item: "Item",
join: "Join", label: "Label", language: "Language", layout: "Layout", link: "Link", list: "List", live: "Live status",
main: "Main content", member: "Member", members: "Members", menu: "Menu", menuitem: "Menu item", message: "Message",
messages: "Messages", metrics: "Metrics", microphone: "Microphone", mobile: "Mobile", more: "More", move: "Move",
name: "Name", nav: "Navigation", note: "Note", notice: "Notice", notification: "Notification", online: "Online status",
open: "Open", option: "Option", output: "Output", panel: "Panel", performance: "Performance", placeholder: "Placeholder",
player: "Player", poke: "Poke", rail: "Rail", range: "Range", reconnect: "Reconnect", relay: "Relay", restore: "Restore",
route: "Route", row: "Row", screen: "Screen", scroll: "Scrollable area", search: "Search", security: "Security",
select: "Select", send: "Send", server: "Server", servers: "Servers", settings: "Settings", share: "Share",
shell: "Application shell", skin: "Skin", sonar: "Sonar effect", source: "Source", speaking: "Speaking status",
stage: "Stage", stats: "Statistics", status: "Status", stop: "Stop", strip: "Strip", submenu: "Submenu",
submit: "Submit", switch: "Switch", switcher: "Switcher", tab: "Tab", tabs: "Tabs", target: "Target", textarea: "Text area",
title: "Title", toast: "Notifications", toggle: "Toggle", tools: "Tools", tooltip: "Tooltip", trigger: "Trigger",
user: "User", video: "Video", viewer: "Viewer", viewers: "Viewers", visitors: "Visitors", voice: "Voice",
volume: "Volume", wave: "Wave", waveform: "Waveform", webrtc: "WebRTC", whisper: "Whisper", workspace: "Workspace",
wrap: "Wrapper", zone: "Drop zone",
};
function componentName(id: string): string {
return id.split(".").map((part) => part.split("-").map((word) => COMPONENT_NAME_PARTS[word]
?? (word.charAt(0).toUpperCase() + word.slice(1))).join(" ")).join(" · ");
}
function describeComponent(id: string, page: SkinLayoutPage | "common", controlKind?: string): SkinLayoutComponent {
const category: SkinLayoutComponent["category"] = TRUSTED_PART_IDS.has(id) ? "trusted-chrome"
: DECORATIVE_PART_IDS.has(id) ? "optional" : "core";
const purpose: SkinLayoutComponent["purpose"] = TRUSTED_PART_IDS.has(id) ? "trusted-status"
: SHELL_PART_IDS.has(id) ? "host-shell"
: ACTION_PART_IDS.has(id) || Boolean(controlKind) ? "host-action"
: IDENTITY_PART_IDS.has(id) ? "identity-content"
: DECORATIVE_PART_IDS.has(id) ? "decoration"
: page === "voice" ? "session-content" : "page-content";
const allowedContainers = category === "trusted-chrome" ? [] : ["app"];
const editable = category !== "trusted-chrome";
const isControl = editable && (Boolean(controlKind) || id === "control" || purpose === "host-action" || INTERACTIVE_PART_IDS.has(id));
return {
id,
page,
selectorPart: id.startsWith("control.") ? "control" : id,
...(controlKind ? { controlKind } : {}),
name: componentName(id),
purpose,
category,
allowedContainers,
layoutModes: editable ? LAYOUT_MODES : [],
dataSensitivity: IDENTITY_PART_IDS.has(id) ? "identity" : page === "voice" ? "session" : purpose === "decoration" ? "none" : "public",
keyboardBehavior: "host-native",
focusOrder: "host-dom",
accessibleNamePolicy: "preserve-host-name",
narrowScreenBehavior: category === "trusted-chrome" ? "trusted-fixed" : category === "optional" ? "decorative" : "host-responsive",
minWidth: editable ? isControl ? 44 : 12 : 0,
minHeight: editable ? isControl ? 44 : 12 : 0,
maxWidth: editable ? isControl ? 1600 : 2400 : 0,
maxHeight: editable ? isControl ? 1200 : 2400 : 0,
minScale: editable ? isControl ? 1 : 0.5 : 1,
maxScale: editable ? isControl ? 3 : 4 : 1,
minTouchTarget: isControl ? 44 : 0,
allowedStyleTokens: editable ? STYLE_TOKENS : [],
editable,
};
}
const regularComponents: SkinLayoutComponent[] = [...PUBLIC_PART_IDS].flatMap((id) => {
const page = pageOfPart(id);
return page ? [describeComponent(id, page)] : [];
});
const virtualControls: SkinLayoutComponent[] = CONTROL_KINDS.map((kind) => ({
...describeComponent("control." + kind, "common", kind),
}));
export const SKIN_LAYOUT_COMPONENTS: readonly SkinLayoutComponent[] = [
...regularComponents,
...virtualControls,
];
const componentById = new Map(SKIN_LAYOUT_COMPONENTS.map((component) => [component.id, component]));
function dynamicSkinPartPage(id: string): SkinLayoutPage | undefined {
const match = /^skin\.(home|voice|demo)\.((?:[a-z][a-z0-9-]{0,63}|runtime_plugin_root_[a-z][a-z0-9-]{0,63}|runtime_plugin_[a-z][a-z0-9-]{0,63}__[a-z][a-z0-9-]{0,63}))(?:\.(control-)?(node-root(?:-\d+){0,32}|part-[a-z][a-z0-9-]{0,63}))?$/.exec(id);
return match?.[1] as SkinLayoutPage | undefined;
}
function isDynamicSkinControl(id: string): boolean {
return /^skin\.(?:home|voice|demo)\.(?:[a-z][a-z0-9-]{0,63}|runtime_plugin_root_[a-z][a-z0-9-]{0,63}|runtime_plugin_[a-z][a-z0-9-]{0,63}__[a-z][a-z0-9-]{0,63})\.control-(?:node-root(?:-\d+){0,32}|part-[a-z][a-z0-9-]{0,63})$/.test(id);
}
const dynamicSkinPartCache = new Map<string, SkinLayoutComponent>();
function dynamicSkinLayoutComponent(id: string, page: SkinLayoutPage): SkinLayoutComponent {
let component = dynamicSkinPartCache.get(id);
if (!component) {
component = describeComponent(id, page, isDynamicSkinControl(id) ? "button" : undefined);
if (dynamicSkinPartCache.size >= 4096) dynamicSkinPartCache.clear();
dynamicSkinPartCache.set(id, component);
}
return component;
}
/** Dynamic IDs are generated only for declared skin component roots and nodes. */
export function getSkinLayoutComponents(page: SkinLayoutPage, dynamicParts: readonly string[] = []): SkinLayoutComponent[] {
const components = SKIN_LAYOUT_COMPONENTS.filter((component) => component.page === "common" || component.page === page);
const seen = new Set(components.map((component) => component.id));
for (const id of dynamicParts) {
if (seen.has(id) || dynamicSkinPartPage(id) !== page) continue;
seen.add(id);
components.push(dynamicSkinLayoutComponent(id, page));
}
return components;
}
export function getSkinLayoutComponent(id: string, page?: SkinLayoutPage): SkinLayoutComponent | undefined {
const component = componentById.get(id)
?? (dynamicSkinPartPage(id) ? dynamicSkinLayoutComponent(id, dynamicSkinPartPage(id)!) : undefined);
if (!component || (page && component.page !== "common" && component.page !== page)) return undefined;
return component;
}
export function canEditSkinLayoutComponent(id: string, page: SkinLayoutPage, ancestorIds: readonly string[] = []): boolean {
const component = getSkinLayoutComponent(id, page);
if (!component?.editable) return false;
return ancestorIds.every((ancestorId) => getSkinLayoutComponent(ancestorId, page)?.category !== "trusted-chrome");
}
export function getSkinLayoutComponentId(part: string | undefined, controlKind?: string): string | null {
if (!part) return null;
if (part === "control" && controlKind) return "control." + controlKind;
return part;
}
const ALLOWED_PLACEMENT_FIELDS = new Set([
"visible", "x", "y", "scale", "order", "width", "height", "foreground", "background", "border", "radius",
]);
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function assertOnlyKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>, context: string): void {
for (const key of Object.keys(value)) {
if (!allowed.has(key)) throw new Error(context + " contains an unknown field: " + key);
}
}
function readNumber(value: unknown, key: string, minimum: number, maximum: number): number | undefined {
if (value === undefined) return undefined;
if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum) {
throw new Error("Skin layout field " + key + " is outside its allowed range.");
}
return value;
}
function readColor(value: unknown, key: string): string | undefined {
if (value === undefined) return undefined;
if (typeof value !== "string" || !/^#[0-9a-f]{6}$/i.test(value)) throw new Error("Skin layout field " + key + " must be a six-digit hex color.");
return value.toLowerCase();
}
export function validateSkinLayout(value: unknown): SkinLayoutDocument {
if (!isRecord(value) || value.schemaVersion !== 1 || !isRecord(value.pages)) {
throw new Error("Skin layout must use schemaVersion 1 and contain a pages object.");
}
assertOnlyKeys(value, new Set(["schemaVersion", "pages"]), "Skin layout");
const pages: SkinLayoutDocument["pages"] = {};
let placementCount = 0;
for (const [pageKey, pageValue] of Object.entries(value.pages)) {
if (!(["home", "voice", "demo"] as string[]).includes(pageKey) || !isRecord(pageValue)) {
throw new Error("Skin layout contains an unsupported page.");
}
assertOnlyKeys(pageValue, new Set(["desktop", "tablet", "mobile"]), "Skin layout page");
const profiles: Partial<Record<SkinLayoutProfile, Record<string, SkinLayoutPlacement>>> = {};
for (const profile of ["desktop", "tablet", "mobile"] as const) {
const profileValue = pageValue[profile];
if (profileValue === undefined) continue;
if (!isRecord(profileValue)) throw new Error("Skin layout profile must be a component map.");
const placements: Record<string, SkinLayoutPlacement> = {};
for (const [id, rawPlacement] of Object.entries(profileValue)) {
placementCount += 1;
if (placementCount > 512) throw new Error("Skin layout contains too many component placements.");
const component = getSkinLayoutComponent(id, pageKey as SkinLayoutPage);
if (!component) throw new Error("Skin layout references an unknown component: " + id);
if (!component.editable) throw new Error("Skin layout cannot change trusted component: " + id);
if (!isRecord(rawPlacement)) throw new Error("Skin component placement must be an object.");
assertOnlyKeys(rawPlacement, ALLOWED_PLACEMENT_FIELDS, "Skin component placement");
const supportedFields = new Set<string>();
if (component.layoutModes.includes("visibility")) supportedFields.add("visible");
if (component.layoutModes.includes("position")) { supportedFields.add("x"); supportedFields.add("y"); }
if (component.layoutModes.includes("size")) { supportedFields.add("scale"); supportedFields.add("width"); supportedFields.add("height"); }
if (component.layoutModes.includes("appearance")) component.allowedStyleTokens.forEach((token) => supportedFields.add(token));
if (component.layoutModes.includes("order")) supportedFields.add("order");
assertOnlyKeys(rawPlacement, supportedFields, "Skin component placement");
const placement: SkinLayoutPlacement = {};
if (rawPlacement.visible !== undefined) {
if (typeof rawPlacement.visible !== "boolean") throw new Error("Skin layout visible must be a boolean.");
placement.visible = rawPlacement.visible;
}
const x = readNumber(rawPlacement.x, "x", -2000, 2000);
const y = readNumber(rawPlacement.y, "y", -2000, 2000);
const scale = readNumber(rawPlacement.scale, "scale", component.minScale, component.maxScale);
const order = readNumber(rawPlacement.order, "order", -100, 100);
const width = readNumber(rawPlacement.width, "width", component.minWidth, component.maxWidth);
const height = readNumber(rawPlacement.height, "height", component.minHeight, component.maxHeight);
const radius = readNumber(rawPlacement.radius, "radius", 0, 64);
if (x !== undefined) placement.x = x;
if (y !== undefined) placement.y = y;
if (scale !== undefined) placement.scale = scale;
if (order !== undefined) placement.order = order;
if (width !== undefined) placement.width = width;
if (height !== undefined) placement.height = height;
if (radius !== undefined) placement.radius = radius;
const foreground = readColor(rawPlacement.foreground, "foreground");
const background = readColor(rawPlacement.background, "background");
const border = readColor(rawPlacement.border, "border");
if (foreground !== undefined) placement.foreground = foreground;
if (background !== undefined) placement.background = background;
if (border !== undefined) placement.border = border;
placements[id] = placement;
}
profiles[profile] = placements;
}
pages[pageKey as SkinLayoutPage] = profiles;
}
return { schemaVersion: 1, pages };
}
export function parseSkinLayoutJson(source: string): SkinLayoutDocument {
if (!source || new TextEncoder().encode(source).byteLength > 128 * 1024) {
throw new Error("Skin layout must be smaller than 128 KiB.");
}
let value: unknown;
try { value = JSON.parse(source); }
catch { throw new Error("Skin layout is not valid JSON."); }
return validateSkinLayout(value);
}
+246
View File
@@ -0,0 +1,246 @@
import {
parseSkinPluginDocument,
skinPluginWidgetPermissions,
type SkinPluginComponent,
type SkinPluginDocument,
type SkinPluginNode,
} from "./skin-plugin.js";
/** Normalize an older declarative package before editing while preserving its validated data. */
export function editableSkinPluginDocument(input: unknown): SkinPluginDocument {
// The package parser materializes the schema-v1 default `mode: "widget"` in
// its normalized object. Remove that derived field before validating the
// normalized document again, since schema v1 itself does not declare mode.
const source = input && typeof input === "object" && !Array.isArray(input)
&& (input as { schemaVersion?: unknown }).schemaVersion === 1
&& Array.isArray((input as { components?: unknown }).components)
? {
...(input as Record<string, unknown>),
components: ((input as { components: unknown[] }).components).map((component) => {
if (!component || typeof component !== "object" || Array.isArray(component)
|| (component as { mode?: unknown }).mode !== "widget") return component;
const withoutDefaultMode = { ...(component as Record<string, unknown>) };
delete withoutDefaultMode.mode;
return withoutDefaultMode;
}),
}
: input;
const parsed = parseSkinPluginDocument(source);
if (parsed.schemaVersion === 3) return parsed;
const components = parsed.components.map((component) => {
const permissions = new Set(component.permissions);
const visit = (node: SkinPluginNode) => {
if (node.widget) skinPluginWidgetPermissions(node.widget, node.options).forEach((permission) => permissions.add(permission));
node.children?.forEach(visit);
};
visit(component.root);
return { ...component, permissions: [...permissions] };
});
return parseSkinPluginDocument({ schemaVersion: 3, components });
}
export function assertSkinPluginAuthoringDocument(input: unknown): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
const visit = (node: SkinPluginNode) => {
const reserved = Object.keys(node.attributes ?? {}).find((key) => key.startsWith("data-ws-"));
if (reserved) throw new Error("The " + reserved + " attribute is owned by WebSpeak and cannot be authored by a skin.");
node.children?.forEach(visit);
};
document.components.forEach((component) => visit(component.root));
return document;
}
function checked(input: unknown): SkinPluginDocument {
return editableSkinPluginDocument(input);
}
function componentIndex(document: SkinPluginDocument, id: string): number {
const index = document.components.findIndex((component) => component.id === id);
if (index < 0) throw new Error("The skin component no longer exists.");
return index;
}
function parentNode(component: SkinPluginComponent, path: readonly number[]): SkinPluginNode {
if (!path.length) return component.root;
let current = component.root;
for (const index of path) {
const child = current.children?.[index];
if (!child) throw new Error("The selected node no longer exists.");
current = child;
}
return current;
}
function nodeAt(component: SkinPluginComponent, path: readonly number[]): SkinPluginNode {
return parentNode(component, path);
}
function assertChildIndex(index: number, length: number): void {
if (!Number.isInteger(index) || index < 0 || index >= length) throw new Error("The selected node no longer exists.");
}
function updateTree(
input: SkinPluginDocument,
componentId: string,
update: (component: SkinPluginComponent) => SkinPluginComponent,
): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
const index = componentIndex(document, componentId);
const components = [...document.components];
components[index] = update(components[index]);
return checked({ schemaVersion: 3, components });
}
export function addSkinPluginComponent(input: SkinPluginDocument, component: unknown): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
return checked({ schemaVersion: 3, components: [...document.components, component] });
}
export function replaceSkinPluginComponent(input: SkinPluginDocument, componentId: string, component: unknown): SkinPluginDocument {
return updateTree(input, componentId, () => component as SkinPluginComponent);
}
export function removeSkinPluginComponent(input: SkinPluginDocument, componentId: string): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
componentIndex(document, componentId);
return checked({ schemaVersion: 3, components: document.components.filter((component) => component.id !== componentId) });
}
export function moveSkinPluginComponent(
input: SkinPluginDocument,
componentId: string,
direction: -1 | 1,
): SkinPluginDocument {
const document = editableSkinPluginDocument(input);
const from = componentIndex(document, componentId);
const to = from + direction;
if (to < 0 || to >= document.components.length) return document;
const components = [...document.components];
[components[from], components[to]] = [components[to], components[from]];
return checked({ schemaVersion: 3, components });
}
export function addSkinPluginNode(
input: SkinPluginDocument,
componentId: string,
parentPath: readonly number[],
node: unknown,
): SkinPluginDocument {
return updateTree(input, componentId, (component) => {
const parent = nodeAt(component, parentPath);
if (!parent.tag) throw new Error("Only element nodes can contain children.");
const children = [...(parent.children ?? []), node as SkinPluginNode];
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function addSkinPluginNodeSibling(
input: SkinPluginDocument,
componentId: string,
path: readonly number[],
node: unknown,
): SkinPluginDocument {
if (!path.length) throw new Error("A component root cannot have siblings.");
return updateTree(input, componentId, (component) => {
const parentPath = path.slice(0, -1);
const parent = nodeAt(component, parentPath);
if (!parent.tag) throw new Error("Only element nodes can contain children.");
const index = path[path.length - 1];
const children = [...(parent.children ?? [])];
assertChildIndex(index, children.length);
children.splice(index + 1, 0, node as SkinPluginNode);
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function replaceSkinPluginNode(
input: SkinPluginDocument,
componentId: string,
path: readonly number[],
node: unknown,
): SkinPluginDocument {
return updateTree(input, componentId, (component) => ({
...component,
root: replaceNodeAtPath(component.root, path, node as SkinPluginNode),
}));
}
export function removeSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginDocument {
if (!path.length) throw new Error("A component root cannot be removed; delete the component instead.");
return updateTree(input, componentId, (component) => {
const parentPath = path.slice(0, -1);
const parent = nodeAt(component, parentPath);
const index = path[path.length - 1];
const children = [...(parent.children ?? [])];
assertChildIndex(index, children.length);
children.splice(index, 1);
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function moveSkinPluginNode(
input: SkinPluginDocument,
componentId: string,
path: readonly number[],
direction: -1 | 1,
): SkinPluginDocument {
if (!path.length) throw new Error("A component root cannot be reordered.");
return updateTree(input, componentId, (component) => {
const parentPath = path.slice(0, -1);
const parent = nodeAt(component, parentPath);
const children = [...(parent.children ?? [])];
const from = path[path.length - 1];
const to = from + direction;
assertChildIndex(from, children.length);
if (from < 0 || from >= children.length || to < 0 || to >= children.length) return component;
[children[from], children[to]] = [children[to], children[from]];
return { ...component, root: replaceNodeAtPath(component.root, parentPath, { ...parent, children }) };
});
}
export function replaceNodeAtPath(root: SkinPluginNode, path: readonly number[], replacement: SkinPluginNode): SkinPluginNode {
if (!path.length) return replacement;
const [index, ...rest] = path;
const children = [...(root.children ?? [])];
assertChildIndex(index, children.length);
children[index] = replaceNodeAtPath(children[index], rest, replacement);
return { ...root, children };
}
export function getSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginNode {
const document = editableSkinPluginDocument(input);
return nodeAt(document.components[componentIndex(document, componentId)], path);
}
/** Give a duplicated subtree fresh stable layout parts so it cannot alias its source nodes. */
export function duplicateSkinPluginNode(input: SkinPluginDocument, componentId: string, path: readonly number[]): SkinPluginNode {
if (!path.length) throw new Error("A component root cannot be duplicated.");
const document = editableSkinPluginDocument(input);
const component = document.components[componentIndex(document, componentId)];
const source = nodeAt(component, path);
const usedParts = new Set<string>();
const exclude = (node: SkinPluginNode, currentPath: readonly number[]): void => {
if (currentPath.length === path.length && currentPath.every((index, position) => index === path[position])) return;
if (node.part) usedParts.add(node.part);
node.children?.forEach((child, index) => exclude(child, [...currentPath, index]));
};
exclude(component.root, []);
const copy = JSON.parse(JSON.stringify(source)) as SkinPluginNode;
const refreshParts = (node: SkinPluginNode): void => {
if (node.part) {
const stem = node.part.slice(0, 54) + "-copy";
let candidate = stem;
let suffix = 2;
while (usedParts.has(candidate)) {
const tail = "-" + suffix++;
candidate = stem.slice(0, 64 - tail.length) + tail;
}
node.part = candidate;
usedParts.add(candidate);
}
node.children?.forEach(refreshParts);
};
refreshParts(copy);
return copy;
}
+797
View File
@@ -0,0 +1,797 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import {
parseSkinPluginDocument,
parseSkinPluginJson,
skinPluginWidgetPermissions,
type SkinPluginDocument,
type SkinPluginNode,
} from "./skin-plugin.js";
function validDocument(): SkinPluginDocument {
return {
schemaVersion: 1,
components: [{
id: "channel-list",
name: "Channel list",
page: "voice",
accessibleName: "TeamSpeak channels",
permissions: ["session.channels.read", "session.channel.join"],
actions: {
join: { type: "voice.joinChannel", args: { channelId: "{{channel.id}}" } },
},
root: {
tag: "nav",
repeat: { path: "session.channels", as: "channel" },
children: [{
tag: "button",
attributes: { type: "button", "aria-label": "{{channel.name}}" },
events: { dblclick: "join" },
children: [{ text: "{{channel.name}}" }],
}],
},
}],
};
}
function errorCode(run: () => unknown, expected: string): void {
assert.throws(run, (error: unknown) => error instanceof Error
&& "code" in error && error.code === expected);
}
test("skin plugin accepts a bounded channel list with a double-click host action", () => {
const parsed = parseSkinPluginDocument(validDocument());
assert.equal(parsed.schemaVersion, 1, "legacy documents retain their original capability boundary");
assert.equal(parsed.components[0].mode, "widget");
assert.equal(parsed.components[0].root.repeat?.path, "session.channels");
assert.equal(parsed.components[0].root.children?.[0].events?.dblclick, "join");
});
test("component schema v2 can replace a public page and compose trusted host widgets", () => {
const document = validDocument();
document.schemaVersion = 2;
document.components[0].mode = "surface";
document.components[0].permissions = ["ui.surface.replace"];
document.components[0].actions = {};
document.components[0].root = {
tag: "main",
className: "custom-voice-shell",
children: [
{ widget: "voice.channel-panel", part: "channels" },
{ widget: "voice.chat-panel" },
],
};
const parsed = parseSkinPluginDocument(document);
assert.equal(parsed.components[0].mode, "surface");
assert.deepEqual(parsed.components[0].root.children?.map((node) => node.widget), ["voice.channel-panel", "voice.chat-panel"]);
assert.throws(() => parseSkinPluginDocument({ ...document, schemaVersion: 1 }), { code: "SKIN_PLUGIN_SCHEMA_UNSUPPORTED" });
});
test("page surfaces and stateful host widgets cannot be duplicated", () => {
const document = validDocument();
document.schemaVersion = 2;
document.components[0].mode = "surface";
document.components[0].permissions.push("ui.surface.replace");
document.components[0].root = { tag: "main", children: [{ widget: "voice.chat-panel" }] };
document.components.push({
...document.components[0],
id: "second-surface",
mode: "widget",
root: { tag: "section", children: [{ widget: "voice.chat-panel" }] },
});
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_WIDGET_DUPLICATE");
document.components[1].mode = "surface";
document.components[1].root.children = [{ widget: "voice.member-cards" }];
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_SURFACE_DUPLICATE");
});
test("replacing a built-in public page requires an explicit user approval capability", () => {
const document = validDocument();
document.schemaVersion = 2;
document.components[0].mode = "surface";
document.components[0].permissions = [];
document.components[0].actions = {};
document.components[0].root = { tag: "main", children: [{ tag: "h1", children: [{ text: "Custom client" }] }] };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["ui.surface.replace"];
assert.deepEqual(parseSkinPluginDocument(document).components[0].permissions, ["ui.surface.replace"]);
});
test("custom surfaces can safely render and switch unified favorite and recent server entries", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].permissions = ["servers.quickList.read", "servers.quickList.switch"];
document.components[0].actions = {
switch: { type: "quickServers.switch", args: { quickServerId: "{{server.id}}" } },
};
document.components[0].root = {
tag: "nav",
repeat: { path: "servers.quickList", as: "server" },
children: [{
tag: "button",
attributes: { "aria-disabled": "{{server.switchRestricted}}", title: "{{server.switchTitle}}" },
events: { dblclick: "switch" },
children: [{ text: "{{server.label}}" }],
}],
};
const parsed = parseSkinPluginDocument(document).components[0];
assert.equal(parsed.root.repeat?.path, "servers.quickList");
assert.equal(parsed.root.children?.[0].attributes?.["aria-disabled"], "{{server.switchRestricted}}");
assert.equal(parsed.root.children?.[0].attributes?.title, "{{server.switchTitle}}");
assert.equal(parsed.actions.switch.type, "quickServers.switch");
document.components[0].permissions = ["servers.quickList.read"];
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
});
test("server list skins may display only the host-provided TeamSpeak icon image", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].permissions = ["servers.quickList.read"];
document.components[0].root = {
tag: "nav",
repeat: { path: "servers.quickList", as: "server" },
children: [{ tag: "img", attributes: { src: "{{server.icon}}", alt: "" } }],
};
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].attributes?.src, "{{server.icon}}");
document.components[0].root.children![0].attributes!.src = "https://example.com/icon.png";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
document.components[0].root.children![0].attributes!.src = "{{server.icon}}";
document.components[0].root.children![0].tag = "span";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
});
test("chat panel visibility is host-controlled and its toggle requires chat access", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].permissions = ["chat.channel.read"];
document.components[0].actions = {
toggle: { type: "chat.togglePanel", args: {} },
};
document.components[0].root = {
tag: "button",
attributes: { "aria-expanded": "{{chat.status.panelOpen}}" },
events: { click: "toggle" },
children: [{ text: "{{chat.status.tabLabel}}" }],
};
const parsed = parseSkinPluginDocument(document).components[0];
assert.equal(parsed.actions.toggle.type, "chat.togglePanel");
assert.equal(parsed.root.attributes?.["aria-expanded"], "{{chat.status.panelOpen}}");
document.components[0].permissions = [];
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
});
test("copying a session invite link is an explicit permission-gated host action", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {
invite: { type: "session.copyInviteLink", args: {} },
};
document.components[0].root = {
tag: "button",
events: { click: "invite" },
};
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["session.invite.copy"];
const parsed = parseSkinPluginDocument(document).components[0];
assert.equal(parsed.actions.invite.type, "session.copyInviteLink");
assert.equal(Object.keys(parsed.actions.invite.args).length, 0);
});
test("host widget references stay allowlisted and cannot be used on the demo page", () => {
const unknownWidget = validDocument();
unknownWidget.schemaVersion = 2;
unknownWidget.components[0].root = { tag: "main", children: [{ widget: "filesystem.read" as never }] };
errorCode(() => parseSkinPluginDocument(unknownWidget), "SKIN_PLUGIN_WIDGET_INVALID");
const demoWidget = validDocument();
demoWidget.schemaVersion = 2;
demoWidget.components[0].page = "demo";
demoWidget.components[0].root = { tag: "main", children: [{ widget: "voice.chat-panel" }] };
errorCode(() => parseSkinPluginDocument(demoWidget), "SKIN_PLUGIN_WIDGET_INVALID");
});
test("starting screen share from a skin host widget requires its own permission", () => {
const document = validDocument();
document.schemaVersion = 2;
document.components[0].root = { tag: "main", children: [{ widget: "voice.screen-share-start" }] };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["voice.screenShare.control"];
document.components[0].actions = {};
const parsed = parseSkinPluginDocument(document);
assert.equal(parsed.components[0].root.children?.[0].widget, "voice.screen-share-start");
});
test("server banner host widget only exposes public session status fields", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].root = { tag: "main", children: [{ widget: "voice.server-banner" }] };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["session.status.read"];
const parsed = parseSkinPluginDocument(document);
assert.equal(parsed.components[0].root.children?.[0].widget, "voice.server-banner");
});
test("home connection status widget requires the public session status permission", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].page = "home";
document.components[0].actions = {};
document.components[0].root = { tag: "main", children: [{ widget: "home.connection-status" }] };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["session.status.read"];
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].widget, "home.connection-status");
assert.deepEqual(skinPluginWidgetPermissions("home.connection-status"), ["session.status.read"]);
});
test("generic identity-provider entry is a host button with no connection permission or skin action", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].page = "home";
document.components[0].permissions = [];
document.components[0].actions = {};
document.components[0].root = {
tag: "main",
children: [{ widget: "home.identity-provider", options: { identityProviderId: "myts", identityProviderLabel: "myts" } }],
};
const parsed = parseSkinPluginDocument(document);
assert.equal(parsed.components[0].root.children?.[0].widget, "home.identity-provider");
assert.deepEqual(parsed.components[0].root.children?.[0].options, { identityProviderId: "myts", identityProviderLabel: "myts" });
assert.deepEqual(skinPluginWidgetPermissions("home.identity-provider"), []);
assert.deepEqual(Object.keys(parsed.components[0].actions), []);
});
test("skin SVG illustrations support bounded path and circle geometry attributes", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].root = {
tag: "svg",
attributes: { viewbox: "0 0 100 100", role: "img" },
children: [
{ tag: "circle", attributes: { cx: 25, cy: 30, r: 12, fill: "#b0f49b" } },
{ tag: "path", attributes: { d: "M10 20h30v40", stroke: "white", "stroke-width": 2, fill: "none" } },
],
};
const parsed = parseSkinPluginDocument(document).components[0].root;
assert.equal(parsed.children?.[0].attributes?.cx, 25);
assert.equal(parsed.children?.[1].attributes?.d, "M10 20h30v40");
document.components[0].root.children![1].attributes!.d = "x".repeat(513);
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
});
test("schema v3 host audio controls require read and control permissions while v2 remains compatible", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].root = { tag: "main", children: [{ widget: "voice.audio-controls" }] };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["audio.status.read", "audio.microphone.control"];
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["audio.status.read", "audio.microphone.control", "audio.output.control"];
document.components[0].root.children![0] = { widget: "voice.audio-controls" };
const genericAudioControls = parseSkinPluginDocument(document).components[0].root.children?.[0];
assert.equal(genericAudioControls?.widget, "voice.audio-controls");
assert.equal(genericAudioControls?.options, undefined);
const invalidLayout = structuredClone(document);
invalidLayout.components[0].root.children![0] = { widget: "voice.audio-controls", options: { layout: "room-panel" } as never };
errorCode(() => parseSkinPluginDocument(invalidLayout), "SKIN_PLUGIN_WIDGET_OPTIONS_INVALID");
const legacyDocument = structuredClone(document);
legacyDocument.schemaVersion = 2;
legacyDocument.components[0].permissions = [];
legacyDocument.components[0].root.children![0] = { widget: "voice.audio-controls" };
assert.equal(parseSkinPluginDocument(legacyDocument).components[0].root.children?.[0].widget, "voice.audio-controls");
});
test("schema v3 member cards require a separate permission to display cached profile pictures", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].permissions = ["session.members.read", "voice.screenShare.read", "voice.screenShare.control"];
document.components[0].root = { tag: "main", children: [{ widget: "voice.member-cards" }] };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions.push("session.memberAvatars.read");
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].widget, "voice.member-cards");
});
test("generic home identity-provider widget validates provider metadata", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].page = "home";
document.components[0].permissions = [];
document.components[0].actions = {};
document.components[0].root = {
tag: "main",
children: [{ widget: "home.identity-provider", options: { identityProviderId: "myts", identityProviderLabel: "myts" } }],
};
const widget = parseSkinPluginDocument(document).components[0].root.children?.[0];
assert.equal(widget?.widget, "home.identity-provider");
assert.deepEqual(widget?.options, { identityProviderId: "myts", identityProviderLabel: "myts" });
const missing = structuredClone(document);
missing.components[0].root.children![0] = { widget: "home.identity-provider" };
errorCode(() => parseSkinPluginDocument(missing), "SKIN_PLUGIN_WIDGET_OPTIONS_INVALID");
const invalidProvider = structuredClone(document);
invalidProvider.components[0].root.children![0] = {
widget: "home.identity-provider",
options: { identityProviderId: "myts/login", identityProviderLabel: "myts" } as never,
};
errorCode(() => parseSkinPluginDocument(invalidProvider), "SKIN_PLUGIN_WIDGET_OPTIONS_INVALID");
});
test("schema v3 scopes local UI state only to approved public scalar context fields", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].permissions.push("session.status.read");
document.components[0].stateScope = "session.status.channelId";
assert.equal(parseSkinPluginDocument(document).components[0].stateScope, "session.status.channelId");
const missingPermission = structuredClone(document);
missingPermission.components[0].permissions = missingPermission.components[0].permissions.filter((permission) => permission !== "session.status.read");
errorCode(() => parseSkinPluginDocument(missingPermission), "SKIN_PLUGIN_PERMISSION_MISSING");
const privateContext = structuredClone(document);
privateContext.components[0].stateScope = "session.credentials.privateKey";
errorCode(() => parseSkinPluginDocument(privateContext), "SKIN_PLUGIN_STATE_SCOPE_INVALID");
const collection = structuredClone(document);
collection.components[0].stateScope = "session.channels";
errorCode(() => parseSkinPluginDocument(collection), "SKIN_PLUGIN_STATE_SCOPE_INVALID");
const legacy = structuredClone(document);
legacy.schemaVersion = 2;
errorCode(() => parseSkinPluginDocument(legacy), "SKIN_PLUGIN_SCHEMA_UNSUPPORTED");
});
test("custom member screen-share fields require read permission and can bind a watch action", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {
watch: { type: "voice.joinScreenShare", args: { streamId: "{{member.screenShareStreamId}}" } },
};
document.components[0].permissions = ["session.members.read", "voice.screenShare.read", "voice.screenShare.control"];
document.components[0].root = {
tag: "ul",
children: [{
tag: "li",
repeat: { path: "session.members", as: "member" },
children: [{
tag: "button",
when: { path: "member.screenSharing", equals: true },
events: { click: "watch" },
}],
}],
};
const parsed = parseSkinPluginDocument(document);
assert.equal(parsed.components[0].root.children?.[0].children?.[0].when?.path, "member.screenSharing");
assert.equal(parsed.components[0].actions.watch.args.streamId, "{{member.screenShareStreamId}}");
const missingRead = structuredClone(document);
missingRead.components[0].permissions = missingRead.components[0].permissions.filter((permission) => permission !== "voice.screenShare.read");
errorCode(() => parseSkinPluginDocument(missingRead), "SKIN_PLUGIN_PERMISSION_MISSING");
const missingControl = structuredClone(document);
missingControl.components[0].permissions = missingControl.components[0].permissions.filter((permission) => permission !== "voice.screenShare.control");
errorCode(() => parseSkinPluginDocument(missingControl), "SKIN_PLUGIN_PERMISSION_MISSING");
});
test("schema v3 trusted widgets can omit screen-share UI and request only the permissions they use", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].permissions = ["session.members.read", "session.memberAvatars.read"];
document.components[0].root = { tag: "main", children: [{ widget: "voice.member-cards", options: { screenShare: false, memberActions: true } }] };
assert.deepEqual(parseSkinPluginDocument(document).components[0].root.children?.[0]?.options, { screenShare: false, memberActions: true });
const memberCardsDefault = structuredClone(document);
memberCardsDefault.components[0].root.children![0] = { widget: "voice.member-cards" };
errorCode(() => parseSkinPluginDocument(memberCardsDefault), "SKIN_PLUGIN_PERMISSION_MISSING");
const performanceWithoutShare = structuredClone(document);
performanceWithoutShare.components[0].permissions = [];
performanceWithoutShare.components[0].root.children![0] = { widget: "voice.performance-panel", options: { screenShare: false } };
assert.equal(parseSkinPluginDocument(performanceWithoutShare).components[0].root.children?.[0]?.widget, "voice.performance-panel");
const performanceWithShare = structuredClone(performanceWithoutShare);
performanceWithShare.components[0].root.children![0] = { widget: "voice.performance-panel", options: { screenShare: true } };
errorCode(() => parseSkinPluginDocument(performanceWithShare), "SKIN_PLUGIN_PERMISSION_MISSING");
performanceWithShare.components[0].permissions = ["voice.screenShare.read"];
assert.equal(parseSkinPluginDocument(performanceWithShare).components[0].root.children?.[0]?.widget, "voice.performance-panel");
const invalidOption = structuredClone(document);
invalidOption.components[0].root.children![0] = { widget: "voice.member-cards", options: { screenShare: "false" } as never };
errorCode(() => parseSkinPluginDocument(invalidOption), "SKIN_PLUGIN_WIDGET_OPTIONS_INVALID");
const memberActionsOnWrongWidget = structuredClone(document);
memberActionsOnWrongWidget.components[0].root.children![0] = { widget: "voice.performance-panel", options: { memberActions: true } };
errorCode(() => parseSkinPluginDocument(memberActionsOnWrongWidget), "SKIN_PLUGIN_WIDGET_OPTIONS_INVALID");
const invalidMemberActions = structuredClone(document);
invalidMemberActions.components[0].root.children![0] = { widget: "voice.member-cards", options: { memberActions: "yes" } as never };
errorCode(() => parseSkinPluginDocument(invalidMemberActions), "SKIN_PLUGIN_WIDGET_OPTIONS_INVALID");
const legacyOption = structuredClone(document);
legacyOption.schemaVersion = 2;
legacyOption.components[0].root.children![0] = { widget: "voice.member-cards", options: { screenShare: false } };
errorCode(() => parseSkinPluginDocument(legacyOption), "SKIN_PLUGIN_SCHEMA_UNSUPPORTED");
const misplacedOption = structuredClone(document);
misplacedOption.components[0].root.children![0] = { tag: "div", options: { screenShare: false } } as never;
errorCode(() => parseSkinPluginDocument(misplacedOption), "SKIN_PLUGIN_WIDGET_OPTIONS_INVALID");
});
test("trusted channel tree and server switcher widgets require scoped read and control permissions", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].permissions = [
"session.status.read",
"session.channels.read",
"session.members.read",
"session.memberAvatars.read",
"session.channel.join",
"servers.quickList.read",
"servers.quickList.switch",
];
document.components[0].root = {
tag: "header",
children: [
{ widget: "voice.server-switcher", part: "server-switcher" },
{ widget: "voice.server-header", part: "server-header" },
{ widget: "voice.channel-tree", part: "channel-tree", options: { layout: "server-sidebar", memberActions: true, memberDragDrop: true } },
],
};
assert.deepEqual(parseSkinPluginDocument(document).components[0].root.children?.map(({ widget }) => widget), [
"voice.server-switcher",
"voice.server-header",
"voice.channel-tree",
]);
assert.deepEqual(parseSkinPluginDocument(document).components[0].root.children?.[2]?.options, { layout: "server-sidebar", memberActions: true, memberDragDrop: true });
const invalidMemberDragDrop = structuredClone(document);
invalidMemberDragDrop.components[0].root.children![2] = { widget: "voice.channel-tree", options: { memberDragDrop: "yes" } as never };
errorCode(() => parseSkinPluginDocument(invalidMemberDragDrop), "SKIN_PLUGIN_WIDGET_OPTIONS_INVALID");
const memberDragDropOnWrongWidget = structuredClone(document);
memberDragDropOnWrongWidget.components[0].root.children![2] = { widget: "voice.performance-panel", options: { memberDragDrop: true } };
errorCode(() => parseSkinPluginDocument(memberDragDropOnWrongWidget), "SKIN_PLUGIN_WIDGET_OPTIONS_INVALID");
for (const missingPermission of [
"session.status.read",
"session.channels.read",
"session.members.read",
"session.memberAvatars.read",
"session.channel.join",
"servers.quickList.read",
"servers.quickList.switch",
] as const) {
const missing = structuredClone(document);
missing.components[0].permissions = missing.components[0].permissions.filter((permission) => permission !== missingPermission);
errorCode(() => parseSkinPluginDocument(missing), "SKIN_PLUGIN_PERMISSION_MISSING");
}
});
test("KAAK v3 example declares the connection home and complete voice workspace", async () => {
const source = await readFile(new URL("../../docs/examples/kaak-voice/components.json", import.meta.url), "utf8");
const parsed = parseSkinPluginJson(source);
const home = parsed.components.find((component) => component.id === "kaak-home");
const workspace = parsed.components.find((component) => component.id === "kaak-workspace");
assert.ok(home);
assert.ok(workspace);
assert.equal(home.page, "home");
assert.equal(home.mode, "surface");
assert.deepEqual(home.permissions, ["ui.surface.replace", "session.status.read"]);
const homeSocialLinks = home.root.children?.at(-2);
assert.equal(homeSocialLinks?.part, "home-social-links");
assert.equal(homeSocialLinks?.widget, "home.social-links");
assert.equal(home.root.children?.at(-1)?.part, "home-language", "social icons appear immediately to the left of the language switcher");
const connectionCard = home.root.children?.[1].children?.[0].children?.[1];
assert.equal(connectionCard?.part, "connection-card");
assert.equal(connectionCard?.children?.[0].part, "card-heading");
assert.equal(connectionCard?.children?.[0].children?.[0].part, "connection-title");
assert.equal(connectionCard?.children?.[0].children?.[1].widget, "home.identity-provider");
assert.deepEqual(connectionCard?.children?.[0].children?.[1].options, { identityProviderId: "myts", identityProviderLabel: "myts" });
assert.equal(connectionCard?.children?.[2].widget, "home.connection-form");
assert.equal(connectionCard?.children?.[4].widget, "home.connection-status");
const serverAnnouncement = home.root.children?.[0].children?.[2];
assert.equal(serverAnnouncement?.part, "server-announcement");
assert.equal(serverAnnouncement?.widget, "home.server-announcement");
const heroMedia = home.root.children?.[0].children?.[3];
assert.equal(heroMedia?.part, "hero-media");
assert.equal(heroMedia?.children?.[0].tag, "svg");
assert.equal(workspace.page, "voice");
assert.equal(workspace.mode, "surface");
assert.ok(workspace.permissions.includes("session.channels.read"));
assert.ok(workspace.permissions.includes("session.status.read"));
assert.ok(workspace.permissions.includes("session.members.read"));
assert.ok(workspace.permissions.includes("session.memberAvatars.read"));
assert.ok(workspace.permissions.includes("session.channel.join"));
assert.ok(workspace.permissions.includes("servers.quickList.read"));
assert.ok(workspace.permissions.includes("servers.quickList.switch"));
assert.ok(workspace.permissions.includes("chat.channel.read"));
assert.ok(workspace.permissions.includes("chat.channel.send"));
assert.ok(workspace.permissions.includes("audio.microphone.control"));
assert.ok(workspace.permissions.includes("voice.screenShare.control"));
assert.ok(workspace.permissions.includes("voice.screenShare.read"));
assert.ok(workspace.permissions.includes("voice.screenShare.status.read"));
assert.equal(workspace.actions["stop-screen-share"].type, "voice.stopScreenShare");
assert.equal(workspace.actions["join-channel"], undefined, "channel joining is handled by the trusted tree widget");
assert.equal(workspace.actions["toggle-chat-panel"].type, "chat.togglePanel");
const nodes: SkinPluginNode[] = [];
const visit = (node: SkinPluginNode): void => {
nodes.push(node);
node.children?.forEach(visit);
};
visit(workspace.root);
assert.ok(nodes.some((node) => node.widget === "voice.member-cards"));
assert.ok(nodes.some((node) => node.part === "desktop-room-controls" && node.tag === "div"), "the desktop audio dock is composed in the skin document");
assert.ok(nodes.some((node) => node.part === "desktop-room-noise-suppression" && node.events?.click === "toggle-noise-suppression"));
assert.ok(nodes.some((node) => node.part === "desktop-room-accompaniment" && node.events?.click === "toggle-accompaniment"));
assert.ok(nodes.some((node) => node.part === "mobile-room-controls" && node.tag === "div"), "the mobile room toolbar is composed in the skin document");
assert.ok(nodes.some((node) => node.part === "mobile-room-microphone" && node.events?.click === "toggle-microphone"));
assert.ok(nodes.some((node) => node.part === "mobile-room-speaker" && node.events?.click === "open-audio-settings"));
assert.ok(nodes.some((node) => node.part === "mobile-room-exit" && node.events?.click === "disconnect"));
assert.ok(nodes.some((node) => node.widget === "voice.server-header"), "the server header exposes trusted search and quick switching");
assert.ok(nodes.some((node) => node.widget === "voice.channel-tree" && node.options?.layout === "server-sidebar"), "the KAAK channel tree opts into its isolated sidebar layout");
assert.equal(nodes.find((node) => node.part === "record-placeholder"), undefined, "the KAAK voice dock does not expose a recording control");
assert.ok(nodes.some((node) => node.widget === "voice.screen-share-start"), "the voice dock exposes WebSpeak screen sharing");
assert.ok(nodes.some((node) => node.widget === "voice.screen-share-player"), "the voice stage keeps WebSpeak's screen-share player");
assert.ok(nodes.some((node) => node.widget === "voice.chat-panel"), "KAAK uses the unified host chat panel for channel, server, and private messages");
assert.equal(nodes.find((node) => node.part === "screen-share-stop")?.events?.click, "stop-screen-share");
assert.ok(!nodes.some((node) => node.repeat?.path === "session.members"), "member imagery stays inside the trusted host widget");
assert.ok(!nodes.some((node) => node.tag === "input" && node.bindValue === "message"), "chat input state stays in the host-owned panel");
});
test("skin plugin binds form controls only to declared local state", () => {
const document = validDocument();
document.components[0].state = { search: "" };
document.components[0].root.children = [{
tag: "input",
bindValue: "search",
events: { input: "filter" },
}];
document.components[0].actions.filter = { type: "ui.setState", args: { key: "search", value: "{{state.search}}" } };
assert.equal(parseSkinPluginDocument(document).components[0].state?.search, "");
});
test("skin plugin rejects undeclared permissions, arbitrary paths, and executable markup", () => {
const missingPermission = validDocument();
missingPermission.components[0].permissions = ["session.channel.join"];
errorCode(() => parseSkinPluginDocument(missingPermission), "SKIN_PLUGIN_PERMISSION_MISSING");
const hiddenPath = validDocument();
hiddenPath.components[0].root.children![0].children = [{ text: "{{session.credentials.privateKey}}" }];
errorCode(() => parseSkinPluginDocument(hiddenPath), "SKIN_PLUGIN_BINDING_INVALID");
const executable = validDocument();
executable.components[0].root.children![0].attributes = { onclick: "alert(1)" };
errorCode(() => parseSkinPluginDocument(executable), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
const unsafeTag = validDocument();
unsafeTag.components[0].root.children![0].tag = "iframe";
errorCode(() => parseSkinPluginDocument(unsafeTag), "SKIN_PLUGIN_ELEMENT_INVALID");
const externalSvgPaint = validDocument();
externalSvgPaint.components[0].root.children![0].attributes = { fill: "url(https://example.invalid/payload.svg#paint)" };
errorCode(() => parseSkinPluginDocument(externalSvgPaint), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
const skinOwnedPopover = validDocument();
skinOwnedPopover.components[0].root.children![0].attributes = { popover: "manual" };
errorCode(() => parseSkinPluginDocument(skinOwnedPopover), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
const skinOwnedPopoverTrigger = validDocument();
skinOwnedPopoverTrigger.components[0].root.children![0].attributes = { popovertarget: "host-editor" };
errorCode(() => parseSkinPluginDocument(skinOwnedPopoverTrigger), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
});
test("skin plugin restricts repeated fields to the selected collection", () => {
const document = validDocument();
document.components[0].root.repeat = { path: "session.channels", as: "channel" };
document.components[0].root.children = [{ text: "{{channel.author}}" }];
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_BINDING_INVALID");
});
test("skin plugins can repeat channel members only under a channel alias and with member permission", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].permissions.push("session.members.read");
document.components[0].root.children = [{
tag: "ul",
children: [{
tag: "li",
repeat: { path: "channel.members", as: "member" },
children: [{ text: "{{channel.name}} — {{member.avatarInitial}} {{member.name}}" }],
}],
}];
const parsed = parseSkinPluginDocument(document);
const nestedMember = parsed.components[0].root.children?.[0].children?.[0];
assert.deepEqual(nestedMember?.repeat, { path: "channel.members", as: "member" });
assert.equal(nestedMember?.children?.[0]?.text, "{{channel.name}} — {{member.avatarInitial}} {{member.name}}");
const membersOnly = structuredClone(document);
membersOnly.components[0].root.children = [{
tag: "ul",
when: { path: "channel.members", empty: false },
children: [{ tag: "li", repeat: { path: "channel.members", as: "member" } }],
}];
const parsedCondition = parseSkinPluginDocument(membersOnly).components[0].root.children?.[0];
assert.deepEqual(parsedCondition?.when, { path: "channel.members", empty: false });
const missingConditionPermission = structuredClone(membersOnly);
missingConditionPermission.components[0].permissions = ["session.channels.read", "session.channel.join"];
missingConditionPermission.components[0].root.children![0].children = [];
errorCode(() => parseSkinPluginDocument(missingConditionPermission), "SKIN_PLUGIN_PERMISSION_MISSING");
const invalidNestedCondition = structuredClone(membersOnly);
invalidNestedCondition.components[0].root.children![0].when = { path: "channel.members" };
errorCode(() => parseSkinPluginDocument(invalidNestedCondition), "SKIN_PLUGIN_CONDITION_INVALID");
const missingPermission = structuredClone(document);
missingPermission.components[0].permissions = ["session.channels.read", "session.channel.join"];
errorCode(() => parseSkinPluginDocument(missingPermission), "SKIN_PLUGIN_PERMISSION_MISSING");
const outsideChannel = structuredClone(document);
outsideChannel.components[0].root.repeat = undefined;
outsideChannel.components[0].root.children = [{ tag: "ul", repeat: { path: "channel.members", as: "member" } }];
errorCode(() => parseSkinPluginDocument(outsideChannel), "SKIN_PLUGIN_REPEAT_INVALID");
});
test("skin plugins keep live typing local but can run host actions on committed changes", () => {
const document = validDocument();
const input = document.components[0].root.children![0];
input.events = { input: "join" };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_EVENT_INVALID");
input.events = { change: "join" };
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].events?.change, "join");
});
test("skin conditions can compare public repeated data with local component state", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].state = { selectedchannel: "" };
document.components[0].root.children![0].when = {
path: "state.selectedchannel",
equals: "{{channel.id}}",
};
const parsed = parseSkinPluginDocument(document);
assert.deepEqual(parsed.components[0].root.children?.[0].when, {
path: "state.selectedchannel",
equals: "{{channel.id}}",
});
const legacyDocument = structuredClone(document);
legacyDocument.schemaVersion = 2;
errorCode(() => parseSkinPluginDocument(legacyDocument), "SKIN_PLUGIN_SCHEMA_UNSUPPORTED");
document.components[0].root.children![0].when!.equals = "{{channel.address}}";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_BINDING_INVALID");
});
test("schema v3 can render empty states only for permissioned public collections", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].permissions.push("chat.channel.read");
document.components[0].root.children = [{
tag: "p",
when: { path: "chat.messages", empty: true },
children: [{ text: "No messages yet" }],
}];
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].when?.empty, true);
document.components[0].permissions.push("session.status.read");
document.components[0].root.children[0].when!.path = "session.status.serverLabel";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_CONDITION_INVALID");
});
test("component schema v3 exposes composable interaction patterns and permission-gated voice actions", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].permissions = [
"audio.microphone.control", "audio.output.control", "audio.status.read", "audio.settings.open", "voice.disconnect", "voice.presence.write",
"voice.whisper.control", "voice.whisper.status.read", "voice.screenShare.control", "voice.screenShare.read", "voice.screenShare.status.read",
];
document.components[0].state = { menuopen: false, chatopen: true, volume: 0.5, awaymessage: "" };
document.components[0].actions = {
"toggle-menu": { type: "ui.toggleState", args: { key: "menuopen", resetKey: "chatopen" } },
microphone: { type: "voice.toggleMicrophone", args: {} },
speaker: { type: "voice.toggleOutputMute", args: {} },
settings: { type: "audio.openSettings", args: {} },
volume: { type: "voice.setOutputVolume", args: { volume: "{{state.volume}}" } },
disconnect: { type: "voice.disconnect", args: {} },
away: { type: "voice.setAway", args: { away: true, message: "{{state.awaymessage}}" } },
whisper: { type: "voice.setWhisperActive", args: { active: true } },
"start-share": { type: "voice.startScreenShare", args: {} },
"stop-share": { type: "voice.stopScreenShare", args: {} },
"join-share": { type: "voice.joinScreenShare", args: { streamId: "{{share.streamId}}" } },
"leave-share": { type: "voice.leaveScreenShare", args: {} },
};
document.components[0].root = {
tag: "main",
attributes: { "data-layout": "room", "aria-label": "Custom voice page" },
children: [
{ tag: "button", events: { contextmenu: "toggle-menu", pointerenter: "toggle-menu" }, children: [{ text: "Menu" }] },
{ tag: "button", events: { click: "microphone" }, children: [{ text: "Microphone" }] },
{ tag: "button", events: { click: "speaker" }, children: [{ text: "Speaker" }] },
{ tag: "button", events: { click: "settings" }, children: [{ text: "Audio settings" }] },
{ tag: "button", events: { click: "volume" }, children: [{ text: "Volume" }] },
{ tag: "button", events: { click: "disconnect" }, children: [{ text: "Disconnect" }] },
{ tag: "button", events: { click: "away" }, children: [{ text: "Away" }] },
{ tag: "button", events: { click: "whisper" }, children: [{ text: "Whisper" }] },
{ tag: "button", events: { click: "start-share" }, children: [{ text: "Share" }] },
{ tag: "button", events: { click: "stop-share" }, children: [{ text: "Stop sharing" }] },
{ tag: "div", repeat: { path: "screenShare.streams", as: "share" }, children: [
{ tag: "button", events: { click: "join-share" }, children: [{ text: "{{share.name}}" }] },
] },
{ tag: "button", events: { click: "leave-share" }, children: [{ text: "Leave share" }] },
],
};
const parsed = parseSkinPluginDocument(document);
assert.equal(parsed.schemaVersion, 3);
assert.equal(parsed.components[0].root.children?.[0].events?.contextmenu, "toggle-menu");
assert.equal(parsed.components[0].actions["join-share"].type, "voice.joinScreenShare");
assert.equal(parsed.components[0].actions.settings.type, "audio.openSettings");
assert.equal(parsed.components[0].actions["toggle-menu"].args.resetKey, "chatopen");
assert.equal(parsed.components[0].root.children?.[10].repeat?.path, "screenShare.streams");
const invalidResetKey = structuredClone(document);
invalidResetKey.components[0].actions["toggle-menu"].args.resetKey = "missing";
errorCode(() => parseSkinPluginDocument(invalidResetKey), "SKIN_PLUGIN_ACTION_INVALID");
const passiveVoiceControl = structuredClone(document);
passiveVoiceControl.components[0].root.children![0].events = { pointerenter: "microphone" };
errorCode(() => parseSkinPluginDocument(passiveVoiceControl), "SKIN_PLUGIN_EVENT_INVALID");
const missingPermission = structuredClone(document);
missingPermission.components[0].permissions = missingPermission.components[0].permissions.filter((item) => item !== "audio.microphone.control");
errorCode(() => parseSkinPluginDocument(missingPermission), "SKIN_PLUGIN_PERMISSION_MISSING");
const missingAudioSettingsPermission = structuredClone(document);
missingAudioSettingsPermission.components[0].permissions = missingAudioSettingsPermission.components[0].permissions.filter((item) => item !== "audio.settings.open");
errorCode(() => parseSkinPluginDocument(missingAudioSettingsPermission), "SKIN_PLUGIN_PERMISSION_MISSING");
const oldSchema = structuredClone(document);
oldSchema.schemaVersion = 2;
errorCode(() => parseSkinPluginDocument(oldSchema), "SKIN_PLUGIN_SCHEMA_UNSUPPORTED");
});
test("skin plugin JSON parser enforces a bounded document size and valid JSON", () => {
assert.throws(() => parseSkinPluginJson("{"));
assert.throws(() => parseSkinPluginJson(" ".repeat(256 * 1024 + 1)));
assert.equal(parseSkinPluginJson(JSON.stringify(validDocument())).components.length, 1);
});
test("skin plugin enforces each component's node and nesting limits", () => {
const broad = validDocument();
broad.components[0].root.children = Array.from({ length: 101 }, () => ({ text: "item" }));
errorCode(() => parseSkinPluginDocument(broad), "SKIN_PLUGIN_TREE_INVALID");
const tooMany = validDocument();
const branch = (depth: number): SkinPluginNode => depth === 0
? { tag: "span", children: [{ text: "item" }] }
: { tag: "span", children: Array.from({ length: 3 }, () => branch(depth - 1)) };
tooMany.components[0].root.children = Array.from({ length: 3 }, () => branch(5));
errorCode(() => parseSkinPluginDocument(tooMany), "SKIN_PLUGIN_COMPLEXITY_LIMIT");
});
+727
View File
@@ -0,0 +1,727 @@
/** Safe, declarative UI extensions shipped inside a v3 skin package.
* Extension authors provide a bounded component tree and action declarations,
* never executable HTML, JavaScript, or browser APIs.
*/
export const SKIN_PLUGIN_SCHEMA_VERSION = 3 as const;
export const SKIN_PLUGIN_SUPPORTED_SCHEMA_VERSIONS = Object.freeze([1, 2, 3] as const);
export const SKIN_PLUGIN_DOCUMENT_LIMIT_BYTES = 256 * 1024;
export const SKIN_PLUGIN_COMPONENT_LIMIT = 128;
export const SKIN_PLUGIN_NODE_LIMIT = 2048;
export const SKIN_PLUGIN_TREE_DEPTH_LIMIT = 32;
export const SKIN_PLUGIN_REPEAT_LIMIT = 250;
export const SKIN_PLUGIN_RENDER_NODE_LIMIT = 8192;
export const SKIN_PLUGIN_PERMISSIONS = Object.freeze({
"ui.surface.replace": Object.freeze({ policyVersion: 1, description: "Replace the built-in public page with a custom skin surface; the host recovery controls remain available." }),
"ui.input.read": Object.freeze({ policyVersion: 1, description: "Read values entered or autofilled in this plugin's own input fields. Never enter passwords or other secrets." }),
"session.status.read": Object.freeze({ policyVersion: 1, description: "Read the current connection and channel summary." }),
"session.invite.copy": Object.freeze({ policyVersion: 1, description: "Copy a WebSpeak invite link for the current public server and channel; credentials are excluded." }),
"session.channels.read": Object.freeze({ policyVersion: 1, description: "Read the public TeamSpeak channel tree; the demo page uses synthetic sample data." }),
"session.members.read": Object.freeze({ policyVersion: 1, description: "Read visible member names, initials derived from those names, and speaking states; the demo page uses synthetic sample data." }),
"session.memberAvatars.read": Object.freeze({ policyVersion: 1, description: "Display cached TeamSpeak profile pictures for visible members inside trusted host member-card or channel-tree widgets. Images are not exposed to skin markup or plugin runtimes." }),
"chat.channel.read": Object.freeze({ policyVersion: 1, description: "Read the current public text channel; the demo page uses synthetic sample data." }),
"chat.channel.send": Object.freeze({ policyVersion: 1, description: "Send to the current public text channel; the demo page only simulates this action." }),
"favorites.read": Object.freeze({ policyVersion: 1, description: "Read favorite labels and opaque local identifiers, without server addresses or credentials." }),
"favorites.switch": Object.freeze({ policyVersion: 1, description: "Select a saved TeamSpeak server using the host's connection flow." }),
"servers.quickList.read": Object.freeze({ policyVersion: 1, description: "Read favorite and recent server labels, public server icons, and opaque local identifiers, without server addresses or credentials." }),
"servers.quickList.switch": Object.freeze({ policyVersion: 1, description: "Switch to a user-selected favorite or recent server through the host connection flow." }),
"session.channel.join": Object.freeze({ policyVersion: 1, description: "Request joining a visible TeamSpeak channel through the host; the demo page only changes simulated state." }),
"audio.status.read": Object.freeze({ policyVersion: 1, description: "Read the user's own microphone and speaker mute states." }),
"audio.microphone.control": Object.freeze({ policyVersion: 1, description: "Toggle the user's own microphone through WebSpeak's audio pipeline." }),
"audio.output.control": Object.freeze({ policyVersion: 1, description: "Toggle or adjust the user's local speaker output." }),
"audio.settings.open": Object.freeze({ policyVersion: 1, description: "Open WebSpeak's trusted audio device and processing settings." }),
"voice.presence.write": Object.freeze({ policyVersion: 1, description: "Set the user's own away status through the connected TeamSpeak session." }),
"voice.whisper.control": Object.freeze({ policyVersion: 1, description: "Enable or disable the user's existing TeamSpeak whisper target selection." }),
"voice.disconnect": Object.freeze({ policyVersion: 1, description: "Disconnect the user's current TeamSpeak voice session." }),
"voice.whisper.status.read": Object.freeze({ policyVersion: 1, description: "Read whether whisper is active and how many existing targets are selected." }),
"voice.screenShare.status.read": Object.freeze({ policyVersion: 1, description: "Read the user's own screen-share state." }),
"voice.screenShare.read": Object.freeze({ policyVersion: 1, description: "Read visible screen-share names, owners, audio flags, and viewer counts." }),
"voice.screenShare.control": Object.freeze({ policyVersion: 1, description: "Start or stop the user's screen share, or join/leave a visible share through the host." }),
} as const);
export type SkinPluginPermission = keyof typeof SKIN_PLUGIN_PERMISSIONS;
export type SkinPluginPage = "home" | "voice" | "demo";
export type SkinPluginComponentMode = "widget" | "surface";
export const SKIN_PLUGIN_HOST_WIDGETS = Object.freeze([
"home.connection-form",
"home.connection-status",
"home.server-announcement",
"home.social-links",
"home.identity-provider",
"app.skin-switcher",
"app.language-switcher",
"voice.server-switcher",
"voice.server-header",
"voice.server-banner",
"voice.channel-tree",
"voice.channel-panel",
"voice.member-cards",
"voice.chat-panel",
"voice.audio-controls",
"voice.screen-share-player",
"voice.screen-share-start",
"voice.whisper-controls",
"voice.performance-panel",
"voice.connection-controls",
"voice.disconnect-control",
] as const);
export type SkinPluginHostWidget = typeof SKIN_PLUGIN_HOST_WIDGETS[number];
export interface SkinPluginWidgetOptions {
/** Hide screen-share UI and its stream details for widgets that support it. */
screenShare?: boolean;
/** Enable host member actions on member cards and a right-click menu on channel-tree rows. */
memberActions?: boolean;
/** Enable trusted host member drag-and-drop between channel-tree rows. */
memberDragDrop?: boolean;
/** Select a supported host presentation for a channel tree. */
layout?: "default" | "server-sidebar";
/** Provider identity used by the generic, UI-only home sign-in entry. */
identityProviderId?: string;
/** Provider display name used by the generic, UI-only home sign-in entry. */
identityProviderLabel?: string;
}
const widgetPermissions = (...permissions: SkinPluginPermission[]): readonly SkinPluginPermission[] => Object.freeze(permissions);
export const SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS: Partial<Record<SkinPluginHostWidget, readonly SkinPluginPermission[]>> = Object.freeze({
"home.connection-status": widgetPermissions("session.status.read"),
"voice.channel-tree": widgetPermissions("session.channels.read", "session.members.read", "session.memberAvatars.read", "session.channel.join"),
"voice.server-switcher": widgetPermissions("servers.quickList.read", "servers.quickList.switch"),
"voice.server-header": widgetPermissions("session.status.read", "servers.quickList.read", "servers.quickList.switch"),
"voice.server-banner": widgetPermissions("session.status.read"),
"voice.audio-controls": widgetPermissions("audio.status.read", "audio.microphone.control", "audio.output.control"),
"voice.chat-panel": widgetPermissions("chat.channel.read", "chat.channel.send"),
"voice.connection-controls": widgetPermissions("voice.disconnect"),
"voice.disconnect-control": widgetPermissions("voice.disconnect"),
"voice.member-cards": widgetPermissions("session.members.read", "session.memberAvatars.read", "voice.screenShare.read", "voice.screenShare.control"),
"voice.screen-share-player": widgetPermissions("voice.screenShare.read", "voice.screenShare.control"),
"voice.screen-share-start": widgetPermissions("voice.screenShare.control"),
"voice.whisper-controls": widgetPermissions("voice.whisper.status.read", "voice.whisper.control"),
});
export function skinPluginWidgetPermissions(
widget: SkinPluginHostWidget,
options?: SkinPluginWidgetOptions,
): readonly SkinPluginPermission[] {
if (widget === "voice.performance-panel") return options?.screenShare === true ? widgetPermissions("voice.screenShare.read") : [];
const permissions = SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS[widget] ?? [];
if (options?.screenShare !== false || widget !== "voice.member-cards") return permissions;
return permissions.filter((permission) => permission !== "voice.screenShare.read" && permission !== "voice.screenShare.control");
}
export function missingSkinPluginWidgetPermission(
widget: SkinPluginHostWidget,
permissions: readonly SkinPluginPermission[],
options?: SkinPluginWidgetOptions,
): SkinPluginPermission | undefined {
return skinPluginWidgetPermissions(widget, options).find((permission) => !permissions.includes(permission));
}
export type SkinPluginEvent =
| "click" | "dblclick" | "change" | "input" | "submit" | "keydown"
| "keyup" | "contextmenu" | "focus" | "blur" | "pointerdown" | "pointerup"
| "pointerenter" | "pointerleave" | "dragstart" | "dragover" | "drop";
export type SkinPluginAction =
| "ui.setState" | "ui.toggleState"
| "session.copyInviteLink"
| "voice.joinChannel" | "favorites.switch" | "quickServers.switch" | "chat.sendMessage" | "chat.togglePanel"
| "voice.toggleMicrophone" | "voice.toggleOutputMute" | "voice.setOutputVolume" | "audio.openSettings"
| "audio.toggleNoiseSuppression" | "audio.toggleAccompaniment"
| "voice.disconnect" | "voice.setAway" | "voice.setWhisperActive"
| "voice.startScreenShare" | "voice.stopScreenShare" | "voice.joinScreenShare" | "voice.leaveScreenShare";
export interface SkinPluginActionDefinition {
type: SkinPluginAction;
args: Record<string, string | number | boolean>;
}
export interface SkinPluginNode {
widget?: SkinPluginHostWidget;
options?: SkinPluginWidgetOptions;
tag?: string;
text?: string;
part?: string;
className?: string;
attributes?: Record<string, string | number | boolean>;
asset?: string;
bindValue?: string;
repeat?: { path: string; as: string };
when?: { path: string; equals?: string | number | boolean; empty?: boolean };
events?: Partial<Record<SkinPluginEvent, string>>;
children?: SkinPluginNode[];
}
export interface SkinPluginComponent {
id: string;
name: string;
page: SkinPluginPage;
mode?: SkinPluginComponentMode;
accessibleName: string;
permissions: SkinPluginPermission[];
/** Keep local UI state separate for each approved scalar context value. */
stateScope?: string;
state?: Record<string, string | number | boolean>;
/** Internal marker used only for generated Wasm views; rejected by package JSON validation. */
runtimeCallbacks?: boolean;
actions: Record<string, SkinPluginActionDefinition>;
root: SkinPluginNode;
}
export interface SkinPluginDocument {
schemaVersion: 1 | 2 | typeof SKIN_PLUGIN_SCHEMA_VERSION;
components: SkinPluginComponent[];
}
export interface SkinPluginApproval {
pluginId: string;
policyVersions: Partial<Record<SkinPluginPermission, number>>;
}
export class SkinPluginValidationError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinPluginValidationError";
}
}
export const SKIN_PLUGIN_ALLOWED_ELEMENTS = Object.freeze([
"article", "aside", "b", "blockquote", "br", "button", "caption", "circle", "cite", "code", "dd", "del", "details", "div", "dl", "dt",
"em", "fieldset", "figcaption", "figure", "footer", "form", "g", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "i", "img", "input",
"kbd", "label", "legend", "li", "line", "main", "mark", "nav", "ol", "option", "output", "p", "path", "polyline", "pre", "progress", "q",
"rect", "s", "section", "select", "small", "span", "strong", "sub", "summary", "sup", "svg", "table", "tbody", "td", "textarea", "th", "thead",
"time", "tr", "u", "ul", "wbr",
] as const);
const ELEMENTS = new Set<string>(SKIN_PLUGIN_ALLOWED_ELEMENTS);
const VOID_ELEMENTS = new Set(["br", "circle", "hr", "img", "input", "line", "path", "polyline", "rect", "wbr"]);
const ATTRIBUTES = new Set([
"alt", "aria-current", "aria-expanded", "aria-hidden", "aria-label", "aria-pressed", "aria-selected", "autocomplete", "checked", "class", "colspan", "cx", "cy", "d", "disabled", "draggable", "fill", "height", "inputmode", "max", "maxlength", "min",
"minlength", "multiple", "name", "open", "placeholder", "required", "role", "rows", "rowspan", "step", "stroke", "stroke-linecap", "stroke-linejoin",
"r", "rx", "src", "stroke-width", "tabindex", "title", "type", "value", "viewbox", "width", "x", "x1", "x2", "y", "y1", "y2",
]);
const EVENTS = new Set<string>([
"click", "dblclick", "change", "input", "submit", "keydown", "keyup", "contextmenu", "focus", "blur", "pointerdown", "pointerup",
"pointerenter", "pointerleave", "dragstart", "dragover", "drop",
]);
const V3_EVENTS = new Set<string>([
"keyup", "contextmenu", "focus", "blur", "pointerdown", "pointerup", "pointerenter", "pointerleave", "dragstart", "dragover", "drop",
]);
const PASSIVE_EVENTS = new Set<string>(["focus", "blur", "pointerenter", "pointerleave", "dragstart", "dragover"]);
const ACTIONS = new Set<string>([
"ui.setState", "ui.toggleState", "session.copyInviteLink", "voice.joinChannel", "favorites.switch", "quickServers.switch", "chat.sendMessage", "chat.togglePanel",
"voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.disconnect", "voice.setAway", "voice.setWhisperActive",
"voice.startScreenShare", "voice.stopScreenShare", "voice.joinScreenShare", "voice.leaveScreenShare",
]);
const V3_ACTIONS = new Set<string>([
"ui.toggleState", "session.copyInviteLink", "chat.togglePanel", "voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.disconnect", "voice.setAway",
"voice.setWhisperActive", "voice.startScreenShare", "voice.stopScreenShare", "voice.joinScreenShare", "voice.leaveScreenShare",
]);
const PERMISSIONS = new Set<string>(Object.keys(SKIN_PLUGIN_PERMISSIONS));
const HOST_WIDGETS = new Set<string>(SKIN_PLUGIN_HOST_WIDGETS);
const ACTION_ARGS: Record<SkinPluginAction, ReadonlySet<string>> = {
"ui.setState": new Set(["key", "value"]),
"ui.toggleState": new Set(["key", "resetKey"]),
"session.copyInviteLink": new Set([]),
"voice.joinChannel": new Set(["channelId"]),
"favorites.switch": new Set(["favoriteId"]),
"quickServers.switch": new Set(["quickServerId"]),
"chat.sendMessage": new Set(["text"]),
"chat.togglePanel": new Set([]),
"voice.toggleMicrophone": new Set([]),
"voice.toggleOutputMute": new Set([]),
"voice.setOutputVolume": new Set(["volume"]),
"audio.openSettings": new Set([]),
"audio.toggleNoiseSuppression": new Set([]),
"audio.toggleAccompaniment": new Set([]),
"voice.disconnect": new Set([]),
"voice.setAway": new Set(["away", "message"]),
"voice.setWhisperActive": new Set(["active"]),
"voice.startScreenShare": new Set([]),
"voice.stopScreenShare": new Set([]),
"voice.joinScreenShare": new Set(["streamId"]),
"voice.leaveScreenShare": new Set([]),
};
const ACTION_PERMISSION: Record<SkinPluginAction, SkinPluginPermission | null> = {
"ui.setState": null,
"ui.toggleState": null,
"session.copyInviteLink": "session.invite.copy",
"voice.joinChannel": "session.channel.join",
"favorites.switch": "favorites.switch",
"quickServers.switch": "servers.quickList.switch",
"chat.sendMessage": "chat.channel.send",
"chat.togglePanel": "chat.channel.read",
"voice.toggleMicrophone": "audio.microphone.control",
"voice.toggleOutputMute": "audio.output.control",
"voice.setOutputVolume": "audio.output.control",
"audio.openSettings": "audio.settings.open",
"audio.toggleNoiseSuppression": "audio.microphone.control",
"audio.toggleAccompaniment": "audio.output.control",
"voice.disconnect": "voice.disconnect",
"voice.setAway": "voice.presence.write",
"voice.setWhisperActive": "voice.whisper.control",
"voice.startScreenShare": "voice.screenShare.control",
"voice.stopScreenShare": "voice.screenShare.control",
"voice.joinScreenShare": "voice.screenShare.control",
"voice.leaveScreenShare": "voice.screenShare.control",
};
export const SKIN_PLUGIN_ACTION_PERMISSIONS: readonly SkinPluginPermission[] = Object.freeze([...new Set(
Object.values(ACTION_PERMISSION).filter((permission): permission is SkinPluginPermission => permission !== null),
)]);
const COLLECTION_PERMISSION: Record<string, SkinPluginPermission> = {
"session.channels": "session.channels.read",
"session.members": "session.members.read",
"favorites.items": "favorites.read",
"servers.quickList": "servers.quickList.read",
"chat.messages": "chat.channel.read",
"screenShare.streams": "voice.screenShare.read",
};
const COLLECTION_FIELDS: Record<string, ReadonlySet<string>> = {
"session.channels": new Set(["id", "name", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]),
"session.members": new Set(["id", "name", "avatarInitial", "channelId", "status", "speaking", "self", "screenSharing", "screenShareStreamId"]),
"favorites.items": new Set(["id", "label", "current", "kind"]),
"servers.quickList": new Set(["id", "label", "monogram", "icon", "tone", "current", "switchRestricted", "switchTitle", "kind", "favorite"]),
"chat.messages": new Set(["id", "author", "text", "time", "kind", "channelId"]),
"screenShare.streams": new Set(["streamId", "source", "ownerClientId", "ownerNickname", "name", "audio", "viewerCount"]),
};
const COLLECTION_FIELD_PERMISSIONS: Record<string, Partial<Record<string, SkinPluginPermission>>> = {
"session.members": {
screenSharing: "voice.screenShare.read",
screenShareStreamId: "voice.screenShare.read",
},
};
const SESSION_STATUS_FIELDS = new Set(["connected", "connecting", "connectionState", "serverLabel", "channelId", "channelName", "userName"]);
const CONTEXT_FIELDS: Record<string, ReadonlySet<string>> = {
"chat.status": new Set(["panelOpen", "tab", "tabLabel"]),
"audio.status": new Set(["microphoneMuted", "outputMuted", "noiseSuppressionEnabled", "accompanimentActive"]),
"screenShare.status": new Set(["active", "starting", "viewing"]),
"whisper.status": new Set(["active", "targetCount"]),
};
const COMPONENT_STATE_SCOPE_PATHS = new Set([
...Array.from(SESSION_STATUS_FIELDS, (field) => `session.status.${field}`),
...Object.entries(CONTEXT_FIELDS).flatMap(([path, fields]) => Array.from(fields, (field) => `${path}.${field}`)),
]);
const CONTEXT_PERMISSIONS: Record<string, SkinPluginPermission> = {
"chat.status": "chat.channel.read",
"audio.status": "audio.status.read",
"screenShare.status": "voice.screenShare.status.read",
"whisper.status": "voice.whisper.status.read",
};
function fail(code: string, message: string): never { throw new SkinPluginValidationError(code, message); }
function isRecord(value: unknown): value is Record<string, unknown> { return Boolean(value) && typeof value === "object" && !Array.isArray(value); }
function onlyKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>, context: string): void {
const unknown = Object.keys(value).find((key) => !allowed.has(key));
if (unknown) fail("SKIN_PLUGIN_FIELD_INVALID", `${context} contains an unsupported field: ${unknown}.`);
}
function boundedText(value: unknown, field: string, max = 160): string {
if (typeof value !== "string" || !value.trim() || value.length > max || value !== value.trim()) fail("SKIN_PLUGIN_FIELD_INVALID", `${field} must be a non-empty bounded string.`);
return value;
}
function identifier(value: unknown, field: string): string {
const result = boundedText(value, field, 64);
if (!/^[a-z][a-z0-9-]*$/.test(result)) fail("SKIN_PLUGIN_FIELD_INVALID", `${field} must use a lowercase identifier.`);
return result;
}
function isNestedChannelMembersPath(path: string, aliases: ReadonlyMap<string, string>): boolean {
const separator = path.lastIndexOf(".");
return separator > 0
&& path.slice(separator + 1) === "members"
&& aliases.get(path.slice(0, separator)) === "session.channels";
}
function bindingPermissions(value: string, aliases: ReadonlyMap<string, string>, stateKeys: ReadonlySet<string>): SkinPluginPermission[] {
const found = new Set<SkinPluginPermission>();
for (const match of value.matchAll(/\{\{\s*([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}/g)) {
const path = match[1].split(".");
if (path[0] === "state") {
if (path.length !== 2 || !stateKeys.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A state binding must reference a declared local state key.");
continue;
}
const aliasCollection = aliases.get(path[0]);
if (aliasCollection) {
if (path.length !== 2 || !COLLECTION_FIELDS[aliasCollection]?.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A repeated item binding references an unsupported public field.");
const fieldPermission = COLLECTION_FIELD_PERMISSIONS[aliasCollection]?.[path[1]];
if (fieldPermission) found.add(fieldPermission);
continue;
}
if (path[0] === "session" && path.length === 3 && path[1] === "status" && SESSION_STATUS_FIELDS.has(path[2])) {
found.add("session.status.read");
continue;
}
const contextPath = path.slice(0, 2).join(".");
if (path.length === 3 && CONTEXT_FIELDS[contextPath]?.has(path[2])) {
found.add(CONTEXT_PERMISSIONS[contextPath]);
continue;
}
const collectionPath = path.slice(0, 2).join(".");
const permission = COLLECTION_PERMISSION[collectionPath];
if (permission && (path.length === 2 || (path.length === 3 && COLLECTION_FIELDS[collectionPath].has(path[2])))) {
found.add(permission);
continue;
}
fail("SKIN_PLUGIN_BINDING_INVALID", `The data path ${match[1]} is not available to skin components.`);
}
if (/\{\{[^}]*\}\}/.test(value.replace(/\{\{\s*[a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5}\s*\}\}/g, ""))) {
fail("SKIN_PLUGIN_BINDING_INVALID", "A component binding must use a simple registered data path.");
}
return [...found];
}
export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
if (!isRecord(input)) fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json must contain an object.");
onlyKeys(input, new Set(["schemaVersion", "components"]), "components.json");
if (!SKIN_PLUGIN_SUPPORTED_SCHEMA_VERSIONS.includes(input.schemaVersion as 1 | 2 | 3) || !Array.isArray(input.components)
|| (input.schemaVersion !== 3 && !input.components.length)
|| input.components.length > (input.schemaVersion === 3 ? SKIN_PLUGIN_COMPONENT_LIMIT : 32)) {
fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json uses an unsupported schema or component count.");
}
const ids = new Set<string>();
const inputSchemaVersion = input.schemaVersion as 1 | 2 | 3;
const components = input.components.map((rawComponent, componentIndex): SkinPluginComponent => {
if (!isRecord(rawComponent)) fail("SKIN_PLUGIN_COMPONENT_INVALID", `Component ${componentIndex} must be an object.`);
onlyKeys(rawComponent, new Set(["id", "name", "page", "mode", "accessibleName", "permissions", "actions", "stateScope", "state", "root"]), "Skin plugin component");
if (inputSchemaVersion < 3 && rawComponent.stateScope !== undefined) fail("SKIN_PLUGIN_SCHEMA_UNSUPPORTED", "Scoped local state requires components schema version 3.");
if (inputSchemaVersion === 1 && rawComponent.mode !== undefined) fail("SKIN_PLUGIN_SCHEMA_UNSUPPORTED", "Page surfaces require components schema version 2.");
const id = identifier(rawComponent.id, "component.id");
if (ids.has(id)) fail("SKIN_PLUGIN_COMPONENT_DUPLICATE", "Component IDs must be unique within the skin.");
ids.add(id);
if (!(rawComponent.page === "home" || rawComponent.page === "voice" || rawComponent.page === "demo")) fail("SKIN_PLUGIN_COMPONENT_INVALID", "A plugin component must target a public page.");
const page = rawComponent.page as SkinPluginPage;
const mode = rawComponent.mode === undefined ? "widget" : rawComponent.mode;
if (mode !== "widget" && mode !== "surface") fail("SKIN_PLUGIN_COMPONENT_INVALID", "A component mode must be widget or surface.");
if (mode === "surface" && page === "demo") fail("SKIN_PLUGIN_COMPONENT_INVALID", "Page surfaces are supported only for the home and voice client pages.");
const name = boundedText(rawComponent.name, "component.name", 80);
const accessibleName = boundedText(rawComponent.accessibleName, "component.accessibleName", 120);
if (!Array.isArray(rawComponent.permissions) || rawComponent.permissions.length > (inputSchemaVersion >= 3 ? 32 : 11)) fail("SKIN_PLUGIN_PERMISSION_INVALID", "A component requests too many explicit permissions.");
const permissions: SkinPluginPermission[] = [];
for (const permission of rawComponent.permissions) {
if (typeof permission !== "string" || !PERMISSIONS.has(permission)) fail("SKIN_PLUGIN_PERMISSION_UNKNOWN", "The component requests an unsupported permission.");
if (permissions.includes(permission as SkinPluginPermission)) fail("SKIN_PLUGIN_PERMISSION_DUPLICATE", "A component permission is duplicated.");
permissions.push(permission as SkinPluginPermission);
}
const stateScope = rawComponent.stateScope === undefined ? undefined : boundedText(rawComponent.stateScope, "component.stateScope", 96);
if (stateScope !== undefined) {
if (!COMPONENT_STATE_SCOPE_PATHS.has(stateScope)) fail("SKIN_PLUGIN_STATE_SCOPE_INVALID", "A component state scope must name a public scalar context field.");
const scopePermissions = bindingPermissions(`{{${stateScope}}}`, new Map(), new Set());
if (scopePermissions.length !== 1 || !permissions.includes(scopePermissions[0])) {
fail("SKIN_PLUGIN_PERMISSION_MISSING", "A component state scope requires the permission that exposes its context field.");
}
}
if (mode === "surface" && !permissions.includes("ui.surface.replace")) {
fail("SKIN_PLUGIN_PERMISSION_MISSING", "A page surface requires ui.surface.replace so users can approve page replacement explicitly.");
}
const state: Record<string, string | number | boolean> = Object.create(null) as Record<string, string | number | boolean>;
if (rawComponent.state !== undefined) {
if (!isRecord(rawComponent.state) || Object.keys(rawComponent.state).length > (inputSchemaVersion >= 3 ? 64 : 32)) fail("SKIN_PLUGIN_STATE_INVALID", "A component declares too many local state values.");
for (const [key, value] of Object.entries(rawComponent.state)) {
identifier(key, "state.key");
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") fail("SKIN_PLUGIN_STATE_INVALID", "Component state values must be scalar.");
if (typeof value === "string" && value.length > 512) fail("SKIN_PLUGIN_STATE_INVALID", "A component state string exceeds its limit.");
state[key] = value;
}
}
const stateKeys = new Set(Object.keys(state));
if (!isRecord(rawComponent.actions)) fail("SKIN_PLUGIN_ACTION_INVALID", "A component must declare an action map.");
const actionEntries = Object.entries(rawComponent.actions);
if (actionEntries.length > (inputSchemaVersion >= 3 ? 64 : 24)) fail("SKIN_PLUGIN_ACTION_INVALID", "A component declares too many actions.");
const actions: Record<string, SkinPluginActionDefinition> = Object.create(null) as Record<string, SkinPluginActionDefinition>;
for (const [actionId, rawAction] of actionEntries) {
identifier(actionId, "action.id");
if (!isRecord(rawAction)) fail("SKIN_PLUGIN_ACTION_INVALID", "An action must be an object.");
onlyKeys(rawAction, new Set(["type", "args"]), "Component action");
if (typeof rawAction.type !== "string" || !ACTIONS.has(rawAction.type)) fail("SKIN_PLUGIN_ACTION_UNKNOWN", "An action type is not supported by the host.");
if (inputSchemaVersion < 3 && V3_ACTIONS.has(rawAction.type)) fail("SKIN_PLUGIN_SCHEMA_UNSUPPORTED", "This action requires components schema version 3.");
if (!isRecord(rawAction.args)) fail("SKIN_PLUGIN_ACTION_INVALID", "An action must define an argument object.");
const requiredPermission = ACTION_PERMISSION[rawAction.type as SkinPluginAction];
if (requiredPermission && !permissions.includes(requiredPermission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The ${rawAction.type} action requires ${requiredPermission}.`);
if (Object.keys(rawAction.args).length > 8) fail("SKIN_PLUGIN_ACTION_INVALID", "An action has too many arguments.");
const args: Record<string, string | number | boolean> = Object.create(null) as Record<string, string | number | boolean>;
for (const [key, value] of Object.entries(rawAction.args)) {
if (!/^[a-z][a-zA-Z0-9]{0,31}$/.test(key) || !ACTION_ARGS[rawAction.type as SkinPluginAction].has(key)) fail("SKIN_PLUGIN_ACTION_INVALID", "An action uses an unsupported argument name.");
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") fail("SKIN_PLUGIN_ACTION_INVALID", "Action arguments must be static scalars or simple data bindings.");
if (typeof value === "string") {
if (value.length > 512) fail("SKIN_PLUGIN_ACTION_INVALID", "An action argument exceeds its length limit.");
}
args[key] = value;
}
if (rawAction.type === "ui.setState" && (typeof args.key !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(args.key) || !stateKeys.has(args.key) || !("value" in args))) {
fail("SKIN_PLUGIN_ACTION_INVALID", "ui.setState requires a local state key and value.");
}
if (rawAction.type === "ui.toggleState" && (typeof args.key !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(args.key) || !stateKeys.has(args.key) || typeof state[args.key] !== "boolean")) {
fail("SKIN_PLUGIN_ACTION_INVALID", "ui.toggleState requires a declared boolean local state key.");
}
if (rawAction.type === "ui.toggleState" && args.resetKey !== undefined && (typeof args.resetKey !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(args.resetKey) || args.resetKey === args.key || !stateKeys.has(args.resetKey) || typeof state[args.resetKey] !== "boolean")) {
fail("SKIN_PLUGIN_ACTION_INVALID", "ui.toggleState resetKey must name a different declared boolean local state key.");
}
if (rawAction.type === "voice.joinChannel" && typeof args.channelId !== "string") fail("SKIN_PLUGIN_ACTION_INVALID", "voice.joinChannel requires a channelId binding.");
if (rawAction.type === "favorites.switch" && typeof args.favoriteId !== "string") fail("SKIN_PLUGIN_ACTION_INVALID", "favorites.switch requires a favoriteId binding.");
if (rawAction.type === "quickServers.switch" && typeof args.quickServerId !== "string") fail("SKIN_PLUGIN_ACTION_INVALID", "quickServers.switch requires a quickServerId binding.");
if (rawAction.type === "chat.sendMessage" && typeof args.text !== "string") fail("SKIN_PLUGIN_ACTION_INVALID", "chat.sendMessage requires a text binding.");
if (rawAction.type === "voice.setOutputVolume" && typeof args.volume !== "number" && typeof args.volume !== "string") fail("SKIN_PLUGIN_ACTION_INVALID", "voice.setOutputVolume requires a volume value.");
if (rawAction.type === "voice.setAway" && typeof args.away !== "boolean") fail("SKIN_PLUGIN_ACTION_INVALID", "voice.setAway requires an away boolean.");
if (rawAction.type === "voice.setWhisperActive" && typeof args.active !== "boolean") fail("SKIN_PLUGIN_ACTION_INVALID", "voice.setWhisperActive requires an active boolean.");
if (rawAction.type === "voice.joinScreenShare" && typeof args.streamId !== "string") fail("SKIN_PLUGIN_ACTION_INVALID", "voice.joinScreenShare requires a visible streamId.");
actions[actionId] = { type: rawAction.type as SkinPluginAction, args };
}
let componentNodes = 0;
const walk = (rawNode: unknown, depth: number, aliases: ReadonlyMap<string, string> = new Map()): SkinPluginNode => {
componentNodes += 1;
if (componentNodes > (inputSchemaVersion >= 3 ? SKIN_PLUGIN_NODE_LIMIT : 256)) fail("SKIN_PLUGIN_COMPLEXITY_LIMIT", "A component contains too many template nodes.");
if (depth > (inputSchemaVersion >= 3 ? SKIN_PLUGIN_TREE_DEPTH_LIMIT : 16) || !isRecord(rawNode)) fail("SKIN_PLUGIN_TREE_INVALID", "A component tree is too deep or contains an invalid node.");
onlyKeys(rawNode, new Set(["widget", "options", "tag", "text", "part", "className", "attributes", "asset", "bindValue", "repeat", "when", "events", "children"]), "Component node");
if (inputSchemaVersion === 1 && rawNode.widget !== undefined) fail("SKIN_PLUGIN_SCHEMA_UNSUPPORTED", "Host widgets require components schema version 2.");
const nodeKinds = Number(rawNode.widget !== undefined) + Number(rawNode.tag !== undefined) + Number(rawNode.text !== undefined);
if (nodeKinds !== 1) fail("SKIN_PLUGIN_TREE_INVALID", "Each component node must define exactly one of widget, tag, or text.");
if (rawNode.options !== undefined && rawNode.widget === undefined) fail("SKIN_PLUGIN_WIDGET_OPTIONS_INVALID", "Only host widgets may declare widget options.");
const node: SkinPluginNode = {};
if (rawNode.widget !== undefined) {
if (typeof rawNode.widget !== "string" || !HOST_WIDGETS.has(rawNode.widget)) fail("SKIN_PLUGIN_WIDGET_INVALID", "The component requests an unsupported host widget.");
if (page === "demo") fail("SKIN_PLUGIN_WIDGET_INVALID", "Host widgets are available only on the home and voice client pages.");
if (rawNode.options !== undefined && inputSchemaVersion < 3) fail("SKIN_PLUGIN_SCHEMA_UNSUPPORTED", "Host widget options require components schema version 3.");
// Preserve existing schema v2 packages; newly authored v3 widgets must declare every
// permission needed by the trusted host UI they embed. Screen-share start was already gated.
let options: SkinPluginWidgetOptions | undefined;
if (rawNode.options !== undefined) {
const supportedOptions = rawNode.widget === "voice.member-cards"
? new Set(["screenShare", "memberActions"])
: rawNode.widget === "voice.channel-tree"
? new Set(["layout", "memberActions", "memberDragDrop"])
: rawNode.widget === "voice.performance-panel"
? new Set(["screenShare"])
: rawNode.widget === "voice.audio-controls"
? new Set(["layout"])
: rawNode.widget === "home.identity-provider"
? new Set(["identityProviderId", "identityProviderLabel"])
: new Set<string>();
if (!isRecord(rawNode.options)
|| Object.keys(rawNode.options).some((key) => !supportedOptions.has(key))
|| (rawNode.options.screenShare !== undefined && typeof rawNode.options.screenShare !== "boolean")
|| (rawNode.options.memberActions !== undefined && typeof rawNode.options.memberActions !== "boolean")
|| (rawNode.options.memberDragDrop !== undefined && typeof rawNode.options.memberDragDrop !== "boolean")
|| (rawNode.options.layout !== undefined
&& rawNode.options.layout !== "default"
&& !(rawNode.widget === "voice.channel-tree" && rawNode.options.layout === "server-sidebar"))
|| (rawNode.options.identityProviderId !== undefined
&& (typeof rawNode.options.identityProviderId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(rawNode.options.identityProviderId)))
|| (rawNode.options.identityProviderLabel !== undefined
&& (typeof rawNode.options.identityProviderLabel !== "string"
|| !rawNode.options.identityProviderLabel.trim()
|| rawNode.options.identityProviderLabel.length > 64
|| rawNode.options.identityProviderLabel !== rawNode.options.identityProviderLabel.trim()))) {
fail("SKIN_PLUGIN_WIDGET_OPTIONS_INVALID", "This host widget uses unsupported options.");
}
options = {
...(rawNode.options.screenShare !== undefined ? { screenShare: rawNode.options.screenShare } : {}),
...(rawNode.options.memberActions !== undefined ? { memberActions: rawNode.options.memberActions } : {}),
...(rawNode.options.memberDragDrop !== undefined ? { memberDragDrop: rawNode.options.memberDragDrop } : {}),
...(rawNode.options.layout !== undefined ? { layout: rawNode.options.layout } : {}),
...(rawNode.options.identityProviderId !== undefined ? { identityProviderId: rawNode.options.identityProviderId } : {}),
...(rawNode.options.identityProviderLabel !== undefined ? { identityProviderLabel: rawNode.options.identityProviderLabel } : {}),
};
}
if (rawNode.widget === "home.identity-provider"
&& (!isRecord(rawNode.options)
|| typeof rawNode.options.identityProviderId !== "string"
|| typeof rawNode.options.identityProviderLabel !== "string")) {
fail("SKIN_PLUGIN_WIDGET_OPTIONS_INVALID", "The identity-provider widget requires a provider ID and display label.");
}
const requiredPermission = inputSchemaVersion >= 3 || rawNode.widget === "voice.screen-share-start"
? missingSkinPluginWidgetPermission(rawNode.widget as SkinPluginHostWidget, permissions, options)
: undefined;
if (requiredPermission) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The ${rawNode.widget} widget requires ${requiredPermission}.`);
const widgetOnlyKeys = new Set(["widget", "options", "part", "className", "when"]);
onlyKeys(rawNode, widgetOnlyKeys, "Host widget node");
node.widget = rawNode.widget as SkinPluginHostWidget;
if (options) node.options = options;
}
if (rawNode.tag !== undefined) {
if (typeof rawNode.tag !== "string" || !ELEMENTS.has(rawNode.tag)) fail("SKIN_PLUGIN_ELEMENT_INVALID", "The component uses an unsupported HTML element.");
node.tag = rawNode.tag;
}
if (rawNode.text !== undefined) {
node.text = boundedText(rawNode.text, "node.text", 2048);
for (const permission of bindingPermissions(node.text, aliases, stateKeys)) {
if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The component data requires ${permission}.`);
}
}
if (rawNode.part !== undefined) node.part = identifier(rawNode.part, "node.part");
if (rawNode.className !== undefined) {
if (typeof rawNode.className !== "string" || rawNode.className.length > 160 || /[<>]/.test(rawNode.className)) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "Component class names must be bounded plain text.");
node.className = rawNode.className;
}
if (rawNode.attributes !== undefined) {
if (!isRecord(rawNode.attributes) || Object.keys(rawNode.attributes).length > (inputSchemaVersion >= 3 ? 48 : 24)) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "Component attributes must be a small object.");
const attrs: Record<string, string | number | boolean> = Object.create(null) as Record<string, string | number | boolean>;
for (const [key, value] of Object.entries(rawNode.attributes)) {
const lowerKey = key.toLowerCase();
const isAriaOrData = inputSchemaVersion >= 3 && /^(?:aria|data)-[a-z][a-z0-9-]{0,47}$/.test(lowerKey);
if ((!ATTRIBUTES.has(lowerKey) && !isAriaOrData) || lowerKey.startsWith("on") || key !== lowerKey) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "The component uses an unsupported or executable attribute.");
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "Component attributes must be scalar values.");
if (lowerKey === "src" && (node.tag !== "img" || value !== "{{server.icon}}")) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "Image sources may only bind to a TeamSpeak server icon.");
if (typeof value === "string" && ["fill", "stroke"].includes(lowerKey) && /\burl\s*\(|javascript\s*:/i.test(value)) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "SVG paint attributes cannot load external or executable resources.");
if (typeof value === "string") {
for (const permission of bindingPermissions(value, aliases, stateKeys)) {
if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The component data requires ${permission}.`);
}
if (value.length > 512) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "A component attribute exceeds its length limit.");
}
attrs[key] = value;
}
node.attributes = attrs;
}
if (rawNode.asset !== undefined) {
const asset = boundedText(rawNode.asset, "node.asset", 120);
if (node.tag !== "img") fail("SKIN_PLUGIN_ASSET_INVALID", "Package image assets can only be attached to img elements.");
if (!/^assets\/[a-zA-Z0-9._/-]+$/.test(asset) || asset.split("/").some((part) => !part || part === "." || part === "..")) fail("SKIN_PLUGIN_ASSET_INVALID", "Component assets must use safe package-relative paths.");
node.asset = asset;
}
if (rawNode.bindValue !== undefined) {
const key = identifier(rawNode.bindValue, "node.bindValue");
if (node.tag !== "input" && node.tag !== "select" && node.tag !== "textarea") fail("SKIN_PLUGIN_BINDING_INVALID", "Only input, select, and textarea elements can bind local state.");
if (!stateKeys.has(key)) fail("SKIN_PLUGIN_BINDING_INVALID", "A bound form control must reference a declared local state key.");
node.bindValue = key;
}
if (rawNode.repeat !== undefined) {
if (!isRecord(rawNode.repeat)) fail("SKIN_PLUGIN_REPEAT_INVALID", "A repeat declaration must be an object.");
onlyKeys(rawNode.repeat, new Set(["path", "as"]), "Repeat declaration");
const path = boundedText(rawNode.repeat.path, "repeat.path", 120);
const nestedChannelMembers = isNestedChannelMembersPath(path, aliases);
if (!(path === "session.channels" || path === "session.members" || path === "favorites.items" || path === "servers.quickList" || path === "chat.messages" || path === "screenShare.streams" || nestedChannelMembers)) {
fail("SKIN_PLUGIN_REPEAT_INVALID", "A component may repeat only a registered public collection or the members of a repeated channel.");
}
const permission = nestedChannelMembers ? "session.members.read" : COLLECTION_PERMISSION[path];
if (!permission || !permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `Repeating ${path} requires ${permission ?? "a registered collection permission"}.`);
const alias = identifier(rawNode.repeat.as, "repeat.as");
if (aliases.has(alias)) fail("SKIN_PLUGIN_REPEAT_INVALID", "Repeat aliases cannot shadow an existing alias.");
node.repeat = { path, as: alias };
}
if (rawNode.when !== undefined) {
if (!isRecord(rawNode.when)) fail("SKIN_PLUGIN_CONDITION_INVALID", "A condition must be an object.");
onlyKeys(rawNode.when, new Set(inputSchemaVersion >= 3 ? ["path", "equals", "empty"] : ["path", "equals"]), "Component condition");
const path = boundedText(rawNode.when.path, "condition.path", 120);
const equals = rawNode.when.equals;
if (equals !== undefined && typeof equals !== "string" && typeof equals !== "number" && typeof equals !== "boolean") fail("SKIN_PLUGIN_CONDITION_INVALID", "A condition comparison must be scalar.");
const empty = rawNode.when.empty;
if (empty !== undefined && (inputSchemaVersion < 3 || typeof empty !== "boolean" || equals !== undefined)) fail("SKIN_PLUGIN_CONDITION_INVALID", "An empty-collection condition must be a schema v3 boolean and cannot also compare a scalar.");
const nestedChannelMembers = isNestedChannelMembersPath(path, aliases);
if (nestedChannelMembers && empty === undefined) fail("SKIN_PLUGIN_CONDITION_INVALID", "Nested channel member conditions must test whether the collection is empty.");
const conditionPermissions = nestedChannelMembers ? ["session.members.read" as const] : bindingPermissions(`{{${path}}}`, aliases, stateKeys);
for (const permission of conditionPermissions) {
if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The condition data requires ${permission}.`);
}
if (typeof equals === "string") {
if (inputSchemaVersion < 3 && equals.includes("{{")) fail("SKIN_PLUGIN_SCHEMA_UNSUPPORTED", "Data-bound condition comparisons require schema v3.");
for (const permission of bindingPermissions(equals, aliases, stateKeys)) {
if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The condition comparison data requires ${permission}.`);
}
}
if (empty !== undefined && !nestedChannelMembers && !["chat.messages", "session.channels", "session.members", "favorites.items", "servers.quickList", "screenShare.streams"].includes(path)) {
fail("SKIN_PLUGIN_CONDITION_INVALID", "An empty condition must reference a registered public collection.");
}
node.when = { path, ...(equals === undefined ? {} : { equals }), ...(empty === undefined ? {} : { empty }) };
}
if (rawNode.events !== undefined) {
if (!isRecord(rawNode.events) || Object.keys(rawNode.events).length > (inputSchemaVersion >= 3 ? 18 : 6)) fail("SKIN_PLUGIN_EVENT_INVALID", "Component events must be a small object.");
const events: Partial<Record<SkinPluginEvent, string>> = {};
for (const [event, actionIdValue] of Object.entries(rawNode.events)) {
if (!EVENTS.has(event) || (inputSchemaVersion < 3 && V3_EVENTS.has(event)) || typeof actionIdValue !== "string" || !actions[actionIdValue]) fail("SKIN_PLUGIN_EVENT_INVALID", "Each component event must refer to a declared host action supported by this schema.");
const action = actions[actionIdValue];
if (action.type !== "ui.setState" && event === "input") fail("SKIN_PLUGIN_EVENT_INVALID", "Host actions cannot run while a form value is being typed; use a committed change or submit event.");
if (action.type !== "ui.setState" && action.type !== "ui.toggleState" && PASSIVE_EVENTS.has(event)) {
fail("SKIN_PLUGIN_EVENT_INVALID", "Voice and host actions require an explicit user activation event.");
}
for (const argument of Object.values(action.args)) {
if (typeof argument !== "string") continue;
for (const permission of bindingPermissions(argument, aliases, stateKeys)) {
if (!permissions.includes(permission)) fail("SKIN_PLUGIN_PERMISSION_MISSING", `The event data requires ${permission}.`);
}
}
events[event as SkinPluginEvent] = actionIdValue;
}
node.events = events;
}
if (rawNode.children !== undefined) {
if (!Array.isArray(rawNode.children) || rawNode.children.length > (inputSchemaVersion >= 3 ? 256 : 100)) fail("SKIN_PLUGIN_TREE_INVALID", "A component node contains too many children.");
if (node.tag && VOID_ELEMENTS.has(node.tag) && rawNode.children.length) fail("SKIN_PLUGIN_TREE_INVALID", "A void element cannot contain child nodes.");
const childAliases = new Map(aliases);
if (node.repeat) childAliases.set(node.repeat.as, node.repeat.path.endsWith(".members") ? "session.members" : node.repeat.path);
node.children = rawNode.children.map((child) => walk(child, depth + 1, childAliases));
}
return node;
};
const root = walk(rawComponent.root, 1);
if (!root.tag && !root.widget) fail("SKIN_PLUGIN_TREE_INVALID", "A plugin component root must be an element or a host widget.");
if (mode === "surface" && (!root.tag || root.repeat || root.when || !root.children?.length)) {
fail("SKIN_PLUGIN_TREE_INVALID", "A page surface root must be a visible container with at least one child.");
}
return { id, name, page, mode, accessibleName, permissions, actions, ...(stateScope ? { stateScope } : {}), ...(Object.keys(state).length ? { state } : {}), root };
});
const surfaces = new Set<SkinPluginPage>();
const widgetsByPage = new Map<SkinPluginPage, Set<SkinPluginHostWidget>>();
for (const component of components) {
if (component.mode === "surface") {
if (surfaces.has(component.page)) fail("SKIN_PLUGIN_SURFACE_DUPLICATE", "A skin may define only one page surface per public page.");
surfaces.add(component.page);
}
const pageWidgets = widgetsByPage.get(component.page) ?? new Set<SkinPluginHostWidget>();
const visit = (node: SkinPluginNode) => {
if (node.widget) {
if (pageWidgets.has(node.widget)) fail("SKIN_PLUGIN_WIDGET_DUPLICATE", "A skin may mount each stateful host widget only once per page.");
pageWidgets.add(node.widget);
}
node.children?.forEach(visit);
};
visit(component.root);
widgetsByPage.set(component.page, pageWidgets);
}
return { schemaVersion: inputSchemaVersion, components };
}
export function parseSkinPluginJson(source: string): SkinPluginDocument {
if (!source || new TextEncoder().encode(source).byteLength > SKIN_PLUGIN_DOCUMENT_LIMIT_BYTES) fail("SKIN_PLUGIN_DOCUMENT_SIZE", "components.json exceeds the 256 KiB limit.");
let input: unknown;
try { input = JSON.parse(source); } catch { fail("SKIN_PLUGIN_DOCUMENT_INVALID", "components.json must contain valid JSON."); }
return parseSkinPluginDocument(input);
}
/** Parse a single runtime action using the same schema and permission rules as declarative skin actions. */
export function parseSkinPluginRuntimeAction(
input: unknown,
permissions: readonly SkinPluginPermission[],
): SkinPluginActionDefinition {
if (!isRecord(input)) fail("SKIN_PLUGIN_ACTION_INVALID", "A runtime action request must be an object.");
const parsed = parseSkinPluginDocument({
schemaVersion: 3,
components: [{
id: "runtime-action",
name: "Runtime action",
page: "voice",
accessibleName: "Runtime action",
permissions: [...permissions],
actions: { request: input },
root: { tag: "main", children: [{ text: "Runtime action" }] },
}],
});
const action = parsed.components[0].actions.request;
if (!action || action.type === "ui.setState" || action.type === "ui.toggleState") {
fail("SKIN_PLUGIN_ACTION_INVALID", "A runtime action request must name a host capability.");
}
return action;
}
export function listSkinPluginAssetPaths(document: SkinPluginDocument): string[] {
const paths = new Set<string>();
const visit = (node: SkinPluginNode) => {
if (node.asset) paths.add(node.asset);
node.children?.forEach(visit);
};
document.components.forEach((component) => visit(component.root));
return [...paths];
}
export function createSkinPluginApproval(pluginId: string, permissions: readonly SkinPluginPermission[]): SkinPluginApproval {
const policyVersions: Partial<Record<SkinPluginPermission, number>> = {};
for (const permission of permissions) policyVersions[permission] = SKIN_PLUGIN_PERMISSIONS[permission].policyVersion;
return { pluginId, policyVersions };
}
export function isSkinPluginPermissionApproved(approval: SkinPluginApproval | null | undefined, pluginId: string, permission: SkinPluginPermission): boolean {
return approval?.pluginId === pluginId && approval.policyVersions[permission] === SKIN_PLUGIN_PERMISSIONS[permission].policyVersion;
}
export function skinPluginActionPermission(action: SkinPluginAction): SkinPluginPermission | null {
return ACTION_PERMISSION[action];
}
@@ -0,0 +1,100 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
computeSkinRuntimePluginDigest,
createSkinRuntimePluginApproval,
isSkinRuntimePluginApproved,
parseSkinRuntimePluginApproval,
SkinRuntimePluginApprovalError,
} from "./skin-runtime-plugin-approval.js";
import { parseSkinRuntimePluginDocument, type SkinRuntimePlugin } from "./skin-runtime-plugins.js";
function plugin(overrides: Record<string, unknown> = {}): SkinRuntimePlugin {
return parseSkinRuntimePluginDocument({
schemaVersion: 1,
plugins: [{
id: "voice-toolbar",
name: "Voice toolbar",
version: "1.0.0",
apiVersion: 1,
page: "voice",
mode: "widget",
entry: "plugins/voice-toolbar/index.js",
style: "plugins/voice-toolbar/style.css",
assets: ["plugins/voice-toolbar/assets/icon.png"],
permissions: ["session.status.read"],
...overrides,
}],
}).plugins[0];
}
function files(entry = "export default () => {};", style = ".toolbar { color: teal; }", icon = "icon-v1") {
return {
"plugins/voice-toolbar/index.js": new Blob([entry]),
"plugins/voice-toolbar/style.css": new Blob([style]),
"plugins/voice-toolbar/assets/icon.png": new Blob([icon]),
};
}
test("plugin digest is deterministic and binds all declared source, style, assets, and descriptor fields", async () => {
const definition = plugin();
const packageFiles = files();
const first = await computeSkinRuntimePluginDigest(definition, packageFiles);
assert.equal(first, await computeSkinRuntimePluginDigest(definition, packageFiles));
assert.match(first, /^[a-f0-9]{64}$/);
assert.notEqual(first, await computeSkinRuntimePluginDigest(definition, files("export default () => 1;")));
assert.notEqual(first, await computeSkinRuntimePluginDigest(definition, files(undefined, ".toolbar { color: red; }")));
assert.notEqual(first, await computeSkinRuntimePluginDigest(definition, files(undefined, undefined, "icon-v2")));
assert.notEqual(first, await computeSkinRuntimePluginDigest(plugin({ permissions: [] }), packageFiles));
assert.notEqual(first, await computeSkinRuntimePluginDigest(plugin({ mode: "surface", permissions: ["ui.surface.replace"] }), packageFiles));
assert.notEqual(first, await computeSkinRuntimePluginDigest(plugin({ mount: "voice.chat.before" }), packageFiles));
});
test("plugin approval is pinned to skin and plugin versions, content digest, and permission policy", async () => {
const definition = plugin();
const digest = await computeSkinRuntimePluginDigest(definition, files());
const approval = createSkinRuntimePluginApproval("community.sample", "2.0.0", definition, digest);
assert.equal(isSkinRuntimePluginApproved(approval, "community.sample", "2.0.0", definition, digest), true);
assert.equal(isSkinRuntimePluginApproved(approval, "community.sample", "2.0.0", definition, "0".repeat(64)), false);
assert.equal(isSkinRuntimePluginApproved(approval, "community.sample", "2.1.0", definition, digest), false);
assert.equal(isSkinRuntimePluginApproved(approval, "other.skin", "2.0.0", definition, digest), false);
assert.equal(isSkinRuntimePluginApproved(approval, "community.sample", "2.0.0", plugin({ version: "1.1.0" }), digest), false);
assert.deepEqual(parseSkinRuntimePluginApproval(approval), approval);
const stalePolicy = parseSkinRuntimePluginApproval({
...approval,
permissions: { "session.status.read": 99 },
});
assert.equal(isSkinRuntimePluginApproved(stalePolicy, "community.sample", "2.0.0", definition, digest), false);
});
test("plugin approval parser rejects malformed identities, digests, and unrecognized grants", async () => {
const definition = plugin();
const digest = await computeSkinRuntimePluginDigest(definition, files());
const approval = createSkinRuntimePluginApproval("community.sample", "2.0.0", definition, digest);
for (const candidate of [
{ ...approval, digest: "short" },
{ ...approval, pluginId: "../other" },
{ ...approval, permissions: { "filesystem.read": 1 } },
{ ...approval, extra: true },
]) {
assert.throws(() => parseSkinRuntimePluginApproval(candidate), (error: unknown) =>
error instanceof SkinRuntimePluginApprovalError && error.code === "SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID");
}
assert.throws(() => createSkinRuntimePluginApproval("", "2.0.0", definition, digest), { code: "SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID" });
});
test("plugin digest refuses missing declared files and packages beyond the ZIP expansion bound", async () => {
const definition = plugin();
await assert.rejects(
computeSkinRuntimePluginDigest(definition, {}),
(error: unknown) => error instanceof SkinRuntimePluginApprovalError && error.code === "SKIN_RUNTIME_PLUGIN_DIGEST_FILE_MISSING",
);
await assert.rejects(
computeSkinRuntimePluginDigest(definition, {
...files(),
"plugins/voice-toolbar/assets/icon.png": new Blob([new Uint8Array(50 * 1024 * 1024)]),
}),
(error: unknown) => error instanceof SkinRuntimePluginApprovalError && error.code === "SKIN_RUNTIME_PLUGIN_DIGEST_SIZE",
);
});
+178
View File
@@ -0,0 +1,178 @@
import { SKIN_PLUGIN_PERMISSIONS, type SkinPluginPermission } from "./skin-plugin.js";
import { parseSkinRuntimePluginDocument, type SkinRuntimePlugin } from "./skin-runtime-plugins.js";
export const SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION = 1 as const;
export const SKIN_RUNTIME_PLUGIN_DIGEST_ALGORITHM = "SHA-256" as const;
export const SKIN_RUNTIME_PLUGIN_DIGEST_TOTAL_LIMIT_BYTES = 50 * 1024 * 1024;
export interface SkinRuntimePluginApproval {
schemaVersion: typeof SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION;
skinId: string;
skinVersion: string;
pluginId: string;
pluginVersion: string;
apiVersion: 1;
digest: string;
permissions: Readonly<Partial<Record<SkinPluginPermission, number>>>;
}
export class SkinRuntimePluginApprovalError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinRuntimePluginApprovalError";
}
}
function invalid(code: string, message: string): never {
throw new SkinRuntimePluginApprovalError(code, message);
}
function isRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function validDigest(value: unknown): value is string {
return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
}
function sha256(bytes: Uint8Array): Promise<string> {
if (!globalThis.crypto?.subtle) {
return Promise.reject(new SkinRuntimePluginApprovalError("SKIN_RUNTIME_PLUGIN_DIGEST_UNAVAILABLE", "Secure plugin approval requires Web Crypto."));
}
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
return globalThis.crypto.subtle.digest(SKIN_RUNTIME_PLUGIN_DIGEST_ALGORITHM, buffer).then((digest) =>
Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""));
}
/**
* Binds local consent to the exact plugin descriptor and every declared package file.
* This is an integrity key for local approval, not a publisher signature.
*/
export async function computeSkinRuntimePluginDigest(
input: SkinRuntimePlugin,
files: Readonly<Record<string, Blob>>,
): Promise<string> {
if (!files || typeof files !== "object" || Array.isArray(files)) {
invalid("SKIN_RUNTIME_PLUGIN_DIGEST_FILE_MISSING", "The declared plugin files are unavailable.");
}
const plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [input] }).plugins[0];
const paths = [plugin.entry, ...(plugin.style ? [plugin.style] : []), ...plugin.assets].sort();
let totalBytes = 0;
const fileDigests: Array<{ path: string; size: number; digest: string }> = [];
for (const path of paths) {
if (!Object.hasOwn(files, path) || !(files[path] instanceof Blob)) {
invalid("SKIN_RUNTIME_PLUGIN_DIGEST_FILE_MISSING", "A declared plugin file is missing from the digest input.");
}
const blob = files[path];
totalBytes += blob.size;
if (totalBytes > SKIN_RUNTIME_PLUGIN_DIGEST_TOTAL_LIMIT_BYTES) {
invalid("SKIN_RUNTIME_PLUGIN_DIGEST_SIZE", "The declared plugin files exceed the skin package size limit.");
}
fileDigests.push({ path, size: blob.size, digest: await sha256(new Uint8Array(await blob.arrayBuffer())) });
}
const canonicalPlugin = {
id: plugin.id,
name: plugin.name,
version: plugin.version,
apiVersion: plugin.apiVersion,
runtime: plugin.runtime,
page: plugin.page,
mode: plugin.mode,
...(plugin.mount ? { mount: plugin.mount } : {}),
entry: plugin.entry,
...(plugin.style ? { style: plugin.style } : {}),
assets: [...plugin.assets].sort(),
permissions: [...plugin.permissions].sort(),
};
const canonical = JSON.stringify({
domain: "webspeak.skin-runtime-plugin-approval",
schemaVersion: SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION,
plugin: canonicalPlugin,
files: fileDigests,
});
return sha256(new TextEncoder().encode(canonical));
}
export function createSkinRuntimePluginApproval(
skinId: string,
skinVersion: string,
input: SkinRuntimePlugin,
digest: string,
): SkinRuntimePluginApproval {
if (typeof skinId !== "string" || !skinId.trim() || skinId.length > 120
|| typeof skinVersion !== "string" || !skinVersion.trim() || skinVersion.length > 32
|| !validDigest(digest)) {
invalid("SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID", "The host approval identity or plugin digest is invalid.");
}
const plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [input] }).plugins[0];
const permissions: Partial<Record<SkinPluginPermission, number>> = {};
for (const permission of plugin.permissions) permissions[permission] = SKIN_PLUGIN_PERMISSIONS[permission].policyVersion;
return Object.freeze({
schemaVersion: SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION,
skinId,
skinVersion,
pluginId: plugin.id,
pluginVersion: plugin.version,
apiVersion: plugin.apiVersion,
digest,
permissions: Object.freeze(permissions),
});
}
export function parseSkinRuntimePluginApproval(input: unknown): SkinRuntimePluginApproval {
const fields = ["schemaVersion", "skinId", "skinVersion", "pluginId", "pluginVersion", "apiVersion", "digest", "permissions"];
if (!isRecord(input) || Object.keys(input).length !== fields.length || fields.some((field) => !Object.hasOwn(input, field))) {
invalid("SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID", "The stored plugin approval has an invalid shape.");
}
if (input.schemaVersion !== SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION
|| typeof input.skinId !== "string" || !input.skinId.trim() || input.skinId.length > 120
|| typeof input.skinVersion !== "string" || !input.skinVersion.trim() || input.skinVersion.length > 32
|| typeof input.pluginId !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(input.pluginId)
|| typeof input.pluginVersion !== "string" || input.pluginVersion.length > 32
|| input.apiVersion !== 1 || !validDigest(input.digest) || !isRecord(input.permissions)) {
invalid("SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID", "The stored plugin approval has invalid identity fields.");
}
const permissions: Partial<Record<SkinPluginPermission, number>> = {};
for (const [permission, policyVersion] of Object.entries(input.permissions)) {
if (!Object.hasOwn(SKIN_PLUGIN_PERMISSIONS, permission)
|| !Number.isSafeInteger(policyVersion) || (policyVersion as number) < 1) {
invalid("SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID", "The stored plugin approval contains an unsupported permission.");
}
permissions[permission as SkinPluginPermission] = policyVersion as number;
}
return Object.freeze({
schemaVersion: SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION,
skinId: input.skinId,
skinVersion: input.skinVersion,
pluginId: input.pluginId,
pluginVersion: input.pluginVersion,
apiVersion: 1,
digest: input.digest,
permissions: Object.freeze(permissions),
});
}
export function isSkinRuntimePluginApproved(
approval: SkinRuntimePluginApproval,
skinId: string,
skinVersion: string,
input: SkinRuntimePlugin,
digest: string,
): boolean {
let plugin: SkinRuntimePlugin;
try { plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [input] }).plugins[0]; }
catch { return false; }
return approval.skinId === skinId
&& approval.skinVersion === skinVersion
&& approval.pluginId === plugin.id
&& approval.pluginVersion === plugin.version
&& approval.apiVersion === plugin.apiVersion
&& approval.digest === digest
&& validDigest(digest)
&& plugin.permissions.every((permission) =>
approval.permissions[permission] === SKIN_PLUGIN_PERMISSIONS[permission].policyVersion);
}
@@ -0,0 +1,175 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
projectSkinRuntimePluginContext,
SKIN_RUNTIME_PLUGIN_CONTEXT_LIMIT_BYTES,
} from "./skin-runtime-plugin-context.js";
test("runtime context exposes only fields covered by declared read permissions", () => {
const projected = projectSkinRuntimePluginContext(["session.channels.read"], {
session: {
status: { connected: true, serverLabel: "voice.internal.example:9987" },
channels: [{ id: "channel-1", name: "Lobby", parentId: null, depth: 0, memberCount: 2, memberCountLabel: "02", maxClients: 10, maxClientsLimited: true, current: true, address: "voice.internal.example:9987", members: [{ name: "private nested member" }] }],
members: [{ id: "member-1", name: "private member" }],
},
favorites: { items: [{ id: "opaque-1", label: "Saved", address: "secret.example:9987" }] },
});
assert.deepEqual(JSON.parse(JSON.stringify(projected)), {
session: {
channels: [{ id: "channel-1", name: "Lobby", parentId: null, depth: 0, memberCount: 2, memberCountLabel: "02", maxClients: 10, maxClientsLimited: true, current: true }],
},
});
assert.equal(JSON.stringify(projected).includes("voice.internal.example"), false);
assert.equal(JSON.stringify(projected).includes("secret.example"), false);
});
test("chat panel state is projected only to plugins with chat read permission", () => {
const context = { chat: { status: { panelOpen: true, tab: "private", tabLabel: "私聊", recipient: "not exposed" } } };
assert.deepEqual(JSON.parse(JSON.stringify(projectSkinRuntimePluginContext(["chat.channel.read"], context))), {
chat: { status: { panelOpen: true, tab: "private", tabLabel: "私聊" } },
});
assert.deepEqual(JSON.parse(JSON.stringify(projectSkinRuntimePluginContext([], context))), {});
});
test("audio processing and accompaniment states are projected only with audio status permission", () => {
const context = {
audio: {
status: {
microphoneMuted: false,
outputMuted: true,
noiseSuppressionEnabled: true,
accompanimentActive: false,
inputVolume: 0.75,
},
},
};
assert.deepEqual(JSON.parse(JSON.stringify(projectSkinRuntimePluginContext(["audio.status.read"], context))), {
audio: { status: { microphoneMuted: false, outputMuted: true, noiseSuppressionEnabled: true, accompanimentActive: false } },
});
assert.deepEqual(JSON.parse(JSON.stringify(projectSkinRuntimePluginContext([], context))), {});
});
test("runtime member screen-share status is separately permission-gated", () => {
const context = {
session: {
members: [{
id: "42",
name: "Sharing member",
channelId: "channel-1",
status: "online",
speaking: false,
self: false,
screenSharing: true,
screenShareStreamId: "share-opaque-id",
}],
},
};
const memberOnly = projectSkinRuntimePluginContext(["session.members.read"], context);
assert.deepEqual(JSON.parse(JSON.stringify(memberOnly)), {
session: { members: [{ id: "42", name: "Sharing member", channelId: "channel-1", status: "online", speaking: false, self: false }] },
});
const withShareRead = projectSkinRuntimePluginContext(["session.members.read", "voice.screenShare.read"], context);
assert.deepEqual(JSON.parse(JSON.stringify(withShareRead)), {
session: { members: [{
id: "42", name: "Sharing member", channelId: "channel-1", status: "online", speaking: false, self: false,
screenSharing: true, screenShareStreamId: "share-opaque-id",
}] },
});
});
test("runtime context keeps safe server names and redacts connection targets from all public labels", () => {
const projected = projectSkinRuntimePluginContext(
["session.status.read", "favorites.read", "servers.quickList.read"],
{
session: { status: { connected: true, connecting: false, connectionState: "connected", serverLabel: "server.example.invalid:9987", channelName: "Lobby" } },
favorites: { items: [{ id: "opaque-favorite", label: "Saved voice.internal.example:9987", kind: "favorite" }] },
servers: { quickList: [
{ id: "opaque-favorite", label: "Saved [2001:db8::1]:9987", favorite: true, kind: "favorite" },
{ id: "opaque-recent", label: "Quick connect server.example.invalid", favorite: false, kind: "recent" },
] },
},
);
assert.deepEqual(JSON.parse(JSON.stringify(projected)), {
session: { status: { connected: true, connecting: false, connectionState: "connected", channelName: "Lobby" } },
favorites: { items: [{ id: "opaque-favorite", label: "Favorite 1", kind: "favorite" }] },
servers: { quickList: [
{ id: "opaque-favorite", label: "Favorite 1", favorite: true, kind: "favorite" },
{ id: "opaque-recent", label: "Recent 2", favorite: false, kind: "recent" },
] },
});
assert.equal(JSON.stringify(projected).includes("server.example.invalid"), false);
assert.equal(JSON.stringify(projected).includes("internal.example"), false);
assert.equal(JSON.stringify(projected).includes("2001:db8::1"), false);
const safeServerName = projectSkinRuntimePluginContext(["session.status.read"], {
session: { status: { connected: true, connectionState: "connected", serverLabel: "兄弟们的teamspeak" } },
});
assert.deepEqual(JSON.parse(JSON.stringify(safeServerName)), {
session: { status: { connected: true, connectionState: "connected", serverLabel: "兄弟们的teamspeak" } },
});
});
test("runtime channel limits are bounded public metadata and do not admit neighboring fields", () => {
const projected = projectSkinRuntimePluginContext(["session.channels.read"], {
session: {
channels: [{
id: "channel-1", name: "Lobby", memberCount: 2, memberCountLabel: "02",
maxClients: 65_536, maxClientsLimited: true, address: "voice.internal.example:9987",
}],
},
});
assert.deepEqual(JSON.parse(JSON.stringify(projected)), {
session: { channels: [{ id: "channel-1", name: "Lobby", memberCount: 2, memberCountLabel: "02", maxClientsLimited: true }] },
});
assert.equal(JSON.stringify(projected).includes("voice.internal.example"), false);
});
test("profile-picture display permission does not expose image data to declarative or Wasm contexts", () => {
const context = {
session: {
members: [{ id: "member-1", name: "Visible member", channelId: "channel-1", status: "online", speaking: false, self: false, avatar: "data:image/png;base64,cHJpdmF0ZQ==" }],
},
};
const displayOnly = projectSkinRuntimePluginContext(["session.memberAvatars.read"], context);
assert.deepEqual(JSON.parse(JSON.stringify(displayOnly)), {});
const readableMembers = projectSkinRuntimePluginContext(["session.members.read", "session.memberAvatars.read"], context);
assert.deepEqual(JSON.parse(JSON.stringify(readableMembers)), {
session: {
members: [{ id: "member-1", name: "Visible member", channelId: "channel-1", status: "online", speaking: false, self: false }],
},
});
assert.equal(JSON.stringify(readableMembers).includes("data:image"), false);
});
test("large runtime context is capped across separately bounded collections", () => {
const projected = projectSkinRuntimePluginContext(["session.channels.read", "chat.channel.read"], {
session: {
channels: Array.from({ length: 1_000 }, (_, index) => ({
id: `channel-${index}`,
name: `Channel ${index} ${"x".repeat(150)}`,
depth: index % 4,
memberCount: index,
current: index === 0,
})),
},
chat: {
messages: Array.from({ length: 50 }, (_, index) => ({
id: `message-${index}`,
text: "x".repeat(1_024),
kind: "message",
})),
},
});
const channels = (projected.session as { channels: unknown[] }).channels;
const messages = (projected.chat as { messages: unknown[] }).messages;
assert.ok(channels.length <= 128, "the channel count remains bounded");
assert.ok(messages.length < 50, "the global byte cap trims a large collection");
assert.ok(new TextEncoder().encode(JSON.stringify(projected)).byteLength <= SKIN_RUNTIME_PLUGIN_CONTEXT_LIMIT_BYTES);
});
+196
View File
@@ -0,0 +1,196 @@
import type { SkinPluginPermission } from "./skin-plugin.js";
/** Maximum serialized, permission-filtered application data passed to one Wasm UI run. */
export const SKIN_RUNTIME_PLUGIN_CONTEXT_LIMIT_BYTES = 48 * 1024;
export const SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS: readonly SkinPluginPermission[] = Object.freeze([
"session.status.read",
"session.channels.read",
"session.members.read",
"chat.channel.read",
"favorites.read",
"servers.quickList.read",
"audio.status.read",
"voice.whisper.status.read",
"voice.screenShare.status.read",
"voice.screenShare.read",
]);
interface CollectionProjection {
path: readonly string[];
permission: SkinPluginPermission;
fields: ReadonlySet<string>;
fieldPermissions?: Readonly<Record<string, SkinPluginPermission>>;
maxItems: number;
keepNewest?: boolean;
}
const COLLECTIONS: readonly CollectionProjection[] = Object.freeze([
{ path: ["session", "channels"], permission: "session.channels.read", fields: new Set(["id", "name", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]), maxItems: 128 },
{
path: ["session", "members"],
permission: "session.members.read",
fields: new Set(["id", "name", "channelId", "status", "speaking", "self", "screenSharing", "screenShareStreamId"]),
fieldPermissions: { screenSharing: "voice.screenShare.read", screenShareStreamId: "voice.screenShare.read" },
maxItems: 256,
},
{ path: ["favorites", "items"], permission: "favorites.read", fields: new Set(["id", "label", "current", "kind"]), maxItems: 100 },
{ path: ["servers", "quickList"], permission: "servers.quickList.read", fields: new Set(["id", "label", "current", "kind", "favorite"]), maxItems: 100 },
{ path: ["chat", "messages"], permission: "chat.channel.read", fields: new Set(["id", "author", "text", "time", "kind", "channelId"]), maxItems: 50, keepNewest: true },
{ path: ["screenShare", "streams"], permission: "voice.screenShare.read", fields: new Set(["streamId", "source", "ownerClientId", "ownerNickname", "name", "audio", "viewerCount"]), maxItems: 32 },
]);
interface ContextProjection {
path: readonly string[];
permission: SkinPluginPermission;
fields: ReadonlySet<string>;
}
const CONTEXTS: readonly ContextProjection[] = Object.freeze([
{ path: ["chat", "status"], permission: "chat.channel.read", fields: new Set(["panelOpen", "tab", "tabLabel"]) },
{ path: ["session", "status"], permission: "session.status.read", fields: new Set(["connected", "connecting", "connectionState", "channelId", "channelName", "userName", "serverLabel"]) },
{ path: ["audio", "status"], permission: "audio.status.read", fields: new Set(["microphoneMuted", "outputMuted", "noiseSuppressionEnabled", "accompanimentActive"]) },
{ path: ["whisper", "status"], permission: "voice.whisper.status.read", fields: new Set(["active", "targetCount"]) },
{ path: ["screenShare", "status"], permission: "voice.screenShare.status.read", fields: new Set(["active", "starting", "viewing"]) },
]);
const BOOLEAN_FIELDS = new Set(["connected", "connecting", "current", "favorite", "speaking", "self", "screenSharing", "audio", "microphoneMuted", "outputMuted", "noiseSuppressionEnabled", "accompanimentActive", "active", "starting", "viewing", "maxClientsLimited", "panelOpen"]);
const NUMBER_FIELDS = new Set(["depth", "memberCount", "targetCount", "ownerClientId", "viewerCount", "maxClients"]);
const TEXT_LIMITS: Readonly<Record<string, number>> = Object.freeze({
id: 128,
streamId: 128,
screenShareStreamId: 128,
channelId: 128,
parentId: 128,
name: 160,
label: 160,
channelName: 160,
userName: 160,
serverLabel: 160,
ownerNickname: 160,
author: 160,
status: 48,
connectionState: 16,
source: 48,
kind: 48,
tab: 16,
tabLabel: 48,
time: 48,
memberCountLabel: 12,
text: 1_024,
});
const CONNECTION_TARGET_PATTERN = /(?:\b(?:\d{1,3}\.){3}\d{1,3}(?::\d{1,5})?\b|\[[0-9a-f:]+\](?::\d{1,5})?|\b(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}(?::\d{1,5})?\b|\b(?:[0-9a-f]{0,4}:){2,}[0-9a-f:]{1,}\b)/i;
function isRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function readPath(value: unknown, path: readonly string[]): unknown {
let current = value;
for (const segment of path) {
if (!isRecord(current) || !Object.hasOwn(current, segment)) return undefined;
current = current[segment];
}
return current;
}
function boundedValue(field: string, value: unknown): string | number | boolean | null | undefined {
if (value === null) return field === "parentId" ? null : undefined;
if (BOOLEAN_FIELDS.has(field)) return typeof value === "boolean" ? value : undefined;
if (NUMBER_FIELDS.has(field)) return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= (field === "maxClients" ? 65_535 : 1_000_000_000)
? value
: undefined;
if (typeof value !== "string") return undefined;
const maximum = TEXT_LIMITS[field] ?? 160;
if (value.length > maximum) return undefined;
return value.replace(/\u0000/g, "");
}
function projectRecord(value: unknown, fields: ReadonlySet<string>): Record<string, unknown> | null {
if (!isRecord(value)) return null;
const projected: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
for (const field of fields) {
if (!Object.hasOwn(value, field)) continue;
const safe = boundedValue(field, value[field]);
if (field === "serverLabel" && typeof safe === "string" && CONNECTION_TARGET_PATTERN.test(safe)) continue;
if (safe !== undefined) projected[field] = safe;
}
return projected;
}
function projectCollectionItem(
definition: CollectionProjection,
value: unknown,
index: number,
): Record<string, unknown> | null {
const projected = projectRecord(value, definition.fields);
if (!projected || typeof projected.label !== "string" || !CONNECTION_TARGET_PATTERN.test(projected.label)) return projected;
const isFavoriteList = definition.path[0] === "favorites" || projected.favorite === true || projected.kind === "favorite";
projected.label = `${isFavoriteList ? "Favorite" : "Recent"} ${index + 1}`;
return projected;
}
function writePath(target: Record<string, unknown>, path: readonly string[], value: unknown): void {
let current = target;
for (const segment of path.slice(0, -1)) {
const existing = current[segment];
if (!isRecord(existing)) current[segment] = Object.create(null) as Record<string, unknown>;
current = current[segment] as Record<string, unknown>;
}
current[path[path.length - 1]] = value;
}
function encodedSize(value: unknown): number {
try { return new TextEncoder().encode(JSON.stringify(value)).byteLength; }
catch { return SKIN_RUNTIME_PLUGIN_CONTEXT_LIMIT_BYTES + 1; }
}
/**
* Copies only public, permission-matched fields into an immutable-by-convention snapshot.
* Addresses, credentials, SDK objects, and unknown fields never cross the guest boundary.
*/
export function projectSkinRuntimePluginContext(
permissions: readonly string[],
context: unknown,
): Record<string, unknown> {
const allowed = new Set(permissions);
const projected: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
const projectedCollections: Array<{ definition: CollectionProjection; items: Record<string, unknown>[] }> = [];
for (const definition of CONTEXTS) {
if (!allowed.has(definition.permission)) continue;
const record = projectRecord(readPath(context, definition.path), definition.fields);
if (record && Object.keys(record).length) writePath(projected, definition.path, record);
}
for (const definition of COLLECTIONS) {
if (!allowed.has(definition.permission)) continue;
const raw = readPath(context, definition.path);
if (!Array.isArray(raw)) continue;
const selected = definition.keepNewest ? raw.slice(-definition.maxItems) : raw.slice(0, definition.maxItems);
const fields = definition.fieldPermissions
? new Set([...definition.fields].filter((field) => !definition.fieldPermissions?.[field] || allowed.has(definition.fieldPermissions[field])))
: definition.fields;
const visibleDefinition = fields === definition.fields ? definition : { ...definition, fields };
const items = selected.map((item, index) => projectCollectionItem(visibleDefinition, item, index)).filter((item): item is Record<string, unknown> => Boolean(item));
writePath(projected, definition.path, items);
projectedCollections.push({ definition: visibleDefinition, items });
}
// Keep the snapshot within the independent context budget even when a server is unusually large.
while (encodedSize(projected) > SKIN_RUNTIME_PLUGIN_CONTEXT_LIMIT_BYTES) {
const largest = projectedCollections
.filter(({ items }) => items.length > 0)
.sort((left, right) => encodedSize(right.items) - encodedSize(left.items))[0];
if (!largest) break;
const nextLength = Math.max(0, Math.floor(largest.items.length * 0.75));
const removeCount = largest.items.length - nextLength;
largest.items.splice(largest.definition.keepNewest ? 0 : nextLength, removeCount);
}
return projected;
}
+132
View File
@@ -0,0 +1,132 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
listSkinRuntimePluginFilePaths,
parseSkinRuntimePluginDocument,
parseSkinRuntimePluginJson,
SkinRuntimePluginValidationError,
SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES,
} from "./skin-runtime-plugins.js";
const plugin = {
id: "voice-toolbar",
name: "Voice toolbar",
version: "1.2.3",
apiVersion: 1,
page: "voice",
mode: "widget",
entry: "plugins/voice-toolbar/index.js",
style: "plugins/voice-toolbar/style.css",
assets: ["plugins/voice-toolbar/assets/icon.png"],
permissions: ["session.channels.read"],
};
function document(plugins: unknown[] = [plugin]): unknown {
return { schemaVersion: 1, plugins };
}
test("v4 plugin descriptors accept bounded local files and freeze their parsed data", () => {
const parsed = parseSkinRuntimePluginDocument(document() as never);
assert.deepEqual(listSkinRuntimePluginFilePaths(parsed), [
"plugins/voice-toolbar/index.js",
"plugins/voice-toolbar/style.css",
"plugins/voice-toolbar/assets/icon.png",
]);
assert.equal(parsed.plugins[0].permissions[0], "session.channels.read");
assert.equal(parsed.plugins[0].runtime, "javascript");
assert.ok(Object.isFrozen(parsed) && Object.isFrozen(parsed.plugins) && Object.isFrozen(parsed.plugins[0]));
assert.ok(Object.isFrozen(parsed.plugins[0].assets) && Object.isFrozen(parsed.plugins[0].permissions));
});
test("v4 plugin descriptors recognize Wasm entries and reject a runtime/file mismatch", () => {
const wasm = parseSkinRuntimePluginDocument(document([{ ...plugin, runtime: "wasm", entry: "plugins/voice-toolbar/index.wasm" }]) as never);
assert.equal(wasm.plugins[0].runtime, "wasm");
assert.equal(wasm.plugins[0].entry, "plugins/voice-toolbar/index.wasm");
assert.throws(
() => parseSkinRuntimePluginDocument(document([{ ...plugin, runtime: "wasm" }]) as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_PATH_INVALID",
);
assert.throws(
() => parseSkinRuntimePluginDocument(document([{ ...plugin, runtime: "native" }]) as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_RUNTIME_INVALID",
);
assert.throws(
() => parseSkinRuntimePluginDocument(document([{ ...plugin, permissions: ["ui.surface.replace"] }]) as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_PERMISSION_INVALID",
);
});
test("surface replacement is an explicit page-scoped plugin capability", () => {
const surface = { ...plugin, mode: "surface", permissions: ["ui.surface.replace"] };
const parsed = parseSkinRuntimePluginDocument(document([surface]) as never);
assert.equal(parsed.plugins[0].mode, "surface");
assert.throws(
() => parseSkinRuntimePluginDocument(document([{ ...surface, permissions: [] }]) as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_PERMISSION_MISSING",
);
assert.throws(
() => parseSkinRuntimePluginDocument(document([surface, { ...surface, id: "other-surface", entry: "plugins/other-surface/index.js", style: "plugins/other-surface/style.css", assets: ["plugins/other-surface/assets/icon.png"] }]) as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_SURFACE_DUPLICATE",
);
});
test("runtime plugins can request explicit access to values from their own UI inputs", () => {
const inputReader = parseSkinRuntimePluginDocument(document([{ ...plugin, permissions: ["ui.input.read"] }]) as never);
assert.deepEqual(inputReader.plugins[0].permissions, ["ui.input.read"]);
});
test("runtime widget mount slots are page-scoped and included in the parsed descriptor", () => {
const voiceWidget = parseSkinRuntimePluginDocument(document([{ ...plugin, mount: "voice.chat.before" }]) as never);
assert.equal(voiceWidget.plugins[0].mount, "voice.chat.before");
for (const value of [
{ ...plugin, mount: "voice.chat.before", page: "home" },
{ ...plugin, mount: "admin.header" },
{ ...plugin, mode: "surface", mount: "voice.workspace.overlay", permissions: ["ui.surface.replace"] },
]) {
assert.throws(
() => parseSkinRuntimePluginDocument(document([value]) as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_MOUNT_INVALID",
);
}
});
test("v4 plugin descriptors reject unknown fields, path escape, wrong ownership, and executable assets", () => {
const cases: Array<[unknown, string]> = [
[{ ...plugin, arbitraryCodeHook: "run" }, "SKIN_RUNTIME_PLUGIN_FIELD_INVALID"],
[{ ...plugin, entry: "plugins/voice-toolbar/../other.js" }, "SKIN_RUNTIME_PLUGIN_PATH_INVALID"],
[{ ...plugin, entry: "plugins/other/index.js" }, "SKIN_RUNTIME_PLUGIN_PATH_INVALID"],
[{ ...plugin, assets: ["plugins/voice-toolbar/assets/plugin.js"] }, "SKIN_RUNTIME_PLUGIN_ASSET_INVALID"],
[{ ...plugin, assets: ["plugins/another/assets/icon.png"] }, "SKIN_RUNTIME_PLUGIN_ASSET_INVALID"],
[{ ...plugin, permissions: ["network.fetch"] }, "SKIN_RUNTIME_PLUGIN_PERMISSION_INVALID"],
[{ ...plugin, assets: [plugin.assets[0], plugin.assets[0]] }, "SKIN_RUNTIME_PLUGIN_ASSET_INVALID"],
];
for (const [value, code] of cases) {
assert.throws(
() => parseSkinRuntimePluginDocument(document([value]) as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === code,
);
}
assert.throws(
() => parseSkinRuntimePluginDocument(document([plugin, { ...plugin }]) as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_ID_INVALID",
);
});
test("v4 plugin documents enforce schema, counts, and UTF-8 byte limits", () => {
assert.throws(
() => parseSkinRuntimePluginDocument({ schemaVersion: 2, plugins: [plugin] } as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID",
);
assert.throws(
() => parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [] } as never),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID",
);
assert.throws(
() => parseSkinRuntimePluginJson(" ".repeat(SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES + 1)),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_DOCUMENT_SIZE",
);
assert.throws(
() => parseSkinRuntimePluginJson("{"),
(error: unknown) => error instanceof SkinRuntimePluginValidationError && error.code === "SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID",
);
});
+232
View File
@@ -0,0 +1,232 @@
import { SKIN_PLUGIN_PERMISSIONS, type SkinPluginPermission } from "./skin-plugin.js";
export const SKIN_RUNTIME_PLUGIN_DOCUMENT_VERSION = 1 as const;
export const SKIN_RUNTIME_PLUGIN_LIMIT = 64;
export const SKIN_RUNTIME_PLUGIN_ASSET_LIMIT = 32;
export const SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES = 256 * 1024;
export const SKIN_RUNTIME_PLUGIN_SOURCE_LIMIT_BYTES = 256 * 1024;
export const SKIN_RUNTIME_PLUGIN_STYLE_LIMIT_BYTES = 512 * 1024;
export type SkinRuntimePluginPage = "home" | "voice";
export type SkinRuntimePluginMode = "widget" | "surface";
export type SkinRuntimePluginRuntime = "javascript" | "wasm";
export const SKIN_RUNTIME_PLUGIN_MOUNT_SLOTS = Object.freeze([
"home.header.after", "home.content.before", "home.content.after", "home.footer.before",
"voice.server-rail.before", "voice.server-rail.after", "voice.header.before", "voice.header.after",
"voice.activity.before", "voice.activity.after", "voice.chat.before", "voice.chat.after",
"voice.channel-panel.before", "voice.channel-panel.after", "voice.audio-dock.before", "voice.audio-dock.after",
"voice.mobile-nav.before", "voice.mobile-nav.after", "voice.workspace.overlay",
] as const);
export type SkinRuntimePluginMountSlot = typeof SKIN_RUNTIME_PLUGIN_MOUNT_SLOTS[number];
export interface SkinRuntimePlugin {
id: string;
name: string;
version: string;
apiVersion: 1;
runtime: SkinRuntimePluginRuntime;
page: SkinRuntimePluginPage;
mode: SkinRuntimePluginMode;
mount?: SkinRuntimePluginMountSlot;
entry: string;
style?: string;
assets: readonly string[];
permissions: readonly SkinPluginPermission[];
}
export interface SkinRuntimePluginDocument {
schemaVersion: typeof SKIN_RUNTIME_PLUGIN_DOCUMENT_VERSION;
plugins: readonly SkinRuntimePlugin[];
}
export class SkinRuntimePluginValidationError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinRuntimePluginValidationError";
}
}
const PLUGIN_ID = /^[a-z][a-z0-9-]{0,63}$/;
const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
const PERMISSIONS = new Set<string>(Object.keys(SKIN_PLUGIN_PERMISSIONS));
const MOUNT_SLOT_PAGES: Readonly<Record<SkinRuntimePluginMountSlot, SkinRuntimePluginPage>> = Object.freeze({
"home.header.after": "home",
"home.content.before": "home",
"home.content.after": "home",
"home.footer.before": "home",
"voice.server-rail.before": "voice",
"voice.server-rail.after": "voice",
"voice.header.before": "voice",
"voice.header.after": "voice",
"voice.activity.before": "voice",
"voice.activity.after": "voice",
"voice.chat.before": "voice",
"voice.chat.after": "voice",
"voice.channel-panel.before": "voice",
"voice.channel-panel.after": "voice",
"voice.audio-dock.before": "voice",
"voice.audio-dock.after": "voice",
"voice.mobile-nav.before": "voice",
"voice.mobile-nav.after": "voice",
"voice.workspace.overlay": "voice",
});
const ASSET_PATH = /^plugins\/([a-z][a-z0-9-]{0,63})\/assets\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.(?:png|jpe?g|webp|avif|gif|woff2)$/i;
function invalid(code: string, message: string): never {
throw new SkinRuntimePluginValidationError(code, message);
}
function isRecord(value: unknown): value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function onlyKeys(value: Record<string, unknown>, allowed: readonly string[], context: string): void {
if (Object.keys(value).some((key) => !allowed.includes(key))) {
invalid("SKIN_RUNTIME_PLUGIN_FIELD_INVALID", `${context} contains an unsupported field.`);
}
}
function text(value: unknown, field: string, maximum: number): string {
if (typeof value !== "string" || !value.trim() || value.length > maximum || value.trim() !== value) {
invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", `${field} must be bounded non-empty text.`);
}
return value;
}
function packageFile(value: unknown, field: string, pluginId: string, suffixes: readonly (".js" | ".css" | ".wasm")[]): string {
const result = text(value, field, 160);
if (result.includes("\\") || result.startsWith("/") || result.split("/").some((part) => !part || part === "." || part === "..")
|| !result.startsWith(`plugins/${pluginId}/`) || !suffixes.some((suffix) => result.toLowerCase().endsWith(suffix))) {
invalid("SKIN_RUNTIME_PLUGIN_PATH_INVALID", `${field} must be a safe plugin file inside its plugin directory.`);
}
return result;
}
/** Parses the v4 author-plugin descriptor. It never evaluates plugin code. */
export function parseSkinRuntimePluginDocument(input: unknown): SkinRuntimePluginDocument {
if (!isRecord(input)) invalid("SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID", "plugins.json must contain an object.");
onlyKeys(input, ["schemaVersion", "plugins"], "plugins.json");
if (input.schemaVersion !== SKIN_RUNTIME_PLUGIN_DOCUMENT_VERSION || !Array.isArray(input.plugins)
|| input.plugins.length < 1 || input.plugins.length > SKIN_RUNTIME_PLUGIN_LIMIT) {
invalid("SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID", "plugins.json uses an unsupported version or plugin count.");
}
const ids = new Set<string>();
const files = new Set<string>();
const plugins: SkinRuntimePlugin[] = [];
for (const raw of input.plugins) {
if (!isRecord(raw)) invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", "A plugin definition must be an object.");
onlyKeys(raw, ["id", "name", "version", "apiVersion", "runtime", "page", "mode", "mount", "entry", "style", "assets", "permissions"], "Plugin definition");
const id = text(raw.id, "plugin.id", 64);
if (!PLUGIN_ID.test(id) || ids.has(id)) invalid("SKIN_RUNTIME_PLUGIN_ID_INVALID", "Plugin IDs must be unique lowercase slugs.");
ids.add(id);
const name = text(raw.name, "plugin.name", 80);
const version = text(raw.version, "plugin.version", 32);
if (!SEMVER.test(version)) invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", "Plugin versions must use semantic version syntax.");
if (raw.apiVersion !== 1) invalid("SKIN_RUNTIME_PLUGIN_API_UNSUPPORTED", "The plugin API version is not supported.");
if (raw.page !== "home" && raw.page !== "voice") invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", "Plugins may target only the public home or voice page.");
if (raw.mode !== "widget" && raw.mode !== "surface") invalid("SKIN_RUNTIME_PLUGIN_MANIFEST_INVALID", "Plugin mode must be widget or surface.");
let mount: SkinRuntimePluginMountSlot | undefined;
if (raw.mount !== undefined) {
if (typeof raw.mount !== "string" || !(SKIN_RUNTIME_PLUGIN_MOUNT_SLOTS as readonly string[]).includes(raw.mount)) {
invalid("SKIN_RUNTIME_PLUGIN_MOUNT_INVALID", "Plugin mount must use a registered public UI slot.");
}
mount = raw.mount as SkinRuntimePluginMountSlot;
if (MOUNT_SLOT_PAGES[mount] !== raw.page || raw.mode === "surface") {
invalid("SKIN_RUNTIME_PLUGIN_MOUNT_INVALID", "Mount slots must match the plugin page and are available to widget plugins only.");
}
}
const runtime = raw.runtime === undefined
? (typeof raw.entry === "string" && raw.entry.toLowerCase().endsWith(".wasm") ? "wasm" : "javascript")
: raw.runtime;
if (runtime !== "javascript" && runtime !== "wasm") invalid("SKIN_RUNTIME_PLUGIN_RUNTIME_INVALID", "A plugin runtime must be javascript or wasm.");
const entry = packageFile(raw.entry, "plugin.entry", id, [runtime === "wasm" ? ".wasm" : ".js"]);
const style = raw.style === undefined ? undefined : packageFile(raw.style, "plugin.style", id, [".css"]);
if (!Array.isArray(raw.assets) || raw.assets.length > SKIN_RUNTIME_PLUGIN_ASSET_LIMIT) {
invalid("SKIN_RUNTIME_PLUGIN_ASSET_INVALID", "A plugin must declare a bounded asset list.");
}
const assets: string[] = [];
for (const rawPath of raw.assets) {
const assetPath = text(rawPath, "plugin.asset", 180);
const match = ASSET_PATH.exec(assetPath);
if (!match || match[1] !== id) invalid("SKIN_RUNTIME_PLUGIN_ASSET_INVALID", "Plugin assets must be safe local image or font files inside that plugin's assets directory.");
assets.push(assetPath);
}
if (new Set(assets.map((path) => path.toLowerCase())).size !== assets.length) {
invalid("SKIN_RUNTIME_PLUGIN_ASSET_INVALID", "A plugin asset path is duplicated.");
}
if (!Array.isArray(raw.permissions) || raw.permissions.length > 32) {
invalid("SKIN_RUNTIME_PLUGIN_PERMISSION_INVALID", "Plugin permissions must be a bounded array.");
}
const permissions: SkinPluginPermission[] = [];
for (const permission of raw.permissions) {
if (typeof permission !== "string" || !PERMISSIONS.has(permission)) {
invalid("SKIN_RUNTIME_PLUGIN_PERMISSION_INVALID", "The plugin requests an unsupported permission.");
}
if (permissions.includes(permission as SkinPluginPermission)) {
invalid("SKIN_RUNTIME_PLUGIN_PERMISSION_DUPLICATE", "A plugin permission is duplicated.");
}
permissions.push(permission as SkinPluginPermission);
}
if (raw.mode === "surface" && !permissions.includes("ui.surface.replace")) {
invalid("SKIN_RUNTIME_PLUGIN_PERMISSION_MISSING", "A surface plugin requires ui.surface.replace.");
}
if (raw.mode !== "surface" && permissions.includes("ui.surface.replace")) {
invalid("SKIN_RUNTIME_PLUGIN_PERMISSION_INVALID", "Only a surface plugin may request ui.surface.replace.");
}
for (const path of [entry, ...(style ? [style] : []), ...assets]) {
const normalized = path.toLowerCase();
if (files.has(normalized)) invalid("SKIN_RUNTIME_PLUGIN_FILE_DUPLICATE", "Plugin files cannot be shared between definitions.");
files.add(normalized);
}
plugins.push({
id,
name,
version,
apiVersion: 1,
runtime,
page: raw.page,
mode: raw.mode,
...(mount ? { mount } : {}),
entry,
...(style ? { style } : {}),
assets,
permissions,
});
}
const surfacePages = new Set<SkinRuntimePluginPage>();
for (const plugin of plugins) {
if (plugin.mode !== "surface") continue;
if (surfacePages.has(plugin.page)) invalid("SKIN_RUNTIME_PLUGIN_SURFACE_DUPLICATE", "Only one surface plugin may replace each public page.");
surfacePages.add(plugin.page);
}
const immutablePlugins = plugins.map((plugin) => Object.freeze({
...plugin,
assets: Object.freeze([...plugin.assets]),
permissions: Object.freeze([...plugin.permissions]),
}));
return Object.freeze({ schemaVersion: SKIN_RUNTIME_PLUGIN_DOCUMENT_VERSION, plugins: Object.freeze(immutablePlugins) });
}
export function parseSkinRuntimePluginJson(source: string): SkinRuntimePluginDocument {
if (typeof source !== "string" || !source.length
|| new TextEncoder().encode(source).byteLength > SKIN_RUNTIME_PLUGIN_DOCUMENT_LIMIT_BYTES) {
invalid("SKIN_RUNTIME_PLUGIN_DOCUMENT_SIZE", "plugins.json is empty or exceeds 256 KiB.");
}
let input: unknown;
try { input = JSON.parse(source); }
catch { invalid("SKIN_RUNTIME_PLUGIN_DOCUMENT_INVALID", "plugins.json must contain valid JSON."); }
return parseSkinRuntimePluginDocument(input);
}
export function listSkinRuntimePluginFilePaths(document: SkinRuntimePluginDocument): string[] {
return document.plugins.flatMap((plugin) => [plugin.entry, ...(plugin.style ? [plugin.style] : []), ...plugin.assets]);
}
+6
View File
@@ -19,6 +19,12 @@ export interface ChannelInfo {
order?: string;
name: string;
description?: string;
/** Maximum clients for this channel, when TeamSpeak reports a finite or unlimited setting. */
maxClients?: number;
/** False means the channel has no individual client limit. */
maxClientsLimited?: boolean;
/** TeamSpeak's public channel flag; absent when the connected server omits it. */
passwordProtected?: boolean;
members?: ChannelMember[];
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+12
View File
@@ -0,0 +1,12 @@
import { readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { zipSync } from "fflate";
const sourceDirectory = new URL("../../docs/examples/harbor-voice/", import.meta.url);
const outputPath = fileURLToPath(new URL("../../docs/examples/harbor-voice.wskin", import.meta.url));
const files = Object.fromEntries(await Promise.all(["manifest.json", "components.json", "skin.css"].map(async (name) => [
name,
await readFile(new URL(name, sourceDirectory)),
])));
await writeFile(outputPath, zipSync(files, { level: 9 }));
+27
View File
@@ -0,0 +1,27 @@
import { readdir, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { zipSync } from "fflate";
const sourceDirectory = new URL("../../docs/examples/illusia-voice/", import.meta.url);
async function collectFiles(directory, prefix = "") {
const entries = await readdir(new URL(prefix, directory), { withFileTypes: true });
const files = [];
for (const entry of entries) {
const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) files.push(...await collectFiles(directory, relativePath));
else if (entry.isFile()) files.push(relativePath);
}
return files;
}
const files = Object.fromEntries(await Promise.all((await collectFiles(sourceDirectory)).map(async (name) => [
name,
await readFile(new URL(name, sourceDirectory)),
])));
const archive = zipSync(files, { level: 9 });
await Promise.all([
writeFile(fileURLToPath(new URL("../../docs/examples/illusia-voice.wskin", import.meta.url)), archive),
writeFile(fileURLToPath(new URL("../public/skins/illusia-voice.wskin", import.meta.url)), archive),
]);
+16
View File
@@ -0,0 +1,16 @@
import { readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { zipSync } from "fflate";
const sourceDirectory = new URL("../../docs/examples/kaak-voice/", import.meta.url);
const sourceFiles = ["manifest.json", "components.json", "content.json", "skin.css"];
const files = Object.fromEntries(await Promise.all(sourceFiles.map(async (name) => [
name,
await readFile(new URL(name, sourceDirectory)),
])));
const archive = zipSync(files, { level: 9 });
await Promise.all([
writeFile(fileURLToPath(new URL("../../docs/examples/kaak-voice.wskin", import.meta.url)), archive),
writeFile(fileURLToPath(new URL("../public/skins/kaak-voice.wskin", import.meta.url)), archive),
]);
@@ -0,0 +1,12 @@
import { readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { zipSync } from "fflate";
const sourceDirectory = new URL("../../docs/examples/open-voice-surface/", import.meta.url);
const outputPath = fileURLToPath(new URL("../../docs/examples/open-voice-surface.wskin", import.meta.url));
const files = Object.fromEntries(await Promise.all(["manifest.json", "components.json", "skin.css"].map(async (name) => [
name,
await readFile(new URL(name, sourceDirectory)),
])));
await writeFile(outputPath, zipSync(files, { level: 9 }));
+189
View File
@@ -0,0 +1,189 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown 0.17.1",
]
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "spin"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
[[package]]
name = "string-interner"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23de088478b31c349c9ba67816fa55d9355232d63c3afea8bf513e31f0f1d2c0"
dependencies = [
"hashbrown 0.15.5",
"serde",
]
[[package]]
name = "syn"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "wasmi"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27"
dependencies = [
"spin",
"wasmi_collections",
"wasmi_core",
"wasmi_ir",
"wasmparser",
]
[[package]]
name = "wasmi_collections"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557"
dependencies = [
"string-interner",
]
[[package]]
name = "wasmi_core"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa"
dependencies = [
"libm",
]
[[package]]
name = "wasmi_ir"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6"
dependencies = [
"wasmi_core",
]
[[package]]
name = "wasmparser"
version = "0.228.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4abf1132c1fdf747d56bbc1bb52152400c70f336870f968b85e89ea422198ae3"
dependencies = [
"bitflags",
"indexmap",
]
[[package]]
name = "webspeak-skin-wasm-interpreter"
version = "0.1.0"
dependencies = [
"wasmi",
]
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "webspeak-skin-wasm-interpreter"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
crate-type = ["cdylib"]
[dependencies]
# On wasm32, the portable loop dispatcher prevents one native Wasm stack frame per guest instruction.
wasmi = { version = "=2.0.0", default-features = false, features = ["std", "validate", "portable-dispatch"] }
+6
View File
@@ -0,0 +1,6 @@
The browser interpreter artifact is built from `wasmi` 2.0.0, licensed under either MIT or Apache-2.0. See the upstream license texts at:
- https://github.com/wasmi-labs/wasmi/blob/v2.0.0/LICENSE-MIT
- https://github.com/wasmi-labs/wasmi/blob/v2.0.0/LICENSE-APACHE
The checked-in `.wasm` artifact is generated from the source in this directory and is not a remotely downloaded runtime.
@@ -0,0 +1,4 @@
[toolchain]
channel = "1.99.0"
profile = "minimal"
targets = ["wasm32-unknown-unknown"]
+432
View File
@@ -0,0 +1,432 @@
use wasmi::{
Caller, Config, Engine, EnforcedLimits, Linker, Memory, MemoryType, Module, Store,
StoreLimits, StoreLimitsBuilder,
};
const SOURCE_LIMIT: usize = 256 * 1024;
const STATUS_LIMIT: usize = 512;
const UI_INPUT_LIMIT: usize = 64 * 1024;
const UI_OUTPUT_LIMIT: usize = 256 * 1024;
const MEMORY_LIMIT_BYTES: usize = 64 * 64 * 1024;
const STATUS_READ_LIMIT: u32 = 10;
const FUEL_LIMIT: u64 = 10_000_000;
const ERROR_NONE: u32 = 0;
const ERROR_INPUT: u32 = 1;
const ERROR_MODULE: u32 = 2;
const ERROR_EXPORT: u32 = 4;
const ERROR_EXECUTION: u32 = 5;
const ERROR_HOST_MEMORY: u32 = 6;
const ERROR_MEMORY_LINK: u32 = 7;
const ERROR_STATUS_LINK: u32 = 8;
const ERROR_INSTANTIATION: u32 = 9;
const ERROR_IMPORT: u32 = 10;
const ERROR_PERMISSION: u32 = 11;
const ERROR_UI_OUTPUT: u32 = 12;
const ERROR_UI_INPUT: u32 = 13;
static mut LAST_ERROR_CODE: u32 = ERROR_NONE;
static mut LAST_STATUS_READ_COUNT: u32 = 0;
static mut LAST_UI_INPUT_READ_COUNT: u32 = 0;
static mut LAST_GUEST_MEMORY_BYTES: u32 = 0;
static mut LAST_UI_OUTPUT: [u8; UI_OUTPUT_LIMIT] = [0; UI_OUTPUT_LIMIT];
static mut LAST_UI_OUTPUT_LENGTH: u32 = 0;
static mut LAST_DIAGNOSTIC: [u8; 256] = [0; 256];
static mut LAST_DIAGNOSTIC_LENGTH: u32 = 0;
struct HostState {
limits: StoreLimits,
status: Vec<u8>,
status_read_count: u32,
ui_input: Vec<u8>,
ui_input_read_count: u32,
ui_input_invalid: bool,
ui_output: Vec<u8>,
ui_output_emitted: bool,
ui_output_invalid: bool,
}
#[unsafe(no_mangle)]
pub extern "C" fn alloc(size: u32) -> u32 {
if size == 0 || size as usize > SOURCE_LIMIT + STATUS_LIMIT + UI_INPUT_LIMIT {
return 0;
}
let allocation = Vec::<u8>::with_capacity(size as usize);
let pointer = allocation.as_ptr() as usize as u32;
core::mem::forget(allocation);
pointer
}
/// Runs one untrusted module inside Wasmi, whose entire allocator is bounded by
/// the fixed maximum memory of this outer Wasm artifact.
///
/// The web worker validates the byte ranges and permission grant before calling
/// this ABI. Every invocation gets a new Store, module, memory, and linker.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn run(
module_pointer: u32,
module_length: u32,
status_pointer: u32,
status_length: u32,
ui_input_pointer: u32,
ui_input_length: u32,
status_permission_granted: u32,
memory_maximum_pages: u32,
fuel: u64,
) -> i64 {
clear_diagnostic();
clear_ui_output();
set_report(ERROR_NONE, 0, 0, 0);
let interpreter_memory_bytes = core::arch::wasm32::memory_size(0) as usize * 64 * 1024;
if module_pointer == 0
|| module_length == 0
|| module_length as usize > SOURCE_LIMIT
|| status_length as usize > STATUS_LIMIT
|| (status_length != 0 && status_pointer == 0)
|| (status_length != 0 && status_permission_granted != 1)
|| ui_input_length == 0
|| ui_input_length as usize > UI_INPUT_LIMIT
|| ui_input_pointer == 0
|| !valid_range(module_pointer, module_length, interpreter_memory_bytes)
|| (status_length > 0 && !valid_range(status_pointer, status_length, interpreter_memory_bytes))
|| !valid_range(ui_input_pointer, ui_input_length, interpreter_memory_bytes)
|| !(1..=64).contains(&memory_maximum_pages)
|| fuel == 0
|| fuel > FUEL_LIMIT
{
set_report(ERROR_INPUT, 0, 0, 0);
return 0;
}
let module_bytes = core::slice::from_raw_parts(module_pointer as usize as *const u8, module_length as usize);
let status = if status_length == 0 {
Vec::new()
} else {
core::slice::from_raw_parts(status_pointer as usize as *const u8, status_length as usize).to_vec()
};
let ui_input = core::slice::from_raw_parts(ui_input_pointer as usize as *const u8, ui_input_length as usize).to_vec();
match execute(module_bytes, status, ui_input, status_permission_granted == 1, memory_maximum_pages, fuel) {
Ok((result, status_reads, ui_input_reads, guest_memory_bytes, ui_output)) => {
set_ui_output(&ui_output);
set_report(ERROR_NONE, status_reads, ui_input_reads, guest_memory_bytes);
result as i64
}
Err((error, status_reads, ui_input_reads, guest_memory_bytes)) => {
set_report(error, status_reads, ui_input_reads, guest_memory_bytes);
0
}
}
}
#[unsafe(no_mangle)]
pub extern "C" fn last_error_code() -> u32 {
unsafe { LAST_ERROR_CODE }
}
#[unsafe(no_mangle)]
pub extern "C" fn last_status_read_count() -> u32 {
unsafe { LAST_STATUS_READ_COUNT }
}
#[unsafe(no_mangle)]
pub extern "C" fn last_ui_input_read_count() -> u32 {
unsafe { LAST_UI_INPUT_READ_COUNT }
}
#[unsafe(no_mangle)]
pub extern "C" fn last_guest_memory_bytes() -> u32 {
unsafe { LAST_GUEST_MEMORY_BYTES }
}
#[unsafe(no_mangle)]
pub extern "C" fn last_ui_output_pointer() -> u32 {
core::ptr::addr_of!(LAST_UI_OUTPUT) as usize as u32
}
#[unsafe(no_mangle)]
pub extern "C" fn last_ui_output_length() -> u32 {
unsafe { LAST_UI_OUTPUT_LENGTH }
}
#[unsafe(no_mangle)]
pub extern "C" fn last_diagnostic_pointer() -> u32 {
core::ptr::addr_of!(LAST_DIAGNOSTIC) as usize as u32
}
#[unsafe(no_mangle)]
pub extern "C" fn last_diagnostic_length() -> u32 {
unsafe { LAST_DIAGNOSTIC_LENGTH }
}
fn clear_diagnostic() {
unsafe { LAST_DIAGNOSTIC_LENGTH = 0; }
}
fn set_diagnostic(message: &str) {
let bytes = message.as_bytes();
let length = bytes.len().min(255);
unsafe {
let destination = core::ptr::addr_of_mut!(LAST_DIAGNOSTIC).cast::<u8>();
core::ptr::copy_nonoverlapping(bytes.as_ptr(), destination, length);
LAST_DIAGNOSTIC_LENGTH = length as u32;
}
}
fn set_report(error: u32, status_reads: u32, ui_input_reads: u32, guest_memory_bytes: u32) {
// Each interpreter instance runs in a dedicated Worker and accepts one job.
unsafe {
LAST_ERROR_CODE = error;
LAST_STATUS_READ_COUNT = status_reads;
LAST_UI_INPUT_READ_COUNT = ui_input_reads;
LAST_GUEST_MEMORY_BYTES = guest_memory_bytes;
}
}
fn clear_ui_output() {
unsafe { LAST_UI_OUTPUT_LENGTH = 0; }
}
fn set_ui_output(output: &[u8]) {
let length = output.len().min(UI_OUTPUT_LIMIT);
unsafe {
let destination = core::ptr::addr_of_mut!(LAST_UI_OUTPUT).cast::<u8>();
core::ptr::copy_nonoverlapping(output.as_ptr(), destination, length);
LAST_UI_OUTPUT_LENGTH = length as u32;
}
}
fn valid_range(pointer: u32, length: u32, memory_bytes: usize) -> bool {
let start = pointer as usize;
let length = length as usize;
pointer != 0 && start <= memory_bytes && length <= memory_bytes.saturating_sub(start)
}
fn execute(
module_bytes: &[u8],
status: Vec<u8>,
ui_input: Vec<u8>,
status_permission_granted: bool,
memory_maximum_pages: u32,
fuel: u64,
) -> Result<(i32, u32, u32, u32, Vec<u8>), (u32, u32, u32, u32)> {
let mut config = Config::default();
config
.consume_fuel(true)
.allow_start_fn(false)
.wasm_reference_types(false)
.wasm_multi_memory(false)
.wasm_bulk_memory(true)
.set_max_recursion_depth(128)
.set_max_stack_height(64 * 1024)
.set_max_cached_stacks(0)
.enforced_limits(EnforcedLimits::strict());
let engine = Engine::new(&config);
let module = Module::new(&engine, &mut &module_bytes[..])
.map_err(|_| (ERROR_MODULE, 0, 0, 0))?;
let mut saw_memory = false;
let mut saw_status = false;
let mut saw_ui_output = false;
let mut saw_ui_input = false;
for import in module.imports() {
match (import.module(), import.name(), import.ty()) {
("env", "memory", wasmi::ExternType::Memory(memory_type))
if !saw_memory
&& memory_type.minimum() <= 1
&& memory_type.maximum().unwrap_or(64) == memory_maximum_pages as u64
&& memory_type.maximum().unwrap_or(64) <= 64 =>
{
saw_memory = true;
}
("env", "session_status_read", wasmi::ExternType::Func(_))
if !saw_status && status_permission_granted =>
{
saw_status = true;
}
("env", "session_status_read", wasmi::ExternType::Func(_)) => {
return Err((ERROR_PERMISSION, 0, 0, 0));
}
("env", "ui_emit_json", wasmi::ExternType::Func(_)) if !saw_ui_output => {
saw_ui_output = true;
}
("env", "ui_input_read", wasmi::ExternType::Func(_)) if !saw_ui_input => {
saw_ui_input = true;
}
_ => return Err((ERROR_IMPORT, 0, 0, 0)),
}
}
if !saw_memory {
return Err((ERROR_IMPORT, 0, 0, 0));
}
let mut exports = module.exports();
let Some(entry) = exports.next() else {
return Err((ERROR_EXPORT, 0, 0, 0));
};
if entry.name() != "run"
|| !matches!(entry.ty(), wasmi::ExternType::Func(_))
|| exports.next().is_some()
{
return Err((ERROR_EXPORT, 0, 0, 0));
}
let limits = StoreLimitsBuilder::new()
.memory_size(MEMORY_LIMIT_BYTES)
.table_elements(0)
.instances(1)
// Wasmi counts the host-created import and the instantiated module's
// view of that import independently inside one Store.
.memories(2)
.tables(0)
.trap_on_grow_failure(true)
.build();
let mut store = Store::new(&engine, HostState {
limits,
status,
status_read_count: 0,
ui_input,
ui_input_read_count: 0,
ui_input_invalid: false,
ui_output: Vec::new(),
ui_output_emitted: false,
ui_output_invalid: false,
});
store.limiter(|state| &mut state.limits);
store.set_fuel(fuel).map_err(|_| (ERROR_EXECUTION, 0, 0, 0))?;
let memory_type = MemoryType::new(1, Some(memory_maximum_pages));
let memory = Memory::new(&mut store, memory_type)
.map_err(|_| (ERROR_HOST_MEMORY, 0, 0, 0))?;
let mut linker = Linker::<HostState>::new(&engine);
linker
.define("env", "memory", memory)
.map_err(|_| (ERROR_MEMORY_LINK, 0, 0, 0))?;
if status_permission_granted {
let status_memory = memory;
linker
.func_wrap(
"env",
"session_status_read",
move |mut caller: Caller<'_, HostState>, pointer: i32, capacity: i32| -> i32 {
if pointer < 0 || capacity < 0 {
return -1;
}
let offset = pointer as usize;
let capacity = capacity as usize;
let (status_size, reads, memory_size) = {
let state = caller.data();
(state.status.len(), state.status_read_count, status_memory.data(&caller).len())
};
if status_size == 0
|| reads >= STATUS_READ_LIMIT
|| capacity < status_size
|| offset > memory_size.saturating_sub(capacity)
{
return -1;
}
let status = caller.data().status.clone();
if status_memory.write(&mut caller, offset, &status).is_err() {
return -1;
}
caller.data_mut().status_read_count += 1;
status_size as i32
},
)
.map_err(|_| (ERROR_STATUS_LINK, 0, 0, 0))?;
}
let output_memory = memory;
linker
.func_wrap(
"env",
"ui_emit_json",
move |mut caller: Caller<'_, HostState>, pointer: i32, length: i32| -> i32 {
if pointer < 0 || length <= 0 || length as usize > UI_OUTPUT_LIMIT {
caller.data_mut().ui_output_invalid = true;
return -1;
}
let offset = pointer as usize;
let length = length as usize;
let memory_bytes = output_memory.data(&caller);
if offset > memory_bytes.len() || length > memory_bytes.len() - offset {
caller.data_mut().ui_output_invalid = true;
return -1;
}
let output = memory_bytes[offset..offset + length].to_vec();
if core::str::from_utf8(&output).is_err() || caller.data().ui_output_emitted {
caller.data_mut().ui_output_invalid = true;
return -1;
}
let state = caller.data_mut();
state.ui_output = output;
state.ui_output_emitted = true;
length as i32
},
)
.map_err(|_| (ERROR_IMPORT, 0, 0, 0))?;
let input_memory = memory;
linker
.func_wrap(
"env",
"ui_input_read",
move |mut caller: Caller<'_, HostState>, pointer: i32, capacity: i32| -> i32 {
if pointer < 0 || capacity < 0 {
caller.data_mut().ui_input_invalid = true;
return -1;
}
let offset = pointer as usize;
let capacity = capacity as usize;
let (input_size, reads, memory_size) = {
let state = caller.data();
(state.ui_input.len(), state.ui_input_read_count, input_memory.data(&caller).len())
};
if input_size == 0
|| input_size > UI_INPUT_LIMIT
|| reads >= 1
|| capacity < input_size
|| offset > memory_size.saturating_sub(capacity)
{
caller.data_mut().ui_input_invalid = true;
return -1;
}
let input = caller.data().ui_input.clone();
if input_memory.write(&mut caller, offset, &input).is_err() {
caller.data_mut().ui_input_invalid = true;
return -1;
}
caller.data_mut().ui_input_read_count += 1;
input_size as i32
},
)
.map_err(|_| (ERROR_IMPORT, 0, 0, 0))?;
let instance = match linker.instantiate_and_start(&mut store, &module) {
Ok(instance) => instance,
Err(error) => {
set_diagnostic(&error.to_string());
return Err((ERROR_INSTANTIATION, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32));
}
};
let function = instance
.get_typed_func::<(), i32>(&store, "run")
.map_err(|_| (ERROR_EXPORT, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32))?;
let result = function
.call(&mut store, ())
.map_err(|_| (ERROR_EXECUTION, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32))?;
if store.data().ui_output_invalid {
return Err((ERROR_UI_OUTPUT, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32));
}
if store.data().ui_input_invalid {
return Err((ERROR_UI_INPUT, store.data().status_read_count, store.data().ui_input_read_count, memory.data(&store).len() as u32));
}
Ok((
result,
store.data().status_read_count,
store.data().ui_input_read_count,
memory.data(&store).len() as u32,
store.data().ui_output.clone(),
))
}
+5
View File
@@ -1,7 +1,12 @@
<template>
<router-view />
<SkinLayoutEditor />
</template>
<script setup lang="ts">
import SkinLayoutEditor from "./components/SkinLayoutEditor.vue";
</script>
<style>
* { box-sizing: border-box; }
body { margin: 0; font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
+109 -97
View File
@@ -1,109 +1,121 @@
<template>
<svg
class="ui-icon"
:width="size"
:height="size"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path v-if="name === 'home'" d="m3 10 9-7 9 7v10a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />
<path v-else-if="name === 'activity'" d="M3 12h4l2.2-7 4.1 14 2.2-7H21" />
<template v-else-if="name === 'server'">
<rect x="4" y="3" width="16" height="7" rx="1.5" />
<rect x="4" y="14" width="16" height="7" rx="1.5" />
<path d="M8 6.5h.01M8 17.5h.01M11 6.5h5M11 17.5h5" />
</template>
<template v-else-if="name === 'compass'">
<circle cx="12" cy="12" r="9" />
<path d="m15.5 8.5-2.2 4.8-4.8 2.2 2.2-4.8z" />
</template>
<template v-else-if="name === 'download'">
<path d="M12 3v12m0 0 4-4m-4 4-4-4M4 19v2h16v-2" />
</template>
<template v-else-if="name === 'settings'">
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0L6.2 6.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
<circle cx="12" cy="12" r="3" />
</template>
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
<template v-else-if="name === 'music'">
<path d="M9 18V5l10-2v13" />
<circle cx="6" cy="18" r="3" />
<circle cx="16" cy="16" r="3" />
</template>
<template>
<svg
class="ui-icon"
:width="size"
:height="size"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path v-if="name === 'home'" d="m3 10 9-7 9 7v10a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />
<path v-else-if="name === 'activity'" d="M3 12h4l2.2-7 4.1 14 2.2-7H21" />
<template v-else-if="name === 'server'">
<rect x="4" y="3" width="16" height="7" rx="1.5" />
<rect x="4" y="14" width="16" height="7" rx="1.5" />
<path d="M8 6.5h.01M8 17.5h.01M11 6.5h5M11 17.5h5" />
</template>
<template v-else-if="name === 'compass'">
<circle cx="12" cy="12" r="9" />
<path d="m15.5 8.5-2.2 4.8-4.8 2.2 2.2-4.8z" />
</template>
<template v-else-if="name === 'download'">
<path d="M12 3v12m0 0 4-4m-4 4-4-4M4 19v2h16v-2" />
</template>
<template v-else-if="name === 'settings'">
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0L6.2 6.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
<circle cx="12" cy="12" r="3" />
</template>
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
<template v-else-if="name === 'music'">
<path d="M9 18V5l10-2v13" />
<circle cx="6" cy="18" r="3" />
<circle cx="16" cy="16" r="3" />
</template>
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 1-1-1z" />
<path v-else-if="name === 'volume'" d="M4 10v4h3l4 3V7l-4 3zm10.5-2.5a6 6 0 0 1 0 9m2-11a9 9 0 0 1 0 13" />
<path v-else-if="name === 'volume-off'" d="m4 4 16 16M4 10v4h3l4 3V7l-4 3z" />
<template v-else-if="name === 'search'">
<circle cx="10.8" cy="10.8" r="6.8" />
<path d="m16 16 4.5 4.5" />
</template>
<path v-else-if="name === 'bell'" d="M18 9a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4" />
<path v-else-if="name === 'clock'" d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-14v5l3 2" />
<path v-else-if="name === 'help'" d="M9.3 9a3 3 0 1 1 4.9 2.3c-1.3 1-2.2 1.5-2.2 3m0 3h.01M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Z" />
<template v-else-if="name === 'info'">
<circle cx="12" cy="12" r="9" />
<path d="M12 10v6m0-9h.01" />
<template v-else-if="name === 'speaker'">
<path d="M3 9v6h4l5 4V5L7 9H3Z" fill="currentColor" stroke="none" />
<path d="M16 9a4 4 0 0 1 0 6m2.5-8.5a7.5 7.5 0 0 1 0 11" />
</template>
<path v-else-if="name === 'volume-off'" d="m4 4 16 16M4 10v4h3l4 3V7l-4 3z" />
<template v-else-if="name === 'search'">
<circle cx="10.8" cy="10.8" r="6.8" />
<path d="m16 16 4.5 4.5" />
</template>
<path v-else-if="name === 'bell'" d="M18 9a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4" />
<path v-else-if="name === 'clock'" d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-14v5l3 2" />
<path v-else-if="name === 'help'" d="M9.3 9a3 3 0 1 1 4.9 2.3c-1.3 1-2.2 1.5-2.2 3m0 3h.01M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Z" />
<template v-else-if="name === 'info'">
<circle cx="12" cy="12" r="9" />
<path d="M12 10v6m0-9h.01" />
</template>
<template v-else-if="name === 'plus'">
<path d="M12 5v14M5 12h14" />
</template>
<path v-else-if="name === 'chevron-down'" d="m6 9 6 6 6-6" />
<path v-else-if="name === 'chevron-right'" d="m9 6 6 6-6 6" />
<path v-else-if="name === 'hash'" d="M9 3 7 21M17 3l-2 18M4 9h16M3 15h16" />
<path v-else-if="name === 'send'" d="m21 3-7.4 18-3.6-7-7-3.6zM21 3 10 14" />
<template v-else-if="name === 'smile'">
<circle cx="12" cy="12" r="9" />
<path d="M8 14s1.5 2 4 2 4-2 4-2M9 9h.01M15 9h.01" />
</template>
<path v-else-if="name === 'paperclip'" d="m20 11-7.5 7.5a5 5 0 0 1-7-7L13 4a3.5 3.5 0 0 1 5 5l-7.5 7.5a2 2 0 0 1-3-3L14 7" />
<path v-else-if="name === 'share'" d="M4 12v7a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7M16 6l-4-4-4 4m4-4v13" />
<path v-else-if="name === 'copy'" d="M8 8V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-3M6 8h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2Z" />
<path v-else-if="name === 'close'" d="m6 6 12 12M18 6 6 18" />
<path v-else-if="name === 'star'" d="m12 3 2.8 5.7 6.2.9-4.5 4.4 1.1 6.2-5.6-3-5.6 3 1.1-6.2L3 9.6l6.2-.9z" />
<path v-else-if="name === 'chevron-down'" d="m6 9 6 6 6-6" />
<path v-else-if="name === 'chevron-right'" d="m9 6 6 6-6 6" />
<path v-else-if="name === 'hash'" d="M9 3 7 21M17 3l-2 18M4 9h16M3 15h16" />
<path v-else-if="name === 'send'" d="m21 3-7.4 18-3.6-7-7-3.6zM21 3 10 14" />
<template v-else-if="name === 'smile'">
<circle cx="12" cy="12" r="9" />
<path d="M8 14s1.5 2 4 2 4-2 4-2M9 9h.01M15 9h.01" />
</template>
<path v-else-if="name === 'paperclip'" d="m20 11-7.5 7.5a5 5 0 0 1-7-7L13 4a3.5 3.5 0 0 1 5 5l-7.5 7.5a2 2 0 0 1-3-3L14 7" />
<path v-else-if="name === 'share'" d="M4 12v7a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7M16 6l-4-4-4 4m4-4v13" />
<path v-else-if="name === 'copy'" d="M8 8V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-3M6 8h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2Z" />
<path v-else-if="name === 'close'" d="m6 6 12 12M18 6 6 18" />
<path v-else-if="name === 'more'" d="M5 12h.01M12 12h.01M19 12h.01" stroke-width="3" />
<path v-else-if="name === 'refresh'" d="M20 11a8 8 0 0 0-14-4L4 9m0-4v4h4M4 13a8 8 0 0 0 14 4l2-2m0 4v-4h-4" />
<path v-else-if="name === 'lock'" d="M6 10h12v10H6zM8 10V7a4 4 0 0 1 8 0v3" />
<path v-else-if="name === 'users'" d="M16 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2m6-10a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm6-7a4 4 0 0 1 0 7m2 5h1a4 4 0 0 1 4 4v1" />
<path v-else-if="name === 'message'" d="M20 11.5a7.5 7.5 0 0 1-8 7.5 9.4 9.4 0 0 1-3-.5L4 20l1.5-3.6A7.2 7.2 0 0 1 4 11.5 7.5 7.5 0 0 1 12 4a7.5 7.5 0 0 1 8 7.5Z" />
<path v-else-if="name === 'menu'" d="M4 6h16M4 12h16M4 18h16" />
<path v-else-if="name === 'refresh'" d="M20 11a8 8 0 0 0-14-4L4 9m0-4v4h4M4 13a8 8 0 0 0 14 4l2-2m0 4v-4h-4" />
<path v-else-if="name === 'lock'" d="M6 10h12v10H6zM8 10V7a4 4 0 0 1 8 0v3" />
<path v-else-if="name === 'users'" d="M16 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2m6-10a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm6-7a4 4 0 0 1 0 7m2 5h1a4 4 0 0 1 4 4v1" />
<path v-else-if="name === 'message'" d="M20 11.5a7.5 7.5 0 0 1-8 7.5 9.4 9.4 0 0 1-3-.5L4 20l1.5-3.6A7.2 7.2 0 0 1 4 11.5 7.5 7.5 0 0 1 12 4a7.5 7.5 0 0 1 8 7.5Z" />
<path v-else-if="name === 'door'" d="M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5m5 14 5-5-5-5m5 5H9" />
<path v-else-if="name === 'power'" d="M12 2v10m-5.9-5.1a9 9 0 1 0 11.8 0" />
<path v-else-if="name === 'waveform'" d="M3 12h2l2-6 3 12 3-9 2 6h6" />
<template v-else-if="name === 'noise-suppression'">
<path d="M2.5 13h2l2-5 2.7 9 2.4-7 1.4 3H15" />
<path d="M19 5.5v4m-2-2h4" />
</template>
<path v-else-if="name === 'shield'" d="M12 21s8-3.5 8-10V5l-8-3-8 3v6c0 6.5 8 10 8 10Z" />
<template v-else-if="name === 'sun'">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42" />
</template>
<path v-else-if="name === 'moon'" d="M20.4 15.2A8.5 8.5 0 0 1 8.8 3.6 8.5 8.5 0 1 0 20.4 15.2Z" />
<template v-else-if="name === 'sun'">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42" />
</template>
<path v-else-if="name === 'moon'" d="M20.4 15.2A8.5 8.5 0 0 1 8.8 3.6 8.5 8.5 0 1 0 20.4 15.2Z" />
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
<path v-else-if="name === 'translate'" fill="currentColor" stroke="none" d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.99-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.14 8.44 10 10.47 8 12.1c-1.31-1.08-2.39-2.39-3.2-3.91H2.8c.93 2.07 2.26 3.9 4.05 5.41l-3.74 3.71L4.5 18.7 8 15.2l2.18 2.18.69-2.31zm4.63-6.07h-2L11 22h2l1.12-3h4.75L20 22h2l-4.5-13zm-2.62 8 1.62-4.33L18.12 17h-3.24z" />
<path v-else-if="name === 'fullscreen'" d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5" />
<path v-else-if="name === 'fullscreen-exit'" d="M9 4v5H4M20 9h-5V4M15 20v-5h5M4 15h5v5" />
<path v-else-if="name === 'github'" fill="currentColor" stroke="none" d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.53-1.33-1.28-1.68-1.28-1.68-1.04-.71.08-.7.08-.7 1.15.08 1.75 1.18 1.75 1.18 1.02 1.75 2.68 1.24 3.33.95.1-.74.4-1.24.73-1.52-2.55-.29-5.23-1.28-5.23-5.68 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.45.11-3.03 0 0 .96-.31 3.15 1.17.91-.25 1.88-.38 2.85-.38.97 0 1.94.13 2.85.38 2.19-1.48 3.15-1.17 3.15-1.17.62 1.58.23 2.74.11 3.03.73.8 1.18 1.82 1.18 3.07 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.04.78 2.1 0 1.52-.01 2.75-.01 3.12 0 .3.21.67.8.56C20.71 21.39 24 17.08 24 12 24 5.65 18.35.5 12 .5Z" />
<template v-else-if="name === 'qq'">
<ellipse cx="12" cy="12.3" rx="7.25" ry="8.85" fill="#202a2a" stroke="none" />
<ellipse cx="12" cy="14.8" rx="4.1" ry="5.55" fill="#fff" stroke="none" />
<circle cx="9.45" cy="9.55" r="1.35" fill="#fff" stroke="none" />
<circle cx="14.55" cy="9.55" r="1.35" fill="#fff" stroke="none" />
<circle cx="9.45" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
<circle cx="14.55" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
<path d="m10 11.15 2-1.05 2 1.05-2 1.45z" fill="#f2a53d" stroke="none" />
<path d="m5.8 18.55-2.1 2.1 3.75-.45m10.75-1.65 2.1 2.1-3.75-.45" fill="#f2a53d" stroke="#f2a53d" stroke-width="1.5" />
</template>
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
<circle v-else cx="12" cy="12" r="8" />
</svg>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ name: string; size?: number }>(), { size: 18 });
</script>
<style scoped>
.ui-icon {
display: block;
flex: 0 0 auto;
}
</style>
<path v-else-if="name === 'fullscreen-exit'" d="M9 4v5H4M20 9h-5V4M15 20v-5h5M4 15h5v5" />
<path v-else-if="name === 'github'" fill="currentColor" stroke="none" d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.53-1.33-1.28-1.68-1.28-1.68-1.04-.71.08-.7.08-.7 1.15.08 1.75 1.18 1.75 1.18 1.02 1.75 2.68 1.24 3.33.95.1-.74.4-1.24.73-1.52-2.55-.29-5.23-1.28-5.23-5.68 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.45.11-3.03 0 0 .96-.31 3.15 1.17.91-.25 1.88-.38 2.85-.38.97 0 1.94.13 2.85.38 2.19-1.48 3.15-1.17 3.15-1.17.62 1.58.23 2.74.11 3.03.73.8 1.18 1.82 1.18 3.07 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.04.78 2.1 0 1.52-.01 2.75-.01 3.12 0 .3.21.67.8.56C20.71 21.39 24 17.08 24 12 24 5.65 18.35.5 12 .5Z" />
<template v-else-if="name === 'qq'">
<ellipse cx="12" cy="12.3" rx="7.25" ry="8.85" fill="#202a2a" stroke="none" />
<ellipse cx="12" cy="14.8" rx="4.1" ry="5.55" fill="#fff" stroke="none" />
<circle cx="9.45" cy="9.55" r="1.35" fill="#fff" stroke="none" />
<circle cx="14.55" cy="9.55" r="1.35" fill="#fff" stroke="none" />
<circle cx="9.45" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
<circle cx="14.55" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
<path d="m10 11.15 2-1.05 2 1.05-2 1.45z" fill="#f2a53d" stroke="none" />
<path d="m5.8 18.55-2.1 2.1 3.75-.45m10.75-1.65 2.1 2.1-3.75-.45" fill="#f2a53d" stroke="#f2a53d" stroke-width="1.5" />
</template>
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
<circle v-else cx="12" cy="12" r="8" />
</svg>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ name: string; size?: number }>(), { size: 18 });
</script>
<style scoped>
.ui-icon {
display: block;
flex: 0 0 auto;
}
</style>
+7 -2
View File
@@ -11,6 +11,7 @@
:aria-controls="menuId"
@click.stop="toggle"
>
<Icon class="language-current-icon" name="translate" :size="24" />
<span class="language-current-flag" aria-hidden="true">{{ currentLanguage.flag }}</span>
<span class="language-current-code">{{ currentLanguage.code }}</span>
<Icon name="chevron-down" :size="13" />
@@ -130,12 +131,12 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
box-shadow: 0 7px 16px rgba(0, 106, 100, .16);
}
.language-trigger .ui-icon {
.language-trigger > .ui-icon:last-child {
margin-left: auto;
transition: transform .16s;
}
.language-switcher.open .language-trigger .ui-icon {
.language-switcher.open .language-trigger > .ui-icon:last-child {
transform: rotate(180deg);
}
@@ -145,6 +146,10 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
line-height: 1;
}
.language-current-icon {
display: none;
}
.language-current-flag {
font-size: 15px;
}
+326
View File
@@ -0,0 +1,326 @@
<template>
<Teleport to="body">
<div v-if="editor.available.value" ref="editorRoot" class="skin-layout-editor" data-ws-layout-editor @keydown.esc.stop.prevent="editor.setOpen(false)">
<button
v-if="editorMode.isAdmin.value"
class="skin-editor-mode-trigger"
type="button"
:aria-pressed="editorMode.isEnabled.value"
@click="toggleEditorMode"
>
<span aria-hidden="true">⚙</span>
{{ editorMode.isEnabled.value ? "退出编辑器 / Exit editor" : "编辑器模式 / Editor mode" }}
</button>
<button
v-if="editorMode.isEnabled.value"
ref="triggerButton"
class="skin-layout-trigger"
type="button"
:aria-expanded="editor.isOpen.value"
aria-controls="skin-layout-panel"
@click="editor.setOpen(!editor.isOpen.value)"
>
<span aria-hidden="true">⠿</span>
{{ editor.labels.value.editButton }}
</button>
<section
v-if="editorMode.isEnabled.value && editor.isOpen.value"
id="skin-layout-panel"
class="skin-layout-panel"
role="dialog"
aria-modal="false"
:aria-label="editor.labels.value.title"
>
<header class="skin-layout-heading">
<div>
<h2>{{ editor.labels.value.title }}</h2>
<p>{{ editor.labels.value.hint }}</p>
</div>
<button ref="closeButton" type="button" class="skin-layout-close" :aria-label="editor.labels.value.close" @click="editor.setOpen(false)">×</button>
</header>
<label class="skin-layout-toggle">
<input type="checkbox" :checked="editor.isEditing.value" @change="editor.setEditing(($event.target as HTMLInputElement).checked)" />
<span>{{ editor.labels.value.editMode }}</span>
</label>
<label class="skin-layout-toggle">
<input type="checkbox" :checked="editor.focusPreviewEnabled.value" @change="editor.setFocusPreview(($event.target as HTMLInputElement).checked)" />
<span>{{ editor.labels.value.focusPreview }}</span>
</label>
<ol v-if="editor.focusPreviewEnabled.value" class="skin-layout-focus-list" :aria-label="editor.labels.value.focusPreview">
<li v-if="!editor.focusPreviewTargets.value.length" class="skin-layout-focus-empty">
{{ editor.labels.value.focusPreviewEmpty }}
</li>
<li v-for="target in editor.focusPreviewTargets.value" :key="target.key" :class="{ 'is-small': !target.meetsTouchTarget }">
<span class="skin-layout-focus-number" aria-hidden="true">{{ target.order }}</span>
<span class="skin-layout-focus-name"><strong>{{ target.componentName }}</strong><small>{{ target.accessibleName || editor.labels.value.focusPreviewUnnamed }}</small></span>
<span class="skin-layout-focus-size">{{ editor.labels.value.focusPreviewTargetSize.replace("{width}", String(Math.round(target.width))).replace("{height}", String(Math.round(target.height))) }}<small>{{ target.meetsTouchTarget ? editor.labels.value.focusPreviewTargetAdequate : editor.labels.value.focusPreviewTargetSmall }}</small></span>
</li>
</ol>
<label class="skin-layout-field">
<span>{{ editor.labels.value.component }}</span>
<input v-model="editor.filter.value" type="search" :placeholder="editor.labels.value.filter" />
<select :value="editor.selectedComponentId.value" @change="editor.selectComponent(($event.target as HTMLSelectElement).value)">
<option v-for="component in editor.filteredComponents.value" :key="component.id" :value="component.id">{{ component.name }} ({{ component.id }})</option>
</select>
</label>
<label class="skin-layout-toggle">
<input type="checkbox" :checked="editor.selectedVisible.value" @change="editor.setVisible(($event.target as HTMLInputElement).checked)" />
<span>{{ editor.labels.value.visible }}</span>
</label>
<div class="skin-layout-range">
<label><span>{{ editor.labels.value.positionX }}</span><output>{{ Math.round(editor.selectedX.value) }} px</output></label>
<input type="range" :min="editor.positionBoundsX.value.minimum" :max="editor.positionBoundsX.value.maximum" step="1" :value="editor.selectedX.value" @input="editor.setX(Number(($event.target as HTMLInputElement).value))" />
</div>
<div class="skin-layout-range">
<label><span>{{ editor.labels.value.positionY }}</span><output>{{ Math.round(editor.selectedY.value) }} px</output></label>
<input type="range" :min="editor.positionBoundsY.value.minimum" :max="editor.positionBoundsY.value.maximum" step="1" :value="editor.selectedY.value" @input="editor.setY(Number(($event.target as HTMLInputElement).value))" />
</div>
<div class="skin-layout-range">
<label><span>{{ editor.labels.value.size }}</span><output>{{ Math.round(editor.selectedScale.value * 100) }}%</output></label>
<input type="range" :min="editor.selectedSizeBounds.value.minScale" :max="editor.selectedSizeBounds.value.maxScale" step="0.05" :value="editor.selectedScale.value" @input="editor.setScale(Number(($event.target as HTMLInputElement).value))" />
</div>
<div class="skin-layout-range">
<label><span>{{ editor.labels.value.width }}</span><output>{{ Math.round(editor.selectedWidth.value) }} px</output></label>
<input type="range" :min="editor.selectedSizeBounds.value.minWidth" :max="editor.selectedSizeBounds.value.maxWidth" step="4" :value="editor.selectedWidth.value" @input="editor.setWidth(Number(($event.target as HTMLInputElement).value))" />
</div>
<div class="skin-layout-range">
<label><span>{{ editor.labels.value.height }}</span><output>{{ Math.round(editor.selectedHeight.value) }} px</output></label>
<input type="range" :min="editor.selectedSizeBounds.value.minHeight" :max="editor.selectedSizeBounds.value.maxHeight" step="4" :value="editor.selectedHeight.value" @input="editor.setHeight(Number(($event.target as HTMLInputElement).value))" />
</div>
<div class="skin-layout-range" :title="editor.labels.value.orderHint">
<label><span>{{ editor.labels.value.order }}</span><output>{{ editor.selectedOrder.value }}</output></label>
<input type="range" min="-100" max="100" step="1" :value="editor.selectedOrder.value" @input="editor.setOrder(Number(($event.target as HTMLInputElement).value))" />
</div>
<div class="skin-layout-colors">
<label><span>{{ editor.labels.value.foreground }}</span><input type="color" :value="editor.selectedForeground.value" @input="editor.setForeground(($event.target as HTMLInputElement).value)" /></label>
<label><span>{{ editor.labels.value.background }}</span><input type="color" :value="editor.selectedBackground.value" @input="editor.setBackground(($event.target as HTMLInputElement).value)" /></label>
<label><span>{{ editor.labels.value.border }}</span><input type="color" :value="editor.selectedBorder.value" @input="editor.setBorder(($event.target as HTMLInputElement).value)" /></label>
</div>
<div class="skin-layout-range">
<label><span>{{ editor.labels.value.radius }}</span><output>{{ Math.round(editor.selectedRadius.value) }} px</output></label>
<input type="range" min="0" max="64" step="1" :value="editor.selectedRadius.value" @input="editor.setRadius(Number(($event.target as HTMLInputElement).value))" />
</div>
<div class="skin-layout-actions">
<button type="button" :disabled="!editor.canUndo.value" @click="editor.undo">{{ editor.labels.value.undo }}</button>
<button type="button" :disabled="!editor.canRedo.value" @click="editor.redo">{{ editor.labels.value.redo }}</button>
</div>
<div class="skin-layout-actions">
<button type="button" @click="editor.resetComponent">{{ editor.labels.value.resetItem }}</button>
<button type="button" @click="editor.resetAll">{{ editor.labels.value.resetAll }}</button>
</div>
<div class="skin-layout-actions">
<button type="button" @click="editor.exportCurrent">{{ editor.labels.value.export }}</button>
<button type="button" @click="importInput?.click()">{{ editor.labels.value.import }}</button>
<input ref="importInput" class="skin-layout-file" type="file" accept="application/json,.json" @change="onImport" />
</div>
<p v-if="editor.statusMessage.value" class="skin-layout-status" role="status">{{ editor.statusMessage.value }}</p>
<div v-if="editor.layoutWarnings.value.length" class="skin-layout-warning" role="status">
<p v-for="warning in editor.layoutWarnings.value" :key="warning">{{ warning }}</p>
<button type="button" @click="editor.ignoreLayoutWarnings">{{ editor.labels.value.ignoreWarnings }}</button>
</div>
<div v-if="editor.migrationRecovery.value" class="skin-layout-warning" role="status">
<span>{{ editor.labels.value.migrationWarning(editor.migrationRecoveryCount.value) }}</span>
<button type="button" @click="editor.exportRecovery">{{ editor.labels.value.exportRecovery }}</button>
</div>
<p class="skin-layout-context">{{ editor.context.value?.skinId }} · {{ editor.context.value?.page }} · {{ editor.context.value?.profile }}</p>
</section>
</div>
<div v-if="editorMode.isEnabled.value && editor.focusPreviewEnabled.value" class="skin-layout-focus-overlay" aria-hidden="true">
<span
v-for="target in editor.focusPreviewTargets.value"
:key="target.key"
class="skin-layout-focus-marker"
:class="{ 'is-small': !target.meetsTouchTarget }"
:style="{ left: `${target.left}px`, top: `${target.top}px`, width: `${target.width}px`, height: `${target.height}px` }"
>{{ target.order }}</span>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { useSkinLayoutEditor } from "../composables/useSkinLayoutEditor.js";
import { promoteHostEditorToTopLayer } from "../services/host-editor-top-layer.js";
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
import { useRoute } from "vue-router";
const editor = useSkinLayoutEditor();
const editorMode = useSkinEditorMode();
const route = useRoute();
const editorRoot = ref<HTMLElement | null>(null);
const importInput = ref<HTMLInputElement | null>(null);
const triggerButton = ref<HTMLButtonElement | null>(null);
const closeButton = ref<HTMLButtonElement | null>(null);
let accessCheckTimer: number | undefined;
function refreshAdminAccess(): void {
if (document.visibilityState !== "hidden") void editorMode.refreshAdminAccess();
}
async function toggleEditorMode(): Promise<void> {
const enabled = await editorMode.setEnabled(!editorMode.isEnabled.value);
if (!enabled) editor.setOpen(false);
}
onMounted(() => {
refreshAdminAccess();
window.addEventListener("focus", refreshAdminAccess);
document.addEventListener("visibilitychange", refreshAdminAccess);
});
onUnmounted(() => {
window.removeEventListener("focus", refreshAdminAccess);
document.removeEventListener("visibilitychange", refreshAdminAccess);
if (accessCheckTimer !== undefined) window.clearInterval(accessCheckTimer);
});
watch(editorRoot, promoteHostEditorToTopLayer, { flush: "post" });
watch(() => route.fullPath, refreshAdminAccess);
watch(editorMode.isEnabled, (enabled) => {
if (accessCheckTimer !== undefined) window.clearInterval(accessCheckTimer);
accessCheckTimer = enabled ? window.setInterval(refreshAdminAccess, 60_000) : undefined;
if (!enabled) editor.setOpen(false);
});
watch(editor.isOpen, async (isOpen) => {
await nextTick();
(isOpen ? closeButton.value : triggerButton.value)?.focus();
});
async function onImport(event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
await editor.importFile(input.files?.[0]);
input.value = "";
}
</script>
<style scoped>
.skin-layout-editor {
position: fixed;
inset: auto;
z-index: 2147483647;
top: auto;
left: auto;
right: 14px;
bottom: 14px;
width: auto;
height: auto;
max-width: none;
max-height: none;
overflow: visible;
margin: 0;
padding: 0;
border: 0;
color: #172033;
background: transparent;
font: 13px/1.45 Inter, ui-sans-serif, system-ui, sans-serif;
}
.skin-layout-editor button,
.skin-layout-editor input,
.skin-layout-editor select {
font: inherit;
}
.skin-layout-trigger {
display: inline-flex;
align-items: center;
gap: 7px;
min-height: 44px;
padding: 0 14px;
border: 1px solid #cbd5e1;
border-radius: 999px;
color: #fff;
background: #273449;
box-shadow: 0 5px 22px #0f172a55;
cursor: pointer;
}
.skin-editor-mode-trigger {
display: inline-flex;
align-items: center;
gap: 7px;
min-height: 44px;
margin-inline-end: 8px;
padding: 0 14px;
border: 1px solid #cbd5e1;
border-radius: 999px;
color: #fff;
background: #334155;
box-shadow: 0 5px 22px #0f172a55;
cursor: pointer;
}
.skin-editor-mode-trigger span { font-size: 19px; line-height: 1; }
.skin-editor-mode-trigger:focus-visible { outline: 3px solid #fbbf24; outline-offset: 3px; }
.skin-layout-trigger span { font-size: 19px; line-height: 1; }
.skin-layout-panel {
position: absolute;
right: 0;
bottom: 56px;
display: grid;
gap: 12px;
width: min(360px, calc(100vw - 24px));
max-height: min(78vh, 720px);
overflow: auto;
padding: 16px;
border: 1px solid #cbd5e1;
border-radius: 16px;
background: #fff;
box-shadow: 0 18px 60px #0f172a44;
}
.skin-layout-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.skin-layout-heading h2 { margin: 0; font-size: 16px; }
.skin-layout-heading p { margin: 5px 0 0; color: #475569; font-size: 12px; }
.skin-layout-close { width: 44px; height: 44px; border-radius: 8px; color: #334155; background: #f1f5f9; font-size: 22px !important; cursor: pointer; }
.skin-layout-toggle { display: flex; align-items: center; gap: 8px; min-height: 44px; }
.skin-layout-field { display: grid; gap: 6px; }
.skin-layout-field > span,
.skin-layout-range label,
.skin-layout-colors span { color: #475569; font-size: 12px; }
.skin-layout-field input[type="search"],
.skin-layout-field select { width: 100%; min-height: 44px; padding: 6px 9px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #fff; }
.skin-layout-range { display: grid; gap: 3px; }
.skin-layout-range label { display: flex; justify-content: space-between; gap: 8px; }
.skin-layout-range output { color: #172033; font-variant-numeric: tabular-nums; }
.skin-layout-range input { width: 100%; min-height: 44px; accent-color: #4f46e5; }
.skin-layout-colors { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
.skin-layout-colors label { display: grid; gap: 4px; }
.skin-layout-colors input { width: 100%; height: 44px; padding: 2px; border: 1px solid #cbd5e1; border-radius: 7px; background: #fff; }
.skin-layout-actions { display: flex; flex-wrap: wrap; gap: 7px; }
.skin-layout-actions button { min-height: 44px; padding: 0 10px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #f8fafc; cursor: pointer; }
.skin-layout-actions button:disabled { opacity: .5; cursor: not-allowed; }
.skin-layout-file { display: none; }
.skin-layout-status { margin: 0; color: #4338ca; }
.skin-layout-warning { margin: 0; padding: 8px 10px; border: 1px solid #fcd34d; border-radius: 8px; color: #854d0e; background: #fffbeb; }
.skin-layout-warning button { min-height: 44px; margin-top: 6px; padding: 0 9px; border: 1px solid #d97706; border-radius: 7px; color: #78350f; background: #fff; cursor: pointer; }
.skin-layout-context { margin: 0; color: #64748b; font-size: 11px; overflow-wrap: anywhere; }
.skin-layout-editor :focus-visible { outline: 2px solid #4f46e5; outline-offset: 2px; }
.skin-layout-focus-list { display: grid; gap: 6px; max-height: 220px; overflow: auto; margin: 0; padding: 0; list-style: none; }
.skin-layout-focus-list > li { display: flex; align-items: flex-start; gap: 8px; min-width: 0; padding: 7px; border: 1px solid #86efac; border-radius: 8px; background: #f0fdf4; }
.skin-layout-focus-list > li.is-small { border-color: #fca5a5; background: #fef2f2; }
.skin-layout-focus-list .skin-layout-focus-empty { border-color: #cbd5e1; background: #f8fafc; color: #475569; }
.skin-layout-focus-number { display: grid; place-items: center; flex: 0 0 22px; width: 22px; height: 22px; border-radius: 50%; color: #fff; background: #15803d; font-weight: 700; }
.is-small .skin-layout-focus-number { background: #b91c1c; }
.skin-layout-focus-name, .skin-layout-focus-size { display: grid; min-width: 0; gap: 2px; overflow-wrap: anywhere; }
.skin-layout-focus-name { flex: 1; }
.skin-layout-focus-name small, .skin-layout-focus-size small { color: #475569; font-size: 10px; }
.skin-layout-focus-size { flex: 0 0 auto; text-align: right; }
.skin-layout-focus-overlay { position: fixed; z-index: 2147483647; inset: 0; pointer-events: none; }
.skin-layout-focus-marker { position: fixed; box-sizing: border-box; display: grid; place-items: start; padding: 0 2px; border: 2px solid #15803d; border-radius: 3px; color: #fff; background: #15803d40; font: 700 11px/16px ui-sans-serif, system-ui, sans-serif; }
.skin-layout-focus-marker.is-small { border-color: #b91c1c; background: #b91c1c40; }
@media (max-width: 520px) {
.skin-layout-editor { right: 10px; bottom: 10px; }
.skin-layout-panel { max-height: 72vh; }
}
</style>
@@ -0,0 +1,52 @@
<template>
<Teleport to="body">
<section v-if="error" class="skin-load-recovery" role="alert">
<p>{{ labels.skinLoadError(error.skinId) }}</p>
<button type="button" @click="$emit('use-built-in')">{{ labels.skinUseBuiltIn }}</button>
</section>
</Teleport>
</template>
<script setup lang="ts">
import { computed } from "vue";
import type { Language } from "../i18n/web-client.js";
import { resolveSkinLayoutLanguage, skinLayoutLabels } from "../i18n/skin-layout.js";
defineEmits<{ "use-built-in": [] }>();
const props = defineProps<{
error: { skinId: string } | null;
language: Language;
}>();
const labels = computed(() => skinLayoutLabels[resolveSkinLayoutLanguage(props.language)]);
</script>
<style scoped>
.skin-load-recovery {
position: fixed;
z-index: 2147482500;
top: max(12px, env(safe-area-inset-top));
left: 50%;
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
width: min(720px, calc(100vw - 24px));
padding: 10px 12px;
transform: translateX(-50%);
border: 1px solid #f59e0b;
border-radius: 12px;
color: #78350f;
background: #fffbeb;
box-shadow: 0 8px 28px #0f172a33;
font: 14px/1.45 ui-sans-serif, system-ui, sans-serif;
}
.skin-load-recovery p { flex: 1; min-width: 0; margin: 0; overflow-wrap: anywhere; }
.skin-load-recovery button { flex: 0 0 auto; min-height: 44px; max-width: 100%; padding: 7px 10px; border: 1px solid #b45309; border-radius: 8px; color: #78350f; background: #fff; cursor: pointer; white-space: normal; }
.skin-load-recovery button:focus-visible { outline: 3px solid #1d4ed8; outline-offset: 2px; }
@media (max-width: 520px) {
.skin-load-recovery { align-items: stretch; flex-direction: column; gap: 7px; }
.skin-load-recovery button { width: 100%; }
}
</style>
+558
View File
@@ -0,0 +1,558 @@
<template>
<Teleport to="body">
<div v-if="skinId" ref="editorRoot" class="skin-plugin-editor" data-ws-plugin-editor>
<button ref="triggerButton" class="skin-plugin-trigger" type="button" aria-controls="skin-plugin-panel" :aria-expanded="open" @click="open = !open" @keydown.esc.stop.prevent="open = false">
{{ english ? "Components" : "组件结构" }}
</button>
<section v-if="open" id="skin-plugin-panel" class="skin-plugin-panel" role="dialog" aria-modal="false" tabindex="-1" :aria-label="english ? 'Skin component editor' : '皮肤组件编辑器'" @keydown.esc.stop.prevent="open = false">
<header class="skin-plugin-heading">
<div>
<h2>{{ english ? "Skin components" : "皮肤组件" }}</h2>
<p>{{ english ? "Edits are local to this skin version and use the same permission and markup checks as packages." : "修改保存在本机当前皮肤版本中,并继续使用皮肤包相同的权限和标记校验。" }}</p>
</div>
<button ref="closeButton" type="button" class="skin-plugin-close" :aria-label="english ? 'Close' : '关闭'" @click="open = false">×</button>
</header>
<div class="skin-plugin-actions">
<button type="button" :disabled="draftDirty || storageInvalid" @click="createComponent">{{ english ? "Add component" : "新增组件" }}</button>
<button type="button" :disabled="!canUndo || draftDirty || storageInvalid" @click="undo">{{ english ? "Undo" : "撤销" }}</button>
<button type="button" :disabled="!canRedo || draftDirty || storageInvalid" @click="redo">{{ english ? "Redo" : "重做" }}</button>
</div>
<label class="skin-plugin-label">
<span>{{ english ? "Components" : "组件列表" }}</span>
<select :value="selectedComponentId" :disabled="draftDirty || storageInvalid" @change="selectComponent(($event.target as HTMLSelectElement).value)">
<option value="">{{ english ? "Select a component" : "选择组件" }}</option>
<option v-for="component in document.components" :key="component.id" :value="component.id">{{ component.name }} · {{ component.page }} · {{ component.id }}</option>
</select>
</label>
<p v-if="!selectedComponent" class="skin-plugin-empty">{{ english ? "No skin components yet. Add one to begin." : "当前皮肤还没有自定义组件,可以从新增组件开始。" }}</p>
<template v-if="selectedComponent">
<div class="skin-plugin-actions">
<button type="button" :disabled="draftDirty || storageInvalid || !canMoveComponent(-1)" :aria-label="english ? 'Move component up' : '组件上移'" @click="moveComponent(-1)">↑</button>
<button type="button" :disabled="draftDirty || storageInvalid || !canMoveComponent(1)" :aria-label="english ? 'Move component down' : '组件下移'" @click="moveComponent(1)">↓</button>
<button type="button" :disabled="draftDirty || storageInvalid" @click="duplicateComponent">{{ english ? "Duplicate component" : "复制组件" }}</button>
<button type="button" class="is-danger" :disabled="draftDirty || storageInvalid" @click="deleteComponent">{{ english ? "Delete component" : "删除组件" }}</button>
</div>
<label class="skin-plugin-label">
<span>{{ english ? "Component tree" : "组件树" }}</span>
<select :value="selectedPathKey" :disabled="draftDirty || storageInvalid" @change="selectPath(($event.target as HTMLSelectElement).value)">
<option value="">{{ english ? "Select a node to edit" : "选择节点进行编辑" }}</option>
<option v-for="row in nodeRows" :key="row.key" :value="row.key" :style="{ paddingInlineStart: (row.depth * 12) + 'px' }">{{ row.label }}</option>
</select>
</label>
<label class="skin-plugin-label">
<span>{{ english ? "New node type" : "新增节点类型" }}</span>
<select :value="newNodeType" :disabled="draftDirty || storageInvalid" :aria-label="english ? 'New node type' : '新增节点类型'" @change="newNodeType = ($event.target as HTMLSelectElement).value">
<option value="text">{{ english ? "Text node" : "文本节点" }}</option>
<option v-for="tag in allowedElementTags" :key="tag" :value="tag">{{ "<" + tag + ">" }}</option>
</select>
</label>
<div class="skin-plugin-actions">
<button type="button" :disabled="!canAddChild || draftDirty || storageInvalid" @click="addChild">{{ english ? "Add child" : "添加子节点" }}</button>
<button type="button" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="addSibling">{{ english ? "Add sibling" : "添加同级节点" }}</button>
<button type="button" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="duplicateNode">{{ english ? "Duplicate node" : "复制节点" }}</button>
<button type="button" :disabled="!selectedPath.length || !canMove(-1) || draftDirty || storageInvalid" :aria-label="english ? 'Move node up' : '节点上移'" @click="moveNode(-1)">↑</button>
<button type="button" :disabled="!selectedPath.length || !canMove(1) || draftDirty || storageInvalid" :aria-label="english ? 'Move node down' : '节点下移'" @click="moveNode(1)">↓</button>
<button type="button" class="is-danger" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="deleteNode">{{ english ? "Delete node" : "删除节点" }}</button>
</div>
<label class="skin-plugin-label skin-plugin-json-label">
<span>{{ editorTarget === "component" ? (english ? "Component definition" : "组件定义") : (english ? "Node definition" : "节点定义") }}</span>
<small>{{ english ? "JSON edits are validated before they are saved or rendered." : "JSON 修改会先经过 schema、权限和安全校验,再保存和渲染。" }}</small>
<textarea v-model="draftJson" :disabled="storageInvalid" spellcheck="false" :aria-label="english ? 'Component or node JSON' : '组件或节点 JSON'"></textarea>
</label>
<div class="skin-plugin-actions">
<button type="button" class="is-primary" :disabled="storageInvalid" @click="applyDraft">{{ english ? "Apply definition" : "应用定义" }}</button>
<button type="button" @click="resetDraft">{{ english ? "Discard draft" : "放弃草稿" }}</button>
</div>
</template>
<div class="skin-plugin-actions skin-plugin-file-actions">
<button type="button" @click="exportDocument">{{ english ? "Export components.json" : "导出 components.json" }}</button>
<button type="button" :disabled="draftDirty || storageInvalid" @click="importInput?.click()">{{ english ? "Import components.json" : "导入 components.json" }}</button>
<button type="button" :disabled="!hasLocalEdits || draftDirty" @click="resetAll">{{ english ? "Reset local edits" : "清除本地修改" }}</button>
<input ref="importInput" class="skin-plugin-file" type="file" accept="application/json,.json" @change="importDocument" />
</div>
<p v-if="errorMessage" class="skin-plugin-error" role="alert">{{ errorMessage }}</p>
<p v-else-if="draftDirty" class="skin-plugin-status" role="status">{{ english ? "Unapplied draft. Apply it or discard it before other edits." : "有尚未应用的草稿;请先应用或放弃,再进行其他修改。" }}</p>
<p v-else-if="statusMessage" class="skin-plugin-status" role="status">{{ statusMessage }}</p>
<p class="skin-plugin-context">{{ skinId }}@{{ skinVersion }}</p>
</section>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from "vue";
import {
addSkinPluginComponent,
addSkinPluginNode,
addSkinPluginNodeSibling,
editableSkinPluginDocument,
getSkinPluginNode,
moveSkinPluginComponent as movePluginComponent,
moveSkinPluginNode as movePluginNode,
duplicateSkinPluginNode,
removeSkinPluginComponent,
removeSkinPluginNode,
replaceSkinPluginComponent,
replaceSkinPluginNode,
} from "../../../src/shared/skin-plugin-editor.js";
import { SKIN_PLUGIN_ALLOWED_ELEMENTS, type SkinPluginComponent, type SkinPluginDocument, type SkinPluginNode } from "../../../src/shared/skin-plugin.js";
import {
clearSkinPluginAuthoringDocument,
exportSkinPluginAuthoringDocument,
hasSkinPluginAuthoringDocument,
importSkinPluginAuthoringDocument,
loadSkinPluginAuthoringDocument,
saveSkinPluginAuthoringDocument,
} from "../services/skin-plugin-authoring.js";
import { promoteHostEditorToTopLayer } from "../services/host-editor-top-layer.js";
const props = defineProps<{
skinId: string;
skinVersion: string;
baseDocument?: SkinPluginDocument;
page: "home" | "voice" | "demo";
lang?: string;
}>();
const emit = defineEmits<{ updated: [] }>();
type NodeRow = { key: string; label: string; depth: number };
const emptyDocument: SkinPluginDocument = { schemaVersion: 3, components: [] };
const allowedElementTags = SKIN_PLUGIN_ALLOWED_ELEMENTS;
const voidNodeTags = new Set(["br", "circle", "hr", "img", "input", "line", "path", "polyline", "rect", "wbr"]);
const open = ref(false);
const document = ref<SkinPluginDocument>(emptyDocument);
const selectedComponentId = ref("");
const selectedPath = ref<number[]>([]);
const editorTarget = ref<"component" | "node">("component");
const newNodeType = ref("div");
const draftJson = ref("");
const errorMessage = ref("");
const statusMessage = ref("");
const importInput = ref<HTMLInputElement | null>(null);
const editorRoot = ref<HTMLElement | null>(null);
const triggerButton = ref<HTMLButtonElement | null>(null);
const closeButton = ref<HTMLButtonElement | null>(null);
const history = ref<SkinPluginDocument[]>([]);
const historyIndex = ref(-1);
const editRevision = ref(0);
const storageInvalid = ref(false);
const english = computed(() => (props.lang ?? "").toLowerCase().startsWith("en"));
const selectedComponent = computed(() => document.value.components.find((component) => component.id === selectedComponentId.value) ?? null);
const selectedNode = computed(() => selectedComponent.value ? getSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value) : null);
const canAddChild = computed(() => Boolean(selectedNode.value?.tag && !voidNodeTags.has(selectedNode.value.tag)));
const selectedPathKey = computed(() => editorTarget.value === "node"
? (selectedPath.value.length ? selectedPath.value.join(".") : "root")
: "");
const canUndo = computed(() => historyIndex.value > 0);
const canRedo = computed(() => historyIndex.value >= 0 && historyIndex.value < history.value.length - 1);
const canMoveComponent = (direction: -1 | 1) => {
const index = document.value.components.findIndex((component) => component.id === selectedComponentId.value);
return index >= 0 && index + direction >= 0 && index + direction < document.value.components.length;
};
const hasLocalEdits = computed(() => { editRevision.value; return hasSkinPluginAuthoringDocument(props.skinId, props.skinVersion); });
const draftDirty = computed(() => {
const current = editorTarget.value === "component" ? selectedComponent.value : selectedNode.value;
return Boolean(current && draftJson.value !== JSON.stringify(current, null, 2));
});
const nodeRows = computed<NodeRow[]>(() => {
const component = selectedComponent.value;
if (!component) return [];
const rows: NodeRow[] = [];
const visit = (node: SkinPluginNode, path: number[], depth: number) => {
const name = node.widget ? "widget: " + node.widget : node.tag ? "<" + node.tag + ">" : "text: " + (node.text ?? "").slice(0, 42);
const label = (path.length ? path.map((index) => index + 1).join(".") : "root") + " · " + name;
rows.push({ key: path.length ? path.join(".") : "root", label, depth });
node.children?.forEach((child, index) => visit(child, [...path, index], depth + 1));
};
visit(component.root, [], 0);
return rows;
});
function activeBase(): SkinPluginDocument {
return editableSkinPluginDocument(props.baseDocument ?? emptyDocument);
}
function loadDocument(): void {
try {
const hasStoredDocument = hasSkinPluginAuthoringDocument(props.skinId, props.skinVersion);
const savedDocument = loadSkinPluginAuthoringDocument(props.skinId, props.skinVersion);
storageInvalid.value = hasStoredDocument && !savedDocument;
document.value = savedDocument ?? activeBase();
selectedPath.value = [];
editorTarget.value = "component";
if (!document.value.components.some((component) => component.id === selectedComponentId.value)) {
selectedComponentId.value = document.value.components[0]?.id ?? "";
}
history.value = [document.value];
historyIndex.value = 0;
resetDraft();
errorMessage.value = storageInvalid.value
? (english.value ? "Saved edits are invalid. Clear this skin version's local edits to restore its package." : "本地修改无法通过校验。清除当前皮肤版本的本地修改即可恢复皮肤包。")
: "";
} catch (error) {
document.value = activeBase();
errorMessage.value = message(error);
}
}
function message(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function createNodeDefinition(): SkinPluginNode {
const type = newNodeType.value;
if (type === "text") return { text: english.value ? "New content" : "新建内容" };
if (!SKIN_PLUGIN_ALLOWED_ELEMENTS.some((tag) => tag === type)) throw new Error("Choose a supported safe node type.");
const node: SkinPluginNode = { tag: type };
if (type === "img") node.attributes = { alt: english.value ? "Skin image" : "皮肤图片" };
if (type === "svg") node.children = [{ tag: "g" }];
else if (type !== "g" && !voidNodeTags.has(type)) node.children = [{ text: english.value ? "New content" : "新建内容" }];
return node;
}
function snapshot<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
function save(next: unknown): boolean {
try {
if (storageInvalid.value) throw new Error(english.value ? "Clear the invalid local edits before saving." : "请先清除无效的本地修改,再保存。");
const normalized = editableSkinPluginDocument(next);
saveSkinPluginAuthoringDocument(props.skinId, props.skinVersion, normalized);
const nextHistory = history.value.slice(0, historyIndex.value + 1);
nextHistory.push(snapshot(normalized));
history.value = nextHistory.slice(-50);
historyIndex.value = history.value.length - 1;
editRevision.value += 1;
document.value = normalized;
if (!normalized.components.some((component) => component.id === selectedComponentId.value)) {
selectedComponentId.value = normalized.components[0]?.id ?? "";
selectedPath.value = [];
}
if (editorTarget.value === "node" && selectedComponent.value) {
try { getSkinPluginNode(normalized, selectedComponentId.value, selectedPath.value); }
catch { selectedPath.value = []; editorTarget.value = "component"; }
}
statusMessage.value = english.value ? "Saved on this device." : "已保存到本机。";
errorMessage.value = "";
resetDraft();
emit("updated");
return true;
} catch (error) {
errorMessage.value = message(error);
statusMessage.value = "";
return false;
}
}
function selectComponent(id: string): void {
selectedComponentId.value = id;
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
}
function selectPath(key: string): void {
if (!key) {
selectedPath.value = [];
editorTarget.value = "component";
} else {
selectedPath.value = key === "root" ? [] : key.split(".").map(Number);
editorTarget.value = "node";
}
resetDraft();
}
function resetDraft(): void {
const component = selectedComponent.value;
if (!component) { draftJson.value = ""; return; }
const current = editorTarget.value === "component" ? component : selectedNode.value;
draftJson.value = current ? JSON.stringify(current, null, 2) : "";
}
function applyDraft(): void {
try {
const parsed: unknown = JSON.parse(draftJson.value);
if (editorTarget.value === "component") {
const next = replaceSkinPluginComponent(document.value, selectedComponentId.value, parsed);
const nextComponent = (parsed as SkinPluginComponent).id;
if (save(next)) {
selectedComponentId.value = nextComponent;
selectedPath.value = [];
resetDraft();
}
} else {
const next = replaceSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value, parsed);
save(next);
}
} catch (error) { errorMessage.value = message(error); statusMessage.value = ""; }
}
function createComponent(): void {
const baseId = "custom-component";
const ids = new Set(document.value.components.map((component) => component.id));
let suffix = 1;
while (ids.has(baseId + "-" + suffix)) suffix += 1;
const id = baseId + "-" + suffix;
const component: SkinPluginComponent = {
id,
name: english.value ? "Custom component" : "自定义组件",
page: props.page === "demo" ? "home" : props.page,
accessibleName: english.value ? "Custom component" : "自定义组件",
permissions: [],
actions: {},
root: { tag: "section", children: [{ text: english.value ? "New component" : "新建组件" }] },
};
try {
if (!save(addSkinPluginComponent(document.value, component))) return;
selectedComponentId.value = id;
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function duplicateComponent(): void {
const source = selectedComponent.value;
if (!source) return;
const stem = source.id.slice(0, 56);
let suffix = 2;
let id = stem + "-" + suffix;
const ids = new Set(document.value.components.map((component) => component.id));
while (ids.has(id)) id = stem + "-" + (++suffix);
const copy = { ...snapshot(source), id, name: source.name.slice(0, 72) + (english.value ? " copy" : " 副本"), accessibleName: source.accessibleName.slice(0, 108) + (english.value ? " copy" : " 副本") };
try {
if (!save(addSkinPluginComponent(document.value, copy))) return;
selectedComponentId.value = id;
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function deleteComponent(): void {
if (!selectedComponentId.value) return;
try {
if (!save(removeSkinPluginComponent(document.value, selectedComponentId.value))) return;
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
}
catch (error) { errorMessage.value = message(error); }
}
function moveComponent(direction: -1 | 1): void {
if (!selectedComponentId.value || !canMoveComponent(direction)) return;
try { save(movePluginComponent(document.value, selectedComponentId.value, direction)); }
catch (error) { errorMessage.value = message(error); }
}
function addChild(): void {
if (!selectedNode.value?.tag || voidNodeTags.has(selectedNode.value.tag)) return;
const parent = selectedPath.value;
const childIndex = selectedNode.value.children?.length ?? 0;
try {
const next = addSkinPluginNode(document.value, selectedComponentId.value, parent, createNodeDefinition());
if (!save(next)) return;
selectedPath.value = [...parent, childIndex];
editorTarget.value = "node";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function addSibling(): void {
if (!selectedPath.value.length) return;
const path = [...selectedPath.value];
const parent = getSkinPluginNode(document.value, selectedComponentId.value, path.slice(0, -1));
try {
if (!parent.tag) throw new Error("Only element nodes can contain siblings.");
const next = addSkinPluginNodeSibling(document.value, selectedComponentId.value, path, createNodeDefinition());
if (!save(next)) return;
path[path.length - 1] += 1;
selectedPath.value = path;
editorTarget.value = "node";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function duplicateNode(): void {
if (!selectedPath.value.length || !selectedNode.value) return;
const path = [...selectedPath.value];
const copy = duplicateSkinPluginNode(document.value, selectedComponentId.value, path);
try {
const next = addSkinPluginNodeSibling(document.value, selectedComponentId.value, path, copy);
if (!save(next)) return;
path[path.length - 1] += 1;
selectedPath.value = path;
editorTarget.value = "node";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function deleteNode(): void {
if (!selectedPath.value.length) return;
try {
const next = removeSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value);
if (!save(next)) return;
selectedPath.value = selectedPath.value.slice(0, -1);
editorTarget.value = "node";
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function canMove(direction: -1 | 1): boolean {
if (!selectedPath.value.length) return false;
const index = selectedPath.value[selectedPath.value.length - 1];
const parent = getSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value.slice(0, -1));
return index + direction >= 0 && index + direction < (parent.children?.length ?? 0);
}
function moveNode(direction: -1 | 1): void {
try {
const next = movePluginNode(document.value, selectedComponentId.value, selectedPath.value, direction);
if (!save(next)) return;
const path = [...selectedPath.value];
path[path.length - 1] += direction;
selectedPath.value = path;
resetDraft();
} catch (error) { errorMessage.value = message(error); }
}
function undo(): void {
if (!canUndo.value) return;
historyIndex.value -= 1;
const value = history.value[historyIndex.value];
try {
document.value = saveSkinPluginAuthoringDocument(props.skinId, props.skinVersion, value);
editRevision.value += 1;
if (!document.value.components.some((component) => component.id === selectedComponentId.value)) selectedComponentId.value = document.value.components[0]?.id ?? "";
selectedPath.value = [];
editorTarget.value = "component";
statusMessage.value = english.value ? "Change undone." : "已撤销。";
resetDraft();
emit("updated");
} catch (error) { historyIndex.value += 1; errorMessage.value = message(error); }
}
function redo(): void {
if (!canRedo.value) return;
historyIndex.value += 1;
const value = history.value[historyIndex.value];
try {
document.value = saveSkinPluginAuthoringDocument(props.skinId, props.skinVersion, value);
editRevision.value += 1;
if (!document.value.components.some((component) => component.id === selectedComponentId.value)) selectedComponentId.value = document.value.components[0]?.id ?? "";
selectedPath.value = [];
editorTarget.value = "component";
statusMessage.value = english.value ? "Change redone." : "已重做。";
resetDraft();
emit("updated");
} catch (error) { historyIndex.value -= 1; errorMessage.value = message(error); }
}
function resetAll(): void {
try {
clearSkinPluginAuthoringDocument(props.skinId, props.skinVersion);
storageInvalid.value = false;
editRevision.value += 1;
document.value = activeBase();
selectedComponentId.value = document.value.components[0]?.id ?? "";
selectedPath.value = [];
editorTarget.value = "component";
history.value = [document.value];
historyIndex.value = 0;
resetDraft();
errorMessage.value = "";
statusMessage.value = english.value ? "Local edits cleared." : "本地修改已清除。";
emit("updated");
} catch (error) { errorMessage.value = message(error); }
}
function download(source: string, filename: string): void {
const url = URL.createObjectURL(new Blob([source], { type: "application/json" }));
const anchor = window.document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.click();
window.setTimeout(() => URL.revokeObjectURL(url), 0);
}
function exportDocument(): void {
try { download(exportSkinPluginAuthoringDocument(document.value), props.skinId + "-components.json"); }
catch (error) { errorMessage.value = message(error); }
}
async function importDocument(event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = "";
if (!file) return;
try {
if (file.size > 256 * 1024) throw new Error("components.json exceeds the 256 KiB limit.");
const imported = importSkinPluginAuthoringDocument(await file.text());
if (!save(imported)) return;
selectedComponentId.value = imported.components[0]?.id ?? "";
selectedPath.value = [];
editorTarget.value = "component";
resetDraft();
} catch (error) { errorMessage.value = message(error); statusMessage.value = ""; }
}
watch(() => [props.skinId, props.skinVersion, props.baseDocument] as const, loadDocument, { immediate: true });
watch(() => [selectedComponentId.value, selectedPathKey.value, editorTarget.value] as const, resetDraft);
onMounted(() => {
promoteHostEditorToTopLayer(editorRoot.value);
});
watch(open, async (isOpen) => {
await nextTick();
const target = isOpen ? closeButton.value : triggerButton.value;
target?.focus?.();
});
</script>
<style scoped>
.skin-plugin-editor { position: fixed; inset: auto; z-index: 2147483647; top: auto; left: auto; right: 14px; bottom: 72px; width: auto; height: auto; max-width: none; max-height: none; overflow: visible; margin: 0; padding: 0; border: 0; color: #172033; background: transparent; font: 13px/1.45 Inter, ui-sans-serif, system-ui, sans-serif; }
.skin-plugin-editor button, .skin-plugin-editor select, .skin-plugin-editor textarea { font: inherit; }
.skin-plugin-trigger { min-height: 44px; padding: 0 14px; border: 1px solid #cbd5e1; border-radius: 999px; color: #fff; background: #4f46e5; box-shadow: 0 5px 22px #0f172a55; cursor: pointer; }
.skin-plugin-panel { position: absolute; right: 0; bottom: 50px; display: grid; gap: 10px; width: min(460px, calc(100vw - 24px)); max-height: min(82vh, 820px); overflow: auto; padding: 14px; border: 1px solid #cbd5e1; border-radius: 15px; background: #fff; box-shadow: 0 18px 60px #0f172a44; }
.skin-plugin-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
.skin-plugin-heading h2 { margin: 0; font-size: 16px; }
.skin-plugin-heading p { margin: 5px 0 0; color: #475569; font-size: 11px; }
.skin-plugin-close { width: 44px; height: 44px; border-radius: 8px; color: #334155; background: #f1f5f9; font-size: 21px !important; cursor: pointer; }
.skin-plugin-actions { display: flex; flex-wrap: wrap; gap: 6px; }
.skin-plugin-actions button { min-height: 44px; padding: 0 9px; border: 1px solid #cbd5e1; border-radius: 7px; color: #172033; background: #f8fafc; cursor: pointer; }
.skin-plugin-actions button:disabled { opacity: .45; cursor: not-allowed; }
.skin-plugin-actions .is-primary { color: #fff; border-color: #4338ca; background: #4f46e5; }
.skin-plugin-actions .is-danger { color: #991b1b; border-color: #fecaca; background: #fef2f2; }
.skin-plugin-label { display: grid; gap: 5px; color: #475569; font-size: 12px; }
.skin-plugin-label select { width: 100%; min-height: 44px; padding: 5px 8px; border: 1px solid #cbd5e1; border-radius: 7px; color: #172033; background: #fff; }
.skin-plugin-json-label small { color: #64748b; }
.skin-plugin-json-label textarea { width: 100%; min-height: 230px; resize: vertical; padding: 10px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #f8fafc; font: 12px/1.45 ui-monospace, SFMono-Regular, Consolas, monospace; tab-size: 2; }
.skin-plugin-file { display: none; }
.skin-plugin-error, .skin-plugin-status, .skin-plugin-context { margin: 0; overflow-wrap: anywhere; }
.skin-plugin-error { color: #b91c1c; }
.skin-plugin-status { color: #4338ca; }
.skin-plugin-context { color: #64748b; font-size: 10px; }
.skin-plugin-editor :focus-visible { outline: 2px solid #4f46e5; outline-offset: 2px; }
@media (max-width: 520px) {
.skin-plugin-editor { right: max(10px, env(safe-area-inset-right)); bottom: calc(10px + env(safe-area-inset-bottom)); }
.skin-plugin-panel {
box-sizing: border-box;
width: min(460px, calc(100vw - 20px - env(safe-area-inset-left) - env(safe-area-inset-right)));
max-height: min(76vh, 620px);
}
}
@supports (height: 100dvh) {
@media (max-width: 520px) {
.skin-plugin-panel { max-height: min(620px, calc(100dvh - 76px - env(safe-area-inset-top) - env(safe-area-inset-bottom))); }
}
}
</style>
Loaded 100 of 219 files, more files were not shown because too many files have changed in this diff. Show more