diff --git a/README.md b/README.md index b60cf70..8977332 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ - [Deutsch](./docs/README.de.md) - [Русский](./docs/README.ru.md) - [日本語](./docs/README.ja.md) +- [皮肤开发规范](./docs/SKIN_DEVELOPMENT.md) ## 社区 · Community diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md new file mode 100644 index 0000000..8cc206f --- /dev/null +++ b/docs/SKIN_DEVELOPMENT.md @@ -0,0 +1,231 @@ +# WebSpeak 皮肤开发规范 + +本文说明如何制作、校验并发布 WebSpeak `.wskin` 皮肤包。皮肤可以彻底重做公开页面的视觉表现:背景图、字体、布局、头像框、滚动条、按钮、设置面板、语音成员、聊天和屏幕共享播放器都可以用 CSS 定制;首页文字和功能介绍也可以按语言替换。 + +皮肤不注入 HTML 或 JavaScript,也不改变语音、权限、连接、拖动和屏幕共享行为。页面结构和必要控件由应用提供,皮肤通过样式与有限的文案配置改变呈现。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。** + +可直接查看 [Aurora Voice 示例源码](examples/aurora-voice/),其中包含本地图片资源、多语言首页文案、演示页翻译、头像框、滚动条、播放器和动效的完整用法。 + +## 使用与发布 + +管理员在 `/admin/skins` 上传 `.wskin` 包,可查看预览、替换同 ID 版本或删除皮肤。皮肤发布到当前 WebSpeak 实例后,访客可在连接首页、语音工作区或 `/demo` 的“皮肤”选择器中切换;选择保存在该浏览器。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。 + +选择器提供“日间”“夜间”和实例发布的皮肤;没有“跟随系统”选项。自定义皮肤同时继承当前日间或夜间的基础令牌,再由自己的 CSS 覆盖。切换为日间或夜间时,会停用当前自定义包。 + +## 包结构 + +`.wskin` 是标准 ZIP 容器,推荐把下列文件直接放在 ZIP 根目录: + +```text +manifest.json # 必需:身份、版本与入口 +skin.css # 必需:皮肤样式 +content.json # 可选:首页内容与多语言界面文案 +assets/preview.jpg # 可选:管理后台显示的预览图,也可在 CSS 中使用 +assets/background.webp # 可选:页面艺术素材 +assets/brand.woff2 # 可选:自带字体 +``` + +所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。 + +### `manifest.json` + +```json +{ + "schemaVersion": 1, + "id": "studio.aurora-voice", + "name": "Aurora Voice", + "version": "1.0.0", + "author": "Your name", + "license": "CC-BY-4.0", + "description": "An aurora-inspired voice workspace.", + "entry": "skin.css", + "content": "content.json", + "preview": "assets/preview.jpg", + "minAppVersion": "0.2.4" +} +``` + +| 字段 | 规则 | +| --- | --- | +| `schemaVersion` | 当前必须为数字 `1`。 | +| `id` | 必需,最多 80 个字符;只允许小写字母、数字、点和连字符;不能以 `builtin.` 开头。发布后不要更改。 | +| `name`、`author`、`license` | 必需,各最多 80 个字符。资源授权由作者负责确认。 | +| `version`、`minAppVersion` | 必需,使用语义化版本号,例如 `1.2.0`。 | +| `entry` | 必需,包内 CSS 文件路径,最多 120 个字符。 | +| `content` | 可选,包内 JSON 文件路径,最多 120 个字符。 | +| `preview` | 可选,包内 PNG、JPG/JPEG、WebP、AVIF 或 GIF 图片路径,最多 120 个字符。 | +| `description` | 可选,最多 400 个字符。 | + +清单不得重复声明同一个文件为 CSS、内容或预览入口。 + +## 首页内容和文案 + +`content.json` 可按 locale 覆盖连接首页内容和公开界面文案;不提供的字段继续使用应用文案,不会显示空白。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例: + +```json +{ + "defaultLocale": "en", + "locales": { + "en": { + "home": { + "eyebrow": "A room of your own", + "title": "Talk", + "titleAccent": "together", + "description": "Join a voice room from your browser.", + "welcomeTitle": "Join the room", + "welcomeDescription": "Choose a name and connect.", + "features": [ + { "title": "Clear voice", "description": "Low-latency Opus audio." } + ] + }, + "messages": { + "home.connect": "Enter the room", + "voice.activity-heading": "Voice activity", + "demo.heroLead": "A preview customized by this skin." + } + } + } +} +``` + +`home` 支持 `brandName`、`eyebrow`、`title`、`titleAccent`、`description`、`welcomeTitle`、`welcomeDescription` 和 `features`。普通文字最多 500 个字符;`features` 最多 8 项,每项的 `title` 最多 80 个字符、`description` 最多 240 个字符。功能卡片图标和状态由应用提供,皮肤不能通过 JSON 注入节点。 + +`messages` 的键是公开页面中翻译调用使用的键;首页/语音页键可在 `web/src/i18n/web-client.ts` 查找,演示页键使用 `demo.` 前缀加字段名(例如 `demo.heroLead`、`demo.speakingNow`)。每个 locale 最多覆盖 200 条,每条文案最多 500 个字符。键只能由小写字母开头,并包含字母、数字或点。语言回退顺序为默认 locale、当前语言和更具体的 locale;之后回退到 WebSpeak 原文。 + +管理后台的文字不读取皮肤包,不能通过 `messages` 修改。 + +## CSS 皮肤接口 + +### 自动隔离 + +运行时把 `skin.css` 的每个选择器限定在皮肤自己的公开页面根节点内: + +```css +/* 作者只写部件选择器;运行时自动加上皮肤和页面根作用域。 */ +[data-ws-page="voice"] [data-ws-part="voice.member.avatar"] { + outline: 2px solid var(--accent); + outline-offset: 4px; +} +``` + +实际规则会被限定在类似下面的根节点内,不会匹配 `/admin/**`: + +```css +.ws-skin-root[data-ws-skin="studio.aurora-voice"] [data-ws-page="voice"] [data-ws-part="voice.member.avatar"] +``` + +也可以写 `:root { --accent: ... }` 设置皮肤根令牌;`:root` 会被转换成当前皮肤根。不要写 `:global()`、`html`、`body` 或 Vue 内部 class 作为公开接口。组件 class 可能随版本调整,`data-ws-part` 才是皮肤作者接口。 + +页面根节点使用 `data-ws-page` 区分 `home`、`voice` 和 `demo`。使用 `data-ws-state` 选择明确状态,如 `active`、`idle`、`current`、`drag-over`、`dragging`、`speaking`、`connected`、`self`、`mine` 或 `other`。语音成员还提供 `data-ws-speaking="true|false"` 和 `data-ws-self="true|false"`。交互元素会带有 `data-ws-critical="true"`;没有专属部件名称的按钮、链接、输入框、滑块和可拖动成员会使用通用部件 `data-ws-part="control"`,并以 `data-ws-control-kind` 标出 `button`、`link`、`input`、`checkbox`、`range`、`select`、`textarea`、`menuitem` 或 `draggable`。 + +### 已发布的部件名称 + +下列名称来自当前前端模板。对新功能,作者可以先用通用 `control` 部件;后续新增稳定部件会更新本目录。 + +| 页面区域 | `data-ws-part` | +| --- | --- | +| 通用 | `app`、`app.toast`、`control` | +| 首页 | `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-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.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-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` | +| 聊天与菜单 | `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.empty`、`voice.chat.composer`、`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`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。 + +### 令牌、字体、动效和图片 + +皮肤可自定义任意作用域内的普通 CSS,不限于改色。推荐先定义自己的变量,再为公开部件编写布局: + +```css +:root { + --page-bg: #091317; + --panel: #142329; + --text: #edf8f5; + --muted: #9db5af; + --accent: #47dcc4; + --card-radius: 20px; +} + +[data-ws-part="voice.screen-player"] { + border: 1px solid color-mix(in srgb, var(--accent) 50%, transparent); + border-radius: var(--card-radius); + box-shadow: 0 18px 50px #0008; +} +``` + +`url()` 只允许引用包内图片或 WOFF2 字体。支持 PNG、JPG/JPEG、WebP、AVIF、GIF 和 WOFF2;SVG 不接受。自带字体示例: + +```css +@font-face { + font-family: "Aurora Sans"; + src: url("assets/aurora-sans.woff2") format("woff2"); + font-display: swap; +} + +[data-ws-page="voice"] { font-family: "Aurora Sans", sans-serif; } +``` + +字体必须随包附带并拥有可再分发许可。字体族名和 `@keyframes` / `@layer` 名称会自动隔离,避免与其他皮肤冲突。请支持 `prefers-reduced-motion`,并确保焦点、错误、静音、正在说话等状态仍容易辨认。 + +## 安全边界和限制 + +校验在上传端和服务端执行;服务端只登记有效皮肤包,访客只能下载登记的包。当前限制如下: + +| 项目 | 上限 | +| --- | ---: | +| ZIP `.wskin` | 20 MiB | +| 解压总大小 | 50 MiB | +| ZIP 条目数 | 128 | +| 单个 CSS 文件 | 512 KiB | +| `content.json` | 256 KiB | +| 单张图片(包括预览) | 16 MiB | +| 单个 WOFF2 字体 | 4 MiB | +| 每实例皮肤数 | 50 | +| 每实例皮肤包总存储 | 200 MiB | + +压缩包路径穿越、重复/冲突路径、符号链接、异常 ZIP 元数据和本地文件头/目录不一致都会被拒绝。仅允许受支持的 CSS at-rule:`@media`、`@supports`、`@container`、具名 `@layer`、`@font-face` 和 keyframes。`@import`、脚本、HTML、外部网络资源会被拒绝;`!important` 可用于皮肤作用域内的样式。字体 `local()` 也会拒绝,避免绕过包内字体来源。 + +必要操作控件(加入/退出、麦克风、设置、菜单、屏幕共享退出、音量、全屏等)及其布局容器不能被隐藏或整体重置。校验器会拦截常见的 `display`、`visibility`、`opacity`、`pointer-events`、遮罩、裁切、变换、滤镜和 `all` 隐藏/重置方式。若确实需要移除纯装饰部分,只允许对以下独立元素使用这些写法: + +```css +[data-ws-part="home.hero.eyebrow"] +[data-ws-part="home.gateway-status"] +[data-ws-part="home.features"] +[data-ws-part="home.feature"] +[data-ws-part="home.visitors"] +[data-ws-part="voice.activity-heading"] +[data-ws-part="voice.member.avatar"] +[data-ws-part="voice.member.live-indicator"] +[data-ws-part="voice.member-row.avatar"] +[data-ws-part="voice.screen-player.viewer-avatar"] +[data-ws-part="voice.screen-player.live"] +[data-ws-part="demo.badge"] +[data-ws-part="demo.wave"] +[data-ws-part="demo.avatar"] +[data-ws-part="demo.member-status"] +[data-ws-part="demo.note"] +``` + +上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可隐藏部件引用时,才可使用隐藏写法;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。你仍可自由重排、装饰这些元素,并使用皮肤包自带的图片和字体。校验仅覆盖常见风险写法,不是对任意 CSS 的形式化安全证明;CSS 仍可能造成遮挡、不可读或破坏布局,皮肤作者需在预览中验证每个必要控件。 + +皮肤可重新布置甚至重画控制外观,但不得隐藏或阻断加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等必要操作。校验器还会对固定定位或极端层级给出风险警告;校验成功不代表设计质量合格。提交前要逐页实测窄屏和桌面尺寸、深浅色、键盘焦点与减少动效设置。 + +CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。 + +## 制作与验收 + +1. 复制 `docs/examples/aurora-voice/`,先修改 `manifest.json` 的唯一 `id`、名称、作者、版本和授权。 +2. 只使用本目录公开的 `data-ws-part`、`data-ws-page`、状态属性和包内静态资源。不要依赖 Vue 内部 class。 +3. 使用本地资源编写 `skin.css`;需要改首页文字或公开翻译时补充 `content.json`。 +4. 在包根目录生成 ZIP,再改扩展名为 `.wskin`。PowerShell 示例: + + ```powershell + Compress-Archive -Path .\docs\examples\aurora-voice\* -DestinationPath .\aurora-voice.zip -Force + Rename-Item .\aurora-voice.zip aurora-voice.wskin + ``` + +5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置。 +6. 检查至少一个窄屏尺寸和桌面尺寸,并检查焦点可见、对比度、动效偏好;确认没有第三方素材授权问题。 + +当前自动化回归涵盖 ZIP/清单验证、资源路径、CSS 隔离与拒绝规则、文案结构和服务端皮肤目录读写。视觉排版、内容遮挡和浏览器间表现仍须人工预览。 diff --git a/docs/examples/aurora-voice.wskin b/docs/examples/aurora-voice.wskin new file mode 100644 index 0000000..118ba5c Binary files /dev/null and b/docs/examples/aurora-voice.wskin differ diff --git a/docs/examples/aurora-voice/assets/webspeak-mark.jpg b/docs/examples/aurora-voice/assets/webspeak-mark.jpg new file mode 100644 index 0000000..19cf590 Binary files /dev/null and b/docs/examples/aurora-voice/assets/webspeak-mark.jpg differ diff --git a/docs/examples/aurora-voice/content.json b/docs/examples/aurora-voice/content.json new file mode 100644 index 0000000..0c623a4 --- /dev/null +++ b/docs/examples/aurora-voice/content.json @@ -0,0 +1,40 @@ +{ + "defaultLocale": "en", + "locales": { + "en": { + "home": { + "eyebrow": "A room of your own", + "title": "Talk", + "titleAccent": "together", + "description": "A small example of custom homepage copy and feature text.", + "welcomeTitle": "Join the room", + "welcomeDescription": "Choose a name and connect to your TeamSpeak server.", + "features": [ + { "title": "Clear voice", "description": "Low-latency Opus audio." }, + { "title": "Private by design", "description": "Your connection details stay in this session." }, + { "title": "In sync", "description": "Channels and members update together." } + ] + }, + "messages": { + "demo.heroLead": "This demo is styled by the same package as the connection and voice pages.", + "demo.speakingNow": "On stage", + "demo.skinSelector": "Skin" + } + }, + "zh-CN": { + "home": { + "eyebrow": "属于你的语音空间", + "title": "自在", + "titleAccent": "畅聊", + "description": "示例皮肤可以自定义首页文案、卡片、背景和语音面板。", + "welcomeTitle": "进入房间", + "welcomeDescription": "填写昵称并连接 TeamSpeak 服务器。" + }, + "messages": { + "demo.heroLead": "连接页、语音页和演示页都由同一皮肤包定制。", + "demo.speakingNow": "舞台成员", + "demo.skinSelector": "皮肤" + } + } + } +} diff --git a/docs/examples/aurora-voice/manifest.json b/docs/examples/aurora-voice/manifest.json new file mode 100644 index 0000000..5812f54 --- /dev/null +++ b/docs/examples/aurora-voice/manifest.json @@ -0,0 +1,13 @@ +{ + "schemaVersion": 1, + "id": "community.aurora-voice", + "name": "Aurora Voice", + "version": "1.0.0", + "author": "WebSpeak Project", + "license": "AGPL-3.0-only", + "description": "A compact example showing local artwork, full-page CSS styling, avatar frames, and localized copy.", + "entry": "skin.css", + "content": "content.json", + "preview": "assets/webspeak-mark.jpg", + "minAppVersion": "0.2.4" +} diff --git a/docs/examples/aurora-voice/skin.css b/docs/examples/aurora-voice/skin.css new file mode 100644 index 0000000..50b1390 --- /dev/null +++ b/docs/examples/aurora-voice/skin.css @@ -0,0 +1,101 @@ +/* Every selector is automatically scoped to this package and a public page root. */ +:root { + --page: #07151c; + --surface: #10242b; + --surface-raised: #17333a; + --ink: #effdfa; + --ink-muted: #a2c4be; + --accent: #42dfc7; + --accent-strong: #06a992; + --line: rgba(104, 229, 208, .24); + --glow: 0 18px 48px rgba(0, 0, 0, .26); + --round-card: 22px; +} + +[data-ws-part="home"] { + color: var(--ink); + background: radial-gradient(ellipse at 50% 35%, #173b43, var(--page) 74%); +} + +[data-ws-part="home.join-card"], +[data-ws-part="voice.member-panel"], +[data-ws-part="voice.chat"], +[data-ws-part="demo.main"], +[data-ws-part="demo.channels"], +[data-ws-part="demo.actions"] { + color: var(--ink); + background: linear-gradient(145deg, var(--surface-raised), var(--surface)); + border: 1px solid var(--line); + border-radius: var(--round-card); + box-shadow: var(--glow); +} + +[data-ws-part="home.connect"], +[data-ws-part="voice.audio-dock"], +[data-ws-part="demo.chat.send"] { + color: #041613; + background: linear-gradient(110deg, var(--accent), var(--accent-strong)); + border: 1px solid rgba(162, 255, 235, .55); + border-radius: 14px; + box-shadow: 0 0 22px rgba(66, 223, 199, .2); +} + +[data-ws-part="voice.member.avatar"], +[data-ws-part="voice.member-row.avatar"], +[data-ws-part="demo.avatar"] { + outline: 2px solid var(--accent); + outline-offset: 4px; + box-shadow: 0 0 20px rgba(66, 223, 199, .35); +} + +[data-ws-part="voice.member.live-indicator"], +[data-ws-part="demo.live"] { + color: var(--ink); + background: rgba(6, 169, 146, .25); + border: 1px solid var(--line); + border-radius: 999px; + box-shadow: 0 0 18px rgba(66, 223, 199, .18); +} + +[data-ws-part="voice.screen-player"] { + border: 1px solid var(--line); + border-radius: 20px; + box-shadow: 0 0 36px rgba(66, 223, 199, .18); +} + +[data-ws-part="demo.hero"] { + background-color: #103039; + background-image: linear-gradient(100deg, rgba(7, 21, 28, .12), rgba(7, 21, 28, .76)), url("assets/webspeak-mark.jpg"); + background-position: center, right 22px center; + background-repeat: no-repeat; + background-size: cover, 92px 92px; + border: 1px solid var(--line); + border-radius: var(--round-card); +} + +[data-ws-part="demo.voice-card"][data-ws-state="speaking"] { + outline: 1px solid var(--accent); + box-shadow: 0 0 24px rgba(66, 223, 199, .22); +} + +[data-ws-part="control"][data-ws-control-kind="range"] { + accent-color: var(--accent); +} + +* { + scrollbar-color: var(--accent-strong) transparent; + scrollbar-width: thin; +} + +@keyframes aurora-breathe { + 0%, 100% { filter: brightness(.94); } + 50% { filter: brightness(1.12); } +} + +[data-ws-part="home.visitors"] { + animation: aurora-breathe 5s ease-in-out infinite; +} + +@media (prefers-reduced-motion: reduce) { + [data-ws-part="home.visitors"] { animation: none; } +} diff --git a/package.json b/package.json index b4dabee..424dbef 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", + "test": "node --import tsx --test src/admin/skin-registry.test.ts web/src/services/skin-pack.test.ts", "start": "node dist/index.js", "web:dev": "cd web && npx vite --host", "web:build": "cd web && npx vite build", diff --git a/src/admin/admin-router.ts b/src/admin/admin-router.ts index cdf5d16..01d0946 100644 --- a/src/admin/admin-router.ts +++ b/src/admin/admin-router.ts @@ -1,4 +1,4 @@ -import { Router, type NextFunction, type Request, type Response } from "express"; +import { Router, raw as expressRaw, type NextFunction, type Request, type Response } from "express"; import { existsSync, readFileSync } from "node:fs"; import type { Logger } from "../logger.js"; import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput } from "./admin-service.js"; @@ -6,6 +6,7 @@ import { AdminSessionStore, isSecureRequest } from "./admin-session.js"; import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js"; import { TeamSpeakProbeError } from "../server/teamspeak-probe.js"; import type { AdminSessionSummary } from "../server/voice-bridge.js"; +import { SkinRegistry, SkinRegistryError } from "./skin-registry.js"; export interface AdminConnectionRecord { id: string; @@ -34,6 +35,7 @@ export interface AdminRouterOptions { terminateSession?: (id: string) => Promise; version?: string; logFile?: string; + skinRegistry?: SkinRegistry; startedAt: number; } @@ -120,6 +122,37 @@ export function createAdminRouter(options: AdminRouterOptions): Router { response.json(options.service.getAdminSettings()); }); + router.get("/skins", async (_request, response) => { + response.json({ skins: await options.skinRegistry?.list() ?? [] }); + }); + + router.put("/skins/:id", requireSameOriginBinary, requireCsrf(options.sessions), expressRaw({ type: "application/octet-stream", limit: "20mb" }), async (request, response) => { + try { + const id = typeof request.params.id === "string" ? request.params.id : ""; + if (!options.skinRegistry || !Buffer.isBuffer(request.body)) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE"); + const skin = await options.skinRegistry.save(request.body, id); + options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version }); + response.status(201).json({ ok: true, skin }); + } catch (error: unknown) { + if (error instanceof SkinRegistryError) { + const status = error.code === "SKIN_LIMIT" || error.code === "SKIN_STORAGE_LIMIT" ? 409 : 400; + response.status(status).json({ ok: false, code: error.code, message: error.message }); + return; + } + sendAdminError(response, error); + } + }); + + router.delete("/skins/:id", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => { + const id = typeof request.params.id === "string" ? request.params.id : ""; + if (!options.skinRegistry || !await options.skinRegistry.remove(id)) { + response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" }); + return; + } + options.service.database.addAudit("ADMIN_SKIN_REMOVED", { id }); + response.json({ ok: true }); + }); + router.get("/sessions", (_request, response) => { response.json({ sessions: options.getSessionSummaries?.() ?? [] }); }); @@ -327,6 +360,22 @@ function requireSameOrigin(request: Request, response: Response, next: NextFunct next(); } +function requireSameOriginBinary(request: Request, response: Response, next: NextFunction): void { + if (!request.is("application/octet-stream")) { + response.status(415).json({ ok: false, code: "BINARY_REQUIRED" }); + return; + } + const origin = request.header("origin"); + const host = request.header("host"); + try { + if (!origin || !host || new URL(origin).host !== host) throw new Error("origin mismatch"); + } catch { + response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" }); + return; + } + next(); +} + async function runProbe( service: AdminService, response: Response, diff --git a/src/admin/skin-registry.test.ts b/src/admin/skin-registry.test.ts new file mode 100644 index 0000000..4ebe4ec --- /dev/null +++ b/src/admin/skin-registry.test.ts @@ -0,0 +1,141 @@ +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { SkinRegistry, SkinRegistryError } from "./skin-registry.js"; + +const manifest = { + schemaVersion: 1, + id: "sample-skin", + name: "Sample skin", + version: "1.0.0", + author: "WebSpeak test", + license: "MIT", + minAppVersion: "0.2.4", + entry: "skin.css", + content: "content.json", + preview: "assets/preview.png", +}; + +test("skin registry validates, lists, replaces, serves, and removes packages", async (context) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-registry-")); + context.after(() => rm(directory, { recursive: true, force: true })); + const registry = new SkinRegistry(directory); + + 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); }")], + ["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])], + ]); + const first = await registry.save(firstArchive, "sample-skin"); + assert.equal(first.id, "sample-skin"); + assert.equal(first.previewUrl, "/api/skins/sample-skin/preview"); + assert.equal((await registry.list()).length, 1); + assert.deepEqual(await registry.readArchive("sample-skin"), firstArchive); + assert.deepEqual((await registry.readPreview("sample-skin"))?.bytes, Buffer.from([5, 6, 7, 8])); + + 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; }")], + ]); + const second = await registry.save(secondArchive, "sample-skin"); + assert.equal(second.version, "2.0.0"); + assert.equal(second.installedAt, first.installedAt); + assert.equal(await registry.readPreview("sample-skin"), null); + assert.deepEqual(await registry.readArchive("sample-skin"), secondArchive); + + assert.equal(await registry.remove("sample-skin"), true); + assert.deepEqual(await registry.list(), []); + assert.equal(await registry.readArchive("sample-skin"), null); + assert.equal(await registry.remove("sample-skin"), false); +}); + +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; }")], + ]; + + await assert.rejects(registry.save(createZip([["../escape.png", Buffer.from([1])], ...goodFiles]), "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PATH_INVALID"); + const mismatched = createZip(goodFiles); + mismatched[30] ^= 1; + await assert.rejects(registry.save(mismatched, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ZIP_INVALID"); + + await writeFile(path.join(directory, "orphan.wskin"), createZip(goodFiles)); + assert.equal(await registry.readArchive("orphan"), null); + assert.deepEqual(await registry.list(), []); +}); + +test("the documented Aurora Voice package passes the server-side upload validator", async (context) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-example-")); + context.after(() => rm(directory, { recursive: true, force: true })); + const registry = new SkinRegistry(directory); + const archive = await readFile(new URL("../../docs/examples/aurora-voice.wskin", import.meta.url)); + const entry = await registry.save(archive, "community.aurora-voice"); + assert.equal(entry.name, "Aurora Voice"); + assert.equal(entry.previewUrl, "/api/skins/community.aurora-voice/preview"); + assert.equal((await registry.list()).length, 1); +}); + +function createZip(files: Array<[string, Buffer]>): Buffer { + const localRecords: Buffer[] = []; + const centralRecords: Buffer[] = []; + let localOffset = 0; + for (const [name, bytes] of files) { + const filename = Buffer.from(name, "utf8"); + const checksum = crc32(bytes); + const local = Buffer.alloc(30 + filename.length + bytes.length); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); + local.writeUInt16LE(0, 6); + local.writeUInt16LE(0, 8); + local.writeUInt32LE(checksum, 14); + local.writeUInt32LE(bytes.length, 18); + local.writeUInt32LE(bytes.length, 22); + local.writeUInt16LE(filename.length, 26); + filename.copy(local, 30); + bytes.copy(local, 30 + filename.length); + localRecords.push(local); + + const central = Buffer.alloc(46 + filename.length); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(0x0314, 4); + central.writeUInt16LE(20, 6); + central.writeUInt16LE(0, 8); + central.writeUInt16LE(0, 10); + central.writeUInt32LE(checksum, 16); + central.writeUInt32LE(bytes.length, 20); + central.writeUInt32LE(bytes.length, 24); + central.writeUInt16LE(filename.length, 28); + central.writeUInt32LE(0x81a40000, 38); + central.writeUInt32LE(localOffset, 42); + filename.copy(central, 46); + centralRecords.push(central); + localOffset += local.length; + } + const centralDirectory = Buffer.concat(centralRecords); + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(files.length, 8); + end.writeUInt16LE(files.length, 10); + end.writeUInt32LE(centralDirectory.length, 12); + end.writeUInt32LE(localOffset, 16); + return Buffer.concat([...localRecords, centralDirectory, end]); +} + +function crc32(bytes: Buffer): number { + let crc = 0xffffffff; + for (const byte of bytes) { + crc ^= byte; + for (let bit = 0; bit < 8; bit += 1) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1; + } + return (crc ^ 0xffffffff) >>> 0; +} diff --git a/src/admin/skin-registry.ts b/src/admin/skin-registry.ts new file mode 100644 index 0000000..ebb8b25 --- /dev/null +++ b/src/admin/skin-registry.ts @@ -0,0 +1,400 @@ +import { randomBytes } from "node:crypto"; +import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { inflateRawSync } from "node:zlib"; + +const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024; +const MAX_EXPANDED_BYTES = 50 * 1024 * 1024; +const MAX_FILE_COUNT = 128; +const MAX_CSS_BYTES = 512 * 1024; +const MAX_CONTENT_BYTES = 256 * 1024; +const MAX_IMAGE_BYTES = 16 * 1024 * 1024; +const MAX_FONT_BYTES = 4 * 1024 * 1024; +const MAX_SKINS = 50; +const MAX_TOTAL_ARCHIVES = 200 * 1024 * 1024; +const EOCD_SIGNATURE = 0x06054b50; +const CENTRAL_SIGNATURE = 0x02014b50; +const LOCAL_SIGNATURE = 0x04034b50; + +export interface SkinCatalogEntry { + id: string; + name: string; + version: string; + author: string; + license: string; + description?: string; + minAppVersion: string; + previewUrl?: string; + previewMimeType?: string; + installedAt: number; +} + +interface SkinArchiveEntry { + path: string; + compressedSize: number; + expandedSize: number; + compression: number; + crc: number; + localOffset: number; + flags: number; + isDirectory: boolean; + unixFileType: number; +} + +type ParsedSkinManifest = Omit & { + entry: string; + content?: string; + preview?: string; +}; + +export class SkinRegistryError extends Error { + constructor(message: string, readonly code: string) { + super(message); + this.name = "SkinRegistryError"; + } +} + +export class SkinRegistry { + constructor(private readonly directory: string) {} + + async list(): Promise { + await mkdir(this.directory, { recursive: true }); + const names = await readdir(this.directory); + const entries: SkinCatalogEntry[] = []; + for (const filename of names.filter((item) => item.endsWith(".json"))) { + try { + const value: unknown = JSON.parse(await readFile(path.join(this.directory, filename), "utf8")); + if (!isCatalogEntry(value) || filename !== `${value.id}.json`) continue; + const archiveInfo = await stat(path.join(this.directory, `${value.id}.wskin`)).catch(() => null); + if (!archiveInfo?.isFile() || archiveInfo.size < 22 || archiveInfo.size > MAX_ARCHIVE_BYTES) continue; + entries.push(value); + } catch { + // Ignore incomplete or stale metadata. The archive itself remains untouched. + } + } + return entries.sort((left, right) => left.name.localeCompare(right.name)); + } + + async save(bytes: Buffer, expectedId: string): Promise { + if (!isSafeSkinId(expectedId)) throw new SkinRegistryError("Skin ID is invalid.", "SKIN_ID_INVALID"); + const parsed = validateSkinArchive(bytes, expectedId); + await mkdir(this.directory, { recursive: true }); + const current = await this.list(); + const replacing = current.some((entry) => entry.id === expectedId); + if (!replacing && current.length >= MAX_SKINS) throw new SkinRegistryError("The instance already has the maximum number of skins.", "SKIN_LIMIT"); + const archivePaths = await Promise.all(current.map(async (entry) => ({ id: entry.id, size: (await stat(path.join(this.directory, `${entry.id}.wskin`)).catch(() => ({ size: 0 }))).size }))); + const totalBytes = archivePaths.reduce((sum, entry) => sum + (entry.id === expectedId ? 0 : entry.size), bytes.byteLength); + if (totalBytes > MAX_TOTAL_ARCHIVES) throw new SkinRegistryError("The total skin storage limit is 200 MiB.", "SKIN_STORAGE_LIMIT"); + + const installedAt = replacing ? current.find((entry) => entry.id === expectedId)!.installedAt : Date.now(); + const catalog: SkinCatalogEntry = { + ...parsed.manifest, + installedAt, + ...(parsed.previewMime ? { previewUrl: `/api/skins/${expectedId}/preview`, previewMimeType: parsed.previewMime } : {}), + }; + const nonce = randomBytes(6).toString("hex"); + const archiveTemp = path.join(this.directory, `.${expectedId}.${nonce}.tmp`); + const catalogTemp = path.join(this.directory, `.${expectedId}.${nonce}.json.tmp`); + const previewTemp = path.join(this.directory, `.${expectedId}.${nonce}.preview.tmp`); + try { + await writeFile(archiveTemp, bytes, { flag: "wx", mode: 0o600 }); + await writeFile(catalogTemp, JSON.stringify(catalog), { flag: "wx", mode: 0o600 }); + if (parsed.previewBytes) await writeFile(previewTemp, parsed.previewBytes, { flag: "wx", mode: 0o600 }); + await rename(archiveTemp, path.join(this.directory, `${expectedId}.wskin`)); + await rename(catalogTemp, path.join(this.directory, `${expectedId}.json`)); + const previewPath = path.join(this.directory, `${expectedId}.preview`); + if (parsed.previewBytes) await rename(previewTemp, previewPath); + else await unlink(previewPath).catch(() => undefined); + } catch (error) { + await Promise.all([archiveTemp, catalogTemp, previewTemp].map((file) => unlink(file).catch(() => undefined))); + throw error; + } + return catalog; + } + + async readArchive(id: string): Promise { + if (!isSafeSkinId(id)) return null; + if (!(await this.list()).some((entry) => entry.id === id)) return null; + try { return await readFile(path.join(this.directory, `${id}.wskin`)); } + catch { return null; } + } + + async readPreview(id: string): Promise<{ bytes: Buffer; mimeType: string } | null> { + if (!isSafeSkinId(id)) return null; + const catalog = (await this.list()).find((entry) => entry.id === id); + if (!catalog?.previewUrl) return null; + const mimeType = catalog.previewMimeType || "application/octet-stream"; + try { + const bytes = await readFile(path.join(this.directory, `${id}.preview`)); + return { bytes, mimeType }; + } catch { return null; } + } + + async remove(id: string): Promise { + if (!isSafeSkinId(id)) return false; + const archive = path.join(this.directory, `${id}.wskin`); + const catalog = path.join(this.directory, `${id}.json`); + const preview = path.join(this.directory, `${id}.preview`); + const present = await Promise.all([archive, catalog, preview].map((file) => stat(file).then(() => true).catch(() => false))).then((items) => items.some(Boolean)); + if (!present) return false; + await Promise.all([archive, catalog, preview].map((file) => unlink(file).catch((error: unknown) => { + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error; + }))); + return true; + } +} + +function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } { + const entries = inspectArchive(bytes); + const regularEntries = entries.filter((entry) => !entry.isDirectory); + const rootPrefix = singleRootPrefix(regularEntries.map((entry) => entry.path)); + const fileBytes = new Map(); + for (const entry of regularEntries) { + const packagePath = rootPrefix ? entry.path.slice(rootPrefix.length) : entry.path; + if (!isSafePackagePath(packagePath)) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID"); + const content = extractEntry(bytes, entry); + if (content.byteLength !== entry.expandedSize || crc32(content) !== entry.crc) throw new SkinRegistryError("The package has a damaged file entry.", "SKIN_ZIP_INVALID"); + if (fileBytes.has(packagePath.toLowerCase())) throw new SkinRegistryError("The package contains duplicate paths.", "SKIN_PATH_DUPLICATE"); + fileBytes.set(packagePath, content); + } + const manifestBytes = fileBytes.get("manifest.json"); + if (!manifestBytes || manifestBytes.byteLength > 32 * 1024) throw new SkinRegistryError("The package needs a small root-level manifest.json.", "SKIN_MANIFEST_MISSING"); + const manifest = parseManifest(manifestBytes); + 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."); + + 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; + 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"); + } + 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"); + decodeUtf8(content, "content.json is not valid UTF-8."); + try { JSON.parse(content.toString("utf8")); } + catch { throw new SkinRegistryError("content.json is not valid JSON.", "SKIN_CONTENT_INVALID"); } + } + if (manifest.preview) { + previewBytes = fileBytes.get(manifest.preview); + previewMime = imageMime(manifest.preview) ?? undefined; + if (!previewBytes || !previewMime || previewBytes.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("The preview must be a supported image inside the package.", "SKIN_PREVIEW_INVALID"); + } + return { manifest, ...(previewBytes ? { previewBytes, previewMime } : {}) }; +} + +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); + let endOffset = -1; + for (let offset = bytes.byteLength - 22; offset >= minOffset; offset -= 1) { + if (bytes.readUInt32LE(offset) === EOCD_SIGNATURE) { endOffset = offset; break; } + } + if (endOffset < 0) throw new SkinRegistryError("The upload is not a valid ZIP package.", "SKIN_ZIP_INVALID"); + const disk = bytes.readUInt16LE(endOffset + 4); + const centralDisk = bytes.readUInt16LE(endOffset + 6); + const entriesOnDisk = bytes.readUInt16LE(endOffset + 8); + const entryCount = bytes.readUInt16LE(endOffset + 10); + const centralSize = bytes.readUInt32LE(endOffset + 12); + const centralOffset = bytes.readUInt32LE(endOffset + 16); + const commentLength = bytes.readUInt16LE(endOffset + 20); + if (disk !== 0 || centralDisk !== 0 || entriesOnDisk !== entryCount || entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff || endOffset + 22 + commentLength !== bytes.byteLength) { + throw new SkinRegistryError("Multi-disk and ZIP64 packages are not supported.", "SKIN_ZIP_FORMAT"); + } + if (!entryCount || entryCount > MAX_FILE_COUNT || centralOffset + centralSize !== endOffset) throw new SkinRegistryError("The ZIP directory is invalid or contains too many files.", "SKIN_FILE_COUNT"); + + const decoder = new TextDecoder("utf-8", { fatal: true }); + const entries: SkinArchiveEntry[] = []; + const seenPaths = new Set(); + let offset = centralOffset; + let totalExpanded = 0; + for (let index = 0; index < entryCount; index += 1) { + if (offset + 46 > endOffset || bytes.readUInt32LE(offset) !== CENTRAL_SIGNATURE) throw new SkinRegistryError("The ZIP directory entry is invalid.", "SKIN_ZIP_INVALID"); + const madeBy = bytes.readUInt16LE(offset + 4); + const flags = bytes.readUInt16LE(offset + 8); + const compression = bytes.readUInt16LE(offset + 10); + const crc = bytes.readUInt32LE(offset + 16); + const compressedSize = bytes.readUInt32LE(offset + 20); + const expandedSize = bytes.readUInt32LE(offset + 24); + const nameLength = bytes.readUInt16LE(offset + 28); + const extraLength = bytes.readUInt16LE(offset + 30); + const fileCommentLength = bytes.readUInt16LE(offset + 32); + const diskStart = bytes.readUInt16LE(offset + 34); + const externalAttributes = bytes.readUInt32LE(offset + 38); + const localOffset = bytes.readUInt32LE(offset + 42); + const recordEnd = offset + 46 + nameLength + extraLength + fileCommentLength; + if (recordEnd > endOffset || diskStart !== 0 || flags & ~0x0800 || (compression !== 0 && compression !== 8) || compressedSize === 0xffffffff || expandedSize === 0xffffffff || localOffset === 0xffffffff) { + throw new SkinRegistryError("Encrypted, multi-disk, and unsupported ZIP entries are not allowed.", "SKIN_ZIP_FORMAT"); + } + let entryPath: string; + try { entryPath = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)); } + catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); } + if (!(flags & 0x800) && /[^\x00-\x7f]/.test(entryPath)) throw new SkinRegistryError("Non-ASCII ZIP filenames must be encoded as UTF-8.", "SKIN_PATH_INVALID"); + if (!isSafePackagePath(entryPath, entryPath.endsWith("/"))) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID"); + const normalizedPath = entryPath.toLowerCase(); + if (seenPaths.has(normalizedPath)) throw new SkinRegistryError("The package contains duplicate or case-conflicting paths.", "SKIN_PATH_DUPLICATE"); + seenPaths.add(normalizedPath); + const unixFileType = madeBy >> 8 === 3 ? (externalAttributes >>> 16) & 0xf000 : 0; + if (unixFileType !== 0 && unixFileType !== 0x8000 && unixFileType !== 0x4000) throw new SkinRegistryError("Only regular files and directories are allowed in a skin package.", "SKIN_FILE_TYPE"); + const isDirectory = entryPath.endsWith("/"); + if ((unixFileType === 0x4000) !== isDirectory && unixFileType !== 0) throw new SkinRegistryError("ZIP file type does not match its path.", "SKIN_FILE_TYPE"); + if (isDirectory && (compressedSize !== 0 || expandedSize !== 0)) throw new SkinRegistryError("ZIP directory entries cannot contain data.", "SKIN_ZIP_INVALID"); + if (compression === 0 && compressedSize !== expandedSize) throw new SkinRegistryError("A stored ZIP entry has inconsistent sizes.", "SKIN_ZIP_INVALID"); + if (!isDirectory) { + totalExpanded += expandedSize; + if (totalExpanded > MAX_EXPANDED_BYTES) throw new SkinRegistryError("The expanded package exceeds 50 MiB.", "SKIN_EXPANDED_SIZE"); + if (expandedSize > 1024 * 1024 && expandedSize > Math.max(compressedSize, 1) * 250) throw new SkinRegistryError("The package has an abnormal compression ratio.", "SKIN_COMPRESSION_RATIO"); + } + entries.push({ path: entryPath, compressedSize, expandedSize, compression, crc, localOffset, flags, isDirectory, unixFileType }); + offset = recordEnd; + } + if (offset !== centralOffset + centralSize) throw new SkinRegistryError("The ZIP directory length is inconsistent.", "SKIN_ZIP_INVALID"); + validateLocalEntries(bytes, entries, centralOffset, decoder); + return entries; +} + +function validateLocalEntries(bytes: Buffer, entries: SkinArchiveEntry[], centralOffset: number, decoder: TextDecoder): void { + const spans: Array<{ start: number; end: number }> = []; + for (const entry of entries) { + const offset = entry.localOffset; + if (offset + 30 > centralOffset || bytes.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID"); + const flags = bytes.readUInt16LE(offset + 6); + const compression = bytes.readUInt16LE(offset + 8); + const crc = bytes.readUInt32LE(offset + 14); + const compressedSize = bytes.readUInt32LE(offset + 18); + const expandedSize = bytes.readUInt32LE(offset + 22); + const nameLength = bytes.readUInt16LE(offset + 26); + const extraLength = bytes.readUInt16LE(offset + 28); + const headerEnd = offset + 30 + nameLength + extraLength; + if (headerEnd > centralOffset || flags !== entry.flags || compression !== entry.compression || crc !== entry.crc || compressedSize !== entry.compressedSize || expandedSize !== entry.expandedSize) { + throw new SkinRegistryError("ZIP local and central headers disagree.", "SKIN_ZIP_INVALID"); + } + let localPath: string; + try { localPath = decoder.decode(bytes.subarray(offset + 30, offset + 30 + nameLength)); } + catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); } + if (localPath !== entry.path) throw new SkinRegistryError("ZIP local and central filenames disagree.", "SKIN_ZIP_INVALID"); + const end = headerEnd + entry.compressedSize; + if (end > centralOffset) throw new SkinRegistryError("A ZIP entry overlaps the central directory.", "SKIN_ZIP_INVALID"); + spans.push({ start: offset, end }); + } + spans.sort((left, right) => left.start - right.start); + for (let index = 1; index < spans.length; index += 1) { + if (spans[index].start < spans[index - 1].end) throw new SkinRegistryError("ZIP local file entries overlap.", "SKIN_ZIP_INVALID"); + } +} + +function extractEntry(archive: Buffer, entry: SkinArchiveEntry): Buffer { + const offset = entry.localOffset; + if (offset + 30 > archive.byteLength || archive.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID"); + const flags = archive.readUInt16LE(offset + 6); + const compression = archive.readUInt16LE(offset + 8); + const nameLength = archive.readUInt16LE(offset + 26); + const extraLength = archive.readUInt16LE(offset + 28); + if (flags !== entry.flags || compression !== entry.compression) throw new SkinRegistryError("ZIP headers disagree about file compression.", "SKIN_ZIP_INVALID"); + const dataStart = offset + 30 + nameLength + extraLength; + const dataEnd = dataStart + entry.compressedSize; + if (dataEnd > archive.byteLength) throw new SkinRegistryError("A ZIP entry extends past the archive.", "SKIN_ZIP_INVALID"); + const compressed = archive.subarray(dataStart, dataEnd); + if (entry.compression === 0) return Buffer.from(compressed); + try { return inflateRawSync(compressed, { maxOutputLength: entry.expandedSize + 1 }); } + catch { throw new SkinRegistryError("A ZIP entry could not be safely decompressed.", "SKIN_ZIP_INVALID"); } +} + +function parseManifest(bytes: Buffer): ParsedSkinManifest { + let raw: unknown; + try { raw = JSON.parse(decodeUtf8(bytes, "manifest.json is not valid UTF-8.")); } + 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; + 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"); + 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 content = readOptional("content", 120); + 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"); + 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 } : {}) }; +} + +function singleRootPrefix(paths: string[]): string { + if (!paths.length) return ""; + const firstSlash = paths[0].indexOf("/"); + if (firstSlash < 1) return ""; + const prefix = paths[0].slice(0, firstSlash + 1); + return paths.every((item) => item.startsWith(prefix)) ? prefix : ""; +} + +function isSafePackagePath(value: string, allowDirectory = false): boolean { + const candidate = allowDirectory ? value.slice(0, -1) : value; + return Boolean(candidate) && !candidate.startsWith("/") && !candidate.includes("\\") && !candidate.includes("\0") && !/^[a-z]:/i.test(candidate) + && candidate.split("/").every((part) => Boolean(part) && part !== "." && part !== ".." && !part.includes(":")); +} + +function isSafeSkinId(value: unknown): value is string { + return typeof value === "string" && value.length <= 80 && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(value) && !value.startsWith("builtin."); +} + +function imageMime(filename: string): string | null { + switch (path.extname(filename).toLowerCase()) { + case ".png": return "image/png"; + case ".jpg": case ".jpeg": return "image/jpeg"; + case ".webp": return "image/webp"; + case ".avif": return "image/avif"; + case ".gif": return "image/gif"; + default: return null; + } +} + +function decodeUtf8(bytes: Buffer, message: string): string { + try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); } + catch { throw new SkinRegistryError(message, "SKIN_ENCODING_INVALID"); } +} + +function isCatalogEntry(value: unknown): value is SkinCatalogEntry { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const item = value as Record; + const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; + if (!isSafeSkinId(item.id) || !isShortText(item.name, 80) || !isShortText(item.author, 80) || !isShortText(item.license, 80)) return false; + if (typeof item.version !== "string" || !semver.test(item.version) || typeof item.minAppVersion !== "string" || !semver.test(item.minAppVersion)) return false; + if (!Number.isSafeInteger(item.installedAt) || (item.installedAt as number) < 0) return false; + if (item.description !== undefined && (typeof item.description !== "string" || item.description.length > 400)) return false; + const hasPreview = item.previewUrl !== undefined || item.previewMimeType !== undefined; + return !hasPreview || (item.previewUrl === `/api/skins/${item.id}/preview` && ["image/png", "image/jpeg", "image/webp", "image/avif", "image/gif"].includes(String(item.previewMimeType))); +} + +function isShortText(value: unknown, limit: number): value is string { + return typeof value === "string" && value.trim().length > 0 && value.length <= limit; +} + +const crcTable = (() => { + const table = new Uint32Array(256); + for (let index = 0; index < table.length; index += 1) { + let value = index; + for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1; + table[index] = value >>> 0; + } + return table; +})(); + +function crc32(bytes: Buffer): number { + let value = 0xffffffff; + for (const byte of bytes) value = crcTable[(value ^ byte) & 0xff] ^ (value >>> 8); + return (value ^ 0xffffffff) >>> 0; +} diff --git a/src/index.ts b/src/index.ts index 803e72e..90bef0c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { createAccelerationRelayServer } from "./server/acceleration-relay.js"; import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js"; +import { SkinRegistry } from "./admin/skin-registry.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.resolve(__dirname, ".."); @@ -67,6 +68,7 @@ async function main() { accelerationName: () => adminService.getAccelerationRelayName(), }, adminService, + skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")), logger, nextVisitorNumber: () => database.nextVisitorNumber(), visitorCount: () => database.getVisitorCount(), diff --git a/src/server/server.ts b/src/server/server.ts index a1f5761..0da2eae 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -13,6 +13,7 @@ import { resolveSafeOpenTarget } 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"; +import type { SkinRegistry } from "../admin/skin-registry.js"; export interface WebServerOptions { port: number; @@ -22,6 +23,7 @@ export interface WebServerOptions { certDir?: string; // path to cert.pem + key.pem for HTTPS voiceBridgeOptions: VoiceBridgeOptions; adminService: AdminService; + skinRegistry?: SkinRegistry; logger: Logger; nextVisitorNumber?: () => number; visitorCount?: () => number; @@ -97,6 +99,38 @@ export function createWebServer(options: WebServerOptions): WebServer { }); }); + app.get("/api/skins", async (_request, response) => { + response.setHeader("Cache-Control", "no-cache"); + response.json({ skins: await options.skinRegistry?.list() ?? [] }); + }); + + app.get("/api/skins/:id/package", async (request, response) => { + const id = typeof request.params.id === "string" ? request.params.id : ""; + const archive = await options.skinRegistry?.readArchive(id); + if (!archive) { + response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" }); + return; + } + response.setHeader("Cache-Control", "no-cache"); + response.setHeader("Content-Type", "application/octet-stream"); + response.setHeader("Content-Disposition", `attachment; filename="${id}.wskin"`); + response.setHeader("X-Content-Type-Options", "nosniff"); + response.send(archive); + }); + + app.get("/api/skins/:id/preview", async (request, response) => { + const id = typeof request.params.id === "string" ? request.params.id : ""; + const preview = await options.skinRegistry?.readPreview(id); + if (!preview) { + response.status(404).end(); + return; + } + response.setHeader("Cache-Control", "public, max-age=300"); + response.setHeader("Content-Type", preview.mimeType); + response.setHeader("X-Content-Type-Options", "nosniff"); + response.send(preview.bytes); + }); + app.post("/api/join-ticket", async (request, response) => { response.setHeader("Cache-Control", "no-store"); if (!request.is("application/json") || !isSameOrigin(request)) { @@ -194,6 +228,7 @@ export function createWebServer(options: WebServerOptions): WebServer { getCreatedSessions: () => voiceBridge.getCreatedCount(), getSessionSummaries: () => voiceBridge.getSessionSummaries(), terminateSession: (id) => voiceBridge.terminateSession(id), + skinRegistry: options.skinRegistry, version: options.version, logFile: options.logFile, startedAt, diff --git a/web/package-lock.json b/web/package-lock.json index 5f0fb0a..4be4fdd 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -7,7 +7,11 @@ "name": "webspeak-webclient-frontend", "dependencies": { "@sapphi-red/web-noise-suppressor": "^0.4.0", + "fflate": "^0.8.3", "pinia": "^3.0.2", + "postcss": "^8.5.28", + "postcss-selector-parser": "^7.1.6", + "postcss-value-parser": "^4.2.0", "vue": "^3.5.13", "vue-router": "^4.5.1" }, @@ -1139,6 +1143,18 @@ "url": "https://github.com/sponsors/mesqueeb" } }, + "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/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -1230,6 +1246,12 @@ } } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "license": "MIT" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1354,6 +1376,7 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -1383,9 +1406,9 @@ } }, "node_modules/postcss": { - "version": "8.5.26", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", - "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", "funding": [ { "type": "opencollective", @@ -1402,7 +1425,7 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.17", + "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" }, @@ -1410,6 +1433,25 @@ "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/rfdc": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", @@ -1514,6 +1556,7 @@ "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -1522,12 +1565,19 @@ "node": ">=14.17" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, "node_modules/vite": { "version": "6.4.3", "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", @@ -1609,6 +1659,7 @@ "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.34.tgz", "integrity": "sha512-WdLBG9gm02OgJIG9axd5Hpx0TFLdzVgfG2evFFu8Rur5O/IoGc5cMjnjh3tPL6GnRGsYvUhBSKVPYVcxRKpMCA==", "license": "MIT", + "peer": true, "dependencies": { "@vue/compiler-dom": "3.5.34", "@vue/compiler-sfc": "3.5.34", diff --git a/web/package.json b/web/package.json index 40512ad..de0b39d 100644 --- a/web/package.json +++ b/web/package.json @@ -9,7 +9,11 @@ }, "dependencies": { "@sapphi-red/web-noise-suppressor": "^0.4.0", + "fflate": "^0.8.3", "pinia": "^3.0.2", + "postcss": "^8.5.28", + "postcss-selector-parser": "^7.1.6", + "postcss-value-parser": "^4.2.0", "vue": "^3.5.13", "vue-router": "^4.5.1" }, diff --git a/web/src/components/LanguageSwitcher.vue b/web/src/components/LanguageSwitcher.vue index 2f4e969..646fe74 100644 --- a/web/src/components/LanguageSwitcher.vue +++ b/web/src/components/LanguageSwitcher.vue @@ -239,40 +239,40 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD to { opacity: 1; transform: translateY(0) scale(1); } } -:global(html[data-theme="dark"]) .language-trigger, -:global(:root[data-theme="dark"]) .language-trigger { +:global(html[data-theme="dark"] .admin-root) .language-trigger, +:global(:root[data-theme="dark"] .admin-root) .language-trigger { color: #a9d9d1; background: #203531; border-color: #38564f; } -:global(html[data-theme="dark"]) .language-trigger:hover, -:global(html[data-theme="dark"]) .language-switcher.open .language-trigger, -:global(:root[data-theme="dark"]) .language-trigger:hover, -:global(:root[data-theme="dark"]) .language-switcher.open .language-trigger { +:global(html[data-theme="dark"] .admin-root) .language-trigger:hover, +:global(html[data-theme="dark"] .admin-root) .language-switcher.open .language-trigger, +:global(:root[data-theme="dark"] .admin-root) .language-trigger:hover, +:global(:root[data-theme="dark"] .admin-root) .language-switcher.open .language-trigger { color: #10201d; background: #69d2c7; border-color: #69d2c7; } -:global(html[data-theme="dark"]) .language-dropdown, -:global(:root[data-theme="dark"]) .language-dropdown { +:global(html[data-theme="dark"] .admin-root) .language-dropdown, +:global(:root[data-theme="dark"] .admin-root) .language-dropdown { background: #172321; border-color: #30413d; box-shadow: 0 16px 36px rgba(0, 0, 0, .32); } -:global(html[data-theme="dark"]) .language-option, -:global(:root[data-theme="dark"]) .language-option { +:global(html[data-theme="dark"] .admin-root) .language-option, +:global(:root[data-theme="dark"] .admin-root) .language-option { color: #d7e7e3; } -:global(html[data-theme="dark"]) .language-option:hover, -:global(html[data-theme="dark"]) .language-option:focus-visible, -:global(html[data-theme="dark"]) .language-option.selected, -:global(:root[data-theme="dark"]) .language-option:hover, -:global(:root[data-theme="dark"]) .language-option:focus-visible, -:global(:root[data-theme="dark"]) .language-option.selected { +:global(html[data-theme="dark"] .admin-root) .language-option:hover, +:global(html[data-theme="dark"] .admin-root) .language-option:focus-visible, +:global(html[data-theme="dark"] .admin-root) .language-option.selected, +:global(:root[data-theme="dark"] .admin-root) .language-option:hover, +:global(:root[data-theme="dark"] .admin-root) .language-option:focus-visible, +:global(:root[data-theme="dark"] .admin-root) .language-option.selected { color: #69d2c7; background: #203531; border-color: #38564f; diff --git a/web/src/components/SkinSwitcher.vue b/web/src/components/SkinSwitcher.vue new file mode 100644 index 0000000..3616361 --- /dev/null +++ b/web/src/components/SkinSwitcher.vue @@ -0,0 +1,180 @@ + + + + + diff --git a/web/src/composables/useWebClientChannels.ts b/web/src/composables/useWebClientChannels.ts index d2eb399..26168fd 100644 --- a/web/src/composables/useWebClientChannels.ts +++ b/web/src/composables/useWebClientChannels.ts @@ -113,7 +113,6 @@ export function useWebClientChannels({ const source = currentChannel.value ? currentChannel.value.members : members; return source.map((member) => ({ ...member, isSelf: member.isSelf || member.id === clientId.value })); }); - const roomMembers = computed(() => currentMembers.value.slice(0, 4)); const memberChannels = computed(() => { if (channelTree.value.length) return channelTree.value; return [{ @@ -149,7 +148,6 @@ export function useWebClientChannels({ currentChannelName, currentChannelDescription, currentMembers, - roomMembers, memberChannels, filteredMemberChannels, whisperTargets, diff --git a/web/src/i18n/web-client.ts b/web/src/i18n/web-client.ts index 1d41c9a..f5eb5b4 100644 --- a/web/src/i18n/web-client.ts +++ b/web/src/i18n/web-client.ts @@ -5,6 +5,9 @@ export const webClientTranslations: Record> = { themeSystem: "跟随系统", themeLight: "浅色主题", themeDark: "深色主题", + skinSelector: "皮肤", + skinDay: "日间模式", + skinNight: "夜间模式", switchToLightTheme: "切换到浅色主题", switchToDarkTheme: "切换到深色主题", browserWorkspace: "浏览器语音工作台", @@ -163,8 +166,6 @@ export const webClientTranslations: Record> = { connectedYou: "已连接 · 你", waitingForMembers: "等待成员加入语音", prepareMicrophone: "你可以先在这里准备好麦克风。", - moreMembers: "更多成员", - viewLeft: "在左侧查看", textChannel: "文字频道", channelChat: "{{channel}} 聊天", messageCount: "{{count}} 条消息", @@ -335,6 +336,9 @@ export const webClientTranslations: Record> = { themeSystem: "System theme", themeLight: "Light theme", themeDark: "Dark theme", + skinSelector: "Skin", + skinDay: "Day mode", + skinNight: "Night mode", switchToLightTheme: "Switch to light theme", switchToDarkTheme: "Switch to dark theme", browserWorkspace: "Browser voice workspace", @@ -493,8 +497,6 @@ export const webClientTranslations: Record> = { connectedYou: "Connected · you", waitingForMembers: "Waiting for people to join", prepareMicrophone: "You can get your microphone ready.", - moreMembers: "More members", - viewLeft: "See them on the left", textChannel: "TEXT CHANNEL", channelChat: "{{channel}} chat", messageCount: "{{count}} messages", @@ -668,6 +670,9 @@ webClientTranslations.de = { themeSystem: "Systemdesign", themeLight: "Helles Design", themeDark: "Dunkles Design", + skinSelector: "Design", + skinDay: "Tagesmodus", + skinNight: "Nachtmodus", switchToLightTheme: "Zum hellen Design wechseln", switchToDarkTheme: "Zum dunklen Design wechseln", browserWorkspace: "Sprachbereich im Browser", @@ -817,8 +822,6 @@ webClientTranslations.de = { connectedYou: "Verbunden · du", waitingForMembers: "Warte auf weitere Mitglieder", prepareMicrophone: "Du kannst dein Mikrofon hier vorbereiten.", - moreMembers: "Weitere Mitglieder", - viewLeft: "Links anzeigen", textChannel: "TEXTKANAL", channelChat: "Chat in {{channel}}", messageCount: "{{count}} Nachrichten", @@ -991,6 +994,9 @@ webClientTranslations.ru = { themeSystem: "Системная тема", themeLight: "Светлая тема", themeDark: "Тёмная тема", + skinSelector: "Оформление", + skinDay: "Дневной режим", + skinNight: "Ночной режим", switchToLightTheme: "Включить светлую тему", switchToDarkTheme: "Включить тёмную тему", browserWorkspace: "Голосовое пространство в браузере", @@ -1072,9 +1078,9 @@ webClientTranslations.ru = { rememberIdentity: "Запомнить личность TeamSpeak на этом устройстве", rememberIdentityHint: "Хранится только на этом устройстве и используется при следующем подключении.", rememberIdentityConcurrentWarning: "Одна личность может использоваться только одним подключением в этом браузере. Для второго подключения отключите эту опцию или используйте другой браузер.", - deviceIdentityOptions: "Настройки личности устройства", - enterVoiceSpace: "Войти в голосовое пространство", - connectionDetailsPrivate: "Данные подключения используются только для этой голосовой сессии", + identityOptions: "Настройки личности устройства", + enterVoice: "Войти в голосовое пространство", + connectionAuthorized: "Данные подключения используются только для этой голосовой сессии", recentServers: "Недавние серверы", saveFavorite: "Сохранить в избранное", savedFavoriteToast: "Сервер сохранён в избранное", @@ -1106,6 +1112,9 @@ webClientTranslations.ja = { themeSystem: "システム設定", themeLight: "ライトテーマ", themeDark: "ダークテーマ", + skinSelector: "スキン", + skinDay: "昼モード", + skinNight: "夜モード", switchToLightTheme: "ライトテーマに切り替え", switchToDarkTheme: "ダークテーマに切り替え", browserWorkspace: "ブラウザ音声ワークスペース", @@ -1187,9 +1196,9 @@ webClientTranslations.ja = { rememberIdentity: "この端末に TeamSpeak ID を保存", rememberIdentityHint: "この端末だけに保存し、次回の接続で再利用します。", rememberIdentityConcurrentWarning: "同じブラウザでは、この ID を同時に1接続だけ使用できます。2つ目の接続では無効にするか、別のブラウザを使ってください。", - deviceIdentityOptions: "端末 ID の設定", - enterVoiceSpace: "音声スペースに参加", - connectionDetailsPrivate: "接続情報は今回の音声セッションでのみ使用されます", + identityOptions: "端末 ID の設定", + enterVoice: "音声スペースに参加", + connectionAuthorized: "接続情報は今回の音声セッションでのみ使用されます", recentServers: "最近のサーバー", saveFavorite: "お気に入りに保存", savedFavoriteToast: "サーバーをお気に入りに保存しました", diff --git a/web/src/services/local-persistence.ts b/web/src/services/local-persistence.ts index 0580c93..b82b8d9 100644 --- a/web/src/services/local-persistence.ts +++ b/web/src/services/local-persistence.ts @@ -1,8 +1,10 @@ const DB_NAME = "webspeak-local"; -const DB_VERSION = 1; +const DB_VERSION = 2; const CURRENT_IDENTITY_KEY = "current"; const PREFERENCES_KEY = "singleton"; +import type { InstalledSkin } from "./skin-pack.js"; + export interface StoredIdentity { id: string; label?: string; @@ -33,6 +35,7 @@ export interface LocalPreferences { schemaVersion: 1; locale?: "auto" | "zh-CN" | "en"; theme?: "system" | "light" | "dark"; + skinId?: string; microphoneMuted?: boolean; noiseSuppressionEnabled?: boolean; voxThreshold?: number; @@ -65,6 +68,7 @@ function openDatabase(): Promise { if (!database.objectStoreNames.contains("preferences")) database.createObjectStore("preferences", { keyPath: "id" }); if (!database.objectStoreNames.contains("favorites")) database.createObjectStore("favorites", { keyPath: "id" }); if (!database.objectStoreNames.contains("recent")) database.createObjectStore("recent", { keyPath: "id" }); + if (!database.objectStoreNames.contains("skins")) database.createObjectStore("skins", { keyPath: "id" }); }; request.onsuccess = () => { const database = request.result; @@ -164,6 +168,47 @@ export async function saveLocalPreferences(preferences: LocalPreferences): Promi } } +export async function listInstalledSkins(): Promise { + try { + const skins = await request("skins", "readonly", (store, resolve, reject) => { + const get = store.getAll(); + get.onsuccess = () => resolve(get.result as InstalledSkin[]); + get.onerror = () => reject(get.error); + }); + return skins.sort((a, b) => a.name.localeCompare(b.name)); + } catch { + return []; + } +} + +export async function getInstalledSkin(id: string): Promise { + try { + return await request("skins", "readonly", (store, resolve, reject) => { + const get = store.get(id); + get.onsuccess = () => resolve((get.result as InstalledSkin | undefined) ?? null); + get.onerror = () => reject(get.error); + }); + } catch { + return null; + } +} + +export async function saveInstalledSkin(skin: InstalledSkin): Promise { + await request("skins", "readwrite", (store, resolve, reject) => { + const put = store.put(skin); + put.onsuccess = () => resolve(undefined); + put.onerror = () => reject(put.error); + }); +} + +export async function removeInstalledSkin(id: string): Promise { + await request("skins", "readwrite", (store, resolve, reject) => { + const remove = store.delete(id); + remove.onsuccess = () => resolve(undefined); + remove.onerror = () => reject(remove.error); + }); +} + export async function listFavorites(): Promise { try { return await request("favorites", "readonly", (store, resolve, reject) => { @@ -243,7 +288,7 @@ async function removeRecentServer(id: string): Promise { export async function clearLocalData(): Promise { try { const database = await openDatabase(); - await Promise.all(["identities", "preferences", "favorites", "recent"].map((storeName) => new Promise((resolve, reject) => { + await Promise.all(["identities", "preferences", "favorites", "recent", "skins"].map((storeName) => new Promise((resolve, reject) => { const transaction = database.transaction(storeName, "readwrite"); transaction.objectStore(storeName).clear(); transaction.oncomplete = () => resolve(); diff --git a/web/src/services/skin-catalog.ts b/web/src/services/skin-catalog.ts new file mode 100644 index 0000000..f3d8162 --- /dev/null +++ b/web/src/services/skin-catalog.ts @@ -0,0 +1,66 @@ +export interface SkinCatalogEntry { + id: string; + name: string; + version: string; + author: string; + license: string; + description?: string; + minAppVersion: string; + previewUrl?: string; + installedAt: number; +} + +export async function listPublicSkins(): Promise { + try { + const response = await fetch("/api/skins", { headers: { accept: "application/json" }, cache: "no-cache" }); + if (!response.ok) return []; + const payload: unknown = await response.json(); + if (!payload || typeof payload !== "object" || !Array.isArray((payload as { skins?: unknown }).skins)) return []; + return (payload as { skins: unknown[] }).skins.flatMap((value) => { + if (!value || typeof value !== "object") return []; + const skin = value as Record; + if (typeof skin.id !== "string" || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(skin.id) || skin.id.startsWith("builtin.")) return []; + if ([skin.name, skin.version, skin.author, skin.license, skin.minAppVersion].some((field) => typeof field !== "string")) return []; + const previewUrl = typeof skin.previewUrl === "string" && skin.previewUrl === `/api/skins/${skin.id}/preview` ? skin.previewUrl : undefined; + return [{ + id: skin.id, + name: skin.name as string, + version: skin.version as string, + author: skin.author as string, + license: skin.license as string, + minAppVersion: skin.minAppVersion as string, + ...(typeof skin.description === "string" ? { description: skin.description } : {}), + ...(previewUrl ? { previewUrl } : {}), + installedAt: Number.isFinite(skin.installedAt) ? Number(skin.installedAt) : 0, + }]; + }); + } catch { + return []; + } +} + +export async function uploadSkinPackage(file: File, csrfToken: string, confirmReplace?: (id: string) => boolean): Promise { + const { importSkinPack } = await import("./skin-pack.js"); + const skin = await importSkinPack(file); + if (confirmReplace && !confirmReplace(skin.id)) return null; + const response = await fetch(`/api/admin/skins/${encodeURIComponent(skin.id)}`, { + method: "PUT", + headers: { "content-type": "application/octet-stream", "x-csrf-token": csrfToken, accept: "application/json" }, + body: file, + }); + const payload = await response.json().catch(() => null) as { skin?: SkinCatalogEntry; message?: string; code?: string } | null; + if (!response.ok || !payload?.skin) throw new Error(payload?.message || payload?.code || `HTTP_${response.status}`); + return payload.skin; +} + +export async function deleteSkinPackage(id: string, csrfToken: string): Promise { + const response = await fetch(`/api/admin/skins/${encodeURIComponent(id)}`, { + method: "DELETE", + headers: { "content-type": "application/json", "x-csrf-token": csrfToken, accept: "application/json" }, + body: "{}", + }); + if (!response.ok) { + const payload = await response.json().catch(() => null) as { code?: string } | null; + throw new Error(payload?.code || `HTTP_${response.status}`); + } +} diff --git a/web/src/services/skin-pack.test.ts b/web/src/services/skin-pack.test.ts new file mode 100644 index 0000000..b5dfedc --- /dev/null +++ b/web/src/services/skin-pack.test.ts @@ -0,0 +1,97 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; +import { strToU8, zipSync } from "fflate"; +import { importSkinPack, resolveSkinCssAssets, SkinPackError } from "./skin-pack.js"; + +const manifest = { + schemaVersion: 1, + id: "ocean-night", + name: "Ocean Night", + version: "1.0.0", + author: "WebSpeak test", + license: "MIT", + minAppVersion: "0.2.4", + entry: "skin.css", +}; + +test("skin CSS is scoped, local artwork and fonts work, and global names are isolated", async () => { + const skin = await importSkinPack(makeSkin(` + @font-face { font-family: "Wave Font"; src: url("assets/wave.woff2") format("woff2"); } + @keyframes shimmer { from { opacity: .4; } to { opacity: 1; } } + :root { --accent: #00a99d; } + .voice-card { font-family: "Wave Font", sans-serif; animation: shimmer 1s ease-in-out; background-image: image-set("assets/backdrop.png" 1x); } + `)); + + assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="ocean-night"\] \{ --accent: #00a99d; \}/); + assert.match(skin.css, /@keyframes ws-ocean-night-shimmer/); + assert.match(skin.css, /animation: ws-ocean-night-shimmer/); + assert.match(skin.css, /font-family: "ws-ocean-night-Wave-Font"/); + assert.match(skin.css, /url\("wskin-asset:assets%2Fwave\.woff2"\)/); + assert.match(skin.css, /image-set\("wskin-asset:assets%2Fbackdrop\.png" 1x\)/); + + const resolved = resolveSkinCssAssets(skin.css, skin.assets); + assert.match(resolved.css, /blob:/); + resolved.objectUrls.forEach((url) => URL.revokeObjectURL(url)); +}); + +test("skin CSS permits hiding explicitly optional decoration while protecting controls and containers", async () => { + const skin = await importSkinPack(makeSkin('@keyframes fade-wave { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="demo.wave"] { display: none !important; opacity: var(--decorative-opacity); all: unset; animation: fade-wave 1s; }')); + assert.match(skin.css, /display: none !important/); + assert.match(skin.css, /opacity: var\(--decorative-opacity\)/); + assert.match(skin.css, /all: unset/); + assert.match(skin.css, /from \{ opacity: 0; \}/); + assert.match(skin.css, /animation: ws-ocean-night-fade-wave 1s/); + + await assert.rejects(importSkinPack(makeSkin(".required { display: none; }")), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts")); + await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { opacity: 0; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts")); + await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.wave"] .child { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts")); + await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: var(--hidden); }')), (error: unknown) => error instanceof Error && error.message.includes("indirect values")); + await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { all: unset; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts")); + await assert.rejects(importSkinPack(makeSkin('@keyframes hide-control { to { opacity: 0; } } [data-ws-part="voice.screen-player.exit"] { animation: hide-control 1s infinite; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts")); + await assert.rejects(importSkinPack(makeSkin('@keyframes hide-control { to { opacity: 0; } } [data-ws-part="control"] { animation: var(--custom-animation); }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts")); + await assert.rejects(importSkinPack(makeSkin(".art { background-image: image-set(\"https://example.invalid/remote.png\" 1x); }")), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE"); +}); + +test("all public skin parts are documented and the admin console is outside skin scope", async () => { + const [webClient, demo, admin, documentation] = await Promise.all([ + readFile(new URL("../views/WebClient.vue", import.meta.url), "utf8"), + readFile(new URL("../views/DemoView.vue", import.meta.url), "utf8"), + readFile(new URL("../views/AdminView.vue", import.meta.url), "utf8"), + readFile(new URL("../../../docs/SKIN_DEVELOPMENT.md", import.meta.url), "utf8"), + ]); + const publicParts = new Set([...`${webClient}\n${demo}`.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1])); + for (const part of publicParts) assert.ok(documentation.includes(`\`${part}\``), `Undocumented skin part: ${part}`); + assert.doesNotMatch(admin, /ws-skin-root|data-ws-page=/); +}); + +test("skin content supports localized interface message overrides and includes the preview as an asset", async () => { + const content = { defaultLocale: "en", locales: { en: { home: { title: "Welcome" }, messages: { speakingNow: "Live now" } } } }; + const skin = await importSkinPack(makeSkin(".voice-card { background: url(assets/preview.png); }", content)); + assert.equal(skin.contentData?.locales.en?.messages?.speakingNow, "Live now"); + assert.equal(skin.previewBlob?.type, "image/png"); + assert.ok(skin.assets["assets/preview.png"]); +}); + +test("the documented Aurora Voice example package imports with its artwork and localized copy", async () => { + const bytes = await readFile(new URL("../../../docs/examples/aurora-voice.wskin", import.meta.url)); + const skin = await importSkinPack(new File([bytes], "aurora-voice.wskin", { type: "application/octet-stream" })); + assert.equal(skin.id, "community.aurora-voice"); + assert.equal(skin.contentData?.locales["zh-CN"]?.home?.title, "自在"); + assert.equal(skin.contentData?.locales.en?.messages?.["demo.heroLead"], "This demo is styled by the same package as the connection and voice pages."); + assert.equal(skin.previewBlob?.type, "image/jpeg"); + assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="community\.aurora-voice"\]/); +}); + +function makeSkin(css: string, content?: unknown): File { + const packageFiles: Record = { + "manifest.json": strToU8(JSON.stringify({ ...manifest, ...(content ? { content: "content.json" } : {}), preview: "assets/preview.png" })), + "skin.css": strToU8(css), + "assets/backdrop.png": new Uint8Array([1, 2, 3, 4]), + "assets/preview.png": new Uint8Array([5, 6, 7, 8]), + "assets/wave.woff2": new Uint8Array([9, 10, 11, 12]), + }; + if (content) packageFiles["content.json"] = strToU8(JSON.stringify(content)); + const bytes = zipSync(packageFiles); + return new File([bytes.slice().buffer as ArrayBuffer], "skin.wskin", { type: "application/octet-stream" }); +} diff --git a/web/src/services/skin-pack.ts b/web/src/services/skin-pack.ts new file mode 100644 index 0000000..d4d7468 --- /dev/null +++ b/web/src/services/skin-pack.ts @@ -0,0 +1,665 @@ +import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss"; +import selectorParser from "postcss-selector-parser"; +import valueParser from "postcss-value-parser"; +import { unzipSync } from "fflate"; + +const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024; +const MAX_EXPANDED_BYTES = 50 * 1024 * 1024; +const MAX_FILE_COUNT = 128; +const MAX_CSS_BYTES = 512 * 1024; +const MAX_CONTENT_BYTES = 256 * 1024; +const MAX_IMAGE_BYTES = 16 * 1024 * 1024; +const MAX_FONT_BYTES = 4 * 1024 * 1024; +const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "layer", "font-face", "keyframes", "-webkit-keyframes"]); +const OPTIONAL_VISUAL_PARTS = new Set([ + "home.hero.eyebrow", + "home.gateway-status", + "home.features", + "home.feature", + "home.visitors", + "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", +]); +const ZIP_EOCD = 0x06054b50; +const ZIP_CENTRAL_FILE = 0x02014b50; + +export interface SkinManifest { + schemaVersion: 1; + id: string; + name: string; + version: string; + author: string; + license: string; + description?: string; + entry: string; + content?: string; + minAppVersion: string; + preview?: string; +} + +export interface SkinFeatureCopy { + title: string; + description: string; +} + +export interface SkinHomeCopy { + brandName?: string; + eyebrow?: string; + title?: string; + titleAccent?: string; + description?: string; + welcomeTitle?: string; + welcomeDescription?: string; + features?: SkinFeatureCopy[]; +} + +export interface SkinContent { + defaultLocale: string; + locales: Record }>; +} + +export interface InstalledSkin extends SkinManifest { + css: string; + assets: Record; + contentData?: SkinContent; + previewBlob?: Blob; + warnings: string[]; + installedAt: number; +} + +export class SkinPackError extends Error { + constructor(message: string, readonly code: string) { + super(message); + this.name = "SkinPackError"; + } +} + +interface ZipEntryMetadata { + path: string; + compressedSize: number; + expandedSize: number; + compression: number; + isDirectory: boolean; + flags: number; + crc: number; + localOffset: number; +} + +const decoder = new TextDecoder("utf-8", { fatal: true }); + +export async function importSkinPack(file: File): Promise { + if (!file.name.toLowerCase().endsWith(".wskin")) throw new SkinPackError("Choose a .wskin skin package.", "SKIN_FILE_TYPE"); + if (!file.size || file.size > MAX_ARCHIVE_BYTES) throw new SkinPackError("The skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE"); + + const archiveBytes = new Uint8Array(await file.arrayBuffer()); + const metadata = inspectZip(archiveBytes); + let unpacked: Record; + try { + unpacked = unzipSync(archiveBytes); + } catch { + throw new SkinPackError("The skin package is damaged or uses an unsupported ZIP format.", "SKIN_ZIP_INVALID"); + } + + const regularFiles = metadata.filter((entry) => !entry.isDirectory); + const rootPrefix = findSingleRootFolder(regularFiles.map((entry) => entry.path)); + const files = new Map(); + for (const entry of regularFiles) { + const path = rootPrefix ? entry.path.slice(rootPrefix.length) : entry.path; + if (!path || path.startsWith("/") || path.split("/").some((part) => !part || part === "." || part === "..")) { + throw new SkinPackError("The package contains an unsafe file path.", "SKIN_PATH_INVALID"); + } + const bytes = unpacked[entry.path]; + if (!bytes || bytes.byteLength !== entry.expandedSize) throw new SkinPackError("A package file failed its size check.", "SKIN_ZIP_INVALID"); + files.set(path, bytes); + } + + const manifestBytes = files.get("manifest.json"); + if (!manifestBytes || manifestBytes.byteLength > 32 * 1024) throw new SkinPackError("The package must contain a small root-level manifest.json.", "SKIN_MANIFEST_MISSING"); + const manifest = parseManifest(manifestBytes); + const cssBytes = files.get(manifest.entry); + if (!cssBytes || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE"); + + const assets: Record = Object.create(null) as Record; + for (const [path, bytes] of files) { + if (["manifest.json", manifest.entry, manifest.content].includes(path)) continue; + const mimeType = assetMimeType(path); + if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED"); + if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE"); + if (mimeType.startsWith("image/") && bytes.byteLength > MAX_IMAGE_BYTES) throw new SkinPackError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE"); + assets[path] = new Blob([bytes], { type: mimeType }); + } + + let contentData: SkinContent | undefined; + if (manifest.content) { + const contentBytes = files.get(manifest.content); + if (!contentBytes || contentBytes.byteLength > MAX_CONTENT_BYTES) throw new SkinPackError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE"); + contentData = parseContent(contentBytes); + } + + let previewBlob: Blob | undefined; + if (manifest.preview) { + const previewBytes = files.get(manifest.preview); + const previewMime = assetMimeType(manifest.preview); + if (!previewBytes || !previewMime?.startsWith("image/") || previewBytes.byteLength > MAX_IMAGE_BYTES) { + throw new SkinPackError("The preview must be a supported image inside the package.", "SKIN_PREVIEW_INVALID"); + } + previewBlob = new Blob([previewBytes], { type: previewMime }); + } + + const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets); + return { ...manifest, css: compiled.css, assets, contentData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() }; +} + +export function resolveSkinCssAssets(css: string, assets: Record): { css: string; objectUrls: string[] } { + const objectUrls: string[] = []; + try { + const root = postcss.parse(css, { from: undefined }); + root.walkDecls((declaration) => { + declaration.value = rewriteAssetUrls(declaration.value, (assetPath) => { + const blob = assets[assetPath]; + if (!blob) throw new SkinPackError(`Skin asset is missing: ${assetPath}`, "SKIN_ASSET_MISSING"); + const url = URL.createObjectURL(blob); + objectUrls.push(url); + return url; + }); + }); + return { css: root.toString(), objectUrls }; + } catch (error) { + objectUrls.forEach((url) => URL.revokeObjectURL(url)); + throw error; + } +} + +function inspectZip(bytes: Uint8Array): ZipEntryMetadata[] { + if (bytes.byteLength < 22) throw new SkinPackError("The selected file is not a valid ZIP package.", "SKIN_ZIP_INVALID"); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff); + let eocd = -1; + for (let offset = bytes.byteLength - 22; offset >= minOffset; offset -= 1) { + if (view.getUint32(offset, true) === ZIP_EOCD) { eocd = offset; break; } + } + if (eocd < 0) throw new SkinPackError("The selected file is not a valid ZIP package.", "SKIN_ZIP_INVALID"); + const disk = view.getUint16(eocd + 4, true); + const centralDisk = view.getUint16(eocd + 6, true); + const entriesOnDisk = view.getUint16(eocd + 8, true); + const entryCount = view.getUint16(eocd + 10, true); + const centralSize = view.getUint32(eocd + 12, true); + const centralOffset = view.getUint32(eocd + 16, true); + const commentLength = view.getUint16(eocd + 20, true); + if (disk !== 0 || centralDisk !== 0 || entriesOnDisk !== entryCount || !entryCount || entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff || eocd + 22 + commentLength !== bytes.byteLength) { + throw new SkinPackError("Multi-disk and ZIP64 skin packages are not supported.", "SKIN_ZIP_FORMAT"); + } + if (entryCount > MAX_FILE_COUNT || centralOffset + centralSize !== eocd) throw new SkinPackError("The package contains too many files or an invalid directory.", "SKIN_FILE_COUNT"); + + const entries: ZipEntryMetadata[] = []; + const seenPaths = new Set(); + let expandedTotal = 0; + let compressedTotal = 0; + let offset = centralOffset; + for (let index = 0; index < entryCount; index += 1) { + if (offset + 46 > eocd || view.getUint32(offset, true) !== ZIP_CENTRAL_FILE) throw new SkinPackError("The package has an invalid ZIP directory entry.", "SKIN_ZIP_INVALID"); + const flags = view.getUint16(offset + 8, true); + const compression = view.getUint16(offset + 10, true); + const compressedSize = view.getUint32(offset + 20, true); + const expandedSize = view.getUint32(offset + 24, true); + const nameLength = view.getUint16(offset + 28, true); + const extraLength = view.getUint16(offset + 30, true); + const commentSize = view.getUint16(offset + 32, true); + const diskStart = view.getUint16(offset + 34, true); + const externalAttributes = view.getUint32(offset + 38, true); + const localOffset = view.getUint32(offset + 42, true); + const recordEnd = offset + 46 + nameLength + extraLength + commentSize; + if (recordEnd > eocd || diskStart !== 0 || flags & ~0x0800 || (compression !== 0 && compression !== 8) || compressedSize === 0xffffffff || expandedSize === 0xffffffff || localOffset === 0xffffffff) throw new SkinPackError("Encrypted, multi-disk, and unsupported ZIP entries are not allowed.", "SKIN_ZIP_FORMAT"); + const unixFileType = (externalAttributes >>> 16) & 0xf000; + if (unixFileType !== 0 && unixFileType !== 0x8000 && unixFileType !== 0x4000) throw new SkinPackError("Only regular files and directories are allowed in a skin package.", "SKIN_FILE_TYPE"); + let rawName: string; + try { rawName = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)); } + catch { throw new SkinPackError("A package path is not valid UTF-8.", "SKIN_PATH_INVALID"); } + const path = validateArchivePath(rawName); + const isDirectory = path.endsWith("/"); + if ((unixFileType === 0x4000) !== isDirectory && unixFileType !== 0) throw new SkinPackError("ZIP file type does not match its path.", "SKIN_FILE_TYPE"); + if (isDirectory && (compressedSize !== 0 || expandedSize !== 0)) throw new SkinPackError("ZIP directory entries cannot contain data.", "SKIN_ZIP_INVALID"); + if (compression === 0 && compressedSize !== expandedSize) throw new SkinPackError("A stored ZIP entry has inconsistent sizes.", "SKIN_ZIP_INVALID"); + if (seenPaths.has(path.toLowerCase())) throw new SkinPackError("The package contains duplicate or case-conflicting paths.", "SKIN_PATH_DUPLICATE"); + seenPaths.add(path.toLowerCase()); + expandedTotal += expandedSize; + compressedTotal += compressedSize; + if (expandedTotal > MAX_EXPANDED_BYTES) throw new SkinPackError("The expanded skin package must be smaller than 50 MiB.", "SKIN_EXPANDED_SIZE"); + if (expandedSize > 1024 * 1024 && expandedSize > Math.max(compressedSize, 1) * 250) throw new SkinPackError("The package has an abnormal compression ratio.", "SKIN_COMPRESSION_RATIO"); + entries.push({ path, compressedSize, expandedSize, compression, isDirectory, flags, crc: view.getUint32(offset + 16, true), localOffset }); + offset = recordEnd; + } + if (offset !== centralOffset + centralSize || compressedTotal > bytes.byteLength) throw new SkinPackError("The package directory is inconsistent.", "SKIN_ZIP_INVALID"); + validateLocalEntries(bytes, entries, centralOffset); + return entries; +} + +function validateLocalEntries(bytes: Uint8Array, entries: ZipEntryMetadata[], centralOffset: number): void { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const spans: Array<{ start: number; end: number }> = []; + for (const entry of entries) { + const offset = entry.localOffset; + if (offset + 30 > centralOffset || view.getUint32(offset, true) !== 0x04034b50) throw new SkinPackError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID"); + const flags = view.getUint16(offset + 6, true); + const compression = view.getUint16(offset + 8, true); + const crc = view.getUint32(offset + 14, true); + const compressedSize = view.getUint32(offset + 18, true); + const expandedSize = view.getUint32(offset + 22, true); + const nameLength = view.getUint16(offset + 26, true); + const extraLength = view.getUint16(offset + 28, true); + const headerEnd = offset + 30 + nameLength + extraLength; + if (headerEnd > centralOffset || flags !== entry.flags || compression !== entry.compression || crc !== entry.crc || compressedSize !== entry.compressedSize || expandedSize !== entry.expandedSize) { + throw new SkinPackError("ZIP local and central headers disagree.", "SKIN_ZIP_INVALID"); + } + let localPath: string; + try { localPath = decoder.decode(bytes.subarray(offset + 30, offset + 30 + nameLength)); } + catch { throw new SkinPackError("A package path is not valid UTF-8.", "SKIN_PATH_INVALID"); } + if (localPath !== entry.path) throw new SkinPackError("ZIP local and central filenames disagree.", "SKIN_ZIP_INVALID"); + const end = headerEnd + entry.compressedSize; + if (end > centralOffset) throw new SkinPackError("A ZIP entry overlaps the central directory.", "SKIN_ZIP_INVALID"); + spans.push({ start: offset, end }); + } + spans.sort((left, right) => left.start - right.start); + for (let index = 1; index < spans.length; index += 1) { + if (spans[index].start < spans[index - 1].end) throw new SkinPackError("ZIP local file entries overlap.", "SKIN_ZIP_INVALID"); + } +} + +function validateArchivePath(rawPath: string): string { + if (!rawPath || rawPath.includes("\\") || rawPath.startsWith("/") || /^[a-z]:/i.test(rawPath) || rawPath.includes("\0")) { + throw new SkinPackError("The package contains an absolute or unsafe path.", "SKIN_PATH_INVALID"); + } + const segments = rawPath.split("/"); + const directory = segments.at(-1) === ""; + const usableSegments = directory ? segments.slice(0, -1) : segments; + if (!usableSegments.length || usableSegments.some((segment) => !segment || segment === "." || segment === ".." || segment.includes(":"))) { + throw new SkinPackError("The package contains an unsafe path segment.", "SKIN_PATH_INVALID"); + } + return usableSegments.join("/") + (directory ? "/" : ""); +} + +function findSingleRootFolder(paths: string[]): string { + if (paths.includes("manifest.json")) return ""; + const firstSegments = paths.map((path) => path.split("/")[0]); + const candidate = firstSegments[0]; + if (!candidate || !paths.every((path) => path.startsWith(`${candidate}/`))) return ""; + return `${candidate}/`; +} + +function parseManifest(bytes: Uint8Array): SkinManifest { + let value: unknown; + try { value = JSON.parse(decoder.decode(bytes)); } + catch { throw new SkinPackError("manifest.json must contain valid UTF-8 JSON.", "SKIN_MANIFEST_INVALID"); } + if (!value || typeof value !== "object" || Array.isArray(value)) throw new SkinPackError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID"); + const raw = value as Record; + const stringField = (key: string, max: number, required = true): string | undefined => { + const field = raw[key]; + if (field == null && !required) return undefined; + if (typeof field !== "string" || !field.trim() || field.length > max) throw new SkinPackError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID"); + return field.trim(); + }; + if (raw.schemaVersion !== 1) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION"); + const id = stringField("id", 80)!; + if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(id) || id.startsWith("builtin.")) throw new SkinPackError("Skin IDs must be unique lowercase IDs and cannot use the reserved builtin. prefix.", "SKIN_ID_INVALID"); + const entry = stringField("entry", 120)!; + const content = stringField("content", 120, false); + const preview = stringField("preview", 120, false); + for (const path of [entry, content, preview].filter((item): item is string => Boolean(item))) { + if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID"); + } + const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; + const version = stringField("version", 32)!; + const minAppVersion = stringField("minAppVersion", 32)!; + if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID"); + if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID"); + const declaredFiles = ["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase()); + if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID"); + return { + schemaVersion: 1, + id, + name: stringField("name", 80)!, + version, + author: stringField("author", 80)!, + license: stringField("license", 80)!, + description: stringField("description", 400, false), + entry, + content, + minAppVersion, + preview, + }; +} + +function parseContent(bytes: Uint8Array): SkinContent { + let raw: unknown; + try { raw = JSON.parse(decoder.decode(bytes)); } + catch { throw new SkinPackError("content.json must contain valid UTF-8 JSON.", "SKIN_CONTENT_INVALID"); } + if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinPackError("content.json must be an object.", "SKIN_CONTENT_INVALID"); + const root = raw as Record; + if (typeof root.defaultLocale !== "string" || !/^[a-z]{2,3}(?:-[A-Z]{2})?$/.test(root.defaultLocale) || !root.locales || typeof root.locales !== "object" || Array.isArray(root.locales)) throw new SkinPackError("content.json needs a valid defaultLocale and locales.", "SKIN_CONTENT_INVALID"); + const localeEntries = Object.entries(root.locales as Record); + if (!localeEntries.length || localeEntries.length > 20) throw new SkinPackError("content.json must contain between 1 and 20 locales.", "SKIN_CONTENT_INVALID"); + const allowed = new Set(["brandName", "eyebrow", "title", "titleAccent", "description", "welcomeTitle", "welcomeDescription", "features"]); + const locales: SkinContent["locales"] = {}; + for (const [locale, entry] of localeEntries) { + if (!/^[a-z]{2,3}(?:-[A-Z]{2})?$/.test(locale) || !entry || typeof entry !== "object" || Array.isArray(entry)) throw new SkinPackError("content.json contains an invalid locale entry.", "SKIN_CONTENT_INVALID"); + const localeValue = entry as Record; + const localeCopy: SkinContent["locales"][string] = {}; + if (localeValue.home !== undefined) { + if (!localeValue.home || typeof localeValue.home !== "object" || Array.isArray(localeValue.home)) throw new SkinPackError("A locale home section must be an object.", "SKIN_CONTENT_INVALID"); + const homeCopy: SkinHomeCopy = {}; + for (const [key, field] of Object.entries(localeValue.home as Record)) { + if (!allowed.has(key as keyof SkinHomeCopy)) throw new SkinPackError(`Unknown homepage content field: ${key}`, "SKIN_CONTENT_INVALID"); + if (key === "features") { + if (!Array.isArray(field) || field.length > 8) throw new SkinPackError("Each locale may define up to 8 homepage features.", "SKIN_CONTENT_INVALID"); + homeCopy.features = field.map((item) => { + if (!item || typeof item !== "object" || Array.isArray(item)) throw new SkinPackError("A homepage feature must be an object.", "SKIN_CONTENT_INVALID"); + const feature = item as Record; + if (typeof feature.title !== "string" || typeof feature.description !== "string" || feature.title.length > 80 || feature.description.length > 240) throw new SkinPackError("Homepage feature text is too long or invalid.", "SKIN_CONTENT_INVALID"); + return { title: feature.title, description: feature.description }; + }); + } else if (typeof field === "string" && field.length <= 500) { + homeCopy[key as Exclude] = field; + } else { + throw new SkinPackError(`Invalid or oversized homepage content field: ${key}`, "SKIN_CONTENT_INVALID"); + } + } + localeCopy.home = homeCopy; + } + if (localeValue.messages !== undefined) { + if (!localeValue.messages || typeof localeValue.messages !== "object" || Array.isArray(localeValue.messages)) throw new SkinPackError("Locale messages must be an object.", "SKIN_CONTENT_INVALID"); + const messageEntries = Object.entries(localeValue.messages as Record); + if (messageEntries.length > 200) throw new SkinPackError("Each locale may override up to 200 interface strings.", "SKIN_CONTENT_INVALID"); + const messages: Record = {}; + for (const [key, text] of messageEntries) { + if (!/^[a-z][a-zA-Z0-9.]*$/.test(key) || typeof text !== "string" || text.length > 500) throw new SkinPackError("A locale message key or value is invalid or too long.", "SKIN_CONTENT_INVALID"); + messages[key] = text; + } + localeCopy.messages = messages; + } + if (!localeCopy.home && !localeCopy.messages) throw new SkinPackError("Each locale must define home content or messages.", "SKIN_CONTENT_INVALID"); + locales[locale] = localeCopy; + } + if (!locales[root.defaultLocale]) throw new SkinPackError("defaultLocale must have a matching content entry.", "SKIN_CONTENT_INVALID"); + return { defaultLocale: root.defaultLocale, locales }; +} + +function compileSkinCss(source: string, id: string, assets: Record): { css: string; warnings: string[] } { + const size = new TextEncoder().encode(source).byteLength; + if (!size || size > MAX_CSS_BYTES) throw new SkinPackError("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 SkinPackError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); } + + const scope = `.ws-skin-root[data-ws-skin="${id}"]`; + const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}`; + const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone()); + const warnings = new Set(); + const keyframeNames = new Map(); + const fontFamilyNames = new Map(); + const hideableRules = new WeakSet(); + let nodeCount = 0; + root.walk((node) => { + nodeCount += 1; + if (nodeCount > 12000) throw new SkinPackError("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(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 (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule); + try { + rule.selector = selectorParser((selectors) => { + selectors.each((selector) => { + const text = selector.toString().trim(); + if (!text) throw new SkinPackError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR"); + if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinPackError("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 SkinPackError) throw error; + throw rule.error(`A CSS selector is invalid: ${(error as Error).message}`); + } + }); + + const referencedKeyframes = new Set(); + const nonOptionalKeyframes = new Set(); + 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 = declaration.prop.toLowerCase(); + const value = declaration.value.trim(); + 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 (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(value)) { + throw declaration.error("Executable CSS values are not allowed."); + } + const compactValue = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("").toLowerCase(); + if (["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(value)) { + 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) { + 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(value)) + || (property === "clip-path" && /inset\(\s*50%/i.test(value)) + || (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(value)); + if (visuallyRemoves && !canHideTarget) { + throw declaration.error("Only explicitly optional visual parts may be visually removed."); + } + if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${value}`) || (property === "position" && value === "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) => { + const blob = assets[assetPath]; + if (!blob) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`); + return `wskin-asset:${encodeURIComponent(assetPath)}`; + }); + }); + + return { css: root.toString(), warnings: [...warnings] }; +} + +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 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); +} + +function rewriteAssetUrls(value: string, resolve: (path: string) => string): string { + const parsed = valueParser(value); + const resolvePackageAsset = (rawValue: string): string => { + const raw = rawValue.trim(); + if (!raw || raw.startsWith("#")) throw new SkinPackError("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 SkinPackError("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 SkinPackError("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) { + if (node.type === "function" && node.value.toLowerCase() === "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" && (node.value.toLowerCase() === "image-set" || node.value.toLowerCase() === "-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 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 SkinPackError("@font-face must declare exactly one font family.", "SKIN_FONT_FAMILY"); + } + return parsed[0].value.trim(); +} + +function rewriteScopedNames(value: string, property: string, keyframes: Map, fontFamilies: Map): 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 SkinPackError("An asset URL contains invalid encoding.", "SKIN_ASSET_PATH"); } + if (path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[a-z]:/i.test(path)) throw new SkinPackError("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 SkinPackError("An asset URL cannot leave the skin package.", "SKIN_ASSET_PATH"); + segments.pop(); + } else { + segments.push(segment); + } + } + if (!segments.length) throw new SkinPackError("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; +} + +function assetMimeType(path: string): string | null { + const extension = path.split(".").at(-1)?.toLowerCase(); + switch (extension) { + case "png": return "image/png"; + case "jpg": case "jpeg": return "image/jpeg"; + case "webp": return "image/webp"; + case "avif": return "image/avif"; + case "gif": return "image/gif"; + case "woff2": return "font/woff2"; + default: return null; + } +} diff --git a/web/src/services/skin-runtime.ts b/web/src/services/skin-runtime.ts new file mode 100644 index 0000000..482fe6d --- /dev/null +++ b/web/src/services/skin-runtime.ts @@ -0,0 +1,144 @@ +import { getInstalledSkin, saveInstalledSkin } from "./local-persistence.js"; +import type { InstalledSkin } from "./skin-pack.js"; +import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme, type ThemeMode } from "./theme.js"; + +export const ACTIVE_SKIN_KEY = "webspeak:active-skin"; +export const BUILTIN_LIGHT_SKIN = "builtin.light"; +export const BUILTIN_DARK_SKIN = "builtin.dark"; +const CUSTOM_STYLE_ID = "webspeak-active-custom-skin"; +const BUILTIN_STYLE_ID = "webspeak-active-built-in-skin"; + +let activeAssetUrls: string[] = []; +let criticalControlObserver: MutationObserver | null = null; + +export function getStoredSkinId(): string | null { + return typeof localStorage === "undefined" ? null : localStorage.getItem(ACTIVE_SKIN_KEY); +} + +export function storeSkinId(id: string): void { + if (typeof localStorage !== "undefined") localStorage.setItem(ACTIVE_SKIN_KEY, id); +} + +export async function activateStoredSkin(): Promise { + const storedId = getStoredSkinId(); + const legacyTheme = getStoredTheme(); + const selectedId = storedId || (isDarkTheme(legacyTheme) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN); + storeSkinId(selectedId); + return activateSkin(selectedId); +} + +export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.4"): Promise { + if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) { + clearCustomSkinStyle(); + applyTheme(id === BUILTIN_DARK_SKIN ? "dark" : "light"); + markCoreControls(); + storeSkinId(id); + return null; + } + + let skin = await getInstalledSkin(id); + if (!skin || (expectedVersion && skin.version !== expectedVersion)) { + try { + const response = await fetch(`/api/skins/${encodeURIComponent(id)}/package`, { cache: "no-cache" }); + if (!response.ok) throw new Error("Skin package is no longer available."); + const archive = await response.blob(); + const file = new File([archive], `${id}.wskin`, { type: "application/octet-stream" }); + const { importSkinPack } = await import("./skin-pack.js"); + const downloaded = await importSkinPack(file); + if (downloaded.id !== id) throw new Error("Skin package ID does not match its catalog entry."); + if (expectedVersion && downloaded.version !== expectedVersion) throw new Error("Skin package version does not match its catalog entry."); + skin = downloaded; + await saveInstalledSkin(downloaded).catch(() => undefined); + } catch { + if (!skin) return fallBackToBuiltin(); + } + } + + if (!isVersionCompatible(appVersion, skin.minAppVersion)) return fallBackToBuiltin(); + + try { + const { resolveSkinCssAssets } = await import("./skin-pack.js"); + const compiled = resolveSkinCssAssets(skin.css, skin.assets); + const baseTheme: Exclude = isDarkTheme(getStoredTheme()) ? "dark" : "light"; + applyTheme(baseTheme); + const root = document.getElementById(BUILTIN_STYLE_ID) as HTMLStyleElement | null; + if (root) { + root.dataset.skinPackage = skin.id; + root.textContent = getBuiltinSkinCss(baseTheme).replaceAll(`data-ws-skin="builtin.${baseTheme}"`, `data-ws-skin="${skin.id}"`); + } + document.querySelectorAll(".ws-skin-root").forEach((clientRoot) => { + clientRoot.dataset.wsSkin = skin!.id; + }); + markCoreControls(); + + let style = document.getElementById(CUSTOM_STYLE_ID) as HTMLStyleElement | null; + if (!style) { + style = document.createElement("style"); + style.id = CUSTOM_STYLE_ID; + document.head.append(style); + } + style.dataset.skinPackage = skin.id; + style.textContent = compiled.css; + const previousAssetUrls = activeAssetUrls; + activeAssetUrls = compiled.objectUrls; + previousAssetUrls.forEach((url) => URL.revokeObjectURL(url)); + storeSkinId(id); + return skin; + } catch { + return fallBackToBuiltin(); + } +} + +function fallBackToBuiltin(): null { + const fallback = isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN; + clearCustomSkinStyle(); + applyTheme(fallback === BUILTIN_DARK_SKIN ? "dark" : "light"); + storeSkinId(fallback); + return null; +} + +export function clearCustomSkinStyle(): void { + document.getElementById(CUSTOM_STYLE_ID)?.remove(); + activeAssetUrls.forEach((url) => URL.revokeObjectURL(url)); + activeAssetUrls = []; +} + +function isVersionCompatible(current: string, minimum: string): boolean { + const parse = (value: string) => /^(\d+)\.(\d+)\.(\d+)/.exec(value)?.slice(1).map(Number); + const currentParts = parse(current); + const minimumParts = parse(minimum); + if (!currentParts || !minimumParts) return false; + for (let index = 0; index < 3; index += 1) { + if (currentParts[index] > minimumParts[index]) return true; + if (currentParts[index] < minimumParts[index]) return false; + } + return true; +} + +function markCoreControls(): void { + const roots = [...document.querySelectorAll(".ws-skin-root")]; + const selector = "button, a[href], input, select, textarea, [role='button'], [role='menuitem'], [draggable='true']"; + const markElement = (element: HTMLElement) => { + element.dataset.wsCritical = "true"; + element.dataset.wsPart ||= "control"; + const role = element.getAttribute("role"); + const type = element instanceof HTMLInputElement ? element.type : ""; + element.dataset.wsControlKind = role === "menuitem" ? "menuitem" : role === "button" ? "button" : element instanceof HTMLInputElement && type === "range" ? "range" : element instanceof HTMLInputElement && type === "checkbox" ? "checkbox" : element instanceof HTMLInputElement ? "input" : element instanceof HTMLTextAreaElement ? "textarea" : element instanceof HTMLSelectElement ? "select" : element instanceof HTMLAnchorElement ? "link" : element instanceof HTMLButtonElement ? "button" : "draggable"; + }; + const mark = (root: ParentNode) => { + if (root instanceof HTMLElement && root.matches(selector)) markElement(root); + root.querySelectorAll(selector).forEach(markElement); + }; + roots.forEach(mark); + if (!criticalControlObserver) { + criticalControlObserver = new MutationObserver((records) => { + for (const record of records) for (const node of record.addedNodes) { + if (!(node instanceof HTMLElement)) continue; + const clientRoot = node.matches(".ws-skin-root") ? node : node.closest(".ws-skin-root"); + if (!clientRoot) continue; + mark(node); + } + }); + criticalControlObserver.observe(document.getElementById("app") ?? document.body, { childList: true, subtree: true }); + } +} diff --git a/web/src/services/theme.ts b/web/src/services/theme.ts index 4a39b93..155968e 100644 --- a/web/src/services/theme.ts +++ b/web/src/services/theme.ts @@ -1,6 +1,22 @@ export type ThemeMode = "system" | "light" | "dark"; +import lightManifest from "../skins/builtin/light/manifest.json"; +import lightCss from "../skins/builtin/light/skin.css?inline"; +import darkManifest from "../skins/builtin/dark/manifest.json"; +import darkCss from "../skins/builtin/dark/skin.css?inline"; + const THEME_KEY = "webspeak:theme"; +const SKIN_STYLE_ELEMENT_ID = "webspeak-active-built-in-skin"; +let activeThemeMode: ThemeMode = "system"; + +const builtinSkins = { + light: { manifest: lightManifest, css: lightCss }, + dark: { manifest: darkManifest, css: darkCss }, +} as const; + +export function getBuiltinSkinCss(theme: Exclude): string { + return theme === "dark" ? builtinSkins.dark.css : builtinSkins.light.css; +} export function getStoredTheme(): ThemeMode { const value = typeof localStorage === "undefined" ? "" : localStorage.getItem(THEME_KEY); @@ -9,7 +25,26 @@ export function getStoredTheme(): ThemeMode { export function applyTheme(theme: ThemeMode): void { if (typeof document === "undefined") return; - document.documentElement.dataset.theme = theme; + activeThemeMode = theme; + const root = document.documentElement; + const activeSkin = isDarkTheme(theme) ? builtinSkins.dark : builtinSkins.light; + + // Keep data-theme for the admin console's independent appearance rules. + // Built-in skin CSS is scoped to public roots and can never restyle /admin. + root.dataset.theme = theme; + document.querySelectorAll(".ws-skin-root").forEach((clientRoot) => { + clientRoot.dataset.wsSkin = activeSkin.manifest.id; + }); + + let style = document.getElementById(SKIN_STYLE_ELEMENT_ID) as HTMLStyleElement | null; + if (!style) { + style = document.createElement("style"); + style.id = SKIN_STYLE_ELEMENT_ID; + style.dataset.skinPackage = activeSkin.manifest.id; + document.head.append(style); + } + style.dataset.skinPackage = activeSkin.manifest.id; + style.textContent = activeSkin.css; } export function saveTheme(theme: ThemeMode): void { @@ -30,3 +65,12 @@ export function nextTheme(theme: ThemeMode): ThemeMode { } applyTheme(getStoredTheme()); + +if (typeof window !== "undefined" && typeof window.matchMedia === "function") { + const systemColorScheme = window.matchMedia("(prefers-color-scheme: dark)"); + const updateSystemSkin = () => { + if (activeThemeMode === "system") applyTheme("system"); + }; + if (systemColorScheme.addEventListener) systemColorScheme.addEventListener("change", updateSystemSkin); + else systemColorScheme.addListener?.(updateSystemSkin); +} diff --git a/web/src/skins/builtin/dark/manifest.json b/web/src/skins/builtin/dark/manifest.json new file mode 100644 index 0000000..32e60ad --- /dev/null +++ b/web/src/skins/builtin/dark/manifest.json @@ -0,0 +1,11 @@ +{ + "schemaVersion": 1, + "id": "builtin.dark", + "name": "WebSpeak Dark", + "version": "1.0.0", + "author": "WebSpeak", + "license": "AGPL-3.0-only", + "description": "The built-in dark appearance for public WebSpeak pages.", + "entry": "skin.css", + "minAppVersion": "0.2.4" +} diff --git a/web/src/skins/builtin/dark/skin.css b/web/src/skins/builtin/dark/skin.css new file mode 100644 index 0000000..be4a5dd --- /dev/null +++ b/web/src/skins/builtin/dark/skin.css @@ -0,0 +1,307 @@ +/* Built-in package: builtin.dark. Scoped to public WebSpeak pages only. */ +.ws-skin-root[data-ws-skin="builtin.dark"] { + color-scheme: dark; + --ws-page-bg: #101918; + --ws-surface-1: #172321; + --ws-surface-2: #202f2c; + --ws-text: #e8f3f0; + --ws-text-muted: #9bb0aa; + --ws-accent: #69d2c7; + --ws-success: #78e489; + --ws-warning: #e2b36c; + --ws-danger: #ee8a82; + --ws-border: #30413d; + --surface-0: var(--ws-page-bg); + --surface-1: var(--ws-surface-1); + --surface-2: var(--ws-surface-2); + --text-primary: var(--ws-text); + --text-muted: var(--ws-text-muted); + --accent: var(--ws-accent); + --success: var(--ws-success); + --warning: var(--ws-warning); + --danger: var(--ws-danger); + --border: var(--ws-border); +} + +.ws-skin-root[data-ws-skin="builtin.dark"] { + background: var(--surface-0); + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page { + color: var(--text-primary); + background-color: var(--surface-0); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .app-shell, +.ws-skin-root[data-ws-skin="builtin.dark"] .workspace { + background: var(--surface-1); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .workspace-header, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-panel, +.ws-skin-root[data-ws-skin="builtin.dark"] .voice-card, +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-modal { + background: var(--surface-1); + border-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .workspace-header { + border-bottom-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .workspace-content { + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-card { + background: color-mix(in srgb, var(--surface-1) 94%, transparent); + border-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .field-wrap, +.ws-skin-root[data-ws-skin="builtin.dark"] .message-composer, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-search, +.ws-skin-root[data-ws-skin="builtin.dark"] .mic-mode-switch, +.ws-skin-root[data-ws-skin="builtin.dark"] .mode-note { + background: var(--surface-2); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .field-wrap input, +.ws-skin-root[data-ws-skin="builtin.dark"] .message-composer input, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-search input, +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-select { + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .room-hero { + background: linear-gradient(110deg, color-mix(in srgb, var(--accent) 18%, var(--surface-1)), var(--surface-1) 75%); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .voice-card, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-panel, +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-modal { + box-shadow: 0 7px 18px color-mix(in srgb, var(--text-primary) 8%, transparent); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .section-heading h2, +.ws-skin-root[data-ws-skin="builtin.dark"] .room-hero h1, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-card h2, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-panel-heading h2, +.ws-skin-root[data-ws-skin="builtin.dark"] .message-meta strong, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-copy strong { + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .section-kicker, +.ws-skin-root[data-ws-skin="builtin.dark"] .card-kicker, +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-label, +.ws-skin-root[data-ws-skin="builtin.dark"] .header-note, +.ws-skin-root[data-ws-skin="builtin.dark"] .section-counter, +.ws-skin-root[data-ws-skin="builtin.dark"] .message-meta time, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-copy span, +.ws-skin-root[data-ws-skin="builtin.dark"] .chat-empty, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-description, +.ws-skin-root[data-ws-skin="builtin.dark"] .card-lead { + color: var(--text-muted); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .chat-panel, +.ws-skin-root[data-ws-skin="builtin.dark"] .chat-heading, +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-header, +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-footer, +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-separator { + border-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .message-bubble { + color: var(--text-primary); + background: var(--surface-2); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-content, +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-nav { + background: var(--surface-1); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-nav { + border-right-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-section h3, +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-header h2 { + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .settings-select { + color: var(--text-primary); + background: var(--surface-2); + border-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .audio-level-track, +.ws-skin-root[data-ws-skin="builtin.dark"] .meter i { + background: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .member-presence { + border-color: var(--surface-1); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .member-row:hover, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-row:focus-within { + background: color-mix(in srgb, var(--accent) 10%, var(--surface-1)); + box-shadow: 0 4px 12px color-mix(in srgb, var(--text-primary) 8%, transparent); +} +.ws-skin-root[data-ws-skin="builtin.dark"] :focus-visible { + outline-color: color-mix(in srgb, var(--accent) 55%, transparent); +} + +.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-modal { + color: var(--text-primary); + border-color: var(--border); + background: var(--surface-1); + box-shadow: 0 20px 60px color-mix(in srgb, var(--text-primary) 18%, transparent); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-modal h2 { color: var(--text-primary); } +.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-modal > p { color: var(--text-muted); } +.ws-skin-root[data-ws-skin="builtin.dark"] .channel-password-icon { + color: var(--accent); + background: color-mix(in srgb, var(--accent) 13%, var(--surface-2)); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .acceleration-choice { + color: #b8eee3; + background: #183530; + border-color: #2b645b; +} +.ws-skin-root[data-ws-skin="builtin.dark"] .acceleration-choice small { color: #91b9b0; } +.ws-skin-root[data-ws-skin="builtin.dark"] .acceleration-choice select { + color: #d9f8f1; + background: #203f39; + border-color: #3b766d; +} +.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-submenu-panel { + color: var(--text-primary); + background: var(--surface-1); + border-color: var(--border); + box-shadow: 0 18px 42px color-mix(in srgb, #000 38%, transparent); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu strong { color: var(--text-primary); } +.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu button { color: var(--text-muted); } +.ws-skin-root[data-ws-skin="builtin.dark"] .member-context-menu button:hover { + color: var(--accent); + background: color-mix(in srgb, var(--accent) 14%, var(--surface-2)); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .member-submenu-panel button small, +.ws-skin-root[data-ws-skin="builtin.dark"] .member-submenu-empty { color: var(--text-muted); } +.ws-skin-root[data-ws-skin="builtin.dark"] .breadcrumbs { color: var(--text-muted); } +.ws-skin-root[data-ws-skin="builtin.dark"] .breadcrumbs strong, +.ws-skin-root[data-ws-skin="builtin.dark"] .voice-card > strong { color: var(--text-primary); } +.ws-skin-root[data-ws-skin="builtin.dark"] .member-channel-heading { color: var(--text-muted); } +.ws-skin-root[data-ws-skin="builtin.dark"] .member-channel-group.current .member-channel-heading { + color: var(--accent); + background: color-mix(in srgb, var(--accent) 14%, var(--surface-1)); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .member-channel-group.current .member-channel-heading small { color: var(--accent); } + +.ws-skin-root[data-ws-skin="builtin.dark"] .brand-lockup strong { color: var(--accent); } +.ws-skin-root[data-ws-skin="builtin.dark"] .brand-lockup strong span { color: var(--text-primary); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .brand-lockup small, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .header-note, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-description, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item small, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .card-lead, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-hint, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-meta, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-footer { color: var(--text-muted); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .visitor-count { + color: #b7fff0; + border-color: rgba(105, 210, 199, .42); + background: linear-gradient(110deg, #173b36, #1c2d2a); + box-shadow: 0 10px 28px rgba(0, 0, 0, .24), inset 0 0 0 1px rgba(105, 210, 199, .08); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .visitor-count::before { + background: linear-gradient(105deg, transparent, rgba(125, 255, 174, .18), transparent); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .visitor-count-orbit { border-color: rgba(105, 210, 199, .34); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-card h2, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item b, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-label { color: var(--text-primary); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1 em, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .eyebrow, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .card-kicker, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-label span, +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-footer a { color: var(--accent); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-card { + background: color-mix(in srgb, var(--surface-1) 94%, transparent); + border-color: var(--border); + box-shadow: 0 20px 52px color-mix(in srgb, var(--text-primary) 14%, transparent); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-wrap { color: var(--text-muted); background: var(--surface-2); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-wrap input { color: var(--text-primary); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-modal-card { + color: var(--text-primary); + border-color: var(--border); + background: var(--surface-1); + box-shadow: 0 20px 60px color-mix(in srgb, var(--text-primary) 18%, transparent); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-modal-heading h2 { color: var(--text-primary); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-direct-join { color: var(--text-muted); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-modal-close { + color: var(--text-muted); + background: var(--surface-2); + border-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-join-link { + color: var(--accent); + background: color-mix(in srgb, var(--accent) 12%, var(--surface-2)); + border-color: color-mix(in srgb, var(--accent) 30%, var(--border)); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .qq-join-link:hover { + color: var(--surface-1); + background: var(--accent); + border-color: var(--accent); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .field-wrap input::placeholder { color: var(--text-muted); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-footer { border-top-color: var(--border); } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1 { + color: #f3fffb; + text-shadow: 0 1px 0 #07100f, 0 0 9px rgba(243, 255, 251, .16); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-copy h1 em { + color: #7dffae; + text-shadow: 0 0 10px rgba(125, 255, 174, .38), 0 0 22px rgba(105, 210, 199, .18); + animation-name: join-accent-breathe-dark; +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-description { + color: #c4d9d3; + text-shadow: 0 0 8px rgba(196, 217, 211, .12); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item b { + color: #f0fff9; + text-shadow: 0 0 7px rgba(240, 255, 249, .14); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-item small { color: #a9c6be; } +.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .promise-icon { box-shadow: 0 0 12px rgba(105, 210, 199, .14); } + +.ws-skin-root[data-ws-skin="builtin.dark"], +.ws-skin-root[data-ws-skin="builtin.dark"] * { + scrollbar-color: #438f88 transparent; + scrollbar-width: thin; +} +.ws-skin-root[data-ws-skin="builtin.dark"] *::-webkit-scrollbar-thumb { + background: #438f88; + border-color: transparent; +} +.ws-skin-root[data-ws-skin="builtin.dark"] *::-webkit-scrollbar-thumb:hover { background: #69c7bc; } + +.ws-skin-root[data-ws-skin="builtin.dark"] .language-switcher .language-trigger { + color: #a9d9d1; + background: #203531; + border-color: #38564f; +} +.ws-skin-root[data-ws-skin="builtin.dark"] .language-switcher .language-trigger:hover, +.ws-skin-root[data-ws-skin="builtin.dark"] .language-switcher.open .language-trigger { + color: #10201d; + background: #69d2c7; + border-color: #69d2c7; +} +.ws-skin-root[data-ws-skin="builtin.dark"] .language-switcher .language-dropdown { + background: #172321; + border-color: #30413d; + box-shadow: 0 16px 36px rgba(0, 0, 0, .32); +} +.ws-skin-root[data-ws-skin="builtin.dark"] .language-switcher .language-option { color: #d7e7e3; } +.ws-skin-root[data-ws-skin="builtin.dark"] .language-switcher .language-option:hover, +.ws-skin-root[data-ws-skin="builtin.dark"] .language-switcher .language-option:focus-visible, +.ws-skin-root[data-ws-skin="builtin.dark"] .language-switcher .language-option.selected { + color: #69d2c7; + background: #203531; + border-color: #38564f; +} + +@keyframes join-accent-breathe-dark { + 0%, 100% { transform: translateY(0); text-shadow: 0 0 8px rgba(125, 255, 174, .28), 0 0 18px rgba(105, 210, 199, .14); } + 50% { transform: translateY(-2px); text-shadow: 0 0 13px rgba(125, 255, 174, .5), 0 0 26px rgba(105, 210, 199, .22); } +} diff --git a/web/src/skins/builtin/light/manifest.json b/web/src/skins/builtin/light/manifest.json new file mode 100644 index 0000000..b35a020 --- /dev/null +++ b/web/src/skins/builtin/light/manifest.json @@ -0,0 +1,11 @@ +{ + "schemaVersion": 1, + "id": "builtin.light", + "name": "WebSpeak Light", + "version": "1.0.0", + "author": "WebSpeak", + "license": "AGPL-3.0-only", + "description": "The built-in light appearance for public WebSpeak pages.", + "entry": "skin.css", + "minAppVersion": "0.2.4" +} diff --git a/web/src/skins/builtin/light/skin.css b/web/src/skins/builtin/light/skin.css new file mode 100644 index 0000000..ed53c97 --- /dev/null +++ b/web/src/skins/builtin/light/skin.css @@ -0,0 +1,150 @@ +/* Built-in package: builtin.light. All rules stay inside the public client. */ +.ws-skin-root[data-ws-skin="builtin.light"] { + color-scheme: light; + --ws-page-bg: #f7f9f8; + --ws-surface-1: #fff; + --ws-surface-2: #f1f6f4; + --ws-text: #192120; + --ws-text-muted: #71807c; + --ws-accent: #006a64; + --ws-success: #65d879; + --ws-warning: #c89143; + --ws-danger: #c95a54; + --ws-border: #e4ece9; + --surface-0: var(--ws-page-bg); + --surface-1: var(--ws-surface-1); + --surface-2: var(--ws-surface-2); + --text-primary: var(--ws-text); + --text-muted: var(--ws-text-muted); + --accent: var(--ws-accent); + --success: var(--ws-success); + --warning: var(--ws-warning); + --danger: var(--ws-danger); + --border: var(--ws-border); +} + +.ws-skin-root[data-ws-skin="builtin.light"] { + background: var(--surface-0); + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.light"] .join-page { + color: var(--text-primary); + background-color: var(--surface-0); +} +.ws-skin-root[data-ws-skin="builtin.light"] .app-shell, +.ws-skin-root[data-ws-skin="builtin.light"] .workspace { + background: var(--surface-1); +} +.ws-skin-root[data-ws-skin="builtin.light"] .workspace-header, +.ws-skin-root[data-ws-skin="builtin.light"] .member-panel, +.ws-skin-root[data-ws-skin="builtin.light"] .voice-card, +.ws-skin-root[data-ws-skin="builtin.light"] .settings-modal { + background: var(--surface-1); + border-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.light"] .workspace-header { + border-bottom-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.light"] .workspace-content { + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.light"] .join-card { + background: color-mix(in srgb, var(--surface-1) 92%, transparent); + border-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.light"] .field-wrap, +.ws-skin-root[data-ws-skin="builtin.light"] .message-composer, +.ws-skin-root[data-ws-skin="builtin.light"] .member-search, +.ws-skin-root[data-ws-skin="builtin.light"] .mic-mode-switch, +.ws-skin-root[data-ws-skin="builtin.light"] .mode-note { + background: var(--surface-2); +} +.ws-skin-root[data-ws-skin="builtin.light"] .field-wrap input, +.ws-skin-root[data-ws-skin="builtin.light"] .message-composer input, +.ws-skin-root[data-ws-skin="builtin.light"] .member-search input, +.ws-skin-root[data-ws-skin="builtin.light"] .settings-select { + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.light"] .room-hero { + background: linear-gradient(110deg, color-mix(in srgb, var(--accent) 18%, var(--surface-1)), var(--surface-1) 75%); +} +.ws-skin-root[data-ws-skin="builtin.light"] .voice-card, +.ws-skin-root[data-ws-skin="builtin.light"] .member-panel, +.ws-skin-root[data-ws-skin="builtin.light"] .settings-modal { + box-shadow: 0 7px 18px color-mix(in srgb, var(--text-primary) 8%, transparent); +} +.ws-skin-root[data-ws-skin="builtin.light"] .section-heading h2, +.ws-skin-root[data-ws-skin="builtin.light"] .room-hero h1, +.ws-skin-root[data-ws-skin="builtin.light"] .join-card h2, +.ws-skin-root[data-ws-skin="builtin.light"] .member-panel-heading h2, +.ws-skin-root[data-ws-skin="builtin.light"] .message-meta strong, +.ws-skin-root[data-ws-skin="builtin.light"] .member-copy strong { + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.light"] .section-kicker, +.ws-skin-root[data-ws-skin="builtin.light"] .card-kicker, +.ws-skin-root[data-ws-skin="builtin.light"] .settings-label, +.ws-skin-root[data-ws-skin="builtin.light"] .header-note, +.ws-skin-root[data-ws-skin="builtin.light"] .section-counter, +.ws-skin-root[data-ws-skin="builtin.light"] .message-meta time, +.ws-skin-root[data-ws-skin="builtin.light"] .member-copy span, +.ws-skin-root[data-ws-skin="builtin.light"] .chat-empty, +.ws-skin-root[data-ws-skin="builtin.light"] .join-description, +.ws-skin-root[data-ws-skin="builtin.light"] .card-lead { + color: var(--text-muted); +} +.ws-skin-root[data-ws-skin="builtin.light"] .chat-panel, +.ws-skin-root[data-ws-skin="builtin.light"] .chat-heading, +.ws-skin-root[data-ws-skin="builtin.light"] .settings-header, +.ws-skin-root[data-ws-skin="builtin.light"] .settings-footer, +.ws-skin-root[data-ws-skin="builtin.light"] .settings-separator { + border-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.light"] .message-bubble { + color: var(--text-primary); + background: var(--surface-2); +} +.ws-skin-root[data-ws-skin="builtin.light"] .settings-content, +.ws-skin-root[data-ws-skin="builtin.light"] .settings-nav { + background: var(--surface-1); +} +.ws-skin-root[data-ws-skin="builtin.light"] .settings-nav { + border-right-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.light"] .settings-section h3, +.ws-skin-root[data-ws-skin="builtin.light"] .settings-header h2 { + color: var(--text-primary); +} +.ws-skin-root[data-ws-skin="builtin.light"] .settings-select { + color: var(--text-primary); + background: var(--surface-2); + border-color: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.light"] .audio-level-track, +.ws-skin-root[data-ws-skin="builtin.light"] .meter i { + background: var(--border); +} +.ws-skin-root[data-ws-skin="builtin.light"] .member-presence { + border-color: var(--surface-1); +} +.ws-skin-root[data-ws-skin="builtin.light"] .member-row:hover, +.ws-skin-root[data-ws-skin="builtin.light"] .member-row:focus-within { + background: color-mix(in srgb, var(--accent) 10%, var(--surface-1)); + box-shadow: 0 4px 12px color-mix(in srgb, var(--text-primary) 8%, transparent); +} +.ws-skin-root[data-ws-skin="builtin.light"] :focus-visible { + outline-color: color-mix(in srgb, var(--accent) 55%, transparent); +} +.ws-skin-root[data-ws-skin="builtin.light"], +.ws-skin-root[data-ws-skin="builtin.light"] * { + scrollbar-color: #8fcfc7 transparent; + scrollbar-width: thin; +} +.ws-skin-root[data-ws-skin="builtin.light"] *::-webkit-scrollbar-thumb { + background: #a7d9d2; + background-clip: padding-box; + border-color: transparent; +} +.ws-skin-root[data-ws-skin="builtin.light"] *::-webkit-scrollbar-thumb:hover { + background: #6bbab1; +} diff --git a/web/src/styles/web-client.css b/web/src/styles/web-client.css index cd8fae6..8759cc7 100644 --- a/web/src/styles/web-client.css +++ b/web/src/styles/web-client.css @@ -1,10 +1,10 @@ :global(*) { box-sizing: border-box; } -:global(body) { margin: 0; background: #f7f9f8; color: #192120; font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; } +:global(body) { margin: 0; font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; } :global(button), :global(input) { font: inherit; } :global(button) { border: 0; } -.web-client { min-height: 100dvh; outline: none; background: #f7f9f8; color: #192120; } -.join-page { min-height: 100dvh; display: flex; flex-direction: column; overflow: hidden; background: #f7f9f8; } +.web-client { min-height: 100dvh; outline: none; background: var(--surface-0); color: var(--text-primary); } +.join-page { min-height: 100dvh; display: flex; flex-direction: column; overflow: hidden; background: var(--surface-0); color: var(--text-primary); } .join-header, .join-content, .join-footer { width: min(1240px, calc(100% - 64px)); margin: 0 auto; } .join-header, .join-content, .join-footer { position: relative; z-index: 1; } .join-header { z-index: 10; } @@ -136,17 +136,11 @@ .channel-password-modal h2 { font-size: 22px; } } -:global(html[data-theme="dark"] .channel-password-modal) { color: var(--text-primary); border-color: var(--border); background: var(--surface-1); box-shadow: 0 20px 60px color-mix(in srgb, var(--text-primary) 18%, transparent); } -:global(html[data-theme="dark"] .channel-password-modal h2) { color: var(--text-primary); } -:global(html[data-theme="dark"] .channel-password-modal > p) { color: var(--text-muted); } -:global(html[data-theme="dark"] .channel-password-icon) { color: var(--accent); background: color-mix(in srgb, var(--accent) 13%, var(--surface-2)); } - @keyframes spin { to { transform: rotate(360deg); } } @keyframes wave { from { transform: scaleY(.68); opacity: .65; } to { transform: scaleY(1.08); opacity: 1; } } @keyframes meter { from { transform: scaleY(.65); } to { transform: scaleY(1); } } @keyframes toast-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } } @keyframes join-fade-up { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } } @keyframes join-title-in { from { opacity: 0; letter-spacing: -.02em; transform: translateY(18px) scale(.98); } to { opacity: 1; letter-spacing: -.075em; transform: translateY(0) scale(1); } } @keyframes join-accent-breathe { 0%, 100% { transform: translateY(0); text-shadow: 0 0 0 rgba(0, 106, 100, 0); } 50% { transform: translateY(-2px); text-shadow: 0 5px 18px rgba(0, 106, 100, .16); } } -@keyframes join-accent-breathe-dark { 0%, 100% { transform: translateY(0); text-shadow: 0 0 8px rgba(125, 255, 174, .28), 0 0 18px rgba(105, 210, 199, .14); } 50% { transform: translateY(-2px); text-shadow: 0 0 13px rgba(125, 255, 174, .5), 0 0 26px rgba(105, 210, 199, .22); } } @keyframes join-dot-pulse { 0%, 100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(144, 246, 145, .28); } 50% { transform: scale(1.18); box-shadow: 0 0 0 6px rgba(144, 246, 145, 0); } } @keyframes visitor-shimmer { 0%, 42% { left: -45%; } 72%, 100% { left: 130%; } } @keyframes visitor-spark { 0%, 100% { opacity: .58; transform: scale(.88) rotate(0deg); } 50% { opacity: 1; transform: scale(1.14) rotate(12deg); } } @@ -226,9 +220,6 @@ .remember-identity strong { font-size: 11px; font-weight: 700; } .remember-identity small { margin-top: 3px; color: #8b9994; font-size: 10px; line-height: 1.4; } .identity-warning { margin: 8px 0 0; color: #9a6a32; font-size: 10px; line-height: 1.45; } -:global(html[data-theme="dark"] .acceleration-choice) { color: #b8eee3; background: #183530; border-color: #2b645b; } -:global(html[data-theme="dark"] .acceleration-choice small) { color: #91b9b0; } -:global(html[data-theme="dark"] .acceleration-choice select) { color: #d9f8f1; background: #203f39; border-color: #3b766d; } .local-servers { display: grid; gap: 8px; margin: 1px 0 5px; } .local-server-group { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; } .local-server-group > span { width: 100%; color: #87958f; font-size: 10px; font-weight: 700; } @@ -383,13 +374,6 @@ .member-submenu-panel button small { margin-left: auto; color: #83928c; font-size: 10px; white-space: nowrap; } .member-submenu-empty { display: block; padding: 8px; color: #83928c; font-size: 11px; } .member-menu-disabled { opacity: .55; cursor: not-allowed !important; } -:global(html[data-theme="dark"]) .member-context-menu, -:global(html[data-theme="dark"]) .member-submenu-panel { color: var(--text-primary); background: var(--surface-1); border-color: var(--border); box-shadow: 0 18px 42px color-mix(in srgb, #000 38%, transparent); } -:global(html[data-theme="dark"]) .member-context-menu strong { color: var(--text-primary); } -:global(html[data-theme="dark"]) .member-context-menu button { color: var(--text-muted); } -:global(html[data-theme="dark"]) .member-context-menu button:hover { color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, var(--surface-2)); } -:global(html[data-theme="dark"]) .member-submenu-panel button small, -:global(html[data-theme="dark"]) .member-submenu-empty { color: var(--text-muted); } .menu-volume { display: grid; gap: 6px; padding: 4px 8px 8px; color: #71817c; font-size: 10px; } .menu-volume input { width: 100%; height: 5px; appearance: none; border-radius: 99px; outline: none; cursor: pointer; } .menu-volume input::-webkit-slider-thumb { width: 14px; height: 14px; appearance: none; border: 2px solid #81d8d0; border-radius: 50%; background: #fff; cursor: pointer; } @@ -409,100 +393,14 @@ .audio-level-track i { display: block; height: 100%; min-width: 0; background: linear-gradient(90deg, #69c8bb, #58d675); border-radius: inherit; transition: width .08s linear; } .test-audio { display: block; width: 100%; height: 34px; margin-top: 11px; } -/* M008 semantic theme tokens and keyboard-safe surfaces. */ -:global(:root) { color-scheme: light; --surface-0: #f7f9f8; --surface-1: #fff; --surface-2: #f1f6f4; --text-primary: #192120; --text-muted: #71807c; --border: #e4ece9; --accent: #006a64; --success: #65d879; --warning: #c89143; --danger: #c95a54; } -:global(:root[data-theme="dark"]) { color-scheme: dark; --surface-0: #101918; --surface-1: #172321; --surface-2: #202f2c; --text-primary: #e8f3f0; --text-muted: #9bb0aa; --border: #30413d; --accent: #69d2c7; --success: #78e489; --warning: #e2b36c; --danger: #ee8a82; } -@media (prefers-color-scheme: dark) { :global(:root[data-theme="system"]) { color-scheme: dark; --surface-0: #101918; --surface-1: #172321; --surface-2: #202f2c; --text-primary: #e8f3f0; --text-muted: #9bb0aa; --border: #30413d; --accent: #69d2c7; --success: #78e489; --warning: #e2b36c; --danger: #ee8a82; } } -.web-client { background: var(--surface-0); color: var(--text-primary); } -.join-page { background-color: var(--surface-0); color: var(--text-primary); } +/* Shared interaction/layout rules; appearance is supplied by a built-in skin package. */ .join-page .join-card { position: relative; } -.app-shell, .workspace { background: var(--surface-1); } -.workspace-header, .member-panel, .voice-card, .settings-modal { background: var(--surface-1); border-color: var(--border); } -.workspace-header { border-bottom-color: var(--border); } -.workspace-content { color: var(--text-primary); } -.join-card { background: color-mix(in srgb, var(--surface-1) 92%, transparent); border-color: var(--border); } -.field-wrap, .message-composer, .member-search, .mic-mode-switch, .mode-note { background: var(--surface-2); } -.field-wrap input, .message-composer input, .member-search input, .settings-select { color: var(--text-primary); } -.room-hero { background: linear-gradient(110deg, color-mix(in srgb, var(--accent) 18%, var(--surface-1)), var(--surface-1) 75%); } -.voice-card, .member-panel, .settings-modal { box-shadow: 0 7px 18px color-mix(in srgb, var(--text-primary) 8%, transparent); } -.section-heading h2, .room-hero h1, .join-card h2, .member-panel-heading h2, .message-meta strong, .member-copy strong { color: var(--text-primary); } -.section-kicker, .card-kicker, .settings-label, .header-note, .section-counter, .message-meta time, .member-copy span, .chat-empty, .join-description, .card-lead { color: var(--text-muted); } -.chat-panel, .chat-heading, .settings-header, .settings-footer, .settings-separator { border-color: var(--border); } -.message-bubble { color: var(--text-primary); background: var(--surface-2); } -.settings-content, .settings-nav { background: var(--surface-1); } -.settings-nav { border-right-color: var(--border); } -.settings-section h3, .settings-header h2 { color: var(--text-primary); } - .settings-select { background: var(--surface-2); border-color: var(--border); color: var(--text-primary); } -.audio-level-track, .meter i { background: var(--border); } -.member-presence { border-color: var(--surface-1); } -.member-row:hover, .member-row:focus-within { background: color-mix(in srgb, var(--accent) 10%, var(--surface-1)); box-shadow: 0 4px 12px color-mix(in srgb, var(--text-primary) 8%, transparent); } -:global(button:focus-visible), :global(a:focus-visible), :global(input:focus-visible), :global(select:focus-visible), :global(textarea:focus-visible) { outline: 3px solid color-mix(in srgb, var(--accent) 55%, transparent); outline-offset: 2px; } +.web-client button:focus-visible, .web-client a:focus-visible, .web-client input:focus-visible, .web-client select:focus-visible, .web-client textarea:focus-visible { outline: 3px solid color-mix(in srgb, var(--accent) 55%, transparent); outline-offset: 2px; } .message-composer { position: sticky; bottom: env(safe-area-inset-bottom, 0px); z-index: 3; } @media (max-width: 740px) { .workspace-scroll { overscroll-behavior: contain; }.workspace-content { width: min(100% - 24px, 650px); padding-bottom: calc(24px + env(safe-area-inset-bottom, 0px)); }.message-composer { margin-bottom: 8px; } } @media (max-width: 740px) { .member-context-menu { left: 12px !important; right: 12px; top: auto !important; bottom: env(safe-area-inset-bottom, 0px); min-width: 0; border-radius: 16px 16px 0 0; padding: 14px; } .member-context-menu button { min-height: 42px; font-size: 13px; } .member-context-menu strong { padding: 4px 8px 11px; font-size: 14px; } .menu-volume { font-size: 12px; } } @media (max-width: 740px) { .member-submenu-panel { position: static; min-width: 0; max-height: 190px; margin: 4px 0 0 24px; padding: 4px; border-radius: 10px; box-shadow: none; } .member-submenu-panel button { min-height: 42px; font-size: 13px; } } -:global(html[data-theme="dark"] .join-page .brand-lockup strong) { color: var(--accent); } -:global(html[data-theme="dark"] .join-page .brand-lockup strong span) { color: var(--text-primary); } -:global(html[data-theme="dark"] .join-page .brand-lockup small), -:global(html[data-theme="dark"] .join-page .header-note), -:global(html[data-theme="dark"] .join-page .join-description), -:global(html[data-theme="dark"] .join-page .promise-item small), -:global(html[data-theme="dark"] .join-page .card-lead), -:global(html[data-theme="dark"] .join-page .field-hint), -:global(html[data-theme="dark"] .join-page .join-meta), -:global(html[data-theme="dark"] .join-page .join-footer) { color: var(--text-muted); } -:global(html[data-theme="dark"] .join-page .visitor-count) { color: #b7fff0; border-color: rgba(105, 210, 199, .42); background: linear-gradient(110deg, #173b36, #1c2d2a); box-shadow: 0 10px 28px rgba(0, 0, 0, .24), inset 0 0 0 1px rgba(105, 210, 199, .08); } -:global(html[data-theme="dark"] .join-page .visitor-count::before) { background: linear-gradient(105deg, transparent, rgba(125, 255, 174, .18), transparent); } -:global(html[data-theme="dark"] .join-page .visitor-count-orbit) { border-color: rgba(105, 210, 199, .34); } -:global(html[data-theme="dark"] .join-page .join-copy h1), -:global(html[data-theme="dark"] .join-page .join-card h2), -:global(html[data-theme="dark"] .join-page .promise-item b), -:global(html[data-theme="dark"] .join-page .field-label) { color: var(--text-primary); } -:global(html[data-theme="dark"] .join-page .join-copy h1 em), -:global(html[data-theme="dark"] .join-page .eyebrow), -:global(html[data-theme="dark"] .join-page .card-kicker), -:global(html[data-theme="dark"] .join-page .field-label span), -:global(html[data-theme="dark"] .join-page .join-footer a) { color: var(--accent); } -:global(html[data-theme="dark"] .join-page .join-card) { background: color-mix(in srgb, var(--surface-1) 94%, transparent); border-color: var(--border); box-shadow: 0 20px 52px color-mix(in srgb, var(--text-primary) 14%, transparent); } -:global(html[data-theme="dark"] .join-page .field-wrap) { color: var(--text-muted); background: var(--surface-2); } -:global(html[data-theme="dark"] .join-page .field-wrap input) { color: var(--text-primary); } -:global(html[data-theme="dark"] .join-page .qq-modal-card) { color: var(--text-primary); border-color: var(--border); background: var(--surface-1); box-shadow: 0 20px 60px color-mix(in srgb, var(--text-primary) 18%, transparent); } -:global(html[data-theme="dark"] .join-page .qq-modal-heading h2) { color: var(--text-primary); } -:global(html[data-theme="dark"] .join-page .qq-direct-join) { color: var(--text-muted); } -:global(html[data-theme="dark"] .join-page .qq-modal-close) { color: var(--text-muted); background: var(--surface-2); border-color: var(--border); } -:global(html[data-theme="dark"] .join-page .qq-join-link) { color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, var(--surface-2)); border-color: color-mix(in srgb, var(--accent) 30%, var(--border)); } -:global(html[data-theme="dark"] .join-page .qq-join-link:hover) { color: var(--surface-1); background: var(--accent); border-color: var(--accent); } -:global(html[data-theme="dark"] .join-page .field-wrap input::placeholder) { color: var(--text-muted); } -:global(html[data-theme="dark"] .join-page .join-footer) { border-top-color: var(--border); } - -/* Restore the high-contrast dark welcome treatment. The artwork was removed, - so the copy needs its own restrained glow instead of falling back to the - light-theme charcoal colors on the dark surface. */ -:global(html[data-theme="dark"] .join-page .join-copy h1) { - color: #f3fffb; - text-shadow: 0 1px 0 #07100f, 0 0 9px rgba(243, 255, 251, .16); -} -:global(html[data-theme="dark"] .join-page .join-copy h1 em) { - color: #7dffae; - text-shadow: 0 0 10px rgba(125, 255, 174, .38), 0 0 22px rgba(105, 210, 199, .18); - animation-name: join-accent-breathe-dark; -} -:global(html[data-theme="dark"] .join-page .join-description) { - color: #c4d9d3; - text-shadow: 0 0 8px rgba(196, 217, 211, .12); -} -:global(html[data-theme="dark"] .join-page .promise-item b) { - color: #f0fff9; - text-shadow: 0 0 7px rgba(240, 255, 249, .14); -} -:global(html[data-theme="dark"] .join-page .promise-item small) { - color: #a9c6be; -} -:global(html[data-theme="dark"] .join-page .promise-icon) { - box-shadow: 0 0 12px rgba(105, 210, 199, .14); -} - /* M007 whisper target controls and M008 mobile navigation. */ .whisper-strip { display: flex; align-items: center; gap: 12px; margin-top: 18px; padding: 12px 14px; color: #52645e; border: 1px solid #d6ebe5; border-radius: 10px; background: #eef8f5; } .whisper-strip-copy { display: flex; align-items: center; gap: 8px; min-width: 0; flex: 1; } @@ -584,15 +482,12 @@ .mobile-more-panel { min-height: 0; max-height: none; margin-bottom: 0; overflow-y: auto; } } -/* Match every native scroll surface to the WebSpeak palette. */ -:global(*) { scrollbar-color: #8fcfc7 transparent; scrollbar-width: thin; } -:global(*::-webkit-scrollbar) { width: 8px; height: 8px; } -:global(*::-webkit-scrollbar-track) { background: transparent; } -:global(*::-webkit-scrollbar-thumb) { background: #a7d9d2; background-clip: padding-box; border: 2px solid transparent; border-radius: 999px; } -:global(*::-webkit-scrollbar-thumb:hover) { background: #6bbab1; background-clip: padding-box; border-width: 1px; } -:global(:root[data-theme="dark"] *) { scrollbar-color: #438f88 transparent; } -:global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb) { background: #438f88; border-color: transparent; } -:global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb:hover) { background: #69c7bc; } +/* Scroll geometry is shared; scrollbar colors belong to the active skin. */ +.web-client, .web-client * { scrollbar-width: thin; } +.web-client *::-webkit-scrollbar { width: 8px; height: 8px; } +.web-client *::-webkit-scrollbar-track { background: transparent; } +.web-client *::-webkit-scrollbar-thumb { background-clip: padding-box; border: 2px solid transparent; border-radius: 999px; } +.web-client *::-webkit-scrollbar-thumb:hover { background-clip: padding-box; border-width: 1px; } /* Mobile interaction pass: keep the browser viewport fixed and give each mobile surface its own touch-friendly scroll area. */ @@ -618,7 +513,7 @@ .mobile-brand { display: inline; font-size: 18px; } .workspace-actions { flex: 0 0 auto; gap: 3px; } .workspace-actions .header-action { width: 36px; height: 36px; flex-basis: 36px; } - .workspace-actions .theme-toggle, .workspace-actions .workspace-language { display: none; } + .workspace-actions .workspace-skin-switcher, .workspace-actions .workspace-language { display: none; } .disconnect-button { width: 36px; height: 36px; min-height: 36px; margin-left: 0; padding: 0; justify-content: center; } .disconnect-button .ui-icon { display: block; margin: 0; } .disconnect-button span { display: none; } @@ -748,7 +643,6 @@ .join-page .brand-lockup strong { overflow: hidden; font-size: 15px; text-overflow: ellipsis; white-space: nowrap; } .join-page .brand-lockup small { display: none; } .join-page .header-tools { min-width: 0; flex: 0 0 auto; gap: 2px; } - .join-page .header-tools .theme-toggle { display: none; } .join-page .github-button, .join-page .bilibili-button, .join-page .changelog-button, .join-page .guide-button { width: 28px; min-width: 28px; min-height: 28px; height: 28px; padding: 0; } .join-page .github-button, .join-page .bilibili-button, .join-page .changelog-button, .join-page .guide-button { justify-content: center; } .join-page .github-button .ui-icon { width: 16px; height: 16px; } @@ -976,7 +870,7 @@ .dock-hover-panel, .dock-switch-row input, .mobile-noise-toggle input { transition-duration: .01ms; } } -.screen-share-inline-error { display: flex; align-items: center; gap: 7px; margin: 10px 0 0; padding: 8px 10px; color: #a64d47; border: 1px solid color-mix(in srgb, #d96b62 28%, var(--border)); border-radius: 9px; background: color-mix(in srgb, #f7d9d5 45%, var(--surface-1)); font-size: 10px; line-height: 1.4; } +.screen-share-inline-error { display: flex; align-items: center; gap: 7px; margin: 10px 0 0; padding: 8px 10px; color: var(--danger); border: 1px solid color-mix(in srgb, var(--danger) 45%, var(--border)); border-radius: 9px; background: color-mix(in srgb, var(--danger) 12%, var(--surface-1)); font-size: 10px; line-height: 1.4; } .screen-share-avatar-wrap { position: relative; overflow: visible; } .screen-share-live-indicator { position: absolute; top: -16px; right: 50%; z-index: 2; display: inline-flex; align-items: center; gap: 4px; min-height: 17px; padding: 3px 6px 3px 4px; color: #087b6e; border: 1px solid color-mix(in srgb, var(--accent) 28%, var(--border)); border-radius: 999px; background: var(--surface-1); box-shadow: 0 4px 12px color-mix(in srgb, var(--text-primary) 12%, transparent); font-size: 8px; font-weight: 800; line-height: 1; white-space: nowrap; transform: translateX(50%); } .screen-share-live-indicator::before { content: ""; width: 5px; height: 5px; flex: 0 0 5px; border-radius: 50%; background: #55d783; box-shadow: 0 0 0 3px color-mix(in srgb, #55d783 18%, transparent); animation: screen-share-live-dot 1.2s ease-in-out infinite; } diff --git a/web/src/views/AdminView.vue b/web/src/views/AdminView.vue index deec129..80b3746 100644 --- a/web/src/views/AdminView.vue +++ b/web/src/views/AdminView.vue @@ -23,7 +23,7 @@
@@ -34,12 +34,58 @@

