From c243f272fe8c3f96b35e17829bdbd5b6f038e2ab Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:44:15 +0800 Subject: [PATCH] feat(skin): bind plugin approval to package digest --- docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md | 4 +- docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md | 2 +- docs/SKIN_DEVELOPMENT.md | 2 +- package.json | 2 +- .../skin-runtime-plugin-approval.test.ts | 99 ++++++++++ src/shared/skin-runtime-plugin-approval.ts | 176 ++++++++++++++++++ .../skin-runtime-plugin-approval.test.ts | 79 ++++++++ .../services/skin-runtime-plugin-approval.ts | 93 +++++++++ 8 files changed, 453 insertions(+), 4 deletions(-) create mode 100644 src/shared/skin-runtime-plugin-approval.test.ts create mode 100644 src/shared/skin-runtime-plugin-approval.ts create mode 100644 web/src/services/skin-runtime-plugin-approval.test.ts create mode 100644 web/src/services/skin-runtime-plugin-approval.ts diff --git a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md index 9437cca..5a2c17f 100644 --- a/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_ROADMAP.zh-CN.md @@ -44,7 +44,9 @@ schema v2 支持公开组件布局、桌面/平板/手机配置、本地覆盖 ### R3.3:完整自定义插件运行时(未完成,优先阶段) -- v4 包格式的首个节点已落地:客户端和服务端共用 `plugins.json` 描述校验器,校验插件 ID、版本、页面、模式、权限、入口/样式/素材路径与重复 surface;客户端分开缓存插件文件,服务端验证文件存在、UTF-8 和大小。此节点不执行 JS/CSS,不能作为完整运行时完成态。 +- v4 包格式的首个节点已落地:客户端和服务端共用 `plugins.json` 描述校验器,校验插件 ID、版本、页面、模式、权限、入口/样式/素材路径与重复 surface;客户端分开缓存插件文件,服务端验证文件存在、UTF-8 和大小。 +- 新增插件本地授权的安全基础:SHA-256 摘要绑定插件描述和所有声明文件,授权记录同时绑定皮肤/插件版本、API 版本、摘要与权限策略版本。任一代码、样式、素材、挂载模式或权限变化都会使旧授权不匹配。摘要不是发布者签名,亦不证明包来源可信。 +- 当前仍只校验和缓存 JS/CSS;本机持久化函数尚未接入宿主确认 UI、执行生命周期或运行时,也没有启用插件代码。此节点不能作为完整运行时完成态。 - 继续新增 opt-in 的插件协议,不给旧 v1/v2/v3 包追溯增加代码执行能力;同一皮肤可将界面分成多个独立、可排序、可显示/隐藏、可单独授权和回退的插件。 - 插件可自定义公开界面的 DOM 结构、CSS、组件状态和普通 UI 事件,不局限于当前标签、属性、数据字段和固定动作表。宿主控件目录变成可选的兼容原生组件。 - 尚待定义 widget 插件在宿主页面中的挂载、排序、显隐和用户自定义几何布局;当前 v4 描述只有页面与 widget/surface 模式,没有挂载或实例布局字段。应把用户布局保存在本地宿主状态,并让 CSS/插件沙箱边界保持独立。 diff --git a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md index 584cc89..7348a04 100644 --- a/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md +++ b/docs/OPEN_SKIN_SYSTEM_SPEC.zh-CN.md @@ -22,7 +22,7 @@ v1-v3 包不能提交 HTML 字符串、事件处理代码、JavaScript、WebAsse ### 2.1 完整插件目标协议(v4,运行时尚未实现) -已实现的 v4 包描述为 `plugins.json` schema v1:每包 1–64 个插件,每个插件指定唯一小写 ID、语义版本、API 版本 1、`home`/`voice` 页面、`widget`/`surface` 模式、`plugins//` 下入口 JS/可选 CSS、该目录中的图片/woff2 素材和现有权限表中的权限。每页至多一个 surface,且必须申请 `ui.surface.replace`。清单最多 256 KiB、插件入口最多 256 KiB、插件样式最多 512 KiB、每插件最多 32 个素材;引用文件必须存在且路径不重复。客户端与服务端复用同一解析器。此协议节点只做识别、验证和缓存,尚不加载或执行作者代码。 +已实现的 v4 包描述为 `plugins.json` schema v1:每包 1–64 个插件,每个插件指定唯一小写 ID、语义版本、API 版本 1、`home`/`voice` 页面、`widget`/`surface` 模式、`plugins//` 下入口 JS/可选 CSS、该目录中的图片/woff2 素材和现有权限表中的权限。每页至多一个 surface,且必须申请 `ui.surface.replace`。清单最多 256 KiB、插件入口最多 256 KiB、插件样式最多 512 KiB、每插件最多 32 个素材;引用文件必须存在且路径不重复。客户端与服务端复用同一解析器。另有 SHA-256 摘要与本地授权记录函数:摘要覆盖描述字段和入口、样式、全部素材;本机存储按皮肤、插件 ID 保存授权,并将授权绑定皮肤/插件版本、API 版本、文件摘要及权限策略版本。该摘要仅用于检测本机授权后包内容是否变化,不是发布者签名或来源证明。授权函数尚未接入宿主确认 UI 和执行生命周期;作者代码尚不加载或执行。 当前 descriptor 没有定义 widget 的宿主挂载位置、实例顺序、显隐或几何配置。完整运行时需决定这些默认值随皮肤包分发还是由用户本地覆盖;用户布局应与作者文件分开存储,且沙箱内代码不能改动其他插件的宿主容器或恢复控件。 diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index fdfcb2b..61ebda7 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -153,7 +153,7 @@ components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。s ### schemaVersion 4:插件包描述(运行时尚未启用) -v4 在 open-skin 包中增加必需的 `plugins` 路径。服务端登记和客户端导入共用 `plugins.json` schema v1 校验器;校验插件 ID、页面、模式、权限、文件归属、路径唯一性和包内文件大小,并将插件文件与普通皮肤素材分别缓存。JS、CSS 和素材均不会被此阶段的 WebSpeak 运行时加载或执行,因此 v4 当前只是可验证的包协议,不能作为可运行插件发布。 +v4 在 open-skin 包中增加必需的 `plugins` 路径。服务端登记和客户端导入共用 `plugins.json` schema v1 校验器;校验插件 ID、页面、模式、权限、文件归属、路径唯一性和包内文件大小,并将插件文件与普通皮肤素材分别缓存。SHA-256 授权基础会绑定插件描述、入口、样式和全部素材;本机授权记录还会绑定皮肤/插件版本、API 版本和权限策略版本。摘要只能发现已授权内容被替换,不能证明发布者身份。当前持久化函数尚未连接用户确认界面或运行生命周期。JS、CSS 和素材均不会被 WebSpeak 运行时加载或执行,因此 v4 目前不能作为可运行插件发布。 ```json { diff --git a/package.json b/package.json index 0aab9a1..a25e4d1 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/src/services/identity-import.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-wasm-interpreter.test.ts", + "test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/src/services/identity-import.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-wasm-interpreter.test.ts", "verify": "npm test && npm run build && npm run web:build", "start": "node dist/index.js", "web:dev": "cd web && npx vite --host", diff --git a/src/shared/skin-runtime-plugin-approval.test.ts b/src/shared/skin-runtime-plugin-approval.test.ts new file mode 100644 index 0000000..b958d3b --- /dev/null +++ b/src/shared/skin-runtime-plugin-approval.test.ts @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + computeSkinRuntimePluginDigest, + createSkinRuntimePluginApproval, + isSkinRuntimePluginApproved, + parseSkinRuntimePluginApproval, + SkinRuntimePluginApprovalError, +} from "./skin-runtime-plugin-approval.js"; +import { parseSkinRuntimePluginDocument, type SkinRuntimePlugin } from "./skin-runtime-plugins.js"; + +function plugin(overrides: Record = {}): SkinRuntimePlugin { + return parseSkinRuntimePluginDocument({ + schemaVersion: 1, + plugins: [{ + id: "voice-toolbar", + name: "Voice toolbar", + version: "1.0.0", + apiVersion: 1, + page: "voice", + mode: "widget", + entry: "plugins/voice-toolbar/index.js", + style: "plugins/voice-toolbar/style.css", + assets: ["plugins/voice-toolbar/assets/icon.png"], + permissions: ["session.status.read"], + ...overrides, + }], + }).plugins[0]; +} + +function files(entry = "export default () => {};", style = ".toolbar { color: teal; }", icon = "icon-v1") { + return { + "plugins/voice-toolbar/index.js": new Blob([entry]), + "plugins/voice-toolbar/style.css": new Blob([style]), + "plugins/voice-toolbar/assets/icon.png": new Blob([icon]), + }; +} + +test("plugin digest is deterministic and binds all declared source, style, assets, and descriptor fields", async () => { + const definition = plugin(); + const packageFiles = files(); + const first = await computeSkinRuntimePluginDigest(definition, packageFiles); + assert.equal(first, await computeSkinRuntimePluginDigest(definition, packageFiles)); + assert.match(first, /^[a-f0-9]{64}$/); + assert.notEqual(first, await computeSkinRuntimePluginDigest(definition, files("export default () => 1;"))); + assert.notEqual(first, await computeSkinRuntimePluginDigest(definition, files(undefined, ".toolbar { color: red; }"))); + assert.notEqual(first, await computeSkinRuntimePluginDigest(definition, files(undefined, undefined, "icon-v2"))); + assert.notEqual(first, await computeSkinRuntimePluginDigest(plugin({ permissions: [] }), packageFiles)); + assert.notEqual(first, await computeSkinRuntimePluginDigest(plugin({ mode: "surface", permissions: ["ui.surface.replace"] }), packageFiles)); +}); + +test("plugin approval is pinned to skin and plugin versions, content digest, and permission policy", async () => { + const definition = plugin(); + const digest = await computeSkinRuntimePluginDigest(definition, files()); + const approval = createSkinRuntimePluginApproval("community.sample", "2.0.0", definition, digest); + assert.equal(isSkinRuntimePluginApproved(approval, "community.sample", "2.0.0", definition, digest), true); + assert.equal(isSkinRuntimePluginApproved(approval, "community.sample", "2.0.0", definition, "0".repeat(64)), false); + assert.equal(isSkinRuntimePluginApproved(approval, "community.sample", "2.1.0", definition, digest), false); + assert.equal(isSkinRuntimePluginApproved(approval, "other.skin", "2.0.0", definition, digest), false); + assert.equal(isSkinRuntimePluginApproved(approval, "community.sample", "2.0.0", plugin({ version: "1.1.0" }), digest), false); + assert.deepEqual(parseSkinRuntimePluginApproval(approval), approval); + + const stalePolicy = parseSkinRuntimePluginApproval({ + ...approval, + permissions: { "session.status.read": 99 }, + }); + assert.equal(isSkinRuntimePluginApproved(stalePolicy, "community.sample", "2.0.0", definition, digest), false); +}); + +test("plugin approval parser rejects malformed identities, digests, and unrecognized grants", async () => { + const definition = plugin(); + const digest = await computeSkinRuntimePluginDigest(definition, files()); + const approval = createSkinRuntimePluginApproval("community.sample", "2.0.0", definition, digest); + for (const candidate of [ + { ...approval, digest: "short" }, + { ...approval, pluginId: "../other" }, + { ...approval, permissions: { "filesystem.read": 1 } }, + { ...approval, extra: true }, + ]) { + assert.throws(() => parseSkinRuntimePluginApproval(candidate), (error: unknown) => + error instanceof SkinRuntimePluginApprovalError && error.code === "SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID"); + } + assert.throws(() => createSkinRuntimePluginApproval("", "2.0.0", definition, digest), { code: "SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID" }); +}); + +test("plugin digest refuses missing declared files and packages beyond the ZIP expansion bound", async () => { + const definition = plugin(); + await assert.rejects( + computeSkinRuntimePluginDigest(definition, {}), + (error: unknown) => error instanceof SkinRuntimePluginApprovalError && error.code === "SKIN_RUNTIME_PLUGIN_DIGEST_FILE_MISSING", + ); + await assert.rejects( + computeSkinRuntimePluginDigest(definition, { + ...files(), + "plugins/voice-toolbar/assets/icon.png": new Blob([new Uint8Array(50 * 1024 * 1024)]), + }), + (error: unknown) => error instanceof SkinRuntimePluginApprovalError && error.code === "SKIN_RUNTIME_PLUGIN_DIGEST_SIZE", + ); +}); diff --git a/src/shared/skin-runtime-plugin-approval.ts b/src/shared/skin-runtime-plugin-approval.ts new file mode 100644 index 0000000..d88bd24 --- /dev/null +++ b/src/shared/skin-runtime-plugin-approval.ts @@ -0,0 +1,176 @@ +import { SKIN_PLUGIN_PERMISSIONS, type SkinPluginPermission } from "./skin-plugin.js"; +import { parseSkinRuntimePluginDocument, type SkinRuntimePlugin } from "./skin-runtime-plugins.js"; + +export const SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION = 1 as const; +export const SKIN_RUNTIME_PLUGIN_DIGEST_ALGORITHM = "SHA-256" as const; +export const SKIN_RUNTIME_PLUGIN_DIGEST_TOTAL_LIMIT_BYTES = 50 * 1024 * 1024; + +export interface SkinRuntimePluginApproval { + schemaVersion: typeof SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION; + skinId: string; + skinVersion: string; + pluginId: string; + pluginVersion: string; + apiVersion: 1; + digest: string; + permissions: Readonly>>; +} + +export class SkinRuntimePluginApprovalError extends Error { + constructor(readonly code: string, message: string) { + super(message); + this.name = "SkinRuntimePluginApprovalError"; + } +} + +function invalid(code: string, message: string): never { + throw new SkinRuntimePluginApprovalError(code, message); +} + +function isRecord(value: unknown): value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function validDigest(value: unknown): value is string { + return typeof value === "string" && /^[a-f0-9]{64}$/.test(value); +} + +function sha256(bytes: Uint8Array): Promise { + if (!globalThis.crypto?.subtle) { + return Promise.reject(new SkinRuntimePluginApprovalError("SKIN_RUNTIME_PLUGIN_DIGEST_UNAVAILABLE", "Secure plugin approval requires Web Crypto.")); + } + const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; + return globalThis.crypto.subtle.digest(SKIN_RUNTIME_PLUGIN_DIGEST_ALGORITHM, buffer).then((digest) => + Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")); +} + +/** + * Binds local consent to the exact plugin descriptor and every declared package file. + * This is an integrity key for local approval, not a publisher signature. + */ +export async function computeSkinRuntimePluginDigest( + input: SkinRuntimePlugin, + files: Readonly>, +): Promise { + if (!files || typeof files !== "object" || Array.isArray(files)) { + invalid("SKIN_RUNTIME_PLUGIN_DIGEST_FILE_MISSING", "The declared plugin files are unavailable."); + } + const plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [input] }).plugins[0]; + const paths = [plugin.entry, ...(plugin.style ? [plugin.style] : []), ...plugin.assets].sort(); + let totalBytes = 0; + const fileDigests: Array<{ path: string; size: number; digest: string }> = []; + + for (const path of paths) { + if (!Object.hasOwn(files, path) || !(files[path] instanceof Blob)) { + invalid("SKIN_RUNTIME_PLUGIN_DIGEST_FILE_MISSING", "A declared plugin file is missing from the digest input."); + } + const blob = files[path]; + totalBytes += blob.size; + if (totalBytes > SKIN_RUNTIME_PLUGIN_DIGEST_TOTAL_LIMIT_BYTES) { + invalid("SKIN_RUNTIME_PLUGIN_DIGEST_SIZE", "The declared plugin files exceed the skin package size limit."); + } + fileDigests.push({ path, size: blob.size, digest: await sha256(new Uint8Array(await blob.arrayBuffer())) }); + } + + const canonicalPlugin = { + id: plugin.id, + name: plugin.name, + version: plugin.version, + apiVersion: plugin.apiVersion, + page: plugin.page, + mode: plugin.mode, + entry: plugin.entry, + ...(plugin.style ? { style: plugin.style } : {}), + assets: [...plugin.assets].sort(), + permissions: [...plugin.permissions].sort(), + }; + const canonical = JSON.stringify({ + domain: "webspeak.skin-runtime-plugin-approval", + schemaVersion: SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION, + plugin: canonicalPlugin, + files: fileDigests, + }); + return sha256(new TextEncoder().encode(canonical)); +} + +export function createSkinRuntimePluginApproval( + skinId: string, + skinVersion: string, + input: SkinRuntimePlugin, + digest: string, +): SkinRuntimePluginApproval { + if (typeof skinId !== "string" || !skinId.trim() || skinId.length > 120 + || typeof skinVersion !== "string" || !skinVersion.trim() || skinVersion.length > 32 + || !validDigest(digest)) { + invalid("SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID", "The host approval identity or plugin digest is invalid."); + } + const plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [input] }).plugins[0]; + const permissions: Partial> = {}; + for (const permission of plugin.permissions) permissions[permission] = SKIN_PLUGIN_PERMISSIONS[permission].policyVersion; + return Object.freeze({ + schemaVersion: SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION, + skinId, + skinVersion, + pluginId: plugin.id, + pluginVersion: plugin.version, + apiVersion: plugin.apiVersion, + digest, + permissions: Object.freeze(permissions), + }); +} + +export function parseSkinRuntimePluginApproval(input: unknown): SkinRuntimePluginApproval { + const fields = ["schemaVersion", "skinId", "skinVersion", "pluginId", "pluginVersion", "apiVersion", "digest", "permissions"]; + if (!isRecord(input) || Object.keys(input).length !== fields.length || fields.some((field) => !Object.hasOwn(input, field))) { + invalid("SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID", "The stored plugin approval has an invalid shape."); + } + if (input.schemaVersion !== SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION + || typeof input.skinId !== "string" || !input.skinId.trim() || input.skinId.length > 120 + || typeof input.skinVersion !== "string" || !input.skinVersion.trim() || input.skinVersion.length > 32 + || typeof input.pluginId !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(input.pluginId) + || typeof input.pluginVersion !== "string" || input.pluginVersion.length > 32 + || input.apiVersion !== 1 || !validDigest(input.digest) || !isRecord(input.permissions)) { + invalid("SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID", "The stored plugin approval has invalid identity fields."); + } + const permissions: Partial> = {}; + for (const [permission, policyVersion] of Object.entries(input.permissions)) { + if (!Object.hasOwn(SKIN_PLUGIN_PERMISSIONS, permission) + || !Number.isSafeInteger(policyVersion) || (policyVersion as number) < 1) { + invalid("SKIN_RUNTIME_PLUGIN_APPROVAL_INVALID", "The stored plugin approval contains an unsupported permission."); + } + permissions[permission as SkinPluginPermission] = policyVersion as number; + } + return Object.freeze({ + schemaVersion: SKIN_RUNTIME_PLUGIN_APPROVAL_SCHEMA_VERSION, + skinId: input.skinId, + skinVersion: input.skinVersion, + pluginId: input.pluginId, + pluginVersion: input.pluginVersion, + apiVersion: 1, + digest: input.digest, + permissions: Object.freeze(permissions), + }); +} + +export function isSkinRuntimePluginApproved( + approval: SkinRuntimePluginApproval, + skinId: string, + skinVersion: string, + input: SkinRuntimePlugin, + digest: string, +): boolean { + let plugin: SkinRuntimePlugin; + try { plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [input] }).plugins[0]; } + catch { return false; } + return approval.skinId === skinId + && approval.skinVersion === skinVersion + && approval.pluginId === plugin.id + && approval.pluginVersion === plugin.version + && approval.apiVersion === plugin.apiVersion + && approval.digest === digest + && validDigest(digest) + && plugin.permissions.every((permission) => + approval.permissions[permission] === SKIN_PLUGIN_PERMISSIONS[permission].policyVersion); +} diff --git a/web/src/services/skin-runtime-plugin-approval.test.ts b/web/src/services/skin-runtime-plugin-approval.test.ts new file mode 100644 index 0000000..ccff9c7 --- /dev/null +++ b/web/src/services/skin-runtime-plugin-approval.test.ts @@ -0,0 +1,79 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + approveSkinRuntimePlugin, + getMissingSkinRuntimePluginApprovals, + getSkinRuntimePluginApproval, + revokeSkinRuntimePluginApprovals, +} from "./skin-runtime-plugin-approval.js"; +import { computeSkinRuntimePluginDigest } from "../../../src/shared/skin-runtime-plugin-approval.js"; +import { parseSkinRuntimePluginDocument } from "../../../src/shared/skin-runtime-plugins.js"; + +const STORAGE_KEY = "webspeak:skin-runtime-plugin-approvals"; +function memoryStorage(initial?: string) { + const values = new Map(initial === undefined ? [] : [[STORAGE_KEY, initial]]); + return { + getItem: (key: string) => values.get(key) ?? null, + setItem: (key: string, value: string) => { values.set(key, value); }, + read: () => values.get(STORAGE_KEY), + }; +} + +const plugin = parseSkinRuntimePluginDocument({ + schemaVersion: 1, + plugins: [{ + id: "voice-toolbar", + name: "Voice toolbar", + version: "1.0.0", + apiVersion: 1, + page: "voice", + mode: "widget", + entry: "plugins/voice-toolbar/index.js", + assets: [], + permissions: ["session.status.read"], + }], +}).plugins[0]; + +test("local plugin grants require explicit approval and match the complete package digest", async () => { + const storage = memoryStorage(); + const files = { "plugins/voice-toolbar/index.js": new Blob(["export default () => 1;"]) }; + const digest = await computeSkinRuntimePluginDigest(plugin, files); + assert.deepEqual(getMissingSkinRuntimePluginApprovals("community.sample", "2.0.0", [plugin], { [plugin.id]: digest }, storage), [plugin]); + assert.equal(getSkinRuntimePluginApproval("community.sample", "2.0.0", plugin, digest, storage), null); + + approveSkinRuntimePlugin("community.sample", "2.0.0", plugin, digest, storage); + assert.deepEqual(getMissingSkinRuntimePluginApprovals("community.sample", "2.0.0", [plugin], { [plugin.id]: digest }, storage), []); + assert.equal(getSkinRuntimePluginApproval("community.sample", "2.0.0", plugin, digest, storage)?.digest, digest); + assert.deepEqual(getMissingSkinRuntimePluginApprovals("community.sample", "2.0.0", [plugin], { [plugin.id]: "0".repeat(64) }, storage), [plugin]); + assert.deepEqual(getMissingSkinRuntimePluginApprovals("community.sample", "2.1.0", [plugin], { [plugin.id]: digest }, storage), [plugin]); +}); + +test("plugin approval revocation can target a skin plugin or every plugin in a skin", async () => { + const storage = memoryStorage(); + const other = parseSkinRuntimePluginDocument({ + schemaVersion: 1, + plugins: [{ ...plugin, id: "other-widget", name: "Other widget", entry: "plugins/other-widget/index.js" }], + }).plugins[0]; + const digest = await computeSkinRuntimePluginDigest(plugin, { [plugin.entry]: new Blob(["one"]) }); + const otherDigest = await computeSkinRuntimePluginDigest(other, { [other.entry]: new Blob(["two"]) }); + approveSkinRuntimePlugin("community.sample", "2.0.0", plugin, digest, storage); + approveSkinRuntimePlugin("community.sample", "2.0.0", other, otherDigest, storage); + approveSkinRuntimePlugin("community.other", "2.0.0", plugin, digest, storage); + + revokeSkinRuntimePluginApprovals("community.sample", plugin.id, storage); + assert.equal(getSkinRuntimePluginApproval("community.sample", "2.0.0", plugin, digest, storage), null); + assert.ok(getSkinRuntimePluginApproval("community.sample", "2.0.0", other, otherDigest, storage)); + assert.ok(getSkinRuntimePluginApproval("community.other", "2.0.0", plugin, digest, storage)); + revokeSkinRuntimePluginApprovals("community.sample", undefined, storage); + assert.equal(getSkinRuntimePluginApproval("community.sample", "2.0.0", other, otherDigest, storage), null); + assert.ok(getSkinRuntimePluginApproval("community.other", "2.0.0", plugin, digest, storage)); +}); + +test("corrupt local grant data fails closed and failed persistence cannot create an in-memory grant", async () => { + const corrupt = memoryStorage("not json"); + const digest = await computeSkinRuntimePluginDigest(plugin, { [plugin.entry]: new Blob(["code"]) }); + assert.equal(getSkinRuntimePluginApproval("community.sample", "2.0.0", plugin, digest, corrupt), null); + const readonlyStorage = { getItem: () => null, setItem: () => { throw new Error("quota"); } }; + approveSkinRuntimePlugin("community.sample", "2.0.0", plugin, digest, readonlyStorage); + assert.equal(getSkinRuntimePluginApproval("community.sample", "2.0.0", plugin, digest, readonlyStorage), null); +}); diff --git a/web/src/services/skin-runtime-plugin-approval.ts b/web/src/services/skin-runtime-plugin-approval.ts new file mode 100644 index 0000000..be7310c --- /dev/null +++ b/web/src/services/skin-runtime-plugin-approval.ts @@ -0,0 +1,93 @@ +import { + createSkinRuntimePluginApproval, + isSkinRuntimePluginApproved, + parseSkinRuntimePluginApproval, + type SkinRuntimePluginApproval, +} from "../../../src/shared/skin-runtime-plugin-approval.js"; +import type { SkinRuntimePlugin } from "../../../src/shared/skin-runtime-plugins.js"; + +const STORAGE_KEY = "webspeak:skin-runtime-plugin-approvals"; +interface ApprovalStore { schemaVersion: 1; grants: Record } +type ApprovalStorage = Pick; +const unavailableStorage: ApprovalStorage = { getItem: () => null, setItem: () => undefined }; + +function pluginKey(skinId: string, skinVersion: string, pluginId: string): string { + return JSON.stringify([skinId, skinVersion, pluginId]); +} + +function readStore(storage: ApprovalStorage): ApprovalStore { + try { + const raw: unknown = JSON.parse(storage.getItem(STORAGE_KEY) ?? "null"); + if (!raw || typeof raw !== "object" || (raw as Record).schemaVersion !== 1 + || !(raw as Record).grants || typeof (raw as Record).grants !== "object") { + return { schemaVersion: 1, grants: {} }; + } + const grants: Record = Object.create(null) as Record; + for (const [key, value] of Object.entries((raw as ApprovalStore).grants)) { + try { grants[key] = parseSkinRuntimePluginApproval(value); } catch { /* Ignore corrupt local grants. */ } + } + return { schemaVersion: 1, grants }; + } catch { + return { schemaVersion: 1, grants: {} }; + } +} + +function writeStore(storage: ApprovalStorage, store: ApprovalStore): void { + try { storage.setItem(STORAGE_KEY, JSON.stringify(store)); } catch { /* Approval persistence is optional. */ } +} + +function defaultStorage(): ApprovalStorage { + try { return window.localStorage; } catch { return unavailableStorage; } +} + +export function getSkinRuntimePluginApproval( + skinId: string, + skinVersion: string, + plugin: SkinRuntimePlugin, + digest: string, + storage: ApprovalStorage = defaultStorage(), +): SkinRuntimePluginApproval | null { + const grant = readStore(storage).grants[pluginKey(skinId, skinVersion, plugin.id)]; + return grant && isSkinRuntimePluginApproved(grant, skinId, skinVersion, plugin, digest) ? grant : null; +} + +/** Called only by the host consent UI after a user explicitly approves this exact package. */ +export function approveSkinRuntimePlugin( + skinId: string, + skinVersion: string, + plugin: SkinRuntimePlugin, + digest: string, + storage: ApprovalStorage = defaultStorage(), +): void { + const store = readStore(storage); + const key = pluginKey(skinId, skinVersion, plugin.id); + store.grants[key] = createSkinRuntimePluginApproval(skinId, skinVersion, plugin, digest); + writeStore(storage, store); +} + +export function getMissingSkinRuntimePluginApprovals( + skinId: string, + skinVersion: string, + plugins: readonly SkinRuntimePlugin[], + digests: Readonly>, + storage: ApprovalStorage = defaultStorage(), +): SkinRuntimePlugin[] { + const grants = readStore(storage).grants; + return plugins.filter((plugin) => { + const digest = digests[plugin.id]; + const grant = grants[pluginKey(skinId, skinVersion, plugin.id)]; + return !digest || !grant || !isSkinRuntimePluginApproved(grant, skinId, skinVersion, plugin, digest); + }); +} + +export function revokeSkinRuntimePluginApprovals( + skinId: string, + pluginId?: string, + storage: ApprovalStorage = defaultStorage(), +): void { + const store = readStore(storage); + for (const [key, grant] of Object.entries(store.grants)) { + if (grant.skinId === skinId && (!pluginId || grant.pluginId === pluginId)) delete store.grants[key]; + } + writeStore(storage, store); +}