From 274bd81dc38a2055bf86e1a0c427b853e9d253c9 Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:53:26 +0800 Subject: [PATCH] Fix workshop installs and make plugin configuration editable --- README.md | 3 + docs/PLUGIN_DEVELOPMENT.md | 4 +- docs/SKIN_DEVELOPMENT.md | 2 +- src/admin/skin-store.ts | 4 +- src/plugins/store.ts | 7 +- web/src/components/admin/AdminPlugins.vue | 88 ++++++++++++++- .../components/admin/PluginConfigValue.vue | 102 +++++++++++++++++ web/src/composables/useAdminPlugins.ts | 103 ++++++++++++++++-- web/src/composables/useAdminSkins.ts | 2 + web/src/i18n/plugins.ts | 75 +++++++++++-- web/src/i18n/skin-store.ts | 5 + web/test/plugins.integration.test.ts | 11 +- web/test/skin-store.test.ts | 15 ++- 13 files changed, 389 insertions(+), 32 deletions(-) create mode 100644 web/src/components/admin/PluginConfigValue.vue diff --git a/README.md b/README.md index 0434218..cb1ef80 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,9 @@ The skills complete the contribution workflow automatically: publish validated s - [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。 - [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。 +- [Jh_Harry](https://github.com/JhHarry) — [Persona 3](https://github.com/JhHarry/webspeak-skin-persona3)、[Persona 4](https://github.com/JhHarry/webspeak-skin-persona4) 和 [Persona 5](https://github.com/JhHarry/webspeak-skin-persona5) 的皮肤样式、构建脚本与打包。Theme styles, build scripts, and packaging for the three Persona skins. +- [OddTurtleHead](https://github.com/OddTurtleHead) — [PR #57](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/57) 为皮肤开放宿主装饰的定制接口,完善独立皮肤恢复入口,并提供两套示例皮肤。Host chrome theming, a protected skin recovery control, and two example skins. + ## 许可证 · License diff --git a/docs/PLUGIN_DEVELOPMENT.md b/docs/PLUGIN_DEVELOPMENT.md index b33fe15..baeeb54 100644 --- a/docs/PLUGIN_DEVELOPMENT.md +++ b/docs/PLUGIN_DEVELOPMENT.md @@ -135,7 +135,9 @@ export default async function activate({ dataDir, config, publicConfig, events, ## 分发与验证 -[分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 目录为 `{"schemaVersion":2,"plugins":[{"id":"community.my-app","repository":"https://github.com/OWNER/REPO","metadataPath":"plugin.json"}]}`。插件仓库 `plugin.json` 包含同一 `manifest` 和 `package:{ref,path,sha256}`。`ref` 使用固定提交/不可变标签,`path` 指向已提交包,SHA-256 为包原始字节哈希。宿主限制 GitHub 内容来源、核验哈希与 manifest;目录或安装修订改变会拒绝覆盖,需重新加载。空目录不默认安装插件。 +[分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 目录为 `{"schemaVersion":2,"plugins":[{"id":"community.my-app","repository":"https://github.com/OWNER/REPO","metadataPath":"plugin.json"}]}`。插件仓库 `plugin.json` 包含 `manifest` 和 `package:{ref,path,sha256}`。`ref` 使用固定提交/不可变标签,`path` 指向已提交包,SHA-256 为包原始字节哈希。实例安装时校验包哈希、API 版本、插件 ID、版本、作用域集合与前后端入口。商店展示 `plugin.json` 里的名称、描述、作者和许可证,实例安装后展示包内清单里的值。目录或安装修订改变时需重新加载。空目录不默认安装插件。 + +需要后台配置的插件应在仓库 README 写明公开与私密字段的用途、必填项、凭据获取方式,并提供用占位符的 JSON 示例。管理员可从已安装插件的高级配置打开仓库说明。 验证实际构建包的导入、审核、启用、自定义 HTTP/WS、依赖加载、持久化和关闭/断线/禁用/更新撤销;检查明暗、语言、窄屏。协作另测两位真实参与者及并发/离开/重连。区分模拟身份、真实 TS、浏览器交互与跨网络证据。宿主回归:`npm run verify`。 diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index 0cc50b1..c306b8a 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -68,7 +68,7 @@ v3 保留安全的标准元素和属性白名单;组件可通过完整页面 s } ``` -`package.ref` 使用已发布 tag 或完整提交 SHA,`path` 指向该 ref 中的 `.wskin` 文件。推荐 tag 一经发布不再移动。`skin.json` 必须与归档清单的 ID、名称、版本、作者、许可证和最低应用版本一致。版本和最低应用版本使用语义化版本;`description` 必须是字符串,可以留空。仓库无需提供 GitHub 令牌,实例从 GitHub 的公开原始文件服务读取;不支持私有仓库、任意下载域名或重定向。 +`package.ref` 使用已发布 tag 或完整提交 SHA,`path` 指向该 ref 中的 `.wskin` 文件。推荐 tag 一经发布不再移动。`skin.json` 必须与归档清单的 ID、版本和最低应用版本一致。商店展示 `skin.json` 中的名称、作者和许可证,安装后的实例皮肤展示归档清单中的值。版本和最低应用版本使用语义化版本;`description` 必须是字符串,可以留空。仓库无需提供 GitHub 令牌,实例从 GitHub 的公开原始文件服务读取;不支持私有仓库、任意下载域名或重定向。 发布步骤:先构建并用客户端和服务端导入器验证最终归档;计算 SHA-256;提交源码、归档、许可证和 `skin.json`;为这个提交创建版本 tag;最后提交中央索引条目。后续更新只需在皮肤仓库发布新版本并更新默认分支的 `skin.json`,无需同步修改中央索引。安装时服务端重新检查索引及元数据,核对摘要并运行普通 `.wskin` 校验;校验失败不替换实例皮肤。同 ID 已安装且版本相同或更新时,不提供覆盖或降级操作。多个管理员同时修改实例皮肤时,过期的安装请求会被拒绝,需刷新后重试。 diff --git a/src/admin/skin-store.ts b/src/admin/skin-store.ts index 9e818b6..4ee5e80 100644 --- a/src/admin/skin-store.ts +++ b/src/admin/skin-store.ts @@ -134,8 +134,8 @@ export class SkinStore { const bytes = await this.download(`${source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/")}/${metadata.package.ref}/${metadata.package.path}`, MAX_PACK_BYTES); if (createHash("sha256").update(bytes).digest("hex") !== metadata.package.sha256) return fail("SKIN_STORE_CHECKSUM"); const { manifest } = validateSkinArchive(bytes, input.id); - for (const key of ["id", "name", "version", "author", "license", "minAppVersion"] as const) { - if (manifest[key] !== metadata[key]) return fail("SKIN_STORE_PACKAGE_MISMATCH"); + if (manifest.version !== metadata.version || manifest.minAppVersion !== metadata.minAppVersion) { + return fail("SKIN_STORE_PACKAGE_MISMATCH"); } return registry.save(bytes, input.id); } diff --git a/src/plugins/store.ts b/src/plugins/store.ts index 85bbcc6..6247924 100644 --- a/src/plugins/store.ts +++ b/src/plugins/store.ts @@ -72,7 +72,12 @@ export class PluginStore { pluginAssert(createHash("sha256").update(bytes).digest("hex") === metadata.descriptor.sha256, "PLUGIN_CHECKSUM"); let value: unknown; try { value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch { throw new PluginError("PLUGIN_INVALID"); } - const pack = parsePluginPackage(value); pluginAssert(JSON.stringify(pack.manifest) === JSON.stringify(metadata.manifest), "PLUGIN_PACKAGE_MISMATCH"); + const pack = parsePluginPackage(value); + const actual = pack.manifest, listed = metadata.manifest; + pluginAssert(actual.id === listed.id && actual.version === listed.version + && actual.client.entry === listed.client.entry && actual.server?.entry === listed.server?.entry + && actual.scopes.length === listed.scopes.length && actual.scopes.every(scope => listed.scopes.includes(scope)), + "PLUGIN_PACKAGE_MISMATCH"); return registry.install(pack, input.installedRevision as string | null); } } diff --git a/web/src/components/admin/AdminPlugins.vue b/web/src/components/admin/AdminPlugins.vue index 0fa1a9b..e6c9ac3 100644 --- a/web/src/components/admin/AdminPlugins.vue +++ b/web/src/components/admin/AdminPlugins.vue @@ -9,7 +9,7 @@
- +

{{ notice }}

{{ tab==='store'?text('discover'):tr('installed') }}

{{ text('source') }}
GitHub ↗
@@ -19,20 +19,79 @@
API {{ entry.manifest?.apiVersion ?? '—' }}

{{ entry.manifest?.name ?? entry.id }}

v{{ entry.manifest?.version ?? '—' }}

{{ entry.manifest?.author }} · {{ entry.manifest?.license }}

{{ entry.manifest?.description }}

{{ tr(scope) }}
{{ tr('client') }}{{ tr('backend') }}

{{ entry.error }}

- +

{{ plugin.manifest.name }}

v{{ plugin.manifest.version }} · {{ plugin.manifest.author }}

{{ tr(plugin.runtime?.state ?? 'disabled') }}
-

{{ plugin.manifest.description }}

{{ tr(plugin.settings.scope) }}{{ plugin.manifest.license }}API {{ plugin.manifest.apiVersion }}
+

{{ plugin.manifest.description }}

{{ tr(plugin.settings.scope) }}{{ plugin.manifest.license }}API {{ plugin.manifest.apiVersion }}{{ tr('viewRepository') }} ↗
{{ text('configure') }}
{{ tr('enabled') }}

{{ text('review') }}

{{ tr('enableNote') }}

-
{{ text('advanced') }}
+
+ {{ text('advanced') }} + + +
@@ -44,18 +103,30 @@ diff --git a/web/src/composables/useAdminPlugins.ts b/web/src/composables/useAdminPlugins.ts index 14de453..f25bdb5 100644 --- a/web/src/composables/useAdminPlugins.ts +++ b/web/src/composables/useAdminPlugins.ts @@ -1,23 +1,104 @@ import { reactive, ref, shallowRef } from 'vue'; import { createAdminRequests } from '../services/admin-requests.js'; -import { isAdminRequestCancelled, type AdminApi } from '../services/admin-api.js'; -import { parsePluginPackage, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type PluginCatalog, type PluginStoreEntry, type PluginRuntimeSettings, type PluginSettingsInput } from '../../../src/shared/plugins.js'; +import { AdminApiError, isAdminRequestCancelled, type AdminApi } from '../services/admin-api.js'; +import { parsePluginPackage, pluginRecord, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type JsonValue, type PluginCatalog, type PluginStoreEntry, type PluginRuntimeSettings, type PluginSettingsInput } from '../../../src/shared/plugins.js'; + +export const musicBotId = 'community.webspeak-tsmb'; +export const musicBotRepository = 'https://github.com/Funvvell/webspeak-plugin-tsmb'; + +interface ConfigField { + key: string; + type: 'url' | 'password' | 'text' | 'number' | 'json' | 'select' | 'boolean'; + placeholder?: string; + choices?: readonly string[]; +} + +export const musicBotPrivateFields: readonly ConfigField[] = [ + {key:'baseUrl',type:'url',placeholder:'http://127.0.0.1:3000'}, + {key:'apiKey',type:'password',placeholder:'tsmb_…'}, + {key:'requestTimeoutMs',type:'number',placeholder:'8000'}, + {key:'connectTimeoutMs',type:'number',placeholder:'4000'}, + {key:'maxResponseBytes',type:'number',placeholder:'1048576'}, + {key:'maxCoverBytes',type:'number',placeholder:'2097152'}, + {key:'coverAllowedHosts',type:'json',placeholder:'[]'}, +]; + +export const musicBotPublicFields: readonly ConfigField[] = [ + {key:'botId',type:'text'}, + {key:'botIdByScope',type:'json',placeholder:'{}'}, + {key:'webUiUrl',type:'url'}, + {key:'controlPolicy',type:'select',choices:['everyone','host','readonly'],placeholder:'everyone'}, + {key:'pollIntervalMs',type:'number',placeholder:'2000'}, + {key:'progressIntervalMs',type:'number',placeholder:'500'}, + {key:'searchLimit',type:'number',placeholder:'20'}, + {key:'searchMaxLimit',type:'number',placeholder:'50'}, + {key:'searchOffsetMax',type:'number',placeholder:'500'}, + {key:'maxQueueDisplay',type:'number',placeholder:'50'}, + {key:'lyricsEnabled',type:'boolean',choices:['true','false'],placeholder:'true'}, + {key:'coverProxyEnabled',type:'boolean',choices:['true','false'],placeholder:'true'}, + {key:'heartbeatMs',type:'number',placeholder:'10000'}, + {key:'idleRoomTTLms',type:'number',placeholder:'1800000'}, + {key:'locale',type:'text',placeholder:'auto'}, +]; + +function makeConfigDraft(fields: readonly ConfigField[], config?: JsonValue): Record { + return Object.fromEntries(fields.map(({key,type}) => { + const value = pluginRecord(config) ? config[key] : undefined; + return [key, value === undefined ? '' : type === 'json' ? JSON.stringify(value) : String(value)]; + })); +} + +function readConfigFields(fields: readonly ConfigField[], draft: Record, existing?: JsonValue): Record { + const config = pluginRecord(existing) ? {...existing} as Record : {}; + for (const {key,type} of fields) { + const input = String(draft[key] ?? '').trim(); + if (!input) { delete config[key]; continue; } + if (type === 'number' || type === 'json' || type === 'boolean') { + try { + const value: JsonValue = JSON.parse(input); + if (type === 'number' && !Number.isSafeInteger(value)) throw new Error(); + if (key === 'coverAllowedHosts' && (!Array.isArray(value) || !value.every(host => typeof host === 'string'))) throw new Error(); + if (key === 'botIdByScope' && (!pluginRecord(value) || !Object.values(value).every(id => typeof id === 'string'))) throw new Error(); + config[key] = value; + } catch { throw new Error(`Invalid value: ${key}`); } + } else { + config[key] = input; + } + } + return config; +} export function useAdminPlugins(api: AdminApi) { const installed=shallowRef([]),catalog=shallowRef(null),runtime=shallowRef(null); const origin=ref(''),busy=ref(false),error=ref(''),catalogError=ref(''),requests=createAdminRequests(); - const drafts=reactive>({}); + const drafts=reactive;privateFields:Record}>>({}); function apply(records:InstalledPlugin[]){ installed.value=records; - for(const record of records)if(!drafts[record.manifest.id])drafts[record.manifest.id]={enabled:record.settings.enabled,trusted:record.settings.trusted,toolbarPinned:record.settings.toolbarPinned,scope:record.settings.scope,targets:record.settings.targets.join('\n'),config:JSON.stringify(record.settings.config,null,2),serverConfigAction:'keep',serverConfig:''}; + for(const record of records)if(!drafts[record.manifest.id]){ + const musicBot = record.manifest.id === musicBotId; + drafts[record.manifest.id]={enabled:record.settings.enabled,trusted:record.settings.trusted,toolbarPinned:record.settings.toolbarPinned,scope:record.settings.scope,targets:record.settings.targets.join('\n'),config:JSON.stringify(record.settings.config,null,2),serverConfigAction:'keep',serverConfig:'',publicFields:musicBot?makeConfigDraft(musicBotPublicFields,record.settings.config):{},privateFields:musicBot?makeConfigDraft(musicBotPrivateFields):{}}; + } for(const id of Object.keys(drafts))if(!records.some(r=>r.manifest.id===id))delete drafts[id]; } async function work(run:(signal:AbortSignal,current:()=>boolean)=>Promise){ if(busy.value)return;const request=requests.begin('plugins');busy.value=true;error.value=''; const timer=setTimeout(()=>{if(request.isCurrent()){error.value='PLUGIN_TIMEOUT';requests.cancel('plugins');busy.value=false;}},90_000); - try{await run(request.signal,request.isCurrent);}catch(e){if(request.isCurrent()&&!isAdminRequestCancelled(e))error.value=e instanceof Error?e.message:'PLUGIN_FAILED';} + try{await run(request.signal,request.isCurrent);}catch(e){if(request.isCurrent()&&!isAdminRequestCancelled(e))error.value=e instanceof AdminApiError?e.code:e instanceof Error?e.message:'PLUGIN_FAILED';} finally{clearTimeout(timer);if(request.isCurrent())busy.value=false;request.finish();} } + function configValue(id: string, key: 'config' | 'serverConfig'): JsonValue { + return JSON.parse(drafts[id][key] || '{}') as JsonValue; + } + function setConfigValue(id: string, key: 'config' | 'serverConfig', value: JsonValue) { + drafts[id][key] = JSON.stringify(value); + } + function musicBotCollection(id: string, section: 'publicFields' | 'privateFields', key: string): JsonValue { + const value = drafts[id][section][key]; + return value ? JSON.parse(value) as JsonValue : key === 'coverAllowedHosts' ? [] : {}; + } + function setMusicBotCollection(id: string, section: 'publicFields' | 'privateFields', key: string, value: JsonValue) { + drafts[id][section][key] = JSON.stringify(value); + } function load(){return work(async(signal,current)=>{ const records=await api.plugins(signal);if(current())apply(records.plugins); const settings=await api.pluginRuntime(signal);if(current()){runtime.value=settings.runtime;origin.value=settings.runtime.publicOrigin;} @@ -29,7 +110,13 @@ export function useAdminPlugins(api: AdminApi) { });} function save(record:InstalledPlugin){return work(async(signal,current)=>{ const draft=drafts[record.manifest.id],captured=JSON.stringify(draft); - const settings:PluginSettingsInput={enabled:draft.enabled,trusted:draft.trusted,toolbarPinned:draft.toolbarPinned,scope:draft.scope,targets:draft.targets.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),config:JSON.parse(draft.config),serverConfigAction:draft.serverConfigAction,...(draft.serverConfigAction==='replace'?{serverConfig:JSON.parse(draft.serverConfig)}:{})}; + const musicBot=record.manifest.id===musicBotId; + const settings:PluginSettingsInput={enabled:draft.enabled,trusted:draft.trusted,toolbarPinned:draft.toolbarPinned,scope:draft.scope,targets:draft.targets.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),config:musicBot?readConfigFields(musicBotPublicFields,draft.publicFields,record.settings.config):JSON.parse(draft.config),serverConfigAction:draft.serverConfigAction}; + if(draft.serverConfigAction==='replace'){ + settings.serverConfig=musicBot?readConfigFields(musicBotPrivateFields,draft.privateFields):JSON.parse(draft.serverConfig); + if(musicBot && pluginRecord(settings.serverConfig) && (typeof settings.serverConfig.apiKey !== 'string' || !/^tsmb_[A-Za-z0-9_-]{20,}$/.test(settings.serverConfig.apiKey))) throw new Error('TSMB_API_KEY_REQUIRED'); + } + if(musicBot && draft.enabled && (draft.serverConfigAction==='remove' || (draft.serverConfigAction==='keep' && !record.settings.hasServerConfig))) throw new Error('TSMB_API_KEY_REQUIRED'); const result=await api.configurePlugin(record.manifest.id,record.revision,settings,signal); if(current()){if(JSON.stringify(drafts[record.manifest.id])===captured)delete drafts[record.manifest.id];apply(installed.value.map(p=>p.manifest.id===record.manifest.id?result.plugin:p));} });} @@ -41,7 +128,7 @@ export function useAdminPlugins(api: AdminApi) { const result=await api.uploadPlugin(pack,installed.value.find(p=>p.manifest.id===pack.manifest.id)?.revision??null,signal); if(current()){delete drafts[pack.manifest.id];apply([...installed.value.filter(p=>p.manifest.id!==pack.manifest.id),result.plugin]);} });} - function cancelRequests(){requests.reset();busy.value=false;for(const draft of Object.values(drafts)){draft.serverConfig='';draft.serverConfigAction='keep';}} + function cancelRequests(){requests.reset();busy.value=false;for(const draft of Object.values(drafts)){draft.serverConfig='';draft.serverConfigAction='keep';for(const key of Object.keys(draft.privateFields))draft.privateFields[key]='';}} function reset(){cancelRequests();installed.value=[];catalog.value=null;runtime.value=null;origin.value='';error.value='';catalogError.value='';for(const id of Object.keys(drafts))delete drafts[id];} - return {installed,catalog,runtime,origin,busy,error,catalogError,drafts,load,install,save,restart,saveRuntime,remove,upload,cancelRequests,reset}; + return {installed,catalog,runtime,origin,busy,error,catalogError,drafts,load,install,save,restart,saveRuntime,remove,upload,cancelRequests,reset,configValue,setConfigValue,musicBotCollection,setMusicBotCollection}; } diff --git a/web/src/composables/useAdminSkins.ts b/web/src/composables/useAdminSkins.ts index 7d93605..62ef41c 100644 --- a/web/src/composables/useAdminSkins.ts +++ b/web/src/composables/useAdminSkins.ts @@ -35,6 +35,8 @@ export function useAdminSkins(options: Options) { const code = error instanceof AdminApiError ? error.code : ""; if (["SKIN_STORE_CHANGED", "SKIN_STORE_INSTALLED_CHANGED", "SKIN_STORE_NOT_NEWER"].includes(code)) return options.tr("skinStoreChanged"); if (code === "SKIN_STORE_INCOMPATIBLE") return options.tr("skinStoreIncompatible"); + if (code === "SKIN_STORE_CHECKSUM") return options.tr("skinStoreChecksum"); + if (code === "SKIN_STORE_PACKAGE_MISMATCH") return options.tr("skinStoreMismatch"); if (code.startsWith("SKIN_") && code !== "SKIN_STORE_UNAVAILABLE" && code !== "SKIN_STORAGE_UNAVAILABLE") return options.tr("skinStoreInvalid"); return options.tr("skinStoreUnavailable"); } diff --git a/web/src/i18n/plugins.ts b/web/src/i18n/plugins.ts index b2eb770..bb701df 100644 --- a/web/src/i18n/plugins.ts +++ b/web/src/i18n/plugins.ts @@ -13,7 +13,7 @@ const en = { "server": "TS server scope", "instance": "WebSpeak instance scope", "targets": "Allowed TS targets (one host:port per line)", - "config": "Public configuration (JSON; visible to users)", + "config": "Public settings", "enabled": "Enable plugin", "lead": "Reviewed applications with standard browser capabilities and optional Node services. Updates require renewed trust.", "empty": "No plugins available", @@ -33,7 +33,18 @@ const en = { "originHelp": "Use a separate HTTPS origin, such as https://apps.example.com, proxying to the runtime port. Blank enables local automatic addressing only.", "trust": "I have reviewed and trust this application and its dependencies", "toolbarPin": "Pin this app in the voice toolbar", - "privateConfig": "Private backend configuration (JSON; encrypted at rest)", + "privateConfig": "Private backend settings (encrypted at rest)", + "privateConfigHelp": "The fields depend on this plugin. Copy the private settings from its setup guide and use Replace secret configuration to save them.", + "musicBotConfigHelp": "Enter the API Key created in TSMusicBot WebUI with a member or administrator account. The baseUrl must be reachable from the WebSpeak server. Optional fields use the plugin defaults when blank.", + "viewRepository": "View repository", + "configDefault": "Use default", + "valueType": "Value type", + "fieldKey": "Field name", + "fieldValue": "Value", + "addField": "Add", + "storeChecksum": "Package checksum differs from the catalog. Refresh the store and retry.", + "storeMismatch": "The package version, scope, or entry points differ from the catalog.", + "setupGuide": "Plugin setup guide", "keep": "Keep existing secret configuration", "replace": "Replace secret configuration", "erase": "Remove secret configuration", @@ -65,7 +76,7 @@ zh:{ "server": "TS 服务器范围", "instance": "WebSpeak 实例范围", "targets": "允许的 TS 地址(每行一个 host:port)", - "config": "公开配置(JSON;用户可见)", + "config": "公开配置", "enabled": "启用插件", "lead": "经审核的应用,可使用标准浏览器能力和可选的 Node 服务。更新后需要重新信任。", "empty": "暂无可用插件", @@ -85,7 +96,18 @@ zh:{ "originHelp": "配置独立的 HTTPS 源,如 https://apps.example.com,并反向代理到运行时端口。留空仅支持本地自动地址。", "trust": "我已审核并信任此应用及其依赖", "toolbarPin": "在语音工具栏中固定此应用", - "privateConfig": "后端私密配置(JSON;加密存储)", + "privateConfig": "后端私密配置(加密存储)", + "privateConfigHelp": "字段由插件定义。按插件仓库里的配置说明填写,在这里选择“替换”后保存。", + "musicBotConfigHelp": "API Key 在 TSMusicBot 自己的 WebUI 用成员或管理员账号创建。baseUrl 填 WebSpeak 服务端能访问的机器人地址。选填项留空时使用插件默认值。", + "viewRepository": "查看仓库", + "configDefault": "使用默认值", + "valueType": "字段类型", + "fieldKey": "字段名", + "fieldValue": "字段值", + "addField": "添加", + "storeChecksum": "安装包的 SHA‑256 与商店记录不符。请刷新商店后重试。", + "storeMismatch": "安装包的版本、作用域或入口与商店记录不一致。", + "setupGuide": "插件配置说明", "keep": "保留现有私密配置", "replace": "替换私密配置", "erase": "删除私密配置", @@ -114,7 +136,7 @@ de:{ "server": "TS-Server-Bereich", "instance": "WebSpeak-Instanz-Bereich", "targets": "Erlaubte TS-Ziele (host:port pro Zeile)", - "config": "Öffentliche Konfiguration (JSON; für Nutzer sichtbar)", + "config": "Öffentliche Einstellungen", "enabled": "Plugin aktivieren", "lead": "Geprüfte Anwendungen mit Browserfunktionen und optionalen Node-Diensten. Updates erfordern erneutes Vertrauen.", "empty": "Keine Plugins verfügbar", @@ -134,7 +156,18 @@ de:{ "originHelp": "Separate HTTPS-Origin, z. B. https://apps.example.com, auf den Runtime-Port weiterleiten. Leer nur für lokale automatische Adressen.", "trust": "Ich habe diese Anwendung und ihre Abhängigkeiten geprüft und vertraue ihnen", "toolbarPin": "Diese App in der Sprachsymbolleiste anheften", - "privateConfig": "Private Backend-Konfiguration (JSON; verschlüsselt gespeichert)", + "privateConfig": "Private Backend-Einstellungen (verschlüsselt gespeichert)", + "privateConfigHelp": "Die Felder hängen vom Plugin ab. Übernehmen Sie die privaten Einstellungen aus der Anleitung und wählen Sie „Ersetzen“.", + "musicBotConfigHelp": "Erstellen Sie den API-Schlüssel in der TSMusicBot-WebUI als Mitglied oder Administrator. baseUrl muss für den WebSpeak-Server erreichbar sein. Leere optionale Felder verwenden Standardwerte.", + "viewRepository": "Repository ansehen", + "configDefault": "Standardwert", + "valueType": "Werttyp", + "fieldKey": "Feldname", + "fieldValue": "Wert", + "addField": "Hinzufügen", + "storeChecksum": "Die Paketprüfsumme weicht vom Katalog ab. Aktualisieren Sie den Store.", + "storeMismatch": "Version, Geltungsbereich oder Einstiegspunkte weichen vom Katalog ab.", + "setupGuide": "Plugin-Konfigurationsanleitung", "keep": "Vorhandene private Konfiguration behalten", "replace": "Private Konfiguration ersetzen", "erase": "Private Konfiguration löschen", @@ -163,7 +196,7 @@ ru:{ "server": "Область TS-сервера", "instance": "Область экземпляра WebSpeak", "targets": "Разрешённые адреса TS (host:port, по одному в строке)", - "config": "Публичные настройки (JSON; видны пользователям)", + "config": "Публичные настройки", "enabled": "Включить плагин", "lead": "Проверенные приложения с возможностями браузера и необязательными сервисами Node. Обновления требуют повторного доверия.", "empty": "Нет доступных плагинов", @@ -183,7 +216,18 @@ ru:{ "originHelp": "Отдельный HTTPS-источник, например https://apps.example.com, с проксированием на порт среды. Пустое поле — только для локальных адресов.", "trust": "Я проверил приложение и зависимости и доверяю им", "toolbarPin": "Закрепить приложение на панели голосовой комнаты", - "privateConfig": "Приватные настройки сервиса (JSON; хранятся зашифрованными)", + "privateConfig": "Приватные настройки сервиса (хранятся зашифрованными)", + "privateConfigHelp": "Поля зависят от плагина. Скопируйте настройки из его инструкции и выберите замену приватных настроек.", + "musicBotConfigHelp": "Создайте API Key в WebUI TSMusicBot под учётной записью участника или администратора. Адрес baseUrl должен быть доступен серверу WebSpeak. Пустые поля используют значения по умолчанию.", + "viewRepository": "Открыть репозиторий", + "configDefault": "По умолчанию", + "valueType": "Тип значения", + "fieldKey": "Имя поля", + "fieldValue": "Значение", + "addField": "Добавить", + "storeChecksum": "Контрольная сумма пакета не совпадает с каталогом. Обновите каталог.", + "storeMismatch": "Версия, область или точки входа пакета не совпадают с каталогом.", + "setupGuide": "Инструкция по настройке плагина", "keep": "Сохранить текущие приватные настройки", "replace": "Заменить приватные настройки", "erase": "Удалить приватные настройки", @@ -212,7 +256,7 @@ ja:{ "server": "TS サーバー範囲", "instance": "WebSpeak インスタンス範囲", "targets": "許可する TS アドレス(1行に host:port)", - "config": "公開設定(JSON、ユーザーに公開)", + "config": "公開設定", "enabled": "有効にする", "lead": "標準ブラウザー機能と任意の Node サービスを使う審査済みアプリです。更新後は再度信頼を確認します。", "empty": "利用できるプラグインがありません", @@ -232,7 +276,18 @@ ja:{ "originHelp": "https://apps.example.com のような別 HTTPS オリジンを実行ポートへ転送します。空欄はローカル自動アドレス専用です。", "trust": "アプリと依存関係を審査し、信頼します", "toolbarPin": "このアプリをボイスツールバーに固定", - "privateConfig": "バックエンドの秘密設定(JSON、暗号化して保存)", + "privateConfig": "バックエンドの秘密設定(暗号化して保存)", + "privateConfigHelp": "設定項目はプラグインごとに異なります。設定ガイドに従い、秘密設定の置換を選んで保存してください。", + "musicBotConfigHelp": "API Key は TSMusicBot WebUI でメンバーまたは管理者として発行します。baseUrl は WebSpeak サーバーから接続できる URL です。任意項目が空欄の場合は既定値が使われます。", + "viewRepository": "リポジトリを見る", + "configDefault": "既定値を使用", + "valueType": "値の種類", + "fieldKey": "項目名", + "fieldValue": "値", + "addField": "追加", + "storeChecksum": "パッケージのチェックサムがカタログと一致しません。ストアを更新してください。", + "storeMismatch": "パッケージのバージョン、スコープ、またはエントリがカタログと一致しません。", + "setupGuide": "プラグイン設定ガイド", "keep": "現在の秘密設定を保持", "replace": "秘密設定を置換", "erase": "秘密設定を削除", diff --git a/web/src/i18n/skin-store.ts b/web/src/i18n/skin-store.ts index 3eb3fb8..f845547 100644 --- a/web/src/i18n/skin-store.ts +++ b/web/src/i18n/skin-store.ts @@ -3,6 +3,7 @@ const zh = { skinStoreSource: "分发索引", skinStoreRefresh: "刷新商店", skinStoreRepository: "查看仓库", skinStoreInstall: "安装", skinStoreUpdate: "更新", skinStoreInstalling: "正在下载并校验…", skinStoreInstalled: "已安装", skinStoreNewer: "本地版本较新", skinStoreEmpty: "商店暂时没有皮肤。", skinStoreIncompatible: "需要更高版本的 WebSpeak", skinStoreUnavailable: "无法访问皮肤仓库,请稍后刷新重试;实例已有皮肤不受影响。", + skinStoreChecksum: "皮肤包的 SHA‑256 与商店记录不符。请刷新商店后重试。", skinStoreMismatch: "皮肤包的版本或最低 WebSpeak 版本与商店记录不一致。", skinStoreInvalid: "仓库元数据或皮肤包校验失败,未安装此皮肤。", skinStoreChanged: "商店或实例皮肤已发生变化,请刷新后重试。", skinStoreConfirm: "要用商店版本替换当前实例中的这个皮肤吗?", skinStoreSuccess: "皮肤已安装,可在“实例皮肤”中管理。", skinStorePermissionNote: "安装不会更改默认皮肤,也不会代替访客批准皮肤组件权限。更新保留实例的启停状态。", @@ -14,6 +15,7 @@ const en = { skinStoreSource: "Distribution index", skinStoreRefresh: "Refresh store", skinStoreRepository: "View repository", skinStoreInstall: "Install", skinStoreUpdate: "Update", skinStoreInstalling: "Downloading and validating…", skinStoreInstalled: "Installed", skinStoreNewer: "Local version is newer", skinStoreEmpty: "No skins are available yet.", skinStoreIncompatible: "Requires a newer WebSpeak version", skinStoreUnavailable: "The skin repository is unavailable. Refresh to retry; installed skins are unaffected.", + skinStoreChecksum: "The package checksum differs from the catalog. Refresh and try again.", skinStoreMismatch: "The package version or minimum WebSpeak version differs from the catalog.", skinStoreInvalid: "Repository metadata or package validation failed. The skin was not installed.", skinStoreChanged: "The store or installed skin has changed. Refresh before retrying.", skinStoreConfirm: "Replace this instance's installed skin with the store version?", skinStoreSuccess: "Skin installed. Manage it under Instance skins.", skinStorePermissionNote: "Installing does not change the default skin or approve component permissions for visitors. Updates preserve the instance's enabled state.", @@ -24,6 +26,7 @@ const de = { skinStoreSource: "Verteilungsindex", skinStoreRefresh: "Store aktualisieren", skinStoreRepository: "Repository öffnen", skinStoreInstall: "Installieren", skinStoreUpdate: "Aktualisieren", skinStoreInstalling: "Download und Prüfung…", skinStoreInstalled: "Installiert", skinStoreNewer: "Lokale Version ist neuer", skinStoreEmpty: "Noch keine Skins verfügbar.", skinStoreIncompatible: "Neuere WebSpeak-Version erforderlich", skinStoreUnavailable: "Skin-Repository nicht erreichbar. Bitte erneut laden; installierte Skins bleiben verfügbar.", + skinStoreChecksum: "Die Paketprüfsumme weicht vom Katalog ab. Bitte aktualisieren und erneut versuchen.", skinStoreMismatch: "Paketversion oder minimale WebSpeak-Version weicht vom Katalog ab.", skinStoreInvalid: "Repository-Metadaten oder Paketprüfung fehlgeschlagen. Der Skin wurde nicht installiert.", skinStoreChanged: "Store oder installierter Skin wurde geändert. Bitte zuerst aktualisieren.", skinStoreConfirm: "Den installierten Skin dieser Instanz durch die Store-Version ersetzen?", skinStoreSuccess: "Skin installiert. Verwaltung unter Instanz-Skins.", skinStorePermissionNote: "Die Installation ändert weder den Standard-Skin noch die Berechtigungen der Besucher. Updates behalten den Aktivierungszustand bei.", @@ -34,6 +37,7 @@ const ru = { skinStoreSource: "Каталог распространения", skinStoreRefresh: "Обновить магазин", skinStoreRepository: "Открыть репозиторий", skinStoreInstall: "Установить", skinStoreUpdate: "Обновить", skinStoreInstalling: "Загрузка и проверка…", skinStoreInstalled: "Установлена", skinStoreNewer: "Локальная версия новее", skinStoreEmpty: "В магазине пока нет тем.", skinStoreIncompatible: "Нужна более новая версия WebSpeak", skinStoreUnavailable: "Репозиторий темы недоступен. Обновите каталог позже; установленные темы продолжат работать.", + skinStoreChecksum: "Контрольная сумма пакета не совпадает с каталогом. Обновите каталог и повторите попытку.", skinStoreMismatch: "Версия пакета или минимальная версия WebSpeak не совпадает с каталогом.", skinStoreInvalid: "Ошибка проверки метаданных или пакета. Тема не установлена.", skinStoreChanged: "Каталог или установленная тема изменились. Обновите данные и повторите попытку.", skinStoreConfirm: "Заменить установленную тему этого экземпляра версией из магазина?", skinStoreSuccess: "Тема установлена. Управление доступно в разделе «Темы экземпляра».", skinStorePermissionNote: "Установка не меняет тему по умолчанию и не выдаёт разрешения за посетителей. Обновления сохраняют состояние включения темы.", @@ -44,6 +48,7 @@ const ja = { skinStoreSource: "配布インデックス", skinStoreRefresh: "ストアを更新", skinStoreRepository: "リポジトリを開く", skinStoreInstall: "インストール", skinStoreUpdate: "更新", skinStoreInstalling: "ダウンロード・検証中…", skinStoreInstalled: "インストール済み", skinStoreNewer: "ローカルのバージョンが新しい", skinStoreEmpty: "公開されているスキンはまだありません。", skinStoreIncompatible: "新しい WebSpeak が必要です", skinStoreUnavailable: "リポジトリに接続できません。後で再読み込みしてください。既存のスキンには影響しません。", + skinStoreChecksum: "パッケージのチェックサムがカタログと一致しません。更新して再試行してください。", skinStoreMismatch: "パッケージのバージョンまたは最低 WebSpeak バージョンがカタログと一致しません。", skinStoreInvalid: "メタデータまたはパッケージの検証に失敗しました。スキンはインストールされていません。", skinStoreChanged: "ストアまたは既存のスキンが変更されました。更新して再試行してください。", skinStoreConfirm: "このインスタンスの既存のスキンをストア版に置き換えますか?", skinStoreSuccess: "インストールしました。「インスタンスのスキン」で管理できます。", skinStorePermissionNote: "デフォルトスキンと訪問者の権限承認は変更しません。更新時も有効・無効の設定を維持します。", diff --git a/web/test/plugins.integration.test.ts b/web/test/plugins.integration.test.ts index ecc546d..fa4c446 100644 --- a/web/test/plugins.integration.test.ts +++ b/web/test/plugins.integration.test.ts @@ -118,9 +118,10 @@ test('v2 admin HTTP requires authentication, origin, CSRF and renewed trust; sec const service=new AdminService(database,Buffer.alloc(32,7),logger,path.join(env.directory,'absent.json'),undefined,'test');await service.initialize();await service.changePassword('runtime-test-password'); const pack=await application(true),bytes=JSON.stringify(pack),digest=createHash('sha256').update(bytes).digest('hex'); let packageBytes=bytes; + let listedManifest={...pack.manifest,name:'Catalog name',author:'Catalog author',license:'Catalog license',description:'Catalog description',scopes:[...pack.manifest.scopes].reverse()}; const store=new PluginStore(async(url)=>{ const address=String(url);if(address.endsWith('/index.json'))return Response.json({schemaVersion:2,plugins:[{id:pack.manifest.id,repository:'https://github.com/example/app'}]}); - if(address.endsWith('/plugin.json'))return Response.json({manifest:pack.manifest,package:{ref:'fixed-commit',path:'packages/app.wplugin',sha256:digest}}); + if(address.endsWith('/plugin.json'))return Response.json({manifest:listedManifest,package:{ref:'fixed-commit',path:'packages/app.wplugin',sha256:digest}}); return new Response(packageBytes); }); const app=express();app.use((req,res,next)=>req.path.startsWith('/api/admin/plugins')?next():express.json()(req,res,next)); @@ -135,7 +136,15 @@ test('v2 admin HTTP requires authentication, origin, CSRF and renewed trust; sec assert.equal((await write({origin})).status,403);assert.equal((await write({origin:'https://other.example','x-csrf-token':csrf})).status,403); const catalog=await api.pluginStore();assert.equal(catalog.entries[0].manifest?.apiVersion,2); packageBytes='tampered';await assert.rejects(api.installPlugin({id:pack.manifest.id,revision:catalog.entries[0].revision,installedRevision:null}),/PLUGIN_CHECKSUM/);packageBytes=bytes; + const original=listedManifest; + for (const change of [{version:'9.0.0'},{server:undefined},{scopes:['instance'] as const}]) { + listedManifest={...original,...change,...(change.scopes?{scopes:[...change.scopes]}:{})}; + const {entries:[entry]}=await api.pluginStore(); + await assert.rejects(api.installPlugin({id:pack.manifest.id,revision:entry.revision,installedRevision:null}),/PLUGIN_PACKAGE_MISMATCH/); + } + listedManifest=original; const installed=(await api.installPlugin({id:pack.manifest.id,revision:catalog.entries[0].revision,installedRevision:null})).plugin;assert.equal(installed.settings.trusted,false); + assert.deepEqual(installed.manifest,pack.manifest); await assert.rejects(api.configurePlugin(pack.manifest.id,installed.revision,{...installed.settings,enabled:true}),/PLUGIN_TRUST_REQUIRED/); const enabled=(await api.configurePlugin(pack.manifest.id,installed.revision,{...installed.settings,enabled:true,trusted:true,scope:'instance',serverConfigAction:'replace',serverConfig:{secret:'private-test-value'}})).plugin; assert.equal(enabled.runtime?.state,'running');assert.equal((await api.restartPlugin(pack.manifest.id,enabled.revision)).plugin.runtime?.state,'running'); diff --git a/web/test/skin-store.test.ts b/web/test/skin-store.test.ts index dfd4336..eaf228b 100644 --- a/web/test/skin-store.test.ts +++ b/web/test/skin-store.test.ts @@ -49,11 +49,18 @@ async function registry(t: test.TestContext) { } test("store installs exact verified packages and preserves enabled/default state on update", async t => { const f = fixture(), store = new SkinStore("0.2.8", f.fetcher), skins = await registry(t); + f.overrides.set(`${raw}/HEAD/skin.json`, () => Response.json({ + ...f.metadata(), name: "Catalog display name", author: "Catalog author", license: "MIT (code)", + })); const entry = (await store.list()).entries[0]; assert.equal(entry.compatible, true); const input = { id: entry.id, revision: entry.revision, installedVersion: null }; await store.install(skins, input); assert.deepEqual(await skins.readArchive(entry.id), f.archive()); + const [installed] = await skins.list(); + assert.equal(installed.name, manifest.name); + assert.equal(installed.author, manifest.author); + assert.equal(installed.license, manifest.license); await skins.setDefaultSkin(entry.id); f.setVersion("1.1.0"); const updated = (await store.list(true)).entries[0]; @@ -104,9 +111,11 @@ test("store bounds downloads and validates checksum, package identity and metada f.overrides.set(packageUrl, () => new Response("x", { headers: { "content-length": String(21 * 1024 * 1024) } })); await assert.rejects(store.install(skins, input), errorCode("SKIN_STORE_TOO_LARGE")); f.overrides.delete(packageUrl); - f.overrides.set(`${raw}/HEAD/skin.json`, () => Response.json({ ...f.metadata(), name: "Different display name" })); - const mismatch = (await store.list(true)).entries[0]; - await assert.rejects(store.install(skins, { ...input, revision: mismatch.revision }), errorCode("SKIN_STORE_PACKAGE_MISMATCH")); + for (const fields of [{ version: "1.1.0" }, { minAppVersion: "0.2.7" }]) { + f.overrides.set(`${raw}/HEAD/skin.json`, () => Response.json({ ...f.metadata(), ...fields })); + const mismatch = (await store.list(true)).entries[0]; + await assert.rejects(store.install(skins, { ...input, revision: mismatch.revision }), errorCode("SKIN_STORE_PACKAGE_MISMATCH")); + } f.overrides.set(`${raw}/HEAD/skin.json`, () => Response.json({ ...f.metadata(), package: { ...f.metadata().package, path: "../private.wskin" } })); assert.equal((await store.list(true)).entries[0].error, "SKIN_STORE_INVALID"); assert.deepEqual(await skins.list(), []);