{{ tr('serverSettings') }}

{{ tr('serverSettingsLead') }}

-

{{ tr('teamSpeakTarget') }}

{{ testResultTitle }}{{ testResultText }}
-

{{ tr('accessAndIdentity') }}

{{ tr('accessMode') }}
{{ tr('welcomeLanguageHint') }}
{{ tr('welcomeFallbackHint') }}
-

{{ tr('advancedSettings') }}

{{ tr('advancedSettingsLead') }}

{{ tr('webrtcPortRange') }}{{ tr('webrtcPortRangeLead') }}
{{ tr('webrtcApplyHint') }}
-

{{ tr('relaySettings') }}

{{ tr('relaySettingsLead') }}

{{ tr('relayNodeEmpty') }}
{{ tr('relayManagedHint') }}
+
+ + {{ tr('teamSpeakTarget') }}{{ serverForm.address || '—' }} · {{ serverForm.port || '—' }} + + +
+
+
+ + +
+
+ +
+
+ +
{{ testResultTitle }}{{ testResultText }}
+

{{ tr('runtimeFacts') }}

{{ tr('lastTest') }}
{{ formatDate(serverForm.lastTestAt) }}
{{ tr('latency') }}
{{ serverForm.lastTestLatencyMs == null ? '—' : `${serverForm.lastTestLatencyMs} ms` }}
{{ tr('internalPort') }}
3040
+
+
+
+ +
+ + {{ tr('accessAndIdentity') }}{{ serverForm.accessMode === 'fixed' ? tr('fixedMode') : tr('openMode') }} · {{ serverForm.siteName || 'WebSpeak' }} + + +
+
+
{{ tr('accessMode') }}
+
+ +
{{ tr('welcomeLanguageHint') }}
{{ tr('welcomeFallbackHint') }}
+
+
+
+
+ +
+ + {{ tr('advancedSettings') }}{{ tr('advancedSettingsLead') }} + {{ tr('webrtcSettings') }} · {{ serverForm.webRtcEnabled ? tr('enabledStatus') : tr('disabledStatus') }}{{ tr('relaySettings') }} · {{ tr('relayNodeCount', { count: serverForm.relayNodes.length }) }} + + +
+
+

{{ tr('webrtcSettings') }}

{{ tr('webrtcLead') }}

{{ tr('webrtcPortRange') }}{{ tr('webrtcPortRangeLead') }}
{{ tr('webrtcApplyHint') }}
+

{{ tr('relaySettings') }}

{{ tr('relaySettingsLead') }}

{{ tr('relayNodeEmpty') }}
{{ tr('relayManagedHint') }}
+
+
+
-

{{ tr('runtimeFacts') }}

{{ tr('lastTest') }}
{{ formatDate(serverForm.lastTestAt) }}
{{ tr('latency') }}
{{ serverForm.lastTestLatencyMs == null ? '—' : `${serverForm.lastTestLatencyMs} ms` }}
{{ tr('internalPort') }}
3040
@@ -56,6 +102,22 @@
+
+

{{ tr('skinLibrary') }}

{{ tr('skinLibraryLead') }}

+ +
{{ tr('skinLibraryScope') }}
+ +
{{ skinManagerNotice }}
+
{{ tr('loading') }}
+
+
+
v{{ skin.version }}
+

{{ skin.name }}

{{ skin.id }}

{{ skin.description }}

{{ tr('skinAuthor') }}
{{ skin.author }}
{{ tr('skinLicense') }}
{{ skin.license }}
{{ tr('skinMinVersion') }}
{{ skin.minAppVersion }}
{{ tr('skinPreview') }}
+
+
+
{{ tr('skinEmpty') }}

{{ tr('skinEmptyLead') }}

+
+
{{ tr('legacyImported') }}
{{ tr('systemStatus') }}

{{ tr('everythingRunning') }}

{{ tr('overviewLead') }}

{{ tr('running') }}
@@ -74,6 +136,7 @@ import { RouterLink, useRoute, useRouter } from "vue-router"; import Icon from "../components/Icon.vue"; import LanguageSwitcher from "../components/LanguageSwitcher.vue"; import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js"; +import { deleteSkinPackage, uploadSkinPackage, type SkinCatalogEntry } from "../services/skin-catalog.js"; import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js"; type Language = "zh" | "en" | "de" | "ru" | "ja"; @@ -121,6 +184,13 @@ interface AdminLog { timestamp: string | null; level: string; message: string; c interface AdminConnectionRecord { id: string; nickname: string; clientIp: string; target: string; relayName: string | null; relayTarget: string | null; startedAt: string; connectedAt: string | null; disconnectedAt: string | null; durationSeconds: number | null; status: "active" | "connecting" | "disconnected" | "failed"; reason: string | null; failureDetail: string | null } const operationsLoading = ref(false); const terminatingSession = ref(""); +const skinFileInput = ref(null); +const skinEntries = ref([]); +const skinLoading = ref(false); +const skinUploading = ref(false); +const removingSkinId = ref(""); +const skinManagerError = ref(""); +const skinManagerNotice = ref(""); const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 }); const createdInvite = ref<{ token: string; link: string } | null>(null); const webrtcPortNoticeOpen = ref(false); @@ -154,6 +224,23 @@ const copy = { overview: "概览", server: "服务器", operations: "运维", + skinLibrary: "皮肤", + skinLibraryLead: "上传并管理此实例访客可选择的自定义皮肤。", + skinLibraryScope: "皮肤会作为可选项提供给访客;每位访客可在前台自行选择。管理后台始终保持原样式。", + skinUpload: "导入皮肤包", + skinUploading: "正在校验并导入…", + skinEmpty: "尚未导入自定义皮肤", + skinEmptyLead: "选择符合 WebSpeak 皮肤规范的 .wskin 文件开始使用。", + skinAuthor: "作者", + skinLicense: "许可证", + skinMinVersion: "最低版本", + skinPreview: "查看预览", + skinRemove: "移除", + skinRemoving: "正在移除…", + skinConfirmRemove: "确定从此实例中移除此皮肤吗?已选择该皮肤的访客会在下次加载时回退。", + skinReplaceConfirm: "已有同 ID 皮肤。要用这个版本替换吗?", + skinImported: "皮肤已导入并向访客开放。", + skinRemoved: "皮肤已从实例中移除。", openGuest: "打开访客页面", logout: "退出登录", gatewayRunning: "网关运行中", @@ -196,6 +283,9 @@ const copy = { accessAndIdentity: "访问与站点信息", advancedSettings: "高级参数", advancedSettingsLead: "仅在需要时调整网关的高级传输参数。", + enabledStatus: "已启用", + disabledStatus: "未启用", + relayNodeCount: "{{count}} 个节点", webrtcSettings: "WebRTC 语音", webrtcLead: "由当前 WebSpeak 网关直接提供低延迟语音传输,无需配置其他服务器。", webrtcEnabled: "启用 WebRTC", @@ -358,6 +448,23 @@ const copy = { overview: "Overview", server: "Server", operations: "Operations", + skinLibrary: "Skins", + skinLibraryLead: "Upload and manage custom skins available to visitors of this instance.", + skinLibraryScope: "Skins are offered as visitor-selectable options. Each visitor chooses a skin on the public page; the admin console always keeps its own appearance.", + skinUpload: "Import skin package", + skinUploading: "Validating and importing…", + skinEmpty: "No custom skins yet", + skinEmptyLead: "Choose a .wskin package that follows the WebSpeak skin specification.", + skinAuthor: "Author", + skinLicense: "License", + skinMinVersion: "Minimum version", + skinPreview: "Preview", + skinRemove: "Remove", + skinRemoving: "Removing…", + skinConfirmRemove: "Remove this skin from the instance? Visitors using it will fall back the next time they load the page.", + skinReplaceConfirm: "A skin with this ID already exists. Replace it with this package?", + skinImported: "Skin imported and made available to visitors.", + skinRemoved: "Skin removed from the instance.", openGuest: "Open guest page", logout: "Log out", gatewayRunning: "Gateway running", @@ -400,6 +507,9 @@ const copy = { accessAndIdentity: "Access and site identity", advancedSettings: "Advanced settings", advancedSettingsLead: "Adjust gateway transport options only when needed.", + enabledStatus: "Enabled", + disabledStatus: "Disabled", + relayNodeCount: "{{count}} nodes", webrtcSettings: "WebRTC audio", webrtcLead: "Low-latency voice is provided by this WebSpeak gateway; no extra server is required.", webrtcEnabled: "Enable WebRTC", @@ -560,6 +670,23 @@ const germanCopy = { overview: "Übersicht", server: "Server", operations: "Betrieb", + skinLibrary: "Skins", + skinLibraryLead: "Benutzerdefinierte Skins für Besucher dieser Instanz hochladen und verwalten.", + skinLibraryScope: "Skins werden Besuchern zur Auswahl angeboten. Jeder Besucher wählt das Design auf der öffentlichen Seite; die Administrationsoberfläche bleibt unverändert.", + skinUpload: "Skin-Paket importieren", + skinUploading: "Wird geprüft und importiert…", + skinEmpty: "Noch keine benutzerdefinierten Skins", + skinEmptyLead: "Wähle ein .wskin-Paket nach der WebSpeak-Skin-Spezifikation aus.", + skinAuthor: "Autor", + skinLicense: "Lizenz", + skinMinVersion: "Mindestversion", + skinPreview: "Vorschau", + skinRemove: "Entfernen", + skinRemoving: "Wird entfernt…", + skinConfirmRemove: "Diesen Skin aus der Instanz entfernen? Besucher wechseln beim nächsten Laden zurück.", + skinReplaceConfirm: "Ein Skin mit dieser ID ist bereits vorhanden. Durch dieses Paket ersetzen?", + skinImported: "Skin importiert und für Besucher freigegeben.", + skinRemoved: "Skin aus der Instanz entfernt.", openGuest: "Gastseite öffnen", logout: "Abmelden", gatewayRunning: "Gateway läuft", @@ -601,6 +728,9 @@ const germanCopy = { accessAndIdentity: "Zugriff und Website-Informationen", advancedSettings: "Erweiterte Einstellungen", advancedSettingsLead: "Erweiterte Gateway-Transportparameter nur bei Bedarf ändern.", + enabledStatus: "Aktiviert", + disabledStatus: "Deaktiviert", + relayNodeCount: "{{count}} Knoten", webrtcSettings: "WebRTC-Audio", webrtcEnabled: "WebRTC aktivieren", webrtcPortRange: "WebRTC-UDP-Portbereich", @@ -714,6 +844,23 @@ const russianCopy = { overview: "Обзор", server: "Сервер", operations: "Операции", + skinLibrary: "Оформление", + skinLibraryLead: "Загружайте и управляйте оформлением, доступным посетителям этого экземпляра.", + skinLibraryScope: "Оформление предлагается посетителям на выбор; каждый выбирает его на публичной странице. Панель администратора сохраняет собственный стиль.", + skinUpload: "Импортировать пакет оформления", + skinUploading: "Проверка и импорт…", + skinEmpty: "Пользовательское оформление ещё не добавлено", + skinEmptyLead: "Выберите файл .wskin, соответствующий спецификации WebSpeak.", + skinAuthor: "Автор", + skinLicense: "Лицензия", + skinMinVersion: "Мин. версия", + skinPreview: "Предпросмотр", + skinRemove: "Удалить", + skinRemoving: "Удаление…", + skinConfirmRemove: "Удалить оформление из этого экземпляра? При следующей загрузке посетители вернутся к стандартному.", + skinReplaceConfirm: "Оформление с таким ID уже существует. Заменить его этим пакетом?", + skinImported: "Оформление импортировано и доступно посетителям.", + skinRemoved: "Оформление удалено из экземпляра.", openGuest: "Открыть страницу гостя", logout: "Выйти", gatewayRunning: "Шлюз работает", @@ -739,6 +886,9 @@ const russianCopy = { accessAndIdentity: "Доступ и данные сайта", advancedSettings: "Расширенные настройки", advancedSettingsLead: "Изменяйте расширенные параметры передачи только при необходимости.", + enabledStatus: "Включено", + disabledStatus: "Выключено", + relayNodeCount: "Узлов: {{count}}", webrtcEnabled: "Включить WebRTC", relaySettings: "Сервер ретрансляции", relaySettingsLead: "Настройте узлы ретрансляции для ускоренных подключений.", @@ -833,6 +983,23 @@ const japaneseCopy = { overview: "概要", server: "サーバー", operations: "運用", + skinLibrary: "スキン", + skinLibraryLead: "このインスタンスの訪問者が選択できるカスタムスキンを管理します。", + skinLibraryScope: "スキンは訪問者向けの選択肢として公開され、各訪問者が公開ページで選択します。管理画面の外観は変更されません。", + skinUpload: "スキンパッケージを読み込む", + skinUploading: "検証・読み込み中…", + skinEmpty: "カスタムスキンはまだありません", + skinEmptyLead: "WebSpeak スキン仕様に準拠した .wskin ファイルを選択してください。", + skinAuthor: "作者", + skinLicense: "ライセンス", + skinMinVersion: "最低バージョン", + skinPreview: "プレビュー", + skinRemove: "削除", + skinRemoving: "削除中…", + skinConfirmRemove: "このインスタンスからスキンを削除しますか?利用中の訪問者は次回読み込み時に標準へ戻ります。", + skinReplaceConfirm: "同じ ID のスキンがあります。このパッケージで置き換えますか?", + skinImported: "スキンを読み込み、訪問者が選択できるようにしました。", + skinRemoved: "インスタンスからスキンを削除しました。", openGuest: "ゲストページを開く", logout: "ログアウト", gatewayRunning: "ゲートウェイ稼働中", @@ -858,6 +1025,9 @@ const japaneseCopy = { accessAndIdentity: "アクセスとサイト情報", advancedSettings: "詳細設定", advancedSettingsLead: "必要な場合だけゲートウェイの詳細な転送設定を変更します。", + enabledStatus: "有効", + disabledStatus: "無効", + relayNodeCount: "{{count}} ノード", webrtcEnabled: "WebRTC を有効化", relaySettings: "中継サーバー", relaySettingsLead: "高速接続で使用する中継ノードを設定します。", @@ -961,7 +1131,7 @@ const selectedWelcomeDefault = computed(() => serverForm.welcomeDefaults[welcome function tr(key: keyof typeof copy.zh, vars: Record = {}): string { let value: string = language.value === "zh" ? copy.zh[key] : language.value === "de" ? germanCopy[key] ?? copy.en[key] ?? copy.zh[key] : language.value === "ru" ? russianCopy[key] ?? copy.en[key] ?? copy.zh[key] : language.value === "ja" ? japaneseCopy[key] ?? copy.en[key] ?? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; } const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.value.length * 5 + (/[\s\W]/.test(newPassword.value) ? 15 : 0)))); -const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : route.path === "/admin/operations" ? tr('operations') : tr('overview')); +const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : route.path === "/admin/operations" ? tr('operations') : route.path === "/admin/skins" ? tr('skinLibrary') : tr('overview')); const testResultTitle = computed(() => { const result = testResult.value; if (!result) return ""; @@ -988,9 +1158,9 @@ const webrtcPortRangeText = computed(() => `${serverForm.webRtcUdpStart}–${ser onMounted(loadAdminView); watch(() => [serverForm.address, serverForm.port, serverForm.serverPassword, serverForm.passwordAction], () => { if (!testing.value && screen.value === "admin") testResult.value = null; }); -watch(() => route.path, () => { if (screen.value === "admin" && route.path === "/admin/operations") void loadOperations(); }); +watch(() => route.path, () => { if (screen.value === "admin" && route.path === "/admin/operations") void loadOperations(); else if (screen.value === "admin" && route.path === "/admin/skins") void loadSkinCatalog(); }); -async function loadAdminView() { loading.value = true; try { const session = await getJson("/api/admin/session"); if (!session.authenticated) { screen.value = "login"; if (route.path !== "/admin/login") await router.replace("/admin/login"); } else if (session.mustChangePassword) { csrfToken.value = String(session.csrfToken || ""); screen.value = "change-password"; if (route.path !== "/admin/change-password") await router.replace("/admin/change-password"); } else { csrfToken.value = String(session.csrfToken || ""); screen.value = "admin"; if (route.path === "/admin/login" || route.path === "/admin/change-password") await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); if (route.path === "/admin/operations") await loadOperations(); } } catch { errorMessage.value = tr('requestFailed'); } finally { loading.value = false; } } +async function loadAdminView() { loading.value = true; try { const session = await getJson("/api/admin/session"); if (!session.authenticated) { screen.value = "login"; if (route.path !== "/admin/login") await router.replace("/admin/login"); } else if (session.mustChangePassword) { csrfToken.value = String(session.csrfToken || ""); screen.value = "change-password"; if (route.path !== "/admin/change-password") await router.replace("/admin/change-password"); } else { csrfToken.value = String(session.csrfToken || ""); screen.value = "admin"; if (route.path === "/admin/login" || route.path === "/admin/change-password") await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); if (route.path === "/admin/operations") await loadOperations(); if (route.path === "/admin/skins") await loadSkinCatalog(); } } catch { errorMessage.value = tr('requestFailed'); } finally { loading.value = false; } } async function login() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/login", "POST", { username: loginUsername.value, password: loginPassword.value }, false); csrfToken.value = String(result.csrfToken || ""); loginPassword.value = ""; if (result.mustChangePassword) { screen.value = "change-password"; await router.replace("/admin/change-password"); } else { screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } async function changePassword() { errorMessage.value = ""; if (newPassword.value.length < 12) { errorMessage.value = tr('setupPasswordShort'); return; } if (newPassword.value !== confirmNewPassword.value) { errorMessage.value = tr('setupPasswordsMismatch'); return; } submitting.value = true; try { await sendJson("/api/admin/change-password", "POST", { newPassword: newPassword.value }); newPassword.value = ""; confirmNewPassword.value = ""; screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } async function logout() { try { await sendJson("/api/admin/logout", "POST", {}); } finally { csrfToken.value = ""; screen.value = "login"; await router.replace("/admin/login"); } } @@ -1009,6 +1179,52 @@ function addRelayNode() { serverForm.relayNodes.push(createRelayNode()); serverF function removeRelayNode(index: number) { serverForm.relayNodes.splice(index, 1); serverForm.relaySettingsTouched = true; } async function loadServerSettings() { const value = await getJson("/api/admin/server"); const target = splitTeamSpeakTarget(value.target); Object.assign(serverForm, value, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", welcomeTextDe: String(value.welcomeTextDe || ""), welcomeTextRu: String(value.welcomeTextRu || ""), welcomeTextJa: String(value.welcomeTextJa || ""), welcomeDefaults: { ...DEFAULT_WELCOME_TEXTS, ...(value.welcomeDefaults && typeof value.welcomeDefaults === "object" ? value.welcomeDefaults : {}) }, webRtcEnabled: value.webRtcEnabled === true, webRtcUdpStart: Number(value.webRtcUdpStart || 40000), webRtcUdpEnd: Number(value.webRtcUdpEnd || 40099), relayConfigured: value.relayConfigured === true, relayEnabled: value.relayEnabled === true, relayName: String(value.relayName || ""), relayTarget: String(value.relayTarget || ""), relayToken: "", relayTokenAction: "keep", hasRelayToken: value.hasRelayToken === true, relaySettingsTouched: false, relayNodes: mapRelayNodes(value.relayNodes) }); } async function loadOperations() { operationsLoading.value = true; try { const [sessions, invites, diagnostics, logs, audit] = await Promise.all([getJson("/api/admin/sessions"), getJson("/api/admin/invites"), getJson("/api/admin/diagnostics"), getJson("/api/admin/logs?limit=100"), getJson("/api/admin/audit?limit=50")]); operations.sessions = Array.isArray(sessions.sessions) ? sessions.sessions : []; operations.invites = Array.isArray(invites.invites) ? invites.invites : []; operations.diagnostics = { version: String(diagnostics.gateway?.version || ""), node: String(diagnostics.gateway?.node || ""), platform: String(diagnostics.gateway?.platform || ""), arch: String(diagnostics.gateway?.arch || ""), schemaVersion: Number(diagnostics.database?.schemaVersion || 0), createdSessions: Number(diagnostics.sessions?.created || 0) }; operations.logs = { available: Boolean(logs.available), entries: Array.isArray(logs.entries) ? logs.entries : [], sessions: Array.isArray(logs.sessions) ? logs.sessions : [] }; operations.audit = Array.isArray(audit.events) ? audit.events : []; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { operationsLoading.value = false; } } +async function loadSkinCatalog() { + skinLoading.value = true; + skinManagerError.value = ""; + try { + const value = await getJson("/api/admin/skins"); + skinEntries.value = Array.isArray(value.skins) ? value.skins : []; + } catch { + skinManagerError.value = tr("requestFailed"); + } finally { + skinLoading.value = false; + } +} +async function onSkinFileChanged(event: Event) { + const input = event.target as HTMLInputElement; + const file = input.files?.[0]; + if (!file) return; + skinManagerError.value = ""; + skinManagerNotice.value = ""; + skinUploading.value = true; + try { + const result = await uploadSkinPackage(file, csrfToken.value, (id) => !skinEntries.value.some((entry) => entry.id === id) || window.confirm(`${tr("skinReplaceConfirm")}\n${id}`)); + if (!result) return; + skinManagerNotice.value = tr("skinImported"); + await loadSkinCatalog(); + } catch (error) { + skinManagerError.value = error instanceof Error ? error.message : tr("operationFailed"); + } finally { + input.value = ""; + skinUploading.value = false; + } +} +async function removeSkin(skin: SkinCatalogEntry) { + if (!window.confirm(`${tr("skinConfirmRemove")}\n${skin.name} (${skin.id})`)) return; + removingSkinId.value = skin.id; + skinManagerError.value = ""; + skinManagerNotice.value = ""; + try { + await deleteSkinPackage(skin.id, csrfToken.value); + skinManagerNotice.value = tr("skinRemoved"); + await loadSkinCatalog(); + } catch { + skinManagerError.value = tr("operationFailed"); + } finally { + removingSkinId.value = ""; + } +} async function terminateSession(session: AdminSession) { if (!window.confirm(tr('confirmTerminate', { nickname: session.nickname }))) return; terminatingSession.value = session.id; errorMessage.value = ""; try { await sendJson(`/api/admin/sessions/${encodeURIComponent(session.id)}/terminate`, "POST", {}); await Promise.all([loadOperations(), loadOverview()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { terminatingSession.value = ""; } } async function createInvite() { submitting.value = true; errorMessage.value = ""; createdInvite.value = null; try { const result = await sendJson("/api/admin/invites", "POST", { channel: inviteForm.channel, expiresInHours: inviteForm.expiresInHours, maxUses: inviteForm.maxUses }); if (typeof result.token !== "string") throw new Error("INVITE_CREATE_FAILED"); createdInvite.value = { token: result.token, link: `${location.origin}/?invite=${encodeURIComponent(result.token)}` }; inviteForm.channel = ""; await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('confirmRevoke'))) return; try { await sendJson(`/api/admin/invites/${encodeURIComponent(invite.id)}/revoke`, "POST", {}); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } } @@ -1128,77 +1344,6 @@ async function parseResponse(response: Response) { const value = await response. .webrtc-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}.toggle-choice{margin:0}.webrtc-card>.field-help{margin-top:-8px} @media(max-width:520px){.target-fields{grid-template-columns:1fr}} -/* Keep administration inside the browser viewport. Long data sets scroll in - their own cards instead of pushing the whole page below the fold. */ -.admin-shell{height:100dvh;min-height:100dvh;overflow:hidden} -.admin-main{min-height:0;display:flex;flex-direction:column;overflow:hidden} -.admin-topbar{flex:0 0 auto} -.page-content{flex:1 1 auto;min-height:0;overflow-y:auto} -.operations-page{display:flex;flex-direction:column;width:min(1400px,calc(100% - 48px));height:calc(100dvh - 82px);overflow:hidden;padding-top:28px;padding-bottom:18px} -.operations-page .page-heading{flex:0 0 auto;margin-bottom:16px} -.operations-page .system-notice{flex:0 0 auto;margin-bottom:12px} -.operations-page .operations-grid{min-width:0;min-height:0} -.operations-primary{flex:0 0 auto;grid-template-columns:minmax(0,1.2fr) minmax(360px,.8fr)} -.operations-primary>.operation-card{min-height:0;overflow:hidden} -.operations-primary .table-wrap{max-height:190px} -.operations-primary .invite-list{max-height:132px;overflow-y:auto} -.lower-operations{flex:1 1 0;grid-template-columns:minmax(210px,.9fr) minmax(0,1.1fr) minmax(210px,.9fr);margin-top:14px} -.lower-operations>.operation-card{min-height:0} -.diagnostics-card,.logs-card,.audit-card{overflow:hidden} -.diagnostics-card{display:flex;flex-direction:column;overflow-y:auto} -.diagnostics-card .secondary-button{margin-top:auto} -.logs-card,.audit-card{display:flex;flex-direction:column} -.logs-card .log-list,.audit-card .event-list{flex:1 1 0;min-height:0;max-height:none;overflow-y:auto} - -@media(max-width:850px){ - .admin-main{height:100%} - .operations-page{width:min(100% - 28px,700px);height:auto;min-height:calc(100dvh - 82px);overflow:visible} - .operations-page .lower-operations{flex:none} -} - -/* Keep every admin surface inside the viewport. The page content and data - lists are the scroll containers, never the document body. */ -:global(html),:global(body),:global(#app){width:100%;height:100dvh;min-height:0;max-height:100dvh;overflow:hidden} -.admin-root{height:100dvh;min-height:0;overflow:hidden} -.login-page{height:100dvh;min-height:0;overflow:hidden} -.login-card{max-height:calc(100dvh - 50px);overflow-y:auto} - -@media(max-width:850px){ - .admin-shell{display:flex;flex-direction:column} - .admin-main{height:auto;flex:1 1 auto} -} - -/* Keep static admin cards at their own height. Only long data collections - become scroll surfaces, so a busy event feed cannot stretch its neighbour - or turn the whole admin view into a second page. */ -.admin-main>.page-alert{flex:0 0 auto} -.page-content{display:flex;flex:1 1 auto;min-height:0;flex-direction:column;overflow:hidden} -.overview-page{padding:28px 0 18px} -.overview-page .import-notice{flex:0 0 auto;margin-top:0;margin-bottom:12px} -.overview-page .hero-status{flex:0 0 auto;padding:24px} -.overview-page .metric-grid{flex:0 0 auto;gap:12px;margin:14px 0} -.overview-page .metric-grid article{padding:18px} -.overview-page .overview-columns{flex:1 1 0;min-height:0;align-items:stretch;gap:14px} -.target-health-card{align-self:start} -.recent-events-card{display:flex;height:100%;min-height:0;flex-direction:column;overflow:hidden} -.recent-events-card .event-list{flex:1 1 auto;min-height:0;max-height:none;overflow-y:auto} -.server-page{padding:28px 0 18px} -.server-page .page-heading{flex:0 0 auto;margin-bottom:14px} -.server-page .settings-grid{flex:1 1 auto;min-height:0;align-items:stretch;gap:14px} -.server-page .settings-card{min-height:0;overflow-y:auto;padding:20px} -.server-page .readonly-card{flex:0 0 auto;margin-top:14px;padding:16px 20px} -.server-page .readonly-card dl{gap:10px;margin-top:12px} -.operations-page{height:auto;min-height:0} -.operations-primary{flex:0 0 250px} -.operations-primary>.operation-card{overflow-y:auto} -.operations-primary>.operation-card{padding:14px 16px} -.operations-primary .operation-card header p{line-height:1.3} -.operations-primary .invite-form{gap:6px;margin-top:8px} -.operations-primary label>span{margin-bottom:4px} -.operations-primary input{height:34px;padding:7px 10px} -.operations-primary .field-help{margin-top:-4px} -.operations-primary .primary-button{min-height:34px} - /* Theme all native scrollbars used by the admin surfaces. */ :global(*){scrollbar-color:#8fcfc7 transparent;scrollbar-width:thin} :global(*::-webkit-scrollbar){width:8px;height:8px} @@ -1209,25 +1354,6 @@ async function parseResponse(response: Response) { const value = await response. :global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb){background:#438f88;border-color:transparent} :global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb:hover){background:#69c7bc} -@media(max-width:850px){ - .page-content{width:min(100% - 28px,700px);padding-top:20px;padding-bottom:14px} - .overview-page .hero-status{padding:18px} - .overview-page .hero-status h2{font-size:24px} - .overview-page .metric-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:7px;margin:10px 0} - .overview-page .metric-grid article{padding:12px} - .overview-page .metric-grid article>span{top:10px;right:10px;width:28px;height:28px} - .overview-page .metric-grid strong{margin-top:9px;font-size:15px} - .overview-page .overview-columns{grid-template-rows:minmax(0,1fr) minmax(0,1fr);overflow:hidden} - .overview-page .target-health-card{align-self:stretch;min-height:0;overflow-y:auto} - .overview-page .recent-events-card{height:100%} - .server-page .settings-grid{grid-template-columns:1fr;grid-auto-rows:minmax(190px,1fr);overflow-y:auto} - .server-page .readonly-card dl{grid-template-columns:repeat(2,minmax(0,1fr))} - .operations-page{height:100%;overflow:hidden} - .operations-page .operations-primary,.operations-page .lower-operations{grid-template-columns:1fr;min-height:0;overflow-y:auto;align-content:start} - .operations-page .operations-primary{grid-auto-rows:240px} - .operations-page .lower-operations{grid-auto-rows:190px} - .operations-page .lower-operations{flex:1 1 0} -} .advanced-card{grid-column:1 / -1} .advanced-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5} .advanced-card .toggle-choice{margin:0} @@ -1277,63 +1403,21 @@ async function parseResponse(response: Response) { const value = await response. @media(max-width:520px){.advanced-card{grid-column:auto}.port-inputs{grid-template-columns:1fr}} @media(max-width:520px){.welcome-editor-heading{grid-template-columns:1fr;gap:6px}} -/* Server settings are a short form, not a set of independent data feeds. - Let each card keep its natural height so a few extra pixels do not create - three nested scrollbars. The section itself is the only fallback scroll - surface when a small viewport cannot show the complete form. */ -.server-page{overflow-x:hidden;overflow-y:auto} +/* Server settings keep their natural height; the main content area owns scrolling. */ +.server-page{min-width:0} .server-page .settings-grid{flex:0 0 auto;min-height:auto;align-items:start;overflow:visible;grid-auto-rows:auto} .server-page .settings-card{height:auto;min-height:0;overflow:visible;padding:16px;gap:12px} .server-page .settings-card input{height:40px} .server-page .settings-card .choice{padding:10px;gap:8px} .server-page .settings-card .choice small{margin-top:3px} .server-page .webrtc-port-fields{padding:12px;gap:8px} -.server-page .readonly-card{margin-top:12px;padding:14px 16px} -.server-page .readonly-card dl{gap:8px;margin-top:10px} - -@media(max-width:850px){ - .server-page .settings-grid{overflow:visible;grid-auto-rows:auto} - .server-page .settings-card{overflow:visible} -} - -/* Mobile admin pages should read like one continuous form. Keep the desktop - viewport shell untouched, but let the document grow vertically on narrow - screens instead of trapping content inside cards and nested panes. */ -@media(max-width:850px){ - :global(html),:global(body),:global(#app){height:auto;min-height:100%;max-height:none;overflow:auto} - .admin-root{height:auto;min-height:100dvh;overflow:visible} - .admin-shell{height:auto;min-height:100dvh;overflow:visible} - .admin-main{height:auto;min-height:0;overflow:visible} - .page-content{display:block;height:auto;min-height:0;overflow:visible} - .login-page{height:auto;min-height:100dvh;overflow:visible} - .login-card{max-height:none;overflow:visible} - - .overview-page{height:auto;min-height:0;overflow:visible} - .overview-page .overview-columns{grid-template-rows:auto;overflow:visible} - .overview-page .target-health-card,.overview-page .recent-events-card{height:auto;min-height:0;overflow:visible} - .overview-page .recent-events-card .event-list{max-height:none;overflow:visible} - - .server-page{height:auto;min-height:0;overflow:visible} - .server-page .settings-grid{height:auto;overflow:visible} - - .operations-page{height:auto;min-height:0;overflow:visible} - .operations-page .operations-primary,.operations-page .lower-operations{height:auto;min-height:0;overflow:visible;grid-auto-rows:auto;flex:none} - .operations-page .operation-card{height:auto;min-height:0;overflow:visible} - .operations-primary .table-wrap{max-height:none;overflow-x:auto;overflow-y:visible} - .operations-primary .invite-list{max-height:none;overflow:visible} - .logs-card .log-list,.audit-card .event-list{max-height:none;overflow:visible;flex:none} - .logs-card .log-list{width:100%;min-width:0} - .logs-card .log-row{min-width:0;max-width:100%;overflow:hidden} - .logs-card .log-row>div{width:0;max-width:100%;flex:1 1 auto;min-width:0;overflow:hidden} - .logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word} -} /* Long log messages should wrap on every screen size instead of widening the log card or introducing page-level horizontal scrolling. */ .logs-card .log-row{min-width:0} .logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word} -.connection-list{display:grid;gap:7px;max-height:180px;margin-top:12px;overflow-y:auto} +.connection-list{display:grid;gap:7px;margin-top:12px} .connection-history-heading{display:grid;gap:3px;padding:0 0 6px;border-bottom:1px solid #edf1ef} .connection-history-heading strong{font-size:10px} .connection-history-heading small{color:#899792;font-size:8px} @@ -1363,21 +1447,12 @@ async function parseResponse(response: Response) { const value = await response. .language-link{margin-top:20px!important;padding:0!important;background:transparent!important;border:0!important;border-radius:0!important} .login-actions .language-link{margin-top:0!important} -/* Desktop server settings must keep their own scroll surface. The admin shell - is viewport-locked, so an unconstrained flex item can otherwise push the - relay card below the clipped page-content area. */ +/* Flexible fields must be allowed to shrink within responsive columns. */ .settings-card,.relay-card,.relay-node,.relay-fields,.relay-node-heading,.relay-enabled,.relay-fields>label,.password-row,.password-row>label{min-width:0} .relay-enabled strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .relay-fields input{min-width:0} .password-actions{flex:0 0 auto} -@media(min-width:851px){ - .server-page{flex:1 1 auto;min-width:0;min-height:0;overflow-x:hidden;overflow-y:auto} - .server-page .settings-grid{min-width:0} - .settings-grid{grid-template-columns:minmax(0,1fr) minmax(0,1fr)} - .relay-fields{grid-template-columns:minmax(0,1fr) minmax(0,1fr)} -} - /* The application is zoomed up on large displays so the 1920×1080 layout stays readable. Compensate viewport heights for that zoom; otherwise a 2K viewport becomes a 1920px-tall admin shell and clips its lower cards. */ @@ -1386,6 +1461,263 @@ async function parseResponse(response: Response) { const value = await response. :global(#app),.admin-root,.admin-shell,.admin-sidebar{height:calc(100dvh / var(--ui-scale));min-height:calc(100dvh / var(--ui-scale));max-height:calc(100dvh / var(--ui-scale))} .admin-main{height:100%;min-height:0} } + +/* Server settings: stacked, independently collapsible groups with related + controls arranged in columns when there is enough room. */ +.server-page .settings-grid{display:grid;grid-template-columns:minmax(0,1fr);align-content:start;gap:12px;flex:0 0 auto;min-height:0;overflow:visible} +.server-page .settings-accordion{display:block;min-width:0;height:auto;overflow:visible;padding:0;border-radius:13px} +.settings-accordion-header{display:flex;min-height:70px;align-items:center;gap:18px;padding:14px 18px;list-style:none;cursor:pointer} +.settings-accordion-header::-webkit-details-marker{display:none} +.settings-accordion-header:focus-visible{outline:3px solid color-mix(in srgb,var(--admin-accent) 42%,transparent);outline-offset:3px;border-radius:10px} +.settings-accordion-heading{display:grid;min-width:0;flex:1 1 auto;gap:4px} +.settings-accordion-heading strong{overflow:hidden;color:var(--admin-text);font-size:14px;font-weight:800;text-overflow:ellipsis;white-space:nowrap} +.settings-accordion-heading small{overflow:hidden;color:var(--admin-muted);font-size:10px;line-height:1.45;text-overflow:ellipsis;white-space:nowrap} +.settings-accordion-header>.ui-icon{flex:none;color:var(--admin-muted);transition:transform .18s ease} +.settings-accordion[open]>.settings-accordion-header{border-bottom:1px solid var(--admin-border)} +.settings-accordion[open]>.settings-accordion-header>.ui-icon{transform:rotate(180deg)} +.settings-accordion-statuses{display:flex;align-items:center;justify-content:flex-end;gap:7px;flex:0 1 auto;flex-wrap:wrap} +.settings-summary-chip{display:inline-flex;align-items:center;gap:6px;padding:6px 9px;color:var(--admin-muted);background:var(--admin-raised);border:1px solid var(--admin-border);border-radius:999px;font-size:10px;line-height:1.2;white-space:nowrap} +.settings-summary-chip i{width:7px;height:7px;flex:0 0 7px;border-radius:50%;background:#87958f} +.settings-summary-chip i.active{background:#50c879;box-shadow:0 0 0 3px color-mix(in srgb,#50c879 16%,transparent)} +.settings-accordion-content{min-width:0;padding:16px 18px 18px} +.target-settings-layout{display:grid;min-width:0;grid-template-columns:minmax(0,1fr) minmax(220px,280px);align-items:end;gap:12px} +.access-settings-layout,.advanced-settings-grid{display:grid;min-width:0;grid-template-columns:minmax(0,1fr);align-items:start;gap:14px} +.site-identity-fields{display:grid;min-width:0;align-content:start;gap:13px} +.target-fields{grid-column:1;grid-row:1;grid-template-columns:minmax(0,1fr) 150px;gap:12px} +.target-settings-layout>.password-row{grid-column:1/-1;grid-row:2;align-self:end} +.target-settings-layout>.target-test-button{grid-column:2;grid-row:1;justify-self:stretch;width:100%;min-width:0;min-height:40px;align-self:end} +.target-test-result{grid-column:1/-1;min-width:0;margin:0} +.target-runtime-block{display:grid;grid-column:1/-1;grid-template-columns:max-content minmax(0,1fr);align-items:center;gap:12px;padding-top:2px} +.target-runtime-block h4{margin:0;color:var(--admin-text);font-size:11px} +.target-runtime-facts{display:grid;grid-column:2;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:0} +.target-runtime-facts>div{min-width:0;padding:9px;background:var(--admin-surface);border:1px solid var(--admin-border);border-radius:8px} +.target-runtime-facts>div:first-child{grid-column:auto} +.target-runtime-facts dt{color:var(--admin-muted);font-size:9px} +.target-runtime-facts dd{margin:4px 0 0;overflow-wrap:anywhere;color:var(--admin-text);font-size:11px;font-weight:700} +.access-settings-layout{grid-template-columns:minmax(0,1fr)} +.access-mode-fieldset{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr));align-content:start;gap:9px;min-width:0;margin:0;padding:0;border:0} +.access-mode-fieldset legend{grid-column:1/-1;margin-bottom:2px;color:var(--admin-muted);font-size:10px;font-weight:700} +.site-identity-fields>label{display:grid;gap:6px} +.site-identity-fields>label>span,.access-mode-fieldset .choice strong{color:var(--admin-text)} +.site-identity-fields .welcome-editor{min-width:0;margin:0} +.settings-subsection{display:grid;min-width:0;align-content:start;gap:12px;padding:15px;background:var(--admin-raised);border:1px solid var(--admin-border);border-radius:11px} +.settings-subsection-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:12px} +.settings-subsection-heading h4{margin:0;color:var(--admin-text);font-size:13px} +.settings-subsection-heading .card-help{margin:4px 0 0;color:var(--admin-muted);font-size:10px;line-height:1.5} +.settings-subsection .choice{margin:0;background:var(--admin-surface);border-color:var(--admin-border)} +.settings-subsection .choice strong{color:var(--admin-text)} +.settings-subsection .choice small{color:var(--admin-muted)} +.settings-subsection .field-help{margin:0;color:var(--admin-muted);line-height:1.5} +.settings-subsection .relay-fields{grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr))} +.settings-subsection .relay-fields .password-row{grid-column:1/-1} +.advanced-settings-grid>.relay-card,.advanced-settings-grid>.webrtc-card{grid-column:auto} +.settings-subsection .relay-node{background:var(--admin-surface);border-color:var(--admin-border)} +.settings-subsection .relay-empty{color:var(--admin-muted);background:var(--admin-surface);border-color:var(--admin-border)} + +/* One palette is shared by explicit dark mode and system dark mode. */ +.admin-root{--admin-page:#f4f8f6;--admin-surface:#fff;--admin-raised:#f6f9f8;--admin-field:#fff;--admin-text:#20302c;--admin-muted:#657873;--admin-border:#dfe8e5;--admin-accent:#087d74;--admin-accent-soft:#e4f3ef;color:var(--admin-text);background:var(--admin-page)} +:global(html[data-theme="dark"] .admin-root){--admin-page:#101918;--admin-surface:#172321;--admin-raised:#202f2c;--admin-field:#111d1b;--admin-text:#e8f3f0;--admin-muted:#b6c8c2;--admin-border:#3a514b;--admin-accent:#79ddd1;--admin-accent-soft:#1b3935} +@media(prefers-color-scheme:dark){:global(html[data-theme="system"] .admin-root){--admin-page:#101918;--admin-surface:#172321;--admin-raised:#202f2c;--admin-field:#111d1b;--admin-text:#e8f3f0;--admin-muted:#b6c8c2;--admin-border:#3a514b;--admin-accent:#79ddd1;--admin-accent-soft:#1b3935}} +.admin-root .admin-main{color:var(--admin-text);background:var(--admin-page)} +.admin-root .admin-topbar,.admin-root .settings-card,.admin-root .readonly-card,.admin-root .overview-card,.admin-root .operation-card,.admin-root .metric-grid article,.admin-root .setup-card,.admin-root .login-card{color:var(--admin-text);background:var(--admin-surface);border-color:var(--admin-border)} +.admin-root .settings-card h3,.admin-root .settings-card h4,.admin-root .readonly-card h3,.admin-root .overview-card h3,.admin-root .operation-card h3,.admin-root .page-heading h2,.admin-root .admin-topbar h1,.admin-root .settings-card label>span,.admin-root .settings-card legend,.admin-root .settings-card .choice strong{color:var(--admin-text)} +.admin-root .page-heading p,.admin-root .admin-topbar small,.admin-root .settings-card .card-help,.admin-root .settings-card .field-help,.admin-root .settings-card .choice small,.admin-root .settings-card .welcome-editor-heading>small,.admin-root .settings-card .port-fields-heading small,.admin-root .readonly-card dt,.admin-root .overview-card dt,.admin-root .metric-grid small,.admin-root .metric-grid em,.admin-root .overview-card header p,.admin-root .operation-card header p{color:var(--admin-muted)} +.admin-root input:not([type="checkbox"]):not([type="radio"]),.admin-root textarea,.admin-root select{color:var(--admin-text);background:var(--admin-field);border-color:var(--admin-border)} +.admin-root input::placeholder,.admin-root textarea::placeholder{color:var(--admin-muted);opacity:1} +.admin-root input:disabled,.admin-root textarea:disabled,.admin-root select:disabled{color:var(--admin-muted);background:var(--admin-raised);border-color:var(--admin-border);opacity:1} +.admin-root input[type="checkbox"],.admin-root input[type="radio"]{accent-color:var(--admin-accent)} +.admin-root .settings-card .choice{color:var(--admin-text);background:var(--admin-raised);border-color:var(--admin-border)} +.admin-root .settings-card .choice.selected{background:color-mix(in srgb,var(--admin-accent) 10%,var(--admin-surface));border-color:color-mix(in srgb,var(--admin-accent) 48%,var(--admin-border))} +.admin-root .welcome-editor,.admin-root .webrtc-port-fields,.admin-root .relay-node,.admin-root .relay-empty,.admin-root .readonly-card dl div,.admin-root .overview-card dl div,.admin-root .event-list li,.admin-root .connection-row,.admin-root .connection-history-heading,.admin-root .diagnostic-list div,.admin-root .log-row,.admin-root .invite-row{color:var(--admin-text);background:var(--admin-raised);border-color:var(--admin-border)} +.admin-root .welcome-editor select,.admin-root .welcome-editor textarea{color:var(--admin-text);background:var(--admin-field);border-color:var(--admin-border)} +.admin-root .welcome-editor-heading>small,.admin-root .port-fields-heading small,.admin-root .field-help,.admin-root .relay-empty,.admin-root .target-runtime-facts dt,.admin-root .connection-person small,.admin-root .connection-detail small,.admin-root .connection-history-heading small,.admin-root .diagnostic-list dt,.admin-root .log-row small,.admin-root .invite-row small{color:var(--admin-muted)} +.admin-root .settings-subsection{color:var(--admin-text);background:var(--admin-raised);border-color:var(--admin-border)} +.admin-root .target-runtime-facts>div,.admin-root .settings-subsection .choice,.admin-root .settings-subsection .relay-node,.admin-root .settings-subsection .relay-empty{background:var(--admin-surface);border-color:var(--admin-border)} +.admin-root .password-actions button{color:var(--admin-accent);background:var(--admin-accent-soft)} +.admin-root .password-actions button.active,.admin-root .primary-button{color:#fff;background:#087d74} +.admin-root .password-actions button.danger,.admin-root .danger-button,.admin-root .text-danger{color:#d66d65;background:color-mix(in srgb,#d66d65 12%,var(--admin-surface));border-color:color-mix(in srgb,#d66d65 30%,var(--admin-border))} +.admin-root .secondary-button,.admin-root .admin-topbar button,.admin-root .admin-topbar .language-select,.admin-root .home-link{color:var(--admin-accent);background:var(--admin-accent-soft);border-color:var(--admin-border)} +.admin-root .settings-accordion-header>.ui-icon{color:var(--admin-muted)} +.admin-root .settings-summary-chip{color:var(--admin-muted);background:var(--admin-raised);border-color:var(--admin-border)} +.admin-root .admin-sidebar nav a{color:#c2d8d3} +.admin-root .admin-sidebar nav a.active{color:#eafffb;background:#0d615a} + +@media(max-width:1050px){ + .target-settings-layout{grid-template-columns:minmax(0,1fr) minmax(0,1fr)} + .target-fields,.target-test-result,.target-runtime-block{grid-column:1/-1} + .target-settings-layout>.password-row{grid-column:1} + .target-settings-layout>.target-test-button{grid-column:2} + .access-settings-layout,.advanced-settings-grid{grid-template-columns:minmax(0,1fr)} +} +@media(max-width:850px){ + .server-page .settings-grid{grid-template-columns:minmax(0,1fr);grid-auto-rows:auto;overflow:visible} + .settings-accordion-header{min-height:64px;gap:10px;padding:12px 14px} + .settings-accordion-statuses{justify-content:flex-start} + .settings-accordion-content{padding:13px 14px 15px} + .settings-subsection .relay-fields{grid-template-columns:minmax(0,1fr)} + .settings-subsection .relay-fields .password-row{grid-column:auto} +} +@media(max-width:560px){ + .settings-accordion-header{align-items:flex-start;flex-wrap:wrap} + .settings-accordion-heading{flex-basis:calc(100% - 34px)} + .settings-accordion-statuses{order:3;width:100%;padding-right:25px} + .settings-accordion-header>.ui-icon{margin-left:auto} + .target-settings-layout{grid-template-columns:minmax(0,1fr)} + .target-fields,.port-inputs,.target-runtime-facts{grid-template-columns:minmax(0,1fr)} + .target-settings-layout>.password-row,.target-settings-layout>.target-test-button,.target-test-result,.target-runtime-block{grid-column:1} + .target-runtime-facts>div:first-child{grid-column:auto} + .target-runtime-block{grid-template-columns:minmax(0,1fr)} + .target-runtime-facts{grid-column:auto} + .target-settings-layout,.access-settings-layout,.advanced-settings-grid{gap:11px} + .access-mode-fieldset .choice{padding:10px} +} + +/* Admin layout contract: the desktop shell stays in the viewport, the main + content is the only page-level scroller, and cards size to their content. */ +:global(html),:global(body),:global(#app){width:100%;height:100dvh;min-height:0;max-height:100dvh;overflow:hidden} +.admin-root{min-height:0;overflow:hidden} +.admin-shell{display:grid;min-height:0;grid-template-columns:236px minmax(0,1fr);overflow:hidden} +.admin-main{display:flex;min-width:0;min-height:0;flex-direction:column;overflow:hidden} +.admin-topbar{flex:0 0 auto} +.admin-main>.page-alert{flex:0 0 auto;margin:12px clamp(18px,2.4vw,44px) 0} +.page-content{display:block;flex:1 1 auto;width:100%;max-width:none;min-width:0;min-height:0;margin:0;padding:clamp(18px,2vw,32px) clamp(18px,2.4vw,44px) 34px;overflow-x:hidden;overflow-y:auto} +.login-page{height:100dvh;min-height:0;overflow:hidden} +.login-card{max-height:calc(100dvh - 50px);overflow-y:auto} + +.overview-page{display:grid;align-content:start;grid-template-columns:minmax(0,1fr);gap:14px} +.overview-page .import-notice,.overview-page .metric-grid{margin:0} +.overview-page .hero-status{padding:clamp(18px,2vw,28px)} +.overview-page .metric-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:14px} +.overview-page .overview-columns{display:grid;grid-template-columns:minmax(0,1fr);align-content:start;gap:14px} +.overview-page .overview-card{min-width:0;height:auto;min-height:0;overflow:visible} +.overview-page .target-health-card dl{grid-template-columns:repeat(3,minmax(0,1fr))} +.overview-page .recent-events-card .event-list{grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr));max-height:none;overflow:visible} + +.server-page{min-width:0} +.server-page .settings-grid{grid-template-columns:minmax(0,1fr);align-content:start;gap:12px} +.server-page .settings-card{height:auto;min-height:0;overflow:visible} + +.operations-page{display:grid;align-content:start;gap:14px;width:auto;height:auto;min-height:0;padding-top:0;padding-bottom:0} +.operations-page .page-heading,.operations-page .system-notice{margin:0} +.operations-page .operations-grid{min-width:0;align-items:start;gap:14px} +.operations-primary{grid-template-columns:repeat(auto-fit,minmax(min(100%,400px),1fr))} +.lower-operations{grid-template-columns:repeat(auto-fit,minmax(min(100%,340px),1fr));margin-top:0} +.operation-card{height:auto;min-height:0;overflow:visible} +.operation-empty{min-height:84px} +.operations-primary .table-wrap{max-height:min(42vh,420px);overflow:auto} +.operations-primary .invite-list{max-height:min(32vh,280px);overflow-y:auto} +.connection-list{max-height:min(34vh,280px);overflow-y:auto} +.logs-card .log-list,.audit-card .event-list{max-height:min(38vh,340px);overflow-y:auto} +.logs-card,.audit-card{min-height:0} +.logs-card .log-row{min-width:0;max-width:100%} +.logs-card .log-row>div{min-width:0;flex:1 1 auto} +.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word} + +@media(min-width:1101px){ + .operations-page .invite-form{grid-template-columns:minmax(220px,1.2fr) minmax(280px,1fr) auto;align-items:end;gap:12px 16px} + .operations-page .invite-form>label{grid-column:1;grid-row:1} + .operations-page .invite-form-grid{grid-column:2;grid-row:1;align-self:end} + .operations-page .invite-form>.field-help{grid-column:1/3;grid-row:2} + .operations-page .invite-form>.primary-button{grid-column:3;grid-row:1;white-space:nowrap} + .operations-page .diagnostics-card{display:grid;grid-template-columns:minmax(0,1fr)} + .operations-page .diagnostics-card>header{grid-column:1/-1} + .operations-page .diagnostics-card>.diagnostic-list{grid-column:1;grid-row:2} + .operations-page .diagnostics-card>.secondary-button{grid-column:1;grid-row:3;justify-self:end;white-space:nowrap} +} + +@media(max-width:1100px){ + .target-settings-layout{grid-template-columns:minmax(0,1fr) minmax(180px,.42fr)} + .target-fields{grid-column:1;grid-row:1;grid-template-columns:minmax(0,1fr) 132px} + .target-settings-layout>.password-row{grid-column:1/-1;grid-row:2} + .target-settings-layout>.target-test-button{grid-column:2;grid-row:1} + .access-settings-layout,.advanced-settings-grid{grid-template-columns:minmax(0,1fr)} +} +@media(max-width:850px){ + :global(html),:global(body),:global(#app){height:auto;min-height:100%;max-height:none;overflow:auto} + .admin-root{height:auto;min-height:100dvh;overflow:visible} + .admin-shell{display:flex;height:auto;min-height:100dvh;flex-direction:column;overflow:visible} + .admin-sidebar{position:static;width:100%;height:auto;min-height:0;flex-direction:row;align-items:center;padding:12px 16px} + .admin-sidebar .admin-brand{padding:0} + .admin-sidebar .admin-brand small{display:none} + .admin-sidebar nav{display:flex;margin-left:auto} + .sidebar-bottom{display:flex;margin:0 0 0 8px;padding:0;border:0} + .sidebar-bottom a{display:none} + .sidebar-bottom button{font-size:0} + .admin-main{height:auto;min-height:0;overflow:visible} + .admin-topbar{min-height:68px;padding:0 18px} + .admin-main>.page-alert{margin:10px 14px 0} + .page-content{display:block;width:100%;height:auto;min-height:0;padding:20px clamp(14px,3vw,28px) 28px;overflow:visible} + .login-page{height:auto;min-height:100dvh;overflow:visible} + .login-card{max-height:none;overflow:visible} + .overview-page{min-height:0} + .overview-page .metric-grid{grid-template-columns:repeat(auto-fit,minmax(min(100%,210px),1fr));gap:9px} + .overview-page .overview-columns{grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr))} + .operations-page .operations-primary{grid-template-columns:repeat(auto-fit,minmax(min(100%,360px),1fr))} + .operations-page .lower-operations{grid-template-columns:repeat(auto-fit,minmax(min(100%,320px),1fr))} + .operations-page .operation-card{height:auto;min-height:0;overflow:visible} + .operations-primary .table-wrap{max-height:min(48vh,420px);overflow:auto} + .operations-primary .invite-list{max-height:min(38vh,320px);overflow-y:auto} + .connection-list{max-height:min(38vh,320px);overflow-y:auto} + .logs-card .log-list,.audit-card .event-list{max-height:min(45vh,380px);overflow-y:auto} +} +@media(max-width:560px){ + .admin-topbar{gap:8px} + .admin-topbar>div:last-child{gap:5px} + .overview-page .hero-status{padding:18px} + .overview-page .hero-status h2{font-size:24px} + .overview-page .metric-grid article{padding:14px} + .overview-page .metric-grid article>span{top:11px;right:11px;width:30px;height:30px} + .overview-page .metric-grid strong{margin-top:10px;font-size:16px} + .overview-page .target-health-card dl{grid-template-columns:repeat(auto-fit,minmax(min(100%,190px),1fr))} + .operations-page .operations-primary,.operations-page .lower-operations{grid-template-columns:minmax(0,1fr)} + .operations-page .operation-card{padding:16px} + .operations-page .table-wrap{margin-right:-16px;margin-left:-16px;margin-bottom:-16px} + .operations-page .invite-form-grid,.operations-page .diagnostic-list{grid-template-columns:minmax(0,1fr)} + .operations-page .generated-link{display:grid} + .operations-page .invite-row{align-items:flex-start;flex-direction:column} + .operations-page .invite-row-meta{width:100%;justify-content:flex-end} + .operations-page .connection-row{display:grid;gap:7px} + .operations-page .connection-detail{justify-items:start;text-align:left} + .target-settings-layout{grid-template-columns:minmax(0,1fr)} + .target-fields,.port-inputs,.target-runtime-facts{grid-template-columns:minmax(0,1fr)} + .target-fields{grid-column:1;grid-row:1} + .target-settings-layout>.password-row{grid-column:1;grid-row:2} + .target-settings-layout>.target-test-button{grid-column:1;grid-row:3;justify-self:stretch;width:100%} + .target-test-result{grid-column:1;grid-row:4} + .target-runtime-block{grid-column:1;grid-row:5} + .target-runtime-block{grid-template-columns:minmax(0,1fr)} + .target-runtime-facts{grid-column:auto} +} + + + diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index d6e884e..3ab3027 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -1,29 +1,27 @@