feat(plugin): implement plugin architecture, driver router, theme engine, and CLI/GUI management

This commit is contained in:
Nwflower committed 2026-11-29 08:48:00 -07:00
1 parent 15bc097a94
commit f30d901b7f
81 files changed
+17412 -183

No files matched your search

+2 -2
View File
@@ -34,11 +34,11 @@
## 文档导航
- [`README.md`](README.md) — 项目总览、核心特性与快速开始
- [`README.md`](README.md) / [`README.en.md`](README.en.md) — 项目总览、核心特性与快速开始(中英双语)
- [`CHANGELOG.md`](CHANGELOG.md) — 应用版本更新日志
- [`docs/roadmap.md`](docs/roadmap.md) — 公开路线图与近期重点
- [`docs/architecture.md`](docs/architecture.md) — 系统架构、模块职责与安全边界
- [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案)
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范
- [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构草案(RFC)
- [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范
- [`patches/README.md`](patches/README.md) — 上游临时补丁队列与 PR 跟踪
+455
View File
@@ -0,0 +1,455 @@
# 插件系统架构(Plugin Architecture)
> 状态:**核心内核、内置扩展、主题引擎、Sidecar 托管与 CLI/GUI 管理已落地**;市场远端索引与 L2 脚本层按需迭代。
> 关联文档:[`architecture.md`](architecture.md) · [`design-guidelines.md`](design-guidelines.md) · [`portable-runtime-spec.md`](portable-runtime-spec.md) · [`patches/README.md`](../patches/README.md)
---
## 1. 目标、约束与非目标
### 1.1 目标插件类型
| 类型 | 典型形态 |
| :--- | :--- |
| **主题与美化** | 宿主**不提供主题包,只提供主题扩展接口**;接口须能承载多套配色、字体、部件级样式、状态驱动装饰与交互增强并存的复杂主题(以 DSH 主题 dsh-claude-style 为参照) |
| **运行时** | 自定义构建或镜像源的 `reims-vgpu` 运行时、上游 QEMU/OVMF 等其他运行时种类 |
| **非 macOS 虚拟机** | 以 Linux 虚拟机为代表的客体平台驱动,复用体检、内存预检、绑核、QMP、任务与托盘能力 |
| **Hook 与自动化** | 体检、建机、启停前后的拦截与观察;自定义命令;排障采集器;宿主侧桥接与兼容补偿 |
### 1.2 硬约束
| 约束 | 要求 |
| :--- | :--- |
| **第三方代码不进主进程** | 除编译期内置扩展外,任何插件代码都不在 `reims-go.exe` 进程内执行;插件崩溃、死循环或内存失控不得拖垮主窗口与运行中的 VM |
| **零外部运行时依赖** | 用户无需安装 Node.js / Bun / Python / MSYS2 即可使用任一官方插件层级 |
| **数据目录隔离** | 插件包、私有数据、日志与第三方运行时全部位于 `<DataRoot>` 下 |
| **许可证防火墙** | Apache-2.0 本体与 GPL/LGPL 组件只经独立子进程 + 协议通信协作,禁止静态链接或进程内耦合 |
| **配置写入铁律** | 对 `reims-ctl` 管理的 VM,插件只能提交「意图」,由宿主统一经 `reims-ctl set` 落盘,严禁直改 `vm.toml` |
| **人工确认红线** | UAC 提权、重启 Windows、macOS 图形安装向导等不提供任何插件权限,插件只能请求宿主弹出确认 |
| **敏感字段零外泄** | 序列号、MLB、UUID、ROM、MAC 不进入任何插件可读的数据面;插件贡献的排障内容必经宿主脱敏 |
| **GUI 与 CLI 同源** | 插件管理、驱动路由、Hook 管线位于 `internal/`,桌面与 `reims-go <subcommand>` 行为一致 |
### 1.3 非目标
- 不采用 Go 原生 `plugin` 包(不支持 Windows,且强耦合编译器与依赖版本),不进程内加载第三方 DLL。
- 不把核心拆成「万物皆插件」的全动态微内核:体检、单实例托盘、Wails 窗口与 CLI 路由保持静态编译。
- 不用插件、DLL 注入或 API Hook 替代上游引擎补丁(见 §5.5)。
- 不发布官方主题插件包:除内置浅色/深色外不提供任何主题,但完整保留主题扩展接口(§5.1)。
- 不托管、不分发任何 Apple 专有文件;插件市场拒收此类包。
---
## 2. 参考系统与取舍
| 维度 | Magpie(Go 宿主 + Bun 插件宿主) | DSH(Cordis「万物皆插件」) | Reims-Go 取舍 |
| :--- | :--- | :--- | :--- |
| 内核 | 编译期内置插件注册表(`Requires/Provides/Apply/OnDispose`)+ 社区插件管理器,两者在扩展点交汇 | 极小 DI 内核,所有功能皆插件,依赖就绪自动激活、缺失级联卸载 | 取 Magpie 的**单注册表、两种来源**;取 DSH 的**可逆副作用**与依赖驱动激活;不做全动态微内核 |
| 执行隔离 | 按能力分层:进程内 JS(µs 级热路径,无 I/O,严格时限)/ 共享 Bun 子进程 / 沙箱 iframe | 全部进程内同权限,`node:vm` 与同源 iframe 明确声明非安全边界 | Reims-Go **无微秒级热路径**,进程内脚本收益不足以抵消风险 → 所有插件代码进程外执行,且**每插件独立进程** |
| 失败策略 | 每个扩展点显式 fail-open / fail-closed | 可选插件失败继续、必需清单失败退出;UI 单元格错误边界 | 扩展点契约中写明分发模式与失败策略 |
| UI | `sandbox=allow-scripts` iframe + `connect-src 'none'` + bridge + 服务端二次校验 + 主题变量 | 类型化 Slot(声明即占有)+ 主题令牌 + SVG 校验;共享 React 实例随宿主升级易碎 | 声明式贡献由宿主原生渲染为主;iframe 面板为逃生舱;不共享前端依赖 |
| 分发 | npm/git/本地 + 带 sha512 的兜底分发分支;远端索引 + 内嵌副本 | 事务安装(快照回滚、包名版本核对、下载前兼容预检)、安全模式恢复;无签名 | 事务安装 + 下载前预检 + SHA-256 + 签名分级 + 远端索引与内嵌兜底 |
| 已知教训 | Windows 上包管理器并发写丢失;孤儿进程(需按进程树终止);`Origin: null` 绕过 CORS;空列表保存抹掉全部插件;嵌入引擎无内存上限 | 进程内插件一个未捕获异常拖垮宿主;整段配置替换难用 | 不引入包管理器;Job Object;严格 Origin 校验;状态文件「读失败即报错」;内存上限靠进程级限制 |
---
## 3. 总体架构
### 3.1 一个注册表 + 分层执行
```mermaid
flowchart TB
subgraph Exe["reims-go.exe(可信核心)"]
Reg["扩展点注册表\n依赖解析 · 可逆副作用 · Reconcile"]
Builtin["内置扩展(编译期注册)\nmacOS/reims 驱动 · reims-vgpu 运行时种类 ·\n宿客桥接与兼容补偿 · 浅/深色主题"]
Mgr["插件管理器\n清单校验 · 事务安装 · 状态 · 安全模式"]
Broker["Host API 代理\n权限校验 · 脱敏 · 限流 · 审计"]
Sup["进程监管器\nJob Object · 重启退避 · 健康检查"]
Asset["插件资源路由\nCSP · 路径校验 · Origin 校验"]
end
subgraph L1["L1 声明层(纯数据)"]
D1["主题 · 图标 · 语言 · VM 模板 · 运行时源 · 规则 Hook"]
end
subgraph RT["运行时包(原生二进制)"]
R1["仅由驱动以子进程调用"]
end
subgraph L2["L2 脚本宿主(预留)"]
S1["reims-go 隐藏子命令进程\n内嵌 JS 引擎 · 进程级内存/CPU 上限"]
end
subgraph L3["L3 Sidecar(任意语言 exe)"]
X1["Linux 驱动 · 代码 Hook · 命令 · 排障采集"]
end
subgraph L4["L4 UI"]
U1["声明式贡献(原生渲染)· 沙箱 iframe 面板(后置)"]
end
Builtin --> Reg
Mgr --> Reg
L1 --> Mgr
RT --> Mgr
L2 & L3 <-->|"JSON-RPC 2.0 / stdio"| Sup --> Broker --> Reg
L4 <-->|"bridge"| Asset --> Broker
```
| 层 | 执行机制 | 隔离 | 宿主可强制的约束 | 典型插件 |
| :--- | :--- | :--- | :--- | :--- |
| **Builtin** | Go 代码,编译期注册到同一注册表 | 可信 | 全部 | reims 驱动、宿客桥接、兼容补偿、默认主题 |
| **L1 声明层** | JSON + 静态资源,由宿主解析 | 无代码 | 全部(Schema 白名单) | 主题、图标、语言、VM 模板、运行时源、规则 Hook |
| **运行时包** | 原生二进制,**只被驱动以子进程调用**,自身不注册扩展点 | 进程级 | 来源、哈希、签名 | `reims-vgpu` 变体、Linux 用 QEMU/OVMF |
| **L2 脚本宿主(预留)** | 由 `reims-go.exe` 以隐藏子命令拉起的独立进程,内嵌纯 Go JS 引擎运行单文件脚本;无文件/网络能力,仅宿主注入的 API | 进程级 + 引擎沙箱 | 全部;Job Object 限制内存与 CPU | 轻量 Hook、体检规则、日志告警 |
| **L3 Sidecar** | 独立 exe,每插件一个进程,双向 JSON-RPC 2.0 | 进程级;**OS 权限等同当前用户** | 仅 Host API 访问面 | Linux 驱动、代码 Hook、CLI 命令、排障采集 |
| **L4 UI** | 声明式贡献由宿主原生组件渲染;复杂交互用沙箱 iframe | 强 | 全部 | 驱动专属表单、菜单项、状态卡片、自定义面板 |
**L2 的定位**:Hook 发生在秒级的 VM 生命周期上,没有 Magpie 那样的微秒级热路径,因此不把脚本引擎嵌入主进程。若出现「低信任 + 需要逻辑」的刚需,复用同一个 `reims-go.exe` 以隐藏子命令拉起脚本宿主进程:既不增加分发物、不要求用户装运行时,又获得进程级崩溃隔离与 Job Object 内存上限(纯 Go JS 引擎本身没有堆上限)。在此之前,L1 规则 Hook 与 L3 Sidecar 覆盖需求。
**多合一包**:一个插件可在 `contributes` 中同时声明多种能力,例如 Linux 插件同时提供 L3 驱动、运行时源、规则 Hook 与创建向导 Schema。
### 3.2 内置功能先插件化
扩展点先由内置功能使用一遍再对外开放:reims 驱动成为内置 `builtin.driver.reims-macos`,现有启动准备步骤与宿客桥接迁为内置扩展,经同一注册表注册、可独立启停、禁用后零残留。首批示例插件为默认开启的剪贴板互通与默认关闭的滚轮反转(见 §5.4)。
---
## 4. 内核机制
### 4.1 注册表与可逆副作用
- 每个已启用插件(含内置)拥有一个作用域,所有注册行为(提供服务、贡献扩展点、订阅事件、后台服务、Win32 钩子、QMP 监视)都登记一个释放函数;停用、卸载或升级时**逆序释放**,激活中途失败则回滚已登记项。
- 插件声明 `requires` / `provides`(服务名 + 版本范围)。Reconcile 先关后开:先释放不再需要的插件及依赖其服务的插件,再按依赖求不动点激活。状态为 `off / pending / active / degraded / failed`。
- **使用中不可移除**:仍有 VM 归属的驱动、仍被 VM 使用的运行时,不可停用或卸载;使用情况查询失败按「使用中」处理。
- 内置扩展通过 `pluginApi` 版本做兼容检查;激活 panic 转为 `failed` 并回滚。
### 4.2 扩展点目录
| 扩展点 | 来源层 | 基数 | 失败策略 |
| :--- | :--- | :--- | :--- |
| `themes`(令牌、配色方案、字体、图标、背景、提示音、样式表、状态装饰) | Builtin · L1 | 按 id,同一时刻仅一个主题包生效 | 回退内置默认主题 |
| `uiScripts`(交互主题脚本) | 主窗口受信任脚本 | 随所属主题包 | 单个功能出错只停用该功能;整体失败回退到无脚本的主题 |
| `locales` | Builtin · L1 | 按 id | 回退内置 |
| `inputFilters` | Builtin · L1(仅声明式规则) | 有序列表 | 规则非法即忽略;宿主输入服务异常时卸载钩子、放行原始输入 |
| `vmTemplates` | Builtin · L1 | 列表 | 跳过非法项 |
| `runtimeSources` | Builtin · L1 | 列表 | 跳过该源,回退其他源 |
| `runtimeKinds` / `runtimes` | Builtin · 运行时包 | 按种类 | 不激活,相关 VM 提示运行时不可用 |
| `guestDrivers` | Builtin · L3 | 按 id | 该驱动的 VM 标记「驱动不可用」,其他 VM 不受影响 |
| `hooks` | Builtin · L1 · L2 · L3 | 有序列表 | 按事件模式(§4.3) |
| `commands` | Builtin · L2 · L3 | 按 id | 报错并提示 |
| `menus` / `vmCards` / `settingsPages` / `statusItems` | 声明式 | 列表,设数量上限 | 隐藏该项 |
| `panels` | L4 iframe | 限定槽位 | 错误占位 + 重试 |
| `diagnostics` | Builtin · L3 | 列表 | 跳过;输出强制脱敏 |
UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`、`settings.plugin`,后续按真实需求再增加 `sidebar.footer`、`statusbar.right`、`create.source`;插件只能向已声明槽位贡献。
### 4.3 Hook 事件与分发模式
分发模式与失败策略是事件契约的一部分:
| 事件 | 触发位置 | 模式 | 时限 | 失败策略 |
| :--- | :--- | :--- | :--- | :--- |
| `host.preflight` | 体检完成后 | 收集:追加优化建议/警告 | 500 ms | 丢弃该插件结果 |
| `vm.beforeCreate` | 校验通过后、创建前 | 拦截:校验错误或默认值补丁 | 2 s | 补丁丢弃、放行 |
| `vm.afterCreate` | 创建成功后 | 观察 | 异步 30 s | 只记录 |
| `vm.beforeStart` | 启动准备阶段 | 拦截:返回启动意图(§4.4) | 每插件 2 s,链路 10 s | 意图丢弃、放行;仅声明 `blocking` 且用户启用的守卫可阻断 |
| `vm.afterStart` | 拿到 PID / QMP / SSH 端口后 | 观察:注册后台监视、通知 | 异步 | 只记录 |
| `vm.beforeStop` / `vm.afterStop` / `vm.deleted` | 关机/删除前后 | 观察 | 异步 | 只记录 |
| `log.onLine` | VM 日志行进入监视器 | 观察:里程碑、告警、修复建议 | 批量投递,超时丢弃 | 背压时丢弃,绝不阻塞日志 |
| `command.invoke` | 菜单点击或 CLI 调用 | 请求/响应 | 30 s | 报错 |
同一事件的处理器按「内置 → 用户排序」执行;连续超时或异常达阈值的插件自动降级为 `degraded` 并在插件页提示原因,不阻断 VM 启停。
### 4.4 启动意图与参数归属账本
`vm.beforeStart` 处理器不能直接调用 `reims-ctl`,只能返回启动意图:
| 意图项 | 约束 |
| :--- | :--- |
| QEMU 参数片段 | 带归属(插件 id);只允许宿主白名单内的选项族;同一选项多方设置时按优先级取一并告警 |
| 子进程环境变量 | 仅限插件命名空间前缀,或宿主白名单变量 |
| 前置检查 | 人话化的警告或阻断理由 |
| 启动后动作 | 由宿主执行的受控动作(打开端口转发、注册监视等) |
宿主合并所有意图后,对 `reims-ctl` 管理的 VM **一次**经 `reims-ctl set --extra-args` 写入,并在 VM 目录维护**参数归属账本**,记录每个片段的归属。插件停用或卸载时按账本精确剥离其片段;现有按功能各写一对合并/剥离函数的做法(离线辅助盘、Guest Tools、`kernel-irqchip=off`、Win10 冷重启 QMP 通道)统一迁到账本之上。用户在「高级」中手写的 `--extra-args` 不属于任何插件,永不被自动剥离。
---
## 5. 四类插件专项设计
### 5.1 主题与美化(宿主只提供接口)
除内置浅色/深色外,Reims-Go 不发布主题包,但主题扩展接口按能承载 dsh-claude-style 级复杂主题设计。该主题在 DSH 上的实践表明:宿主没有稳定契约时,主题只能依附带哈希的类名、自建页面观察总线与帧管线、按结构写覆盖层,宿主改版即失效,样式匹配性能也受拖累。Reims-Go 由宿主主动提供这些契约。
**UI 契约(`uiApi`,随 `pluginApi` 版本化,由前端构建生成 `ui-contract.json` 供主题作者校验)**
| 契约 | 内容 |
| :--- | :--- |
| 设计令牌 | 单一来源(令牌数据同时生成 CSS 变量与前端常量),覆盖颜色、字体排印、形状、阴影、动效时长与缓动、层级;动效档位(含系统「减少动态效果」)在一处解析为文档属性,样式与脚本读同一个值 |
| 部件 | 关键区域与控件挂稳定的部件类名(如 `rg-p-sidebar`、`rg-p-vm-header`、`rg-p-statusbar`),每个部件一个独立类名,便于浏览器按类名分桶匹配;主题选择器只允许使用部件、状态属性与令牌,不得依赖内部类名或界面文字 |
| 状态属性 | 文档与区域上的只读状态:外观、当前视图、VM 显示状态、忙碌态、是否有错误、侧栏折叠 |
| 槽位锚点 | 装饰与扩展内容的挂载点(如侧栏底部、VM 预览四角、状态栏、空状态区) |
契约内的部件、状态属性与令牌的重命名或删除属于 `uiApi` 主版本变更;前端构建检查契约中的每个部件仍由某个组件输出。
**三档主题能力**
| 档位 | 能力 | 层级与信任 | 对应复杂主题的典型需求 |
| :--- | :--- | :--- | :--- |
| **令牌主题** | 配色方案集合:少量种子色 + 声明式派生规则(按浅/深外观对种子做亮度、色度、透明度偏移)生成整套表面/文字/边框色阶;用户在宿主提供的编辑器中改种子、新建/复制/重命名/删除方案。字体(包内字体或用户字体目录)、图标与品牌标记替换、背景、按事件配置的提示音 | L1,宿主校验 | 多套配色预设与方案管理、自带字体、品牌标记、提示音 |
| **样式主题** | 面向部件契约的样式表(宿主以 `@layer` 固定层叠顺序:基础 → 主题 → 用户);声明式状态装饰(按状态表达式切换精灵图/动画帧,锚定槽位,如随 VM 启停与任务进度变化的吉祥物) | L1,宿主校验与清洗 | 窗框/侧栏/排印样式、状态动画吉祥物 |
| **交互主题** | 主窗口内运行的受信任 UI 脚本,只经宿主 UI SDK 工作 | 高信任(`ui:script`) | 滚动、折叠、悬停预览等交互增强 |
**UI SDK**(交互主题的唯一受支持接口):
- 生命周期:主题脚本导出装载函数,所有订阅、计时器与挂载都登记释放函数;切换或停用主题时逆序拆除,单个功能抛错不影响其余功能。
- 只读状态订阅:非敏感的 VM 摘要、任务进度、当前视图、外观;不提供原始路径与敏感字段。
- 宿主提供的页面观察总线、帧读写管线与按部件查询:主题不自建节点观察者,也不整页查询文档。
- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。
- 受限动作:仅开放非破坏性界面动作(折叠侧栏、打开设置、前置 VM 窗口等);启停、删除、配置写入不在 SDK 中。
- 主题设置:由 `settings` Schema 定义,宿主渲染设置页。
**边界**:
- 主窗口同一 JS 环境内的脚本不是安全边界(可操作 DOM),交互主题按高信任处理:需 `ui:script` 权限与显式确认,`community` 级默认不可启用;宿主在加载主题脚本前收起 Wails 绑定的全局对象,SDK 是唯一受支持的接口。
- 样式清洗:禁止外部 `url()` 与远程 `@import`,资源只能引用包内清单中的文件;窗口拖拽区、焦点环与最小点击热区等可用性属性由宿主在更高层保留,不被主题覆盖。
- 同一时刻只启用一个主题包,切换时先停用旧主题再装载新主题;安全模式一律回到内置主题。
- 首帧前按当前主题内联令牌防闪烁;无边框窗口的标题栏由前端绘制,可随主题变化。
- 主题只改视觉与交互呈现,不改文案、信息层级与操作入口([`design-guidelines.md`](design-guidelines.md) 的主操作与破坏性操作约束由宿主守住)。
- 需要读写用户文件或常驻服务的主题,以同包 L3 Sidecar 实现。
- 开发支持:`reims-go plugin link` 链接本地目录并热重载;`reims-go plugin doctor` 校验样式只使用契约内的部件、状态属性与令牌。
### 5.2 运行时(运行时种类 + 运行时包)
- `internal/runtime` 从单一 `reims-vgpu` 泛化为**运行时种类注册表**:内置 `reims-vgpu` 种类;插件可提供新种类(如上游 QEMU + OVMF)或同种类的社区构建。
- 运行时 `manifest.json` 在 schema 2 基础上增加:`kind`;`runtime_api`(驱动依赖的命令行契约版本,含 `reims-ctl` 子命令集与输出格式);`capabilities`(补丁与特性标识,替代按补丁名子串判断)。
- 驱动声明所需运行时种类与 `runtime_api` 范围;不兼容时禁止启动并给出人话提示。
- 存量布局 `runtimes/<commit>/` 保持不变,视为 `reims-vgpu` 种类;新种类安装到 `runtimes/<kind>/<version>/`,避免迁移存量数据。
- 复用现有下载、续传、`SHA256SUMS.txt` 强校验、原子解压与多版本切换;第三方运行时不进入官方 `stable` 通道,安装前展示来源、许可证与补丁清单,并要求提供对应源码包(GPL 义务由分发者承担,市场审核把关)。
### 5.3 非 macOS 虚拟机(客体驱动,L3)
**驱动抽象**:当前 `internal/app`、`internal/vmstart`、`internal/cli` 直接依赖 `internal/driver/reims` 的具体类型。抽象后:
| 层 | 内容 |
| :--- | :--- |
| 通用 VM 模型 | 驱动 id + 名称、状态(`stopped / running / broken` 与过渡态)、CPU / 内存 / 磁盘摘要、目录、能力位 |
| 驱动专有数据 | 不透明扩展字段 + 驱动提供的创建/设置 JSON Schema(宿主原生渲染,标注生效时机) |
| 能力位 | `snapshot`、`cow_clone`、`resize`、`qmp`、`ssh`、`guest_tools`、`affinity`、`opencore`、`recovery`、`cloud_init`、`uefi_iso` 等;UI 与 CLI 按能力位显隐操作 |
| 驱动动作 | `List / Show / ValidateCreate / Create / ValidateSet / Set / Start / Stop / Delete`,可选快照、派生、扩容与通用 `InvokeAction` |
- **VM 归属**:VM 目录内标记文件记录驱动 id;无标记的存量 VM 自动归属 `builtin.driver.reims-macos`,零迁移。CLI 增加 `vm create --driver <id>`,其余 `vm` 子命令按归属自动路由。
- **宿主共享服务**(驱动经反向调用复用):体检报告、提交内存预检、大小核绑核、QMP 截屏与键入、缩略图、Guest Tools 注册、进程退出监视、任务进度、日志通道、托盘菜单。
- **VM 进程归宿主托管**:驱动不直接派生 QEMU,而是请求宿主代为启动并返回 PID。这样 VM 进程不随驱动进程的 Job Object 被回收(驱动崩溃或重启不误杀 VM),绑核、退出监视与冷重启补偿也只在宿主实现一份。
- **配置写入**:`reims-ctl set` 铁律约束 reims 管理的 VM;Linux 驱动自管配置文件,同样不允许 UI 拼接原始命令行。
- **Linux 驱动的自身难点**:WHPX 直接启动与 Win10 冷重启补偿复用;显示路径(QEMU 窗口或 virtio-gpu,3D 加速**待验证**);cloud-init seed 生成;发行版镜像下载与校验;客体代理(qemu-guest-agent 或 Guest Tools Linux 版)。上游 `reims-ctl` 是否支持非 macOS 客体**待验证**;若将来支持,Linux 驱动可退化为其薄封装。
- 官方 Linux 驱动作为独立仓库的一方插件交付,用于验证驱动抽象;主程序不为它写特例代码。
### 5.4 Hook 与自动化
- **L1 规则 Hook**:条件 + 动作的声明式规则,条件只能引用宿主定义的事实(Windows 版本、GPU、驱动、能力位、运行时能力),动作只能产出 §4.4 的意图或受控动作,不图灵完备。覆盖「某宿主条件下追加参数」「启动后打开 SSH 终端」等大多数场景。
- **L3 代码 Hook**:Sidecar 订阅事件,经同一意图通道生效;`log.onLine` 以批量形式投递。
- **L2 脚本 Hook**:预留,启用条件见 §3.1。
#### 首批示例插件
两个示例分别覆盖「编译期内置扩展」与「声明式插件包」两条路径,并分别演示默认开启与默认关闭:
| 示例 | 形态 | 默认 | 演示的机制 |
| :--- | :--- | :--- | :--- |
| **剪贴板互通** `builtin.bridge.clipboard` | 内置 Go 扩展 | 开启 | 服务依赖(依赖 Guest Tools 传输服务)、运行中启停与完整拆除、按 VM 设置立即生效、宿主与客体的功能协商、隐私(内容不入日志) |
| **滚轮反转** `reims.input.wheel-invert` | 随主程序附带的 L1 声明式插件包 | 关闭 | 标准插件包格式与清单、按 VM 设置、在宿主热路径上安全扩展(插件只声明策略,不注入代码) |
**剪贴板互通**
- 拆分 Guest Tools:回环 HTTP 鉴权、客体代理、`REIMSTOOLS` 辅助盘与 VM 注册作为内置「Guest Tools 传输服务」,对外提供路由注册与客体功能协商;剪贴板、共享文件夹、盘符只读共享、防休眠与文本输入是其上的功能扩展,剪贴板第一个迁出。
- 激活时向传输服务注册剪贴板路由并启动宿主剪贴板监视,停用时二者随作用域释放;客体代理从配置接口得知功能关闭后停止轮询,旧版代理请求已关闭的路由时得到明确的「功能关闭」应答并退避。
- 设置:全局开关 + 按 VM 覆盖;方向(双向 / 仅宿主到客体 / 仅客体到宿主);是否同步图片与大小上限;均立即生效。
- `vm.card` 显示连接状态;排障包只记录次数与错误,不记录剪贴板内容。
**滚轮反转**
- 背景:macOS 默认开启「自然滚动」,与 Windows 滚轮方向相反。
- 宿主新增内置「输入服务」,统一持有低级键盘/鼠标钩子(现有 IME 桥的键盘钩子迁入),并开放 `inputFilters` 扩展点。低级钩子回调超时会拖慢整个系统的输入,因此过滤器只能是声明式规则(事件类型、轴向、变换、作用范围),任何插件代码都不得进入该路径。
- 插件只声明一条规则:前台窗口属于启用该设置的 VM 时,取反垂直(可选水平)滚轮增量。宿主丢弃原事件并以带自身标记的注入事件重发反向增量,识别标记避免重复处理;仅在存在命中 VM 时安装鼠标钩子,插件停用或没有命中 VM 时卸载。
- 设置按 VM:开关、垂直/水平分别控制,立即生效;渲染在 VM 设置的「键盘与指针」分组。
- 未采用的备选:经 Guest Tools 客体代理修改 macOS 自然滚动偏好。它依赖客体代理在线,安装器与恢复模式中不可用,可能需重新登录才生效(待验证),并会改变客体全局偏好、停用时还需恢复原值。在 SDL 窗口内改写滚轮属于引擎补丁范畴(§5.5),也不采用。
- 待验证:VM 窗口捕获鼠标(相对模式/原始输入)时低级钩子丢弃与重发是否仍生效;精确式触控板高分辨率滚动增量取反后的手感。
#### 其余内置扩展(由现有模块迁入)
| 内置扩展 | 对应现有模块 | 使用的扩展点 |
| :--- | :--- | :--- |
| `builtin.bridge.guest-tools` | `internal/guesttools`、`guesttools_flow.go` | 提供传输服务 + `vm.beforeStart`(注入桥接参数与环境变量)+ `vm.afterStart` + `vm.card`;共享文件夹、盘符共享、防休眠逐步拆为功能扩展 |
| `builtin.input` | `host/ime_hook_windows.go` | 提供输入服务与 `inputFilters`;IME 桥成为其上的功能,停用时卸载钩子线程 |
| `builtin.compat.win10-cold-reboot` | `app.go` 冷重启监视 | `vm.beforeStart`(`-no-reboot` 与独立 QMP 通道)+ `vm.afterStart` + `vm.afterStop` |
| `builtin.compat.whpx-fallback` | `vmstart.applyProbedWHPXCompat` | `host.preflight` + `vm.beforeStart`(按运行时能力决定是否降级) |
| `builtin.prep.offline-helper` / `recovery-boot` / `guest-lang` | `vmstart.Prepare` 其余步骤 | `vm.beforeStart` |
### 5.5 与上游补丁队列的边界
| 类别 | 归属 | 原则 |
| :--- | :--- | :--- |
| 引擎内部崩溃与 Hypervisor 层修复(WHPX 兼容、协程、构建锁文件等) | [`patches/`](../patches/)(编译期) | 外部插件无法等价替代;坚持上游 PR,合入即退役 |
| 窗口内部消息循环拦截(如 SDL 窗口内字符消息) | `patches/`,宿主侧做部分补偿 | 跨进程拦截需 DLL 注入,杀软误报风险高,不做成插件 |
| 宿主侧绕过、兜底补偿与宿客桥接 | 内置扩展(§5.4) | 运行时缺少对应补丁时平滑降级;依据运行时 `capabilities` 判断 |
---
## 6. 插件包与清单
### 6.1 包格式与目录
- 插件包为 zip 归档,根目录含 `plugin.json`、`SHA256SUMS` 与可选签名(ed25519,签名覆盖 `SHA256SUMS`)。
| 路径(位于 `<DataRoot>/plugins/`) | 用途 |
| :--- | :--- |
| `state.json` | 启用状态、版本钉选、已批准权限快照、冲突偏好;写入用临时文件 + rename + `.bak`;**读取失败即报错,绝不视为空表** |
| `pkgs/<id>/<version>/` | 解压后的只读包体,多版本并存,回滚即切换 |
| `data/<id>/` | 插件私有可写目录,同时是 Sidecar 的工作目录 |
| `logs/<id>.log` | 插件 stderr 与宿主审计记录,限额轮转 |
| `index-cache.json` | 市场索引缓存(另有内嵌兜底副本) |
### 6.2 清单字段(`plugin.json`)
| 字段 | 说明 |
| :--- | :--- |
| `schema` | 清单格式版本 |
| `id` / `version` | 反向域名 id;SemVer |
| `name` / `description` | `zh-CN` / `en-US` 本地化文本,**无需执行插件代码即可读取** |
| `publisher` / `license` / `homepage` | 来源与许可,市场审核依据 |
| `engines` | `reims-go` 版本范围与 `pluginApi` 范围,**下载前预检** |
| `platforms` | 如 `windows-x64` |
| `entry` | Sidecar 可执行文件、脚本文件、面板 HTML 根目录;层级由内容推导,不信任自报 |
| `contributes` | 各扩展点贡献(§4.2) |
| `requires` / `provides` | 服务与运行时依赖、提供的服务 |
| `permissions` | Host API 能力(§7.1) |
| `activation` | `onStartup` / `onVMEvent` / `onCommand` / `onPanel`,默认惰性激活 |
| `settings` | JSON Schema;扩展标注 `x-secret`(不回显、不进日志)、`x-effect`(立即生效 / 下次启动生效)与 `x-scope`(`app` 全局 / `vm` 按虚拟机,后者渲染在 VM 设置对应分组) |
| `defaultEnabled` | 安装或首次启动时的默认启用状态;仅内置扩展与随主程序附带的插件可为 `true` |
| `provenance` | **运行时包必填**:上游仓库与 commit、补丁清单与哈希、源码包文件名 |
---
## 7. 权限、信任与安全边界
### 7.1 权限分级
| 等级 | 权限 | 审批 |
| :--- | :--- | :--- |
| **低** | `vm:read`(通用模型,不含敏感字段)、`ui:notify`、`task:progress`、`fs:plugin_data`、`log:read` | 启用时展示说明 |
| **中** | `vm:intent`、`runtime:source`、`net:<origin>`(经宿主代理发出)、`ui:slot`、`input:filter`(声明输入过滤规则) | 首次启用逐项确认 |
| **高** | `driver:vm`、`runtime:provider`、`process:spawn`、`vm:control`、`qmp:write`、`fs:vm_dir`、`fs:shared`、`host:clipboard`、`ui:script` | 强提示(展示可执行文件或脚本路径、SHA-256、发布者、许可证)并显式勾选;升级新增高危权限时暂停并要求重新批准 |
| **不存在** | 敏感字段读取、UAC 提权、重启 Windows、直写 `vm.toml` | 插件只能请求宿主发起人工确认流程 |
### 7.2 如实声明的信任边界
- L1、L2、L4 的权限由宿主强制。**L3 是原生代码,OS 层面无法约束**,权限只约束其对 Host API 的访问;安装与启用 L3 插件时明确告知「此插件能以你的账户身份执行任意操作」。
- 信任等级:`official`(官方密钥签名)、`verified`(审核 + 发布者签名)、`community`(仅哈希)、`dev`(本地链接,需开启开发者模式)。`community` 级 L3 插件默认不可启用,需二次确认。
- 以 AppContainer 或低完整性级别运行 Sidecar 作为后续增强项评估。
### 7.3 UI 与本地接口安全
- 插件资源经 Wails AssetServer 的独立路由提供,路径带每次运行随机生成的令牌,校验目录穿越,附 `X-Content-Type-Options: nosniff` 与 CSP;SVG 一律禁脚本。
- iframe 面板(后置):`sandbox="allow-scripts"`、`connect-src 'none'`;bridge 只应答来源窗口为自身 iframe 的消息,所有读取在 Go 侧按 `permissions` 二次校验并限流;主题令牌经 bridge 下发。
- 宿主本地 HTTP 接口(如 Guest Tools)拒绝 `Origin: null`、跨站请求与 `Sec-Fetch-Dest: iframe` 请求,防止被沙箱 iframe 或外部网页借道调用。
---
## 8. 进程监管与通信协议
- **协议**:stdin/stdout 双向 JSON-RPC 2.0,采用 `Content-Length` 分帧(LSP 风格);握手交换 `pluginApi` 版本与能力;stdout 只走协议帧,日志一律走 stderr 并由宿主采集。截图、磁盘镜像等大对象不进 JSON,经插件数据目录内的文件路径传递。
- **进程模型**:每个 L3 插件独立进程;全部放入设置 `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` 的 Job Object,宿主退出或崩溃时进程树一并回收;L2 脚本宿主额外设置进程内存与 CPU 时间上限。
- **健壮性**:单写协程 + 有界队列提供背压;所有请求可取消;回收依据进程句柄而非管道 EOF;子进程不继承协议管道,工作目录固定为 `data/<id>/`;崩溃后指数退避重启,连续失败熔断为 `failed`;升级与配置变更采用「先起新进程、旧进程处理完在途请求再退出」。
- **惰性与回收**:按 `activation` 惰性拉起;空闲超时回收;托盘常驻模式下只保留有活动 VM 或后台服务的 Sidecar。
- **GUI / CLI**:插件宿主位于核心包。需要常驻进程的能力(Sidecar、后台服务)由界面进程托管,与 Guest Tools 一致;CLI 经现有单实例交接走界面进程,`--data-root` 直连模式按需临时拉起所需 Sidecar,命令结束即回收。
### 8.1 资源预算(零外部插件零开销)
未安装任何外部插件时,插件系统不得明显增加占用。以引入插件系统前的版本为基线,在同一宿主上对比:
| 指标 | 预算 |
| :--- | :--- |
| 常驻内存(空闲、托盘常驻) | 增加 ≤ 3 MB |
| 冷启动到主窗口可交互 | 增加 ≤ 20 ms |
| 常驻进程、后台轮询与全局输入钩子 | 不新增 |
| `reims-go.exe` 体积 | 增加 ≤ 1.5 MB |
| 前端主包 | 插件管理页与 Schema 表单渲染器按需加载,不计入主包 |
| VM 启动前的 `reims-ctl set` 调用 | 不多于改造前(意图合并后至多一次) |
保障预算的实现纪律:
- 事件只在有订阅者时分发,无订阅者时不构造事件对象(尤其是 `log.onLine`)。
- 不引入状态轮询:Reconcile 只由安装、启停、设置变更触发;文件监视仅在开发者模式的本地链接上启用。
- 不预热:Sidecar、脚本宿主、iframe 面板与市场索引均在首次使用时创建或拉取。
- 只使用内置主题时不注入额外样式,UI SDK 仅在启用交互主题时加载。
- 体积较大的依赖(如嵌入式 JS 引擎)不默认编入主程序,引入前单独评估体积代价。
---
## 9. 分发、更新与恢复
- **安装来源**:本地包导入(首批)、市场索引(后续)、开发者模式本地目录链接。
- **随主程序附带的插件**:以标准插件包形式嵌入 `reims-go.exe`(如滚轮反转),信任等级为 `official`,版本跟随主程序;可启用/停用,不可卸载;用于在不依赖市场的情况下走通完整的清单解析、设置渲染与启停链路。
- **事务安装**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 原子 rename 到 `pkgs/<id>/<version>` → 提交 `state.json`。任一步失败都不改变现状。
- **市场索引**:独立仓库发布静态 `index.json`(GitHub 主源 + GitCode 镜像,复用运行时下载源的回退与代理逻辑),含版本、`engines`、下载地址、SHA-256 与签名者;主程序内嵌兜底副本。
- **更新与回滚**:新旧版本并存、切换指针,保留最近若干版本;插件同样区分 `alpha` / `stable` 通道,默认只取 `stable`。
- **安全模式**:`reims-go --safe-mode` 跳过全部第三方插件,界面顶部显示横幅与插件管理入口;以启动哨兵文件检测上次插件初始化阶段异常退出,下次启动询问是否进入安全模式。
- **市场红线**:拒收含 Apple 专有文件、SMBIOS 真值或闭源固件的包;运行时包必须附源码与许可证。
---
## 10. GUI 与 CLI 接入
| 入口 | 内容 |
| :--- | :--- |
| CLI | `reims-go plugin list / install / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor / run <id> <command>`;`vm create --driver <id>` |
| 应用设置 → 插件 | 分组展示内置扩展与第三方插件:来源与信任标签、许可证、权限摘要、启用开关、故障状态与日志入口、本地包导入 |
| 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 |
| VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 |
| 创建向导 | 先选驱动,再按驱动 `CreateSchema` 渲染专属表单 |
所有插件文案遵守 [`design-guidelines.md`](design-guidelines.md) §7,插件贡献的按钮与菜单不得占用页头主操作位。
---
## 11. 技术难点
1. **驱动抽象重构**:VM 详情模型与前端(VM 页、设置面板、托盘、CLI)深度耦合 macOS / reims 字段,需在不回归现有功能的前提下拆出通用模型与能力位,是工作量最大的一步。
2. **意图合并与参数归属**:多插件意图的冲突仲裁、账本与 `reims-ctl set` 的一致性、OpenCore 重建后重放(如客体语言)的时序。
3. **运行时契约脆弱**:`reims-ctl show` 目前为文本解析,第三方运行时若改变输出即破坏驱动;需以 `runtime_api` 严格版本化,并推动上游提供结构化输出。
4. **Windows 进程管理**:Job Object 与 VM 进程归属分离、孤儿进程、未签名 Sidecar 被杀软或 SmartScreen 拦截、非 ASCII 用户名路径。
5. **原生插件安全**:L3 无法沙箱化,只能依靠签名、审核、信任分级与透明告知。
6. **UI 一致性与自由度**:严格设计规范下以声明式贡献为主,iframe 面板需同步主题令牌、DPI、焦点与快捷键。
7. **UI 契约维护**:部件类名、状态属性与令牌成为公共 API 后,前端重构须连同 `uiApi` 版本与契约检查一起演进;交互主题脚本在主窗口内运行,只能靠信任分级与 SDK 约束,无法物理隔离。
8. **全局输入钩子**:低级鼠标钩子影响整个系统的输入延迟,回调必须极短且按需安装;SDL 捕获模式下的行为与杀软启发式误报需真机验证。
9. **公共 API 稳定性**:v0.x 核心演进快,首批扩展点必须克制并版本化,保持对上一 `pluginApi` 主版本的兼容窗口。
10. **Linux 客体图形与集成**:Windows 上缺少与 `reims-vgpu` 等价的 Linux 加速路径,cloud-init 与客体代理需要额外工程。
11. **合规**:第三方运行时的源码义务、插件许可证声明、插件排障内容的强制脱敏。
12. **资源占用**:惰性激活、空闲回收与面板释放,守住 §8.1 的资源预算与现有内存约束。
---
## 12. 分阶段演进与验收标准
```mermaid
flowchart LR
P0["Phase 0\n内部抽象\n(不对外)"] --> P1["Phase 1\n插件底座 + L1\n(主题/模板/运行时源/规则 Hook)"]
P1 --> P2["Phase 2\n运行时种类"]
P1 --> P3["Phase 3\nL3 Sidecar + Host API"]
P3 --> P4["Phase 4\n官方 Linux 驱动"]
P3 --> P5["Phase 5\n生态:签名/市场/iframe/L2"]
```
| 阶段 | 范围 | 验收标准 |
| :--- | :--- | :--- |
| **Phase 0** | 注册表与可逆作用域;驱动抽象(reims 为内置驱动);启动准备与宿客桥接迁为内置扩展;Guest Tools 拆出传输服务与**剪贴板互通示例**;输入服务(IME 键盘钩子迁入);参数归属账本;UI 契约 v1(令牌单一来源、部件类名、状态属性) | `go test ./...` 与前端构建通过;存量 VM 零迁移、行为零回归;剪贴板互通可在 VM 运行中开关且关闭后零残留(无残留路由与剪贴板监视);其余内置扩展同样可独立停用且零残留;满足 §8.1 资源预算 |
| **Phase 1** | 插件包与清单、事务安装、`state.json`、安全模式;插件管理页与 `reims-go plugin`;`inputFilters` 与**滚轮反转示例**;令牌主题与样式主题接口;图标、VM 模板、运行时源、规则 Hook | 滚轮反转默认关闭、按 VM 开启即时生效、停用后钩子卸载;以不发布的测试主题验证配色方案、字体、部件样式与状态装饰;损坏包与不兼容包在落盘前被拒绝;仍满足 §8.1 资源预算 |
| **Phase 2** | 运行时种类注册表、`runtime_api` 与 `capabilities`、来源展示 | 第二种运行时与官方运行时并存切换;不兼容组合被拦截并给出提示 |
| **Phase 3** | JSON-RPC 协议 v1、进程监管、反向 Host API、权限审批、代码 Hook、插件命令、排障采集、轻量 Go SDK | 死循环或崩溃的示例 Sidecar 不影响主窗口与运行中 VM;退出或禁用后无孤儿进程 |
| **Phase 4** | 独立仓库的官方 Linux 驱动 | 不修改主程序源码,经 GUI 与 CLI 完成 Linux VM 创建、WHPX 启动、绑核、截屏、SSH 与快照;真机验证 |
| **Phase 5** | 签名体系与市场索引、iframe 面板、交互主题 UI SDK、按需引入 L2 脚本宿主 | 第三方插件经审核上架;iframe 面板无法越权读取或联网;参照 dsh-claude-style 的功能清单逐项确认可由三档主题能力承载或列出缺口 |
---
## 13. 待决事项
1. **滚轮反转的实现路径**:需在真机上验证 VM 窗口捕获鼠标时低级钩子方案是否可靠;若不可靠,再评估客体侧偏好方案。
2. **L2 脚本宿主是否需要**:仅当出现 L1 规则无法表达、又不适合要求作者交付原生 exe 的真实需求时引入;届时在纯 Go JS 引擎与 WASM 之间选型。
3. **市场形态与审核责任**:首批仅本地包导入;社区索引的维护者、审核流程与签名密钥托管方式待定。
4. **Sidecar 原生沙箱**:AppContainer / 低完整性级别的兼容性与维护成本待评估。
5. **上游结构化输出**:是否向上游提议 `reims-ctl show --json`,以及非 macOS 客体支持的计划,需核对上游实际进展(待验证)。
+1 -1
View File
@@ -5,7 +5,7 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"build": "tsc --noEmit && vite build && node scripts/check-ui-contract.mjs",
"preview": "vite preview"
},
"dependencies": {
+1 -1
View File
@@ -1 +1 @@
f38f2bbc623190aed99c112f7b10c276
fd01023ab020f4fa559696be6708a9a3
+61
View File
@@ -0,0 +1,61 @@
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')
const srcDir = path.join(rootDir, 'src')
const contractSrc = fs.readFileSync(path.join(srcDir, 'styles', 'ui-contract.ts'), 'utf8')
const tokensCss = fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8')
function extractArray(name) {
const re = new RegExp(`export const ${name} = \\[([\\s\\S]*?)\\] as const`)
const m = contractSrc.match(re)
if (!m) throw new Error(`Could not parse ${name} from ui-contract.ts`)
return [...m[1].matchAll(/'([^']+)'/g)].map((x) => x[1])
}
const apiMatch = contractSrc.match(/UI_API_VERSION\s*=\s*'([^']+)'/)
const uiApi = apiMatch ? apiMatch[1] : '1.0.0'
const parts = extractArray('UI_CONTRACT_PARTS')
const stateAttrs = extractArray('UI_CONTRACT_STATE_ATTRS')
const slots = extractArray('UI_CONTRACT_SLOTS')
const tokens = extractArray('UI_CONTRACT_TOKENS')
// Collect all TSX source text to verify every declared part class is actually emitted (§5.1).
function readAllTsx(dir) {
let buf = ''
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) buf += readAllTsx(full)
else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts')) buf += '\n' + fs.readFileSync(full, 'utf8')
}
return buf
}
const allSrc = readAllTsx(srcDir)
const missingParts = parts.filter((p) => {
// Exclude the definition file itself by checking for usage outside ui-contract.ts.
const withoutContract = allSrc.replace(contractSrc, '')
return !withoutContract.includes(p)
})
const missingTokens = tokens.filter((tk) => !tokensCss.includes(`${tk}:`))
if (missingParts.length > 0) {
console.error('[ui-contract] ERROR: contract parts not emitted by any component:', missingParts.join(', '))
process.exit(1)
}
if (missingTokens.length > 0) {
console.error('[ui-contract] ERROR: contract tokens missing in tokens.css:', missingTokens.join(', '))
process.exit(1)
}
const out = { uiApi, tokens, parts, stateAttrs, slots }
const jsonText = JSON.stringify(out, null, 2) + '\n'
fs.writeFileSync(path.join(rootDir, 'ui-contract.json'), jsonText, 'utf8')
const distDir = path.join(rootDir, 'dist')
if (fs.existsSync(distDir)) {
fs.writeFileSync(path.join(distDir, 'ui-contract.json'), jsonText, 'utf8')
}
console.log(`[ui-contract] OK (uiApi=${uiApi}, parts=${parts.length}, tokens=${tokens.length}, slots=${slots.length})`)
+102 -9
View File
@@ -15,12 +15,12 @@ import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './
import { LogLine, appendLog } from './lib/logs'
import { macOSMajor } from './lib/macosRelease'
import { currentTask, finishedTaskTTL, pruneFinishedTasks, upsertTask } from './lib/tasks'
import { applyActiveTheme, type UIStateSnapshot } from './lib/themeEngine'
import { latestVMStats } from './lib/vmStats'
import { AppState, CachedInstaller, CreateOpts, Locale, RuntimeSource, Task, VMDetail } from './types'
import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, RuntimeSource, Task, VMDetail } from './types'
import { Tip, TooltipProvider } from './ui/controls'
import { Toaster, useToasts } from './ui/toast'
import { api, events } from './wails'
import { OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from '../wailsjs/runtime/runtime'
import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails'
// Opened on demand, so each is its own chunk and stays out of the startup
// bundle: the wizard, VM settings and affinity dialogs, first-run setup, and
@@ -85,11 +85,18 @@ export const App: React.FC = () => {
const [sysDark, setSysDark] = useState<boolean>(() =>
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-color-scheme: dark)').matches,
)
const [reducedMotion, setReducedMotion] = useState<boolean>(() =>
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches,
)
const theme: 'light' | 'dark' = themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode
const [pluginUI, setPluginUI] = useState<PluginUIContributions | null>(null)
const [activeThemePayload, setActiveThemePayload] = useState<ActiveThemePayload | null>(null)
const [themeRevision, setThemeRevision] = useState(0)
useEffect(() => {
document.documentElement.dataset.theme = theme
}, [theme])
document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full'
}, [theme, reducedMotion])
useEffect(() => {
const mq = window.matchMedia?.('(prefers-color-scheme: dark)')
@@ -99,6 +106,14 @@ export const App: React.FC = () => {
return () => mq.removeEventListener('change', onChange)
}, [])
useEffect(() => {
const mq = window.matchMedia?.('(prefers-reduced-motion: reduce)')
if (!mq) return
const onChange = (e: MediaQueryListEvent) => setReducedMotion(e.matches)
mq.addEventListener('change', onChange)
return () => mq.removeEventListener('change', onChange)
}, [])
const setThemeMode = (mode: ThemeMode) => {
setThemeModeState(mode)
try {
@@ -163,6 +178,11 @@ export const App: React.FC = () => {
return next
})
})
api.GetState().then(async (s) => {
setState(s)
}).catch(() => {})
api.GetPluginUIContributions().then(setPluginUI).catch(() => {})
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
// Tasks: seed from the backend, then follow events.
api.GetTasks().then((list) => {
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
@@ -226,6 +246,9 @@ export const App: React.FC = () => {
// (VMPage), so a 3-second tick no longer re-renders the whole App.
const locale: Locale = state?.config.locale ?? 'zh-CN'
useEffect(() => {
document.documentElement.lang = locale
}, [locale])
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : ''
const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : []
@@ -282,6 +305,64 @@ export const App: React.FC = () => {
}
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
// UI Contract v1 read-only document state attributes (§5.1).
const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === SETTINGS_ID ? 'settings' : 'vm'
const isBusyAny = Object.keys(busy).length > 0 || runningTasks > 0
const hasAnyError = unseenErrors > 0 || !!loadError
const uiStateRef = useRef<UIStateSnapshot>({
appearance: theme,
motion: reducedMotion ? 'reduced' : 'full',
view: currentView,
vmName: selectedVM?.name ?? '',
vmState: effectiveState,
busy: isBusyAny,
hasError: hasAnyError,
sidebarCollapsed: !sidebarOpen,
safeMode: !!state?.safe_mode,
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
})
uiStateRef.current = {
appearance: theme,
motion: reducedMotion ? 'reduced' : 'full',
view: currentView,
vmName: selectedVM?.name ?? '',
vmState: effectiveState,
busy: isBusyAny,
hasError: hasAnyError,
sidebarCollapsed: !sidebarOpen,
safeMode: !!state?.safe_mode,
vms: vms.map((v) => ({ name: v.name, state: state?.transitions[v.name] ?? v.state })),
}
useEffect(() => {
const el = document.documentElement
el.dataset.view = currentView
el.dataset.vmState = effectiveState || 'none'
el.dataset.busy = String(isBusyAny)
el.dataset.hasError = String(hasAnyError)
el.dataset.sidebarCollapsed = String(!sidebarOpen)
el.dataset.safeMode = String(!!state?.safe_mode)
}, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode])
// Apply active theme pack (zero extra CSS for builtin default theme, §5.1 & §8.1).
useEffect(() => {
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
api.GetPluginUIContributions().then(setPluginUI).catch(() => {})
}, [themeRevision, state?.safe_mode])
useEffect(() => {
void applyActiveTheme(
activeThemePayload,
theme,
() => uiStateRef.current,
{
toggleSidebar,
openSettings: () => setSelected(SETTINGS_ID),
focusVMWindow: (vmName) => { void api.FocusVMWindow(vmName).catch(() => {}) },
},
)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeThemePayload, theme])
const openLogs = (tab: LogTab = 'app') => {
setLogTab(tab)
setLogsOpen(true)
@@ -623,10 +704,10 @@ export const App: React.FC = () => {
return (
<TooltipProvider>
<div className="app-shell">
<header className="titlebar" onDoubleClick={() => WindowToggleMaximise()}>
<div className="app-shell rg-p-shell">
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
{showSetup || !state ? (
<div className="brand">
<div className="brand rg-p-brand">
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
Reims-Go
</div>
@@ -668,6 +749,15 @@ export const App: React.FC = () => {
</div>
</header>
{state?.safe_mode && (
<div className="safe-mode-banner" role="status">
<span>{tr('safeModeBanner')}</span>
<button type="button" className="link-btn" onClick={() => setSelected(SETTINGS_ID)}>
{tr('safeModeManagePlugins')}
</button>
</div>
)}
{showSetup && state ? (
<Suspense fallback={null}>
<Setup
@@ -687,7 +777,7 @@ export const App: React.FC = () => {
/>
</Suspense>
) : (
<div className={`workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
<div className={`workspace rg-p-workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
<Sidebar
locale={locale}
vms={vms}
@@ -703,7 +793,7 @@ export const App: React.FC = () => {
downloading={Object.values(taskMap).some((x) => x.kind === 'installer-download' && x.status === 'running')}
/>
<main className="main">
<main className="main rg-p-main">
<div className="scroll">
<Suspense fallback={null}>
{!state ? (
@@ -764,13 +854,16 @@ export const App: React.FC = () => {
onToast={(title) => toasts.push({ kind: 'ok', title })}
onError={fail}
dropping={dropping}
pluginUI={pluginUI}
/>
) : selected === SETTINGS_ID ? (
<AppSettingsPage
state={state}
locale={locale}
themeMode={themeMode}
appearance={theme}
onThemeMode={setThemeMode}
onThemeChanged={() => setThemeRevision((r) => r + 1)}
onSetLocale={setLang}
onRefresh={refresh}
onError={fail}
+18 -3
View File
@@ -1,5 +1,5 @@
import { Download } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import React, { Suspense, lazy, useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
import { AppState, AppUpdateInfo, Locale } from '../types'
@@ -7,20 +7,24 @@ import { Button } from '../ui/controls'
import { Segmented, Switch } from '../ui/settings'
import { api } from '../wails'
const PluginsSection = lazy(() => import('./PluginsSection').then((m) => ({ default: m.PluginsSection })))
export type ThemeMode = 'light' | 'dark' | 'system'
interface Props {
state: AppState
locale: Locale
themeMode: ThemeMode
appearance?: 'light' | 'dark'
onThemeMode: (mode: ThemeMode) => void
onThemeChanged?: () => void
onSetLocale: (l: Locale) => void
onRefresh: () => void
onError: (title: string, e: unknown) => void
}
export const AppSettingsPage: React.FC<Props> = ({
state, locale, themeMode, onThemeMode, onSetLocale, onRefresh, onError,
state, locale, themeMode, appearance = 'light', onThemeMode, onThemeChanged, onSetLocale, onRefresh, onError,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { host, config, optimizations } = state
@@ -62,7 +66,7 @@ export const AppSettingsPage: React.FC<Props> = ({
})
return (
<div className="page">
<div className="page rg-p-settings">
<header className="page-head">
<div className="page-title"><h1>{tr('sidebarSettings')}</h1></div>
</header>
@@ -151,6 +155,17 @@ export const AppSettingsPage: React.FC<Props> = ({
</div>
</section>
<Suspense fallback={null}>
<PluginsSection
locale={locale}
appearance={appearance}
safeMode={state.safe_mode}
onRefresh={onRefresh}
onError={onError}
onThemeChanged={onThemeChanged}
/>
</Suspense>
<section className="section">
<div className="section-title">{tr('settingsAbout')}</div>
<div className="list">
+87 -6
View File
@@ -1,6 +1,6 @@
import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import React, { Suspense, lazy, useEffect, useState } from 'react'
import { I18nKey, locText, t } from '../i18n'
import {
GUEST_LANG_PRESETS,
MEMORY_MARKS,
@@ -22,12 +22,15 @@ import {
splitLangLabel,
sshCommand,
} from '../lib/format'
import { CachedInstaller, CreateOpts, HostReport, Locale, Release, ValidationIssue } from '../types'
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, ValidationIssue } from '../types'
import { Button, IconButton } from '../ui/controls'
import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
import { Modal } from '../ui/dialog'
import { api } from '../wails'
const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm })))
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
/** Reopen the wizard where the user left it (e.g. after a failed create). */
export interface WizardDraft {
opts: CreateOpts
@@ -71,6 +74,18 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
const [err, setErr] = useState('')
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [cmdPreview, setCmdPreview] = useState('')
const [drivers, setDrivers] = useState<DriverSummary[]>([])
const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER)
const [driverOpts, setDriverOpts] = useState<Record<string, unknown>>({})
const [driverCreating, setDriverCreating] = useState(false)
useEffect(() => {
let live = true
api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch(() => {})
return () => { live = false }
}, [])
const activeDriver = drivers.find((d) => d.id === driverID)
const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver
const [opts, setOpts] = useState<CreateOpts>(draft?.opts ?? {
name: 'macos-tahoe',
@@ -217,6 +232,45 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
<div key={step} className="step-anim">
{step === 1 && (
<>
{drivers.length > 1 && (
<SetGroup title={tr('wizardDriverGroup')}>
<SetRow
title={tr('wizardDriverType')}
control={
<PopupSelect
label={tr('wizardDriverType')}
value={driverID}
options={drivers.map((d) => ({
value: d.id,
label: locText(d.name, locale, d.id),
}))}
onChange={(id) => { setDriverID(id); setErr('') }}
/>
}
/>
</SetGroup>
)}
{isCustomDriver ? (
<div className="stack-3">
<SetGroup title={tr('wizardBasics')}>
<SetRow
title={tr('vmName')}
control={<input className="input" value={opts.name} onChange={(e) => set({ name: e.target.value })} />}
/>
</SetGroup>
{activeDriver.create_schema && (
<Suspense fallback={null}>
<SchemaForm
locale={locale}
schema={activeDriver.create_schema}
values={driverOpts}
onChange={setDriverOpts}
/>
</Suspense>
)}
</div>
) : (
<>
<div className="source-cards" role="radiogroup" aria-label={tr('step1')}>
{SOURCES.map((s) => {
const Icon = s.icon
@@ -256,7 +310,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
<SetRow
title={tr('macosVersion')}
desc={releasesErr
? <span className="warn-text">{tr('offlineListFailed')}:{releasesErr}</span>
? <span className="warn-text">{tr('offlineListFailedDetail', { err: releasesErr })}</span>
: needGB > 0 && host.free_disk_gb > 0 && host.free_disk_gb < needGB + 10
? <span className="warn-text">{tr('offlineSpaceWarn', { free: host.free_disk_gb.toFixed(0), need: needGB })}</span>
: tr('offlineHint')}
@@ -309,6 +363,8 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
}
/>
</SetGroup>
</>
)}
</>
)}
@@ -538,8 +594,33 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
</div>
<div className="dialog-foot">
<Button variant="ghost" disabled={step === 1} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
{step < REVIEW_STEP ? (
<Button variant="ghost" disabled={step === 1 || isCustomDriver} onClick={() => setStep(step - 1)}>{tr('back')}</Button>
{isCustomDriver ? (
<Button
variant="primary"
busy={driverCreating}
disabled={!opts.name.trim() || driverCreating}
onClick={async () => {
setDriverCreating(true)
setErr('')
try {
await api.CreateVMWithDriver({
driver_id: driverID,
name: opts.name.trim(),
dir: opts.dir,
options: driverOpts,
})
onClose()
} catch (e) {
setErr(String(e).replace(/^Error:\s*/, ''))
} finally {
setDriverCreating(false)
}
}}
>
{tr('createNow')}
</Button>
) : step < REVIEW_STEP ? (
<Button variant="primary" onClick={() => setStep(step + 1)}>{tr('next')}</Button>
) : (
<Button
+1 -1
View File
@@ -215,7 +215,7 @@ export const InstallersPage: React.FC<Props> = ({ locale, host, tasks, onCreateW
<div className="notice notice-error" role="alert">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('offlineListFailed')}:{releasesErr}</span>
<span>{tr('offlineListFailedDetail', { err: releasesErr })}</span>
</span>
<Button onClick={loadReleases}>{tr('installersRetry')}</Button>
</div>
+3 -2
View File
@@ -153,7 +153,7 @@ export const LogPanel: React.FC<Props> = ({
}
return (
<div className="logs">
<div className="logs rg-p-logpanel">
{open && (
<div
className="log-resize-handle"
@@ -173,7 +173,7 @@ export const LogPanel: React.FC<Props> = ({
<span className="log-resize-pill" aria-hidden="true" />
</div>
)}
<div className="logbar">
<div className="logbar rg-p-statusbar">
{task ? (
<>
<Tip label={[task.step, taskDetail(task)].filter(Boolean).join(' · ') || taskTitle(locale, task)} side="top">
@@ -294,6 +294,7 @@ export const LogPanel: React.FC<Props> = ({
{open && tab === 'qemu' && (
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshQemu} />
)}
<span className="rg-slot-inline" data-rg-slot="statusbar.right" />
{!open && unseenErrors > 0 && <span className="badge badge-error" aria-hidden="true">{unseenErrors}</span>}
<Tip label={open ? tr('collapseLogs') : tr('expandLogs')} shortcut="Ctrl+L" side="top">
<button
@@ -0,0 +1,125 @@
import React, { useEffect, useRef, useState } from 'react'
import { t } from '../i18n'
import { Locale, PanelContribution } from '../types'
import { Button } from '../ui/controls'
import { api } from '../wails'
import { locText } from './SchemaForm'
interface Props {
locale: Locale
panel: PanelContribution
assetToken: string
appearance: 'light' | 'dark'
}
/**
* Sandboxed L4 iframe panel with strict bridge verification (§4.2, §7.3):
* - `sandbox="allow-scripts"` (no allow-same-origin, no top-navigation)
* - Only responds to postMessage where `event.source === iframe.contentWindow`
* - Routes all Host API calls through Go `PanelBridgeCall` for permission & rate checks
* - Syncs theme tokens into iframe and provides error placeholder + retry.
*/
const RE_SAFE_TOKEN = /^[a-f0-9]+$/
const RE_SAFE_PLUGIN_ID = /^[a-z0-9][a-z0-9._-]*$/
const RE_SAFE_ENTRY_SEG = /^[a-zA-Z0-9._@ -]+$/
function buildSafePanelSrc(assetToken: string, pluginId: string | undefined, entry: string | undefined): string | null {
if (!assetToken || !RE_SAFE_TOKEN.test(assetToken)) return null
if (!pluginId || !RE_SAFE_PLUGIN_ID.test(pluginId) || pluginId.includes('..')) return null
const raw = (entry || 'index.html').trim().replace(/^\/+/, '')
if (!raw || raw.includes('\\') || raw.includes('?') || raw.includes('#') || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(raw)) {
return null
}
const segs = raw.split('/')
for (const seg of segs) {
if (!seg || seg === '.' || seg === '..' || !RE_SAFE_ENTRY_SEG.test(seg)) return null
}
return `/plugin-assets/${encodeURIComponent(assetToken)}/${encodeURIComponent(pluginId)}/${segs.map(encodeURIComponent).join('/')}`
}
export const PluginPanelFrame: React.FC<Props> = ({ locale, panel, assetToken, appearance }) => {
const iframeRef = useRef<HTMLIFrameElement>(null)
const [failed, setFailed] = useState(false)
const [nonce, setNonce] = useState(0)
const src = buildSafePanelSrc(assetToken, panel.pluginId, panel.entry)
const syncTheme = () => {
const win = iframeRef.current?.contentWindow
if (!win) return
const cs = getComputedStyle(document.documentElement)
const tokens: Record<string, string> = {}
for (const k of ['--surface-0', '--surface-1', '--text', '--text-2', '--border', '--accent', '--font-sans']) {
tokens[k] = cs.getPropertyValue(k).trim()
}
win.postMessage({ type: 'reims:theme', appearance, locale, tokens }, '*')
}
useEffect(() => {
syncTheme()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [appearance, locale])
useEffect(() => {
if (!src) return
let cancelled = false
const onMessage = async (e: MessageEvent) => {
const win = iframeRef.current?.contentWindow
// Strict origin + window identity check for sandbox="allow-scripts" opaque origin (§7.3).
if (!win || e.source !== win || e.origin !== 'null') return
const msg = e.data
if (!msg || typeof msg !== 'object' || msg.type !== 'reims:rpc' || typeof msg.id !== 'string' || typeof msg.method !== 'string') return
const rawParams = msg.params
const params: Record<string, unknown> =
rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams)
? (rawParams as Record<string, unknown>)
: {}
try {
const result = await api.PanelBridgeCall(panel.pluginId ?? '', msg.method, params)
if (cancelled || iframeRef.current?.contentWindow !== win) return
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result }, '*')
} catch (err) {
if (cancelled || iframeRef.current?.contentWindow !== win) return
win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: false, error: String(err) }, '*')
}
}
window.addEventListener('message', onMessage)
return () => {
cancelled = true
window.removeEventListener('message', onMessage)
}
}, [panel.pluginId, nonce, src])
if (failed || !src) {
return (
<div className="plugin-panel-error">
<span>{t(locale, 'panelLoadFailed')}</span>
{src && (
<Button onClick={() => { setFailed(false); setNonce((n) => n + 1) }}>
{t(locale, 'installersRetry')}
</Button>
)}
</div>
)
}
return (
<div className="plugin-panel-wrap">
<div className="plugin-panel-head">{locText(panel.title, locale, panel.id)}</div>
<iframe
key={nonce}
ref={iframeRef}
className="plugin-panel-frame"
title={locText(panel.title, locale, panel.id)}
src={src}
sandbox="allow-scripts"
referrerPolicy="no-referrer"
style={{ height: Math.max(120, Math.min(480, panel.height || 220)) }}
onLoad={syncTheme}
onError={() => setFailed(true)}
/>
</div>
)
}
+496
View File
@@ -0,0 +1,496 @@
import { AlertTriangle, FolderOpen, PackagePlus, Palette, Settings2, ShieldAlert, Terminal, Trash2 } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import {
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions,
} from '../types'
import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { PopupSelect, Switch } from '../ui/settings'
import { api } from '../wails'
import { PluginPanelFrame } from './PluginPanelFrame'
import { SchemaForm, locText } from './SchemaForm'
interface Props {
locale: Locale
appearance: 'light' | 'dark'
safeMode?: boolean
onRefresh: () => void
onError: (title: string, e: unknown) => void
onThemeChanged?: () => void
}
/**
* Lazy-loaded Plugin & Theme Management section inside App Settings (§5.1, §8.1, §10).
* Keeps plugin management + SchemaForm out of the startup bundle.
*/
export const PluginsSection: React.FC<Props> = ({
locale, appearance, safeMode, onRefresh, onError, onThemeChanged,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [plugins, setPlugins] = useState<PluginInfo[]>([])
const [contribs, setContribs] = useState<PluginUIContributions | null>(null)
const [activeTheme, setActiveTheme] = useState<ActiveThemePayload | null>(null)
const [busyID, setBusyID] = useState('')
const [approveTarget, setApproveTarget] = useState<PluginInfo | null>(null)
const [approveChecked, setApproveChecked] = useState(false)
const [settingsTarget, setSettingsTarget] = useState<PluginInfo | null>(null)
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
// Theme scheme editor state (§5.1)
const [schemeEditorOpen, setSchemeEditorOpen] = useState(false)
const [schemeName, setSchemeName] = useState('')
const [seedAccent, setSeedAccent] = useState('#007aff')
const [seedSurface, setSeedSurface] = useState('')
const reload = async () => {
try {
const [list, ui, th] = await Promise.all([
api.ListPlugins(),
api.GetPluginUIContributions(),
api.GetActiveTheme(),
])
setPlugins(list ?? [])
setContribs(ui)
setActiveTheme(th)
} catch (e) {
onError(tr('pluginFailLoad'), e)
}
}
useEffect(() => { void reload() }, [])
const togglePlugin = async (p: PluginInfo, enable: boolean) => {
if (enable && p.needs_approval) {
setApproveChecked(false)
setApproveTarget(p)
return
}
setBusyID(p.id)
try {
if (enable) await api.EnablePlugin(p.id, false)
else await api.DisablePlugin(p.id)
await reload()
onRefresh()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailToggle'), e)
} finally {
setBusyID('')
}
}
const confirmApprove = async () => {
if (!approveTarget || !approveChecked) return
const target = approveTarget
setApproveTarget(null)
setBusyID(target.id)
try {
await api.EnablePlugin(target.id, true)
await reload()
onRefresh()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailEnable'), e)
} finally {
setBusyID('')
}
}
const importLocalZip = async () => {
try {
const path = await api.PickFile(tr('pluginImportTitle'), '*.zip')
if (!path) return
await api.InstallPluginArchive(path)
await reload()
onRefresh()
} catch (e) {
onError(tr('pluginFailImport'), e)
}
}
const linkDevDir = async () => {
try {
const dir = await api.PickDirectory(tr('pluginLinkDevTitle'))
if (!dir) return
await api.LinkPluginDev(dir)
await reload()
onRefresh()
} catch (e) {
onError(tr('pluginFailLinkDev'), e)
}
}
const removePlugin = async (p: PluginInfo) => {
setBusyID(p.id)
try {
await api.RemovePlugin(p.id, false)
await reload()
onRefresh()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailRemove'), e)
} finally {
setBusyID('')
}
}
const openPluginSettings = async (p: PluginInfo) => {
try {
const vals = await api.GetPluginSettings(p.id, '')
setSettingsValues((vals ?? {}) as Record<string, unknown>)
setSettingsTarget(p)
} catch (e) {
onError(tr('pluginFailLoadSettings'), e)
}
}
const savePluginSettings = async (next: Record<string, unknown>) => {
setSettingsValues(next)
if (!settingsTarget) return
try {
await api.SetPluginSettings(settingsTarget.id, '', next)
onRefresh()
} catch (e) {
onError(tr('pluginFailSaveSettings'), e)
}
}
const openPluginLog = async (p: PluginInfo) => {
try {
const txt = await api.ReadPluginLog(p.id)
setLogTarget({ id: p.id, text: txt || tr('pluginLogEmpty') })
} catch (e) {
onError(tr('pluginFailReadLog'), e)
}
}
const selectTheme = async (themeID: string, schemeID = '') => {
try {
await api.SetActiveTheme(themeID, schemeID)
await reload()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailSwitchTheme'), e)
}
}
const saveScheme = async () => {
if (!activeTheme || !schemeName.trim()) return
const id = `custom-${Date.now()}`
const scheme: CustomThemeScheme = {
id,
theme_id: activeTheme.theme_id,
name: schemeName.trim(),
appearance,
seeds: {
accent: seedAccent,
...(seedSurface ? { surface: seedSurface } : {}),
},
}
try {
await api.SaveCustomThemeScheme(scheme)
await api.SetActiveTheme(activeTheme.theme_id, id)
setSchemeEditorOpen(false)
setSchemeName('')
await reload()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailSaveScheme'), e)
}
}
const deleteScheme = async (schemeID: string) => {
try {
await api.DeleteCustomThemeScheme(schemeID)
await reload()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailDeleteScheme'), e)
}
}
const builtins = plugins.filter((p) => p.source === 'builtin')
const external = plugins.filter((p) => p.source !== 'builtin')
const themes = contribs?.themes ?? []
const settingsPanels = (contribs?.panels ?? []).filter((p) => p.slot === 'settings.plugin')
const trustLabel = (trLevel: string) => {
if (trLevel === 'official') return tr('pluginTrustOfficial')
if (trLevel === 'verified') return tr('pluginTrustVerified')
if (trLevel === 'dev') return tr('pluginTrustDev')
return tr('pluginTrustCommunity')
}
const stateBadge = (p: PluginInfo) => {
if (p.state === 'active') return <span className="badge badge-ok">{tr('pluginStateActive')}</span>
if (p.state === 'degraded') return <span className="badge badge-warn">{tr('pluginStateDegraded')}</span>
if (p.state === 'failed') return <span className="badge badge-error">{tr('pluginStateFailed')}</span>
if (p.state === 'pending') return <span className="badge">{tr('pluginStatePending')}</span>
return <span className="badge">{tr('pluginStateOff')}</span>
}
const renderRow = (p: PluginInfo) => {
const highPerms = (p.permissions ?? []).filter((x) => x.level === 'high')
return (
<div className="row" key={p.id}>
<div className="row-main">
<div className="row-title">
{locText(p.name, locale, p.id)}
<span className="mono muted">v{p.version}</span>
<span className="badge">{trustLabel(p.trust)}</span>
{p.tier !== 'builtin' && <span className="badge">{p.tier}</span>}
{stateBadge(p)}
</div>
<div className="row-sub">
{locText(p.description, locale, p.id)}
{p.license ? ` · ${p.license}` : ''}
{p.permissions && p.permissions.length > 0
? ` · ${tr('pluginPermissionsLabel', { list: p.permissions.map((x) => x.name).join(', ') })}`
: ''}
</div>
{(p.error || p.degraded_reason) && (
<div className="row-sub warn-text">
<AlertTriangle size={12} style={{ verticalAlign: '-2px', marginRight: 4 }} />
{p.error || p.degraded_reason}
</div>
)}
{p.needs_approval && highPerms.length > 0 && (
<div className="row-sub warn-text">
{tr('pluginHighRiskNotice')}
</div>
)}
</div>
<div className="row-right hstack">
{p.settings && (
<IconButton small label={tr('pluginSettings')} icon={<Settings2 size={14} />} onClick={() => void openPluginSettings(p)} />
)}
{p.log_path && (
<IconButton small label={tr('pluginViewLog')} icon={<Terminal size={14} />} onClick={() => void openPluginLog(p)} />
)}
{p.removable && (
<IconButton
small
disabled={p.in_use || busyID === p.id}
label={p.in_use ? tr('pluginInUse') : tr('pluginRemove')}
icon={<Trash2 size={14} />}
onClick={() => void removePlugin(p)}
/>
)}
<Switch
label={locText(p.name, locale, p.id)}
disabled={busyID === p.id || (p.enabled && p.in_use) || (!!safeMode && p.source !== 'builtin')}
checked={p.enabled}
onChange={(checked) => void togglePlugin(p, checked)}
/>
</div>
</div>
)
}
return (
<>
{themes.length > 1 && (
<section className="section">
<div className="section-title">{tr('pluginThemeSection')}</div>
<div className="list">
<div className="row">
<div className="row-main">
<div className="row-title">{tr('pluginActiveTheme')}</div>
<div className="row-sub">
{safeMode ? tr('pluginThemeSafeModeHint') : tr('pluginThemeHint')}
</div>
</div>
<div className="row-right hstack">
<PopupSelect
label={tr('pluginThemePackLabel')}
value={activeTheme?.theme_id || 'builtin.theme.default'}
options={themes.map((th) => ({
value: th.id,
label: locText(th.name, locale, th.id),
disabled: !!safeMode && th.id !== 'builtin.theme.default',
}))}
onChange={(id) => { if (!safeMode) void selectTheme(id) }}
/>
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' && (
<Button icon={<Palette size={14} />} onClick={() => setSchemeEditorOpen(true)}>
{tr('pluginNewScheme')}
</Button>
)}
</div>
</div>
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' && (
<div className="row">
<div className="row-main">
<div className="row-title">{tr('pluginColorSchemes')}</div>
<div className="row-sub">{tr('pluginColorSchemesHint')}</div>
</div>
<div className="row-right hstack">
{(activeTheme.custom_schemes ?? []).filter((s) => s.theme_id === activeTheme.theme_id).map((s) => (
<span className="hstack" key={s.id}>
<Button
variant={activeTheme.active_scheme === s.id ? 'primary' : undefined}
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
>
{s.name}
</Button>
<IconButton small label={tr('pluginDeleteScheme')} icon={<Trash2 size={13} />} onClick={() => void deleteScheme(s.id)} />
</span>
))}
</div>
</div>
)}
</div>
</section>
)}
<section className="section">
<div className="section-title hstack" style={{ justifyContent: 'space-between' }}>
<span>{tr('pluginExternalSection')}</span>
<span className="hstack">
<Button icon={<FolderOpen size={14} />} onClick={linkDevDir}>
{tr('pluginLinkDevBtn')}
</Button>
<Button icon={<PackagePlus size={14} />} onClick={importLocalZip}>
{tr('pluginImportBtn')}
</Button>
</span>
</div>
<div className="list">
{external.length === 0 ? (
<div className="row"><div className="row-sub">{tr('pluginExternalEmpty')}</div></div>
) : external.map(renderRow)}
</div>
</section>
<section className="section">
<div className="section-title">{tr('pluginBuiltinSection')}</div>
<div className="list">{builtins.map(renderRow)}</div>
</section>
{settingsPanels.length > 0 && contribs?.asset_token ? (
<section className="section" data-rg-slot="settings.plugin">
<div className="section-title">{tr('pluginPanelsSection')}</div>
{settingsPanels.map((panel) => (
<PluginPanelFrame
key={`${panel.pluginId}:${panel.id}`}
locale={locale}
panel={panel}
assetToken={contribs.asset_token!}
appearance={appearance}
/>
))}
</section>
) : (
<div className="rg-slot-anchor" data-rg-slot="settings.plugin" />
)}
{approveTarget && (
<Modal
title={tr('pluginApproveTitle')}
subtitle={locText(approveTarget.name, locale, approveTarget.id)}
closeLabel={tr('close')}
onClose={() => setApproveTarget(null)}
>
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
<div className="notice notice-warn">
<ShieldAlert size={15} aria-hidden="true" style={{ marginRight: 6, verticalAlign: '-2px' }} />
{tr('pluginApproveL3Warn')}
</div>
)}
<div className="list">
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginPublisherLicense')}</div><div className="row-sub">{approveTarget.publisher || '—'} · {approveTarget.license || '—'}</div></div></div>
{approveTarget.entry_path && (
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginEntryPath')}</div><div className="row-sub mono selectable">{approveTarget.entry_path}</div></div></div>
)}
{approveTarget.entry_hash && (
<div className="row"><div className="row-main"><div className="row-title">SHA-256</div><div className="row-sub mono selectable">{approveTarget.entry_hash}</div></div></div>
)}
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginRequestedPerms')}</div><div className="row-sub mono">{(approveTarget.permissions ?? []).length > 0 ? (approveTarget.permissions ?? []).map((p) => `${p.name} (${p.level})`).join(', ') : '—'}</div></div></div>
</div>
<label className="hstack" style={{ cursor: 'pointer' }}>
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
<span>{tr('pluginApproveCheckbox')}</span>
</label>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setApproveTarget(null)}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!approveChecked} onClick={() => void confirmApprove()}>
{tr('pluginApproveConfirm')}
</Button>
</span>
</div>
</Modal>
)}
{settingsTarget && settingsTarget.settings && (
<Modal
title={locText(settingsTarget.name, locale, settingsTarget.id)}
subtitle={tr('pluginGlobalSettings')}
closeLabel={tr('close')}
onClose={() => setSettingsTarget(null)}
>
<div style={{ padding: 'var(--sp-4)' }}>
<SchemaForm
locale={locale}
schema={settingsTarget.settings}
values={settingsValues}
onChange={(next) => void savePluginSettings(next)}
/>
</div>
<div className="dialog-foot">
<span />
<Button variant="primary" onClick={() => setSettingsTarget(null)}>{tr('pluginDone')}</Button>
</div>
</Modal>
)}
{logTarget && (
<Modal
title={tr('pluginLogTitle', { id: logTarget.id })}
closeLabel={tr('close')}
onClose={() => setLogTarget(null)}
>
<pre className="mono selectable" style={{ padding: 'var(--sp-4)', maxHeight: 360, overflow: 'auto', margin: 0 }}>
{logTarget.text}
</pre>
</Modal>
)}
{schemeEditorOpen && (
<Modal
title={tr('pluginSchemeModalTitle')}
closeLabel={tr('close')}
onClose={() => setSchemeEditorOpen(false)}
>
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
<label className="stack-1">
<span>{tr('pluginSchemeName')}</span>
<input className="input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
</label>
<label className="hstack">
<span>{tr('pluginAccentSeed')}</span>
<input type="color" value={seedAccent} onChange={(e) => setSeedAccent(e.target.value)} />
<span className="mono">{seedAccent}</span>
</label>
<label className="stack-1">
<span>{tr('pluginSurfaceSeed')}</span>
<input className="input mono" value={seedSurface} onChange={(e) => setSeedSurface(e.target.value)} placeholder="#1d1e23" />
</label>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setSchemeEditorOpen(false)}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!schemeName.trim()} onClick={() => void saveScheme()}>{tr('save')}</Button>
</span>
</div>
</Modal>
)}
</>
)
}
+157
View File
@@ -0,0 +1,157 @@
import React from 'react'
import { locText, t } from '../i18n'
import { Locale, SettingProperty, SettingsSchema } from '../types'
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
export { locText }
interface Props {
locale: Locale
schema: SettingsSchema
values: Record<string, unknown>
scopeFilter?: 'app' | 'vm'
groupFilter?: string
onChange: (next: Record<string, unknown>) => void
hideGroupHeader?: boolean
}
const SECRET_MASK = '••••••••'
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
/** Lazy-loaded JSON Schema form renderer supporting x-secret, x-effect, x-scope (§6.2, §8.1, §10). */
export const SchemaForm: React.FC<Props> = ({
locale, schema, values, scopeFilter, groupFilter, onChange, hideGroupHeader,
}) => {
const propsMap = schema.properties ?? {}
const keys = (schema['x-order'] && schema['x-order'].length > 0
? schema['x-order'].filter((k) => !FORBIDDEN_KEYS.has(k) && Object.prototype.hasOwnProperty.call(propsMap, k))
: Object.keys(propsMap).filter((k) => !FORBIDDEN_KEYS.has(k))
).filter((k) => {
const prop = propsMap[k]
const effScope = prop['x-scope'] || schema['x-scope'] || 'app'
const effGroup = prop['x-group'] || schema['x-group'] || ''
if (scopeFilter && effScope !== scopeFilter) return false
if (groupFilter && effGroup !== groupFilter) return false
return true
})
if (keys.length === 0) return null
const setKey = (k: string, v: unknown) => {
const next: Record<string, unknown> = {}
for (const [ek, ev] of Object.entries(values)) {
if (propsMap[ek]?.['x-secret'] && ev === SECRET_MASK) continue
next[ek] = ev
}
next[k] = v
onChange(next)
}
const effectBadge = (prop: SettingProperty) => {
const eff = prop['x-effect']
if (!eff) return null
const label = t(locale, eff === 'immediate' ? 'effectImmediate' : 'effectNextStart')
return <span className={`badge ${eff === 'immediate' ? 'badge-ok' : ''}`}>{label}</span>
}
const renderControl = (k: string, prop: SettingProperty) => {
const cur = values[k] ?? prop.default
const label = locText(prop.title, locale, k)
if (prop.type === 'boolean') {
return (
<Switch
label={label}
checked={Boolean(cur)}
onChange={(checked) => setKey(k, checked)}
/>
)
}
if (prop.enum && prop.enum.length > 0) {
const options = prop.enum.map((val, idx) => ({
value: val,
label: locText(prop['x-enumLabels']?.[idx], locale, val),
}))
if (options.length <= 3) {
return (
<Segmented
label={label}
value={String(cur ?? prop.enum[0])}
options={options}
onChange={(val) => setKey(k, val)}
/>
)
}
return (
<PopupSelect
label={label}
value={String(cur ?? prop.enum[0])}
options={options}
onChange={(val) => setKey(k, val)}
/>
)
}
if (prop.type === 'integer' || prop.type === 'number') {
const numVal = Number(cur ?? 0)
return (
<NumberField
label={label}
value={Number.isFinite(numVal) ? numVal : 0}
min={prop.minimum ?? 0}
max={prop.maximum ?? 65535}
step={prop.type === 'number' ? 0.1 : 1}
onChange={(n) => setKey(k, n)}
/>
)
}
if (prop['x-secret']) {
const isMasked = cur === SECRET_MASK
return (
<input
type="password"
className="input"
aria-label={label}
autoComplete="new-password"
placeholder={isMasked ? SECRET_MASK : undefined}
value={isMasked ? '' : String(cur ?? '')}
onChange={(e) => setKey(k, e.target.value)}
/>
)
}
return (
<input
type="text"
className="input"
aria-label={label}
value={String(cur ?? '')}
onChange={(e) => setKey(k, e.target.value)}
/>
)
}
const rows = keys.map((k) => {
const prop = propsMap[k]
const title = locText(prop.title, locale, k)
const desc = locText(prop.description, locale)
const badge = effectBadge(prop)
return (
<SetRow
key={k}
title={title}
desc={badge || desc ? <span className="hstack">{badge}{desc ? <span>{desc}</span> : null}</span> : undefined}
control={renderControl(k, prop)}
/>
)
})
if (hideGroupHeader) return <>{rows}</>
return (
<SetGroup title={locText(schema.title, locale, t(locale, 'pluginSettings'))}>
{rows}
</SetGroup>
)
}
+46 -2
View File
@@ -1,5 +1,5 @@
import { CircleAlert, Copy, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import React, { Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react'
import { I18nKey, t } from '../i18n'
import {
GUEST_LANG_PRESETS,
@@ -25,13 +25,15 @@ import {
optStatusLabel,
parseKernelIrqchip,
} from '../lib/optimizations'
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
import { DiskCompactResult, DiskResizeResult, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
import { api } from '../wails'
import { formatAffinitySummary } from './AffinityDialog'
const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm })))
// VM settings (docs/design-guidelines.md §2–3): edits are staged here and written in
// one `reims-ctl set` on Save, because upstream applies every change on the
// next start. Each row marks itself when it differs from the VM's current
@@ -156,8 +158,48 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
activeVMNameRef.current = detail.name
const [driveErr, setDriveErr] = useState('')
const [affinityStatus, setAffinityStatus] = useState<VMAffinityStatus | null>(null)
const [vmPlugins, setVmPlugins] = useState<PluginInfo[]>([])
const [vmPluginVals, setVmPluginVals] = useState<Record<string, Record<string, unknown>>>({})
const pane = useRef<HTMLDivElement>(null)
useEffect(() => {
let live = true
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(detail.name)])
.then(([list, vals]) => {
if (!live) return
const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings)
setVmPlugins(activeWithVM)
setVmPluginVals((vals ?? {}) as Record<string, Record<string, unknown>>)
})
.catch(() => {})
return () => { live = false }
}, [detail.name])
const updateVMPluginSetting = (pluginID: string, next: Record<string, unknown>) => {
setVmPluginVals((prev) => ({ ...prev, [pluginID]: next }))
void api.SetPluginSettings(pluginID, detail.name, next).catch((e) => setErr(String(e)))
}
const renderVMPluginGroup = (group: string) => {
const matched = vmPlugins.filter((p) => p.settings && (p.settings['x-group'] === group || Object.values(p.settings.properties ?? {}).some((prop) => prop['x-group'] === group)))
if (matched.length === 0) return null
return (
<Suspense fallback={null}>
{matched.map((p) => (
<SchemaForm
key={p.id}
locale={locale}
schema={p.settings!}
values={vmPluginVals[p.id] ?? {}}
scopeFilter="vm"
groupFilter={group}
onChange={(next) => updateVMPluginSetting(p.id, next)}
/>
))}
</Suspense>
)
}
const presets = recommendedDisplayPresets(host)
const presetHit = presets.some((p) => same('resolution', p.resolution, form.resolution))
const [customRes, setCustomRes] = useState(!presetHit)
@@ -327,6 +369,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
<SetValue title={tr('opencore')} value={detail.has_opencore ? tr('configured') : '—'} />
<SetValue title={tr('fieldDir')} value={detail.directory} mono />
</SetGroup>
{renderVMPluginGroup('collaboration')}
</>
)
@@ -769,6 +812,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, stats, host, op
control={<Switch label={tr('captureInput')} checked={!!form.capture} onChange={(capture) => set({ capture })} />}
/>
</SetGroup>
{renderVMPluginGroup('keyboard')}
<SetGroup title={tr('catAudio')} note={tr('audioTroubleshootNote')}>
<SetRow
{...rowProps('audio')}
+2 -2
View File
@@ -1,6 +1,6 @@
import { FolderOpen, HardDrive } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { I18nKey, joinNotices, t } from '../i18n'
import { AppState, DataRootCheck, DataRootChoice, Locale, RuntimeSource, Task } from '../types'
import { Button } from '../ui/controls'
import { Segmented } from '../ui/settings'
@@ -135,7 +135,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
)}
</div>
{notices.length > 0 && (
<div className={check?.error ? 'notice notice-error' : 'hint warn'}>{notices.join(';')}</div>
<div className={check?.error ? 'notice notice-error' : 'hint warn'}>{joinNotices(locale, notices)}</div>
)}
{!check?.error && check?.has_config && <div className="hint">{tr('setupReuse')}</div>}
{customMode && check && check.path === custom && !check.error && (
+6 -5
View File
@@ -67,7 +67,7 @@ export const Sidebar: React.FC<Props> = ({
data-id={id}
className="nav-item"
aria-selected={selected === id}
aria-label={stateLabel ? `${label},${stateLabel}` : label}
aria-label={stateLabel ? t(locale, 'sidebarItemAria', { label, state: stateLabel }) : label}
tabIndex={selected === id ? 0 : -1}
onClick={() => onSelect(id)}
onDoubleClick={onDoubleClick}
@@ -84,13 +84,13 @@ export const Sidebar: React.FC<Props> = ({
return (
<div className="sidebar-wrap">
<aside className="sidebar">
<div className="sidebar-head">
<aside className="sidebar rg-p-sidebar">
<div className="sidebar-head rg-p-sidebar-head">
<span>{tr('sidebarVMs')}</span>
<IconButton small label={tr('newVM')} shortcut="Ctrl+N" icon={<Plus size={15} />} onClick={onNew} tipSide="right" />
</div>
<div className="nav" role="listbox" aria-label={tr('sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
{vms.length === 0 && <div className="nav-empty">{tr('emptyVMs')}</div>}
<div className="nav rg-p-nav" role="listbox" aria-label={tr('sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
{vms.length === 0 && <div className="nav-empty rg-p-empty" data-rg-slot="empty.state">{tr('emptyVMs')}</div>}
{vms.map((vm) => {
const st = transitions[vm.name] ?? vm.state
const running = st === 'running'
@@ -189,6 +189,7 @@ export const Sidebar: React.FC<Props> = ({
null,
)}
</div>
<div className="rg-slot-anchor" data-rg-slot="sidebar.footer" />
</aside>
</div>
)
+33 -9
View File
@@ -39,13 +39,13 @@ import {
UserRound,
} from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { I18nKey, locText, t } from '../i18n'
import {
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, guestLangLabel,
parseMemoryGB, pendingChangeText, splitLangLabel, sshCommand,
} from '../lib/format'
import { useVMStats } from '../lib/vmStats'
import { DiskSnapshot, HostReport, Locale, PendingChange, VMDetail, VMThumbnail } from '../types'
import { DiskSnapshot, HostReport, Locale, PendingChange, PluginUIContributions, VMDetail, VMThumbnail } from '../types'
import { api } from '../wails'
import { Button, IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
import { Switch } from '../ui/settings'
@@ -106,6 +106,7 @@ interface Props {
onToast: (title: string) => void
onError: (title: string, e: unknown) => void
dropping?: boolean
pluginUI?: PluginUIContributions | null
}
type Tone = '' | ' warn' | ' high'
@@ -124,7 +125,7 @@ interface Spec {
}
export const VMPage: React.FC<Props> = ({
locale, name, displayName, onDisplayNameSaved, macosMajor, state, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping,
locale, name, displayName, onDisplayNameSaved, macosMajor, state, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
@@ -402,6 +403,21 @@ export const VMPage: React.FC<Props> = ({
<Menu.Item className="menu-item" disabled={busy} onSelect={() => onAction('exportDiagnostics')}>
<Archive size={14} /> {tr('exportDiagnostics')}
</Menu.Item>
{(pluginUI?.menus ?? [])
.filter((m) => m.slot === 'vm.toolbar' && (!m.when || (m.when === 'vm.running' ? running : m.when === 'vm.stopped' ? state === 'stopped' : true)))
.map((m) => (
<Menu.Item
key={`${m.pluginId}:${m.id}`}
className="menu-item"
onSelect={() => {
void api.InvokePluginCommand(m.pluginId ?? '', m.command, { vm: name })
.then(() => onToast(locText(m.title, locale, m.id)))
.catch((e) => onError(tr('failGeneric'), e))
}}
>
{locText(m.title, locale, m.id)}
</Menu.Item>
))}
<Menu.Separator className="menu-sep" />
{(running || transitioning) && (
<Menu.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
@@ -445,13 +461,13 @@ export const VMPage: React.FC<Props> = ({
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes) : controllerLabel(detail.disk_controller),
tip: diskKnown
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats!.disk_actual_bytes), max: formatBytes(stats!.disk_virtual_bytes) })
: `${tr('factDisk')}:${controllerLabel(detail.disk_controller)}`,
: tr('specDiskTip', { ctl: controllerLabel(detail.disk_controller) }),
meter: { pct: diskPct, tone: meterTone(diskPct, 85, 95), idle: !diskKnown },
},
{
key: 'gfx', label: tr('factGraphics'), icon: <Monitor size={15} aria-hidden="true" />,
value: graphicsLabel(locale, detail, host),
tip: `${tr('factGraphics')}:${graphicsLabel(locale, detail, host)}`,
tip: tr('specGraphicsTip', { gfx: graphicsLabel(locale, detail, host) }),
},
{
key: 'net', label: tr('fieldNetwork'), icon: <Network size={15} aria-hidden="true" />,
@@ -463,7 +479,9 @@ export const VMPage: React.FC<Props> = ({
const lang = splitLangLabel('', guestLangLabel(locale, detail.guest_lang))
specs.push({
key: 'lang', label: tr('specLang'), icon: <Globe size={15} aria-hidden="true" />, value: lang.label,
tip: `${tr('guestLang')}:${lang.detail ? `${lang.label}(${lang.detail})` : lang.label}`,
tip: lang.detail
? tr('specLangTipDetail', { label: lang.label, detail: lang.detail })
: tr('specLangTip', { label: lang.label }),
})
}
}
@@ -492,7 +510,7 @@ export const VMPage: React.FC<Props> = ({
: undefined
return (
<div className="page vm-page vm-page-drop" style={dropStyle}>
<div className="page vm-page vm-page-drop rg-p-vm-page" style={dropStyle}>
{dropping && (
<div className="drop-banner" role="status" aria-live="polite">
<Upload size={16} aria-hidden="true" />
@@ -501,7 +519,12 @@ export const VMPage: React.FC<Props> = ({
)}
{/* Screen + summary: stacked, or side by side when the column is wide (container query in app.css). */}
<div className="vm-top">
<section className="vm-hero" aria-labelledby="vm-name">
<section className="vm-hero rg-p-vm-header" aria-labelledby="vm-name">
<div className="rg-p-vm-preview" style={{ position: 'relative' }}>
<span data-rg-slot="vm.preview.tl" className="rg-preview-anchor tl" />
<span data-rg-slot="vm.preview.tr" className="rg-preview-anchor tr" />
<span data-rg-slot="vm.preview.bl" className="rg-preview-anchor bl" />
<span data-rg-slot="vm.preview.br" className="rg-preview-anchor br" />
<VMScreen
thumb={thumb}
art={<VersionArt shape="screen" className="vm-screen-art" major={macosMajor} name={shownName} />}
@@ -513,6 +536,7 @@ export const VMPage: React.FC<Props> = ({
onShow={running && !busy ? () => onAction('focus') : undefined}
onScreenshot={running && !busy ? () => onAction('screenshot') : undefined}
/>
</div>
{editingName ? (
<input
ref={nameInputRef}
@@ -556,7 +580,7 @@ export const VMPage: React.FC<Props> = ({
</section>
{specs.length > 0 && (
<div className={`vm-spec-card${running ? ' is-live' : ''}`} role="list">
<div className={`vm-spec-card rg-p-vm-summary${running ? ' is-live' : ''}`} role="list" data-rg-slot="vm.card">
{specs.map((s) => (
<Tip key={s.key} label={s.tip}>
<div className="vm-spec-cell" role="listitem" tabIndex={-1}>
+175 -3
View File
@@ -1,4 +1,4 @@
import { Locale } from './types'
import { Locale, LocalizedText } from './types'
// Copy rules: docs/design-guidelines.md §7.2 — verbs on buttons, one short sentence
// per hint, no 请/您/成功, no full stop on buttons or short hints.
@@ -678,6 +678,84 @@ const dict = {
gtUpdate: '更新…',
gtInstallSub: '在 macOS 终端里运行',
pendingRestartHint: '重启虚拟机后生效',
// Safe mode, drivers & plugins
safeModeBanner: '安全模式已启用:已跳过全部第三方插件并回退至内置默认主题',
safeModeManagePlugins: '管理插件',
wizardDriverGroup: '客体平台驱动',
wizardDriverType: '驱动类型',
wizardBasics: '基本信息',
panelLoadFailed: '面板加载失败',
effectImmediate: '立即生效',
effectNextStart: '下次启动生效',
pluginSettings: '插件设置',
pluginGlobalSettings: '插件全局设置',
pluginFailLoad: '加载插件列表失败',
pluginFailToggle: '切换插件状态失败',
pluginFailEnable: '启用插件失败',
pluginImportTitle: '导入本地插件包 (.zip)',
pluginFailImport: '导入插件包失败',
pluginLinkDevTitle: '链接本地开发插件目录',
pluginFailLinkDev: '链接开发插件失败',
pluginFailRemove: '卸载插件失败',
pluginFailLoadSettings: '读取插件设置失败',
pluginFailSaveSettings: '保存插件设置失败',
pluginLogEmpty: '暂无日志记录',
pluginFailReadLog: '读取插件日志失败',
pluginFailSwitchTheme: '切换主题失败',
pluginFailSaveScheme: '保存配色方案失败',
pluginFailDeleteScheme: '删除配色方案失败',
pluginTrustOfficial: '官方',
pluginTrustVerified: '已审核',
pluginTrustDev: '开发',
pluginTrustCommunity: '社区',
pluginStateActive: '已启用',
pluginStateDegraded: '已降级',
pluginStateFailed: '故障',
pluginStatePending: '等待依赖',
pluginStateOff: '已停用',
pluginPermissionsLabel: '权限:{list}',
pluginHighRiskNotice: '包含高危权限,启用前需确认',
pluginViewLog: '查看日志',
pluginInUse: '使用中不可卸载',
pluginRemove: '卸载',
pluginThemeSection: '主题扩展',
pluginActiveTheme: '当前主题包',
pluginThemeSafeModeHint: '安全模式下固定使用内置默认主题',
pluginThemeHint: '同一时刻仅启用一个主题包,停用后自动回退默认主题',
pluginThemePackLabel: '主题包',
pluginNewScheme: '新建配色方案',
pluginColorSchemes: '配色方案',
pluginColorSchemesHint: '修改种子色派生整套界面色阶',
pluginDeleteScheme: '删除方案',
pluginExternalSection: '第三方与附带插件',
pluginLinkDevBtn: '链接开发目录',
pluginImportBtn: '导入本地包',
pluginExternalEmpty: '尚未安装第三方插件',
pluginBuiltinSection: '内置扩展',
pluginPanelsSection: '插件面板',
pluginApproveTitle: '高危权限确认',
pluginApproveL3Warn: '此插件为原生可执行程序(L3 Sidecar),能够以当前 Windows 账户身份执行任意操作',
pluginPublisherLicense: '发布者 / 许可',
pluginEntryPath: '入口路径',
pluginRequestedPerms: '请求权限',
pluginApproveCheckbox: '我已核对来源与权限,确认启用此插件',
pluginApproveConfirm: '确认启用',
pluginDone: '完成',
pluginLogTitle: '{id} — 日志',
pluginSchemeModalTitle: '新建配色方案',
pluginSchemeName: '方案名称',
pluginSchemePlaceholder: '如:柔蓝',
pluginAccentSeed: '强调种子色',
pluginSurfaceSeed: '画布种子色(可选)',
// Locale-aware composite labels
offlineListFailedDetail: '无法读取 Apple 的版本列表:{err}',
specDiskTip: '存储:{ctl}',
specGraphicsTip: '图形:{gfx}',
specLangTip: 'macOS 系统语言:{label}',
specLangTipDetail: 'macOS 系统语言:{label}({detail})',
sidebarItemAria: '{label},{state}',
},
'en-US': {
sidebarVMs: 'Virtual machines',
@@ -1340,18 +1418,112 @@ const dict = {
statsDisk: 'Disk usage',
statsUptime: 'Uptime',
statsDiskSub: '{actual} actual / {virtual} max',
// Safe mode, drivers & plugins
safeModeBanner: 'Safe mode is active: all third-party plugins are disabled and the built-in theme is restored',
safeModeManagePlugins: 'Manage plugins',
wizardDriverGroup: 'Guest driver',
wizardDriverType: 'Driver',
wizardBasics: 'Basics',
panelLoadFailed: 'Panel failed to load',
effectImmediate: 'Immediate',
effectNextStart: 'Next start',
pluginSettings: 'Plugin settings',
pluginGlobalSettings: 'Plugin settings',
pluginFailLoad: 'Couldn’t load plugins',
pluginFailToggle: 'Couldn’t toggle plugin',
pluginFailEnable: 'Couldn’t enable plugin',
pluginImportTitle: 'Import plugin package (.zip)',
pluginFailImport: 'Couldn’t import plugin package',
pluginLinkDevTitle: 'Link local dev plugin folder',
pluginFailLinkDev: 'Couldn’t link dev plugin',
pluginFailRemove: 'Couldn’t remove plugin',
pluginFailLoadSettings: 'Couldn’t load plugin settings',
pluginFailSaveSettings: 'Couldn’t save plugin settings',
pluginLogEmpty: 'No log entries yet',
pluginFailReadLog: 'Couldn’t read plugin log',
pluginFailSwitchTheme: 'Couldn’t switch theme',
pluginFailSaveScheme: 'Couldn’t save color scheme',
pluginFailDeleteScheme: 'Couldn’t delete color scheme',
pluginTrustOfficial: 'Official',
pluginTrustVerified: 'Verified',
pluginTrustDev: 'Dev',
pluginTrustCommunity: 'Community',
pluginStateActive: 'Active',
pluginStateDegraded: 'Degraded',
pluginStateFailed: 'Failed',
pluginStatePending: 'Pending',
pluginStateOff: 'Off',
pluginPermissionsLabel: 'Permissions: {list}',
pluginHighRiskNotice: 'Contains high-risk permissions; approval required before enabling',
pluginViewLog: 'View log',
pluginInUse: 'In use',
pluginRemove: 'Remove',
pluginThemeSection: 'Theme extensions',
pluginActiveTheme: 'Active theme pack',
pluginThemeSafeModeHint: 'Built-in default theme is enforced in safe mode',
pluginThemeHint: 'One active theme pack at a time; disabling falls back to the built-in default',
pluginThemePackLabel: 'Theme pack',
pluginNewScheme: 'New scheme',
pluginColorSchemes: 'Color schemes',
pluginColorSchemesHint: 'Seed colors derive the full surface, text, and accent ramp',
pluginDeleteScheme: 'Delete scheme',
pluginExternalSection: 'External & bundled plugins',
pluginLinkDevBtn: 'Link dev folder',
pluginImportBtn: 'Import package',
pluginExternalEmpty: 'No external plugins installed',
pluginBuiltinSection: 'Built-in extensions',
pluginPanelsSection: 'Plugin panels',
pluginApproveTitle: 'Approve high-risk permissions',
pluginApproveL3Warn: 'This plugin runs native code (L3 Sidecar) and can perform arbitrary actions as your Windows user',
pluginPublisherLicense: 'Publisher / License',
pluginEntryPath: 'Entry path',
pluginRequestedPerms: 'Requested permissions',
pluginApproveCheckbox: 'I have reviewed the source and permissions and confirm enabling this plugin',
pluginApproveConfirm: 'Confirm enable',
pluginDone: 'Done',
pluginLogTitle: '{id} — Log',
pluginSchemeModalTitle: 'New color scheme',
pluginSchemeName: 'Scheme name',
pluginSchemePlaceholder: 'e.g. Soft Blue',
pluginAccentSeed: 'Accent seed',
pluginSurfaceSeed: 'Surface seed (optional)',
// Locale-aware composite labels
offlineListFailedDetail: 'Couldn’t read Apple’s release list: {err}',
specDiskTip: 'Storage: {ctl}',
specGraphicsTip: 'Graphics: {gfx}',
specLangTip: 'macOS system language: {label}',
specLangTipDetail: 'macOS system language: {label} ({detail})',
sidebarItemAria: '{label}, {state}',
},
} as const
export type I18nKey = keyof (typeof dict)['zh-CN']
type ZhKeys = keyof (typeof dict)['zh-CN']
type EnKeys = keyof (typeof dict)['en-US']
type AssertEqualKeys<A, B> = [A] extends [B] ? ([B] extends [A] ? true : never) : never
const _assertI18nParity: AssertEqualKeys<ZhKeys, EnKeys> = true
void _assertI18nParity
export type I18nKey = ZhKeys
export function t(locale: Locale, key: I18nKey, vars?: Record<string, string | number>): string {
const table = dict[locale] ?? dict['zh-CN']
let s: string = table[key] ?? dict['en-US'][key] ?? key
if (vars) {
for (const [k, v] of Object.entries(vars)) {
s = s.replace(`{${k}}`, String(v))
s = s.replaceAll(`{${k}}`, String(v))
}
}
return s
}
export function joinNotices(locale: Locale, items: string[]): string {
return items.join(locale === 'zh-CN' ? ';' : '; ')
}
export function locText(lt: LocalizedText | undefined, locale: Locale, fallback = ''): string {
if (!lt) return fallback
if (locale === 'zh-CN') return lt['zh-CN'] || lt['en-US'] || fallback
return lt['en-US'] || lt['zh-CN'] || fallback
}
+489
View File
@@ -0,0 +1,489 @@
// Three-tier Theme Engine (docs/plugin-architecture.md §5.1):
// - Builtin theme: zero extra CSS injected, zero UI SDK loaded (§8.1).
// - Tier 1 (Token theme): seed colors + declarative lightness/chroma/alpha derivation,
// bundled fonts, brand mark, background, and event sounds.
// - Tier 2 (Style theme): sanitized stylesheet wrapped in `@layer theme` +
// declarative state-driven slot decorations.
// - Tier 3 (Interactive theme): lazy-loads `./uiSdk` only when a trusted `ui_script_url` is active.
import { UI_CONTRACT_TOKENS } from '../styles/ui-contract'
import type { ActiveThemePayload, ThemeDecoration, ThemeDecorationState, TokenDeriveRule } from '../types'
const LEGACY_CACHE_KEY = 'reims-go-theme-tokens-v1'
const THEME_CACHE_KEY = 'reims-go-theme-tokens-v2'
const PREPAINT_EL_ID = 'rg-theme-prepaint'
const STYLE_EL_ID = 'rg-active-theme-style'
const FONT_EL_ID = 'rg-active-theme-fonts'
const ALLOWED_CONTRACT_TOKENS = new Set<string>(UI_CONTRACT_TOKENS)
const RE_FONT_WEIGHT = /^[0-9a-zA-Z -]+$/
const RE_FONT_STYLE = /^(normal|italic|oblique( +-?[0-9]+(\.[0-9]+)?deg)?)$/
const RE_UNICODE_RANGE = /^[U+0-9a-fA-F?, -]+$/
const RE_SAFE_ASSET_REL = /^[a-zA-Z0-9._/@ -]+$/
const RE_ASSET_BASE_URL = /^\/plugin-assets\/[a-f0-9]+\/[a-z0-9][a-z0-9._-]*\/$/
const RE_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:/
const FORBIDDEN_FOCUS_RING_VALUES = new Set(['none', '0', '0px', 'transparent', 'initial', 'unset', 'revert', 'revert-layer'])
interface ThemeTokenCache {
themeId: string
activeScheme: string
light?: Record<string, string>
dark?: Record<string, string>
}
export interface UIStateSnapshot {
appearance: 'light' | 'dark'
motion: 'full' | 'reduced'
view: string
vmName: string
vmState: string
busy: boolean
hasError: boolean
sidebarCollapsed: boolean
safeMode: boolean
vms: Array<{ name: string; state: string }>
}
export interface ThemeSDKHostActions {
toggleSidebar: () => void
openSettings: () => void
focusVMWindow: (name: string) => void
}
let activeUIScriptCleanup: (() => void) | null = null
let activeUIScriptURL = ''
let applyGeneration = 0
function decodeCSSEscapes(s: string): string {
if (!s.includes('\\')) return s
let out = ''
for (let i = 0; i < s.length; ) {
if (s[i] === '\\' && i + 1 < s.length) {
i++
const hexMatch = /^[0-9a-fA-F]{1,6}(?:\r\n|[ \t\n\r\f])?/.exec(s.slice(i))
if (hexMatch) {
const cp = parseInt(hexMatch[0].trim(), 16)
out += cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : '\uFFFD'
i += hexMatch[0].length
} else {
out += s[i]
i++
}
} else {
out += s[i]
i++
}
}
return out
}
/** Validates a token key+value against the UI Contract whitelist and CSS injection rules (B5). */
export function sanitizeTokenValue(key: string, value: string): string | null {
if (!ALLOWED_CONTRACT_TOKENS.has(key)) return null
if (typeof value !== 'string') return null
const trimmed = value.trim()
if (!trimmed || /[\r\n\0{};]/.test(trimmed) || trimmed.endsWith('\\')) return null
if (trimmed.includes('/*') || trimmed.includes('*/')) return null
const decoded = decodeCSSEscapes(trimmed).toLowerCase()
if (/[\r\n\0{};]/.test(decoded)) return null
for (const bad of ['</style', 'url(', 'src(', 'image-set(', '-webkit-image-set(', 'expression(', '@import', 'javascript:', 'data:', 'http://', 'https://', '//']) {
if (decoded.includes(bad)) return null
}
if (key === '--focus-ring' && (FORBIDDEN_FOCUS_RING_VALUES.has(decoded) || /\btransparent\b/.test(decoded))) {
return null
}
return trimmed
}
function sanitizeRelativeAssetPath(rel: string): string | null {
if (typeof rel !== 'string') return null
const cleaned = rel.trim().replace(/^\/+/, '')
if (!cleaned || /["'\\;{}()\r\n\0]/.test(cleaned) || !RE_SAFE_ASSET_REL.test(cleaned)) return null
if (RE_SCHEME.test(cleaned)) return null
for (const seg of cleaned.split('/')) {
if (seg === '..') return null
}
return cleaned
}
/** Verifies stylesheet has balanced braces and no unclosed strings/comments so it cannot escape `@layer theme` (B5). */
export function isBalancedThemeCSS(css: string): boolean {
if (css.toLowerCase().includes('</style')) return false
let depth = 0
const n = css.length
for (let i = 0; i < n; ) {
const c = css[i]
if (c === '/' && i + 1 < n && css[i + 1] === '*') {
const end = css.indexOf('*/', i + 2)
if (end < 0) return false
i = end + 2
continue
}
if (c === '"' || c === "'") {
const q = c
i++
let closed = false
while (i < n) {
if (css[i] === '\\') {
i += 2
continue
}
if (css[i] === '\n' || css[i] === '\r') return false
if (css[i] === q) {
i++
closed = true
break
}
i++
}
if (!closed) return false
continue
}
if (c === '\\') {
// Backslash escapes the next char (e.g. `\{` or `\}`) outside strings so it cannot affect brace depth.
if (i + 1 >= n) return false
i += 2
continue
}
if (c === '{') depth++
else if (c === '}') {
depth--
if (depth < 0) return false
}
i++
}
return depth === 0
}
function resolveInitialAppearance(): 'light' | 'dark' {
try {
const saved = localStorage.getItem('reims-go-theme')
if (saved === 'dark' || saved === 'light') return saved
} catch {
// ignore storage errors
}
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}
function clearLegacyInlineCache(): void {
try {
const raw = localStorage.getItem(LEGACY_CACHE_KEY)
if (raw) {
const prev = JSON.parse(raw) as Record<string, string>
if (prev && typeof prev === 'object') {
for (const k of Object.keys(prev)) {
if (k.startsWith('--')) document.documentElement.style.removeProperty(k)
}
}
localStorage.removeItem(LEGACY_CACHE_KEY)
}
} catch {
// ignore
}
}
function buildTokenVarLines(tokens: Record<string, string>): string {
const lines: string[] = []
for (const [k, v] of Object.entries(tokens)) {
const safe = sanitizeTokenValue(k, v)
if (safe) lines.push(` ${k}: ${safe};`)
}
return lines.join('\n')
}
/**
* Applies cached theme tokens via a `@layer theme` `<style>` element (never
* inline `element.style`, B8) keyed by appearance to avoid FOUC (§5.1).
*/
export function applyCachedThemeTokensSync(): void {
clearLegacyInlineCache()
try {
const raw = localStorage.getItem(THEME_CACHE_KEY)
if (!raw) return
const cache = JSON.parse(raw) as ThemeTokenCache
if (!cache || typeof cache !== 'object') return
const appearance = resolveInitialAppearance()
const tokens = cache[appearance]
if (!tokens || typeof tokens !== 'object') return
const varLines = buildTokenVarLines(tokens)
if (!varLines) return
let el = document.getElementById(PREPAINT_EL_ID) as HTMLStyleElement | null
if (!el) {
el = document.createElement('style')
el.id = PREPAINT_EL_ID
document.head.appendChild(el)
}
el.textContent = `@layer theme {\n:root {\n${varLines}\n}\n}`
} catch {
// ignore corrupt cache
}
}
function clearDynamicThemeStyles(): void {
document.getElementById(PREPAINT_EL_ID)?.remove()
document.getElementById(STYLE_EL_ID)?.remove()
document.getElementById(FONT_EL_ID)?.remove()
clearLegacyInlineCache()
try {
localStorage.removeItem(THEME_CACHE_KEY)
} catch {
// ignore
}
}
/** Parses a #RGB or #RRGGBB hex string into [h (0..360), s (0..1), l (0..1)]. */
function hexToHSL(hex: string): [number, number, number] | null {
const clean = hex.trim().replace(/^#/, '')
let r = 0, g = 0, b = 0
if (clean.length === 3) {
r = parseInt(clean[0] + clean[0], 16) / 255
g = parseInt(clean[1] + clean[1], 16) / 255
b = parseInt(clean[2] + clean[2], 16) / 255
} else if (clean.length === 6) {
r = parseInt(clean.slice(0, 2), 16) / 255
g = parseInt(clean.slice(2, 4), 16) / 255
b = parseInt(clean.slice(4, 6), 16) / 255
} else {
return null
}
if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return null
const max = Math.max(r, g, b)
const min = Math.min(r, g, b)
const l = (max + min) / 2
if (max === min) return [0, 0, l]
const d = max - min
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
let h = 0
if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6
else if (max === g) h = ((b - r) / d + 2) / 6
else h = ((r - g) / d + 4) / 6
return [h * 360, s, l]
}
function clamp01(x: number): number {
return Math.max(0, Math.min(1, x))
}
/** Derives CSS variable values from seed colors using declarative rules (§5.1). */
export function deriveTokensFromSeeds(
seeds: Record<string, string>,
rules: TokenDeriveRule[] | undefined,
appearance: 'light' | 'dark',
): Record<string, string> {
const out: Record<string, string> = {}
if (seeds.accent) {
const hsl = hexToHSL(seeds.accent)
out['--accent'] = seeds.accent
if (hsl) {
const [h, s, l] = hsl
out['--accent-hover'] = `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(l + (appearance === 'dark' ? 0.06 : -0.06)) * 100)}%)`
out['--accent-soft'] = `hsla(${Math.round(h)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%, ${appearance === 'dark' ? 0.2 : 0.12})`
out['--accent-soft-text'] = `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(clamp01(appearance === 'dark' ? Math.max(l, 0.66) : Math.min(l, 0.42)) * 100)}%)`
out['--focus-ring'] = `0 0 0 3px hsla(${Math.round(h)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%, ${appearance === 'dark' ? 0.45 : 0.30})`
}
}
if (seeds.surface) {
out['--surface-0'] = seeds.surface
out['--surface-canvas'] = seeds.surface
}
if (seeds.text) {
out['--text'] = seeds.text
}
for (const rule of rules ?? []) {
if (rule.appearance && rule.appearance !== appearance) continue
if (!ALLOWED_CONTRACT_TOKENS.has(rule.token)) continue
const seedVal = seeds[rule.fromSeed]
if (!seedVal) continue
const hsl = hexToHSL(seedVal)
if (!hsl) continue
const h = Math.round(hsl[0])
const s = Math.round(clamp01(rule.chroma && rule.chroma > 0 ? hsl[1] * rule.chroma : hsl[1]) * 100)
const l = Math.round(clamp01(hsl[2] + (rule.lightness ?? 0)) * 100)
if (rule.alpha && rule.alpha > 0 && rule.alpha < 1) {
out[rule.token] = `hsla(${h}, ${s}%, ${l}%, ${rule.alpha.toFixed(3)})`
} else {
out[rule.token] = `hsl(${h} ${s}% ${l}%)`
}
}
return out
}
/** Evaluates a declarative ThemeDecoration state expression (e.g. "vmState==running"). */
export function matchDecorationState(
decoration: ThemeDecoration,
snap: UIStateSnapshot,
): ThemeDecorationState | null {
let fallback: ThemeDecorationState | null = null
for (const st of decoration.states ?? []) {
const expr = (st.when || '').trim()
if (!expr || expr === 'default') {
fallback = st
continue
}
const [rawKey, rawVal] = expr.split('==').map((s) => s.trim())
if (!rawKey) continue
const map: Record<string, string> = {
vmState: snap.vmState,
view: snap.view,
theme: snap.appearance,
busy: String(snap.busy),
hasError: String(snap.hasError),
sidebarCollapsed: String(snap.sidebarCollapsed),
}
if (map[rawKey] === rawVal) return st
}
return fallback
}
/** Applies the active theme payload to the document, tearing down any previous theme first. */
export async function applyActiveTheme(
payload: ActiveThemePayload | null,
appearance: 'light' | 'dark',
getState: () => UIStateSnapshot,
actions: ThemeSDKHostActions,
): Promise<void> {
const gen = ++applyGeneration
// Always drop prepaint & legacy inline tokens so live theme/builtin always wins (B8).
document.getElementById(PREPAINT_EL_ID)?.remove()
clearLegacyInlineCache()
// Always tear down previous interactive theme script if URL changed or disabled.
const nextScriptURL = payload?.ui_script_url ?? ''
if (activeUIScriptCleanup && activeUIScriptURL !== nextScriptURL) {
try { activeUIScriptCleanup() } catch {}
activeUIScriptCleanup = null
activeUIScriptURL = ''
}
// Builtin default theme (or safe mode) -> zero extra CSS injected (§8.1).
if (!payload || !payload.theme || payload.theme_id === 'builtin.theme.default') {
clearDynamicThemeStyles()
return
}
const th = payload.theme
const rawBaseURL = payload.asset_base_url ?? ''
const baseURL = RE_ASSET_BASE_URL.test(rawBaseURL) && !rawBaseURL.includes('..') ? rawBaseURL : ''
// 1. Resolve active seed colors (custom scheme -> built-in scheme -> theme default seeds).
let seeds: Record<string, string> = { ...(th.seeds ?? {}) }
if (payload.active_scheme) {
const custom = (payload.custom_schemes ?? []).find((s) => s.id === payload.active_scheme && s.theme_id === payload.theme_id)
const preset = (th.schemes ?? []).find((s) => s.id === payload.active_scheme)
if (custom?.seeds) seeds = { ...seeds, ...custom.seeds }
else if (preset?.seeds) seeds = { ...seeds, ...preset.seeds }
}
// 2. Compute derived + explicit tokens and filter strictly through UI Contract whitelist (B5).
const rawTokens: Record<string, string> = {
...deriveTokensFromSeeds(seeds, th.deriveRules, appearance),
...(th.tokens ?? {}),
...(appearance === 'dark' ? (th.darkTokens ?? {}) : {}),
}
const sanitizedTokens: Record<string, string> = {}
for (const [k, v] of Object.entries(rawTokens)) {
const safe = sanitizeTokenValue(k, v)
if (safe) sanitizedTokens[k] = safe
}
// 3. Inject validated bundled @font-face declarations (B5).
let fontCSS = ''
for (const f of th.fonts ?? []) {
const family = typeof f.family === 'string' ? f.family.trim() : ''
if (!family || /["'\\;{}\r\n\0]/.test(family) || family.toLowerCase().includes('</style')) continue
const safeFile = sanitizeRelativeAssetPath(f.file)
if (!safeFile || !baseURL) continue
const safeURL = baseURL + safeFile
const weight = f.weight && RE_FONT_WEIGHT.test(f.weight) ? `font-weight:${f.weight};` : ''
const style = f.style && RE_FONT_STYLE.test(f.style.trim()) ? `font-style:${f.style.trim()};` : ''
const range = f.unicodeRange && RE_UNICODE_RANGE.test(f.unicodeRange) ? `unicode-range:${f.unicodeRange};` : ''
fontCSS += `@font-face{font-family:"${family}";src:url("${safeURL}");font-display:swap;${weight}${style}${range}}\n`
}
if (fontCSS) {
let el = document.getElementById(FONT_EL_ID) as HTMLStyleElement | null
if (!el) {
el = document.createElement('style')
el.id = FONT_EL_ID
document.head.appendChild(el)
}
el.textContent = fontCSS
} else {
document.getElementById(FONT_EL_ID)?.remove()
}
// 4. Write validated token CSS + Tier-2 stylesheet wrapped inside `@layer theme` (§5.1, B5/B7).
const varLines = buildTokenVarLines(sanitizedTokens)
let bgCSS = ''
if (th.background && baseURL) {
const safeBg = sanitizeRelativeAssetPath(th.background)
if (safeBg) {
bgCSS = `.rg-p-shell { background-image: url("${baseURL}${safeBg}"); background-size: cover; }\n`
}
}
const rawThemeCSS = payload.css && isBalancedThemeCSS(payload.css) ? payload.css : ''
const fullCSS = `@layer theme {\n:root {\n${varLines}\n}\n${bgCSS}${rawThemeCSS}\n}`
let styleEl = document.getElementById(STYLE_EL_ID) as HTMLStyleElement | null
if (!styleEl) {
styleEl = document.createElement('style')
styleEl.id = STYLE_EL_ID
document.head.appendChild(styleEl)
}
styleEl.textContent = fullCSS
// Persist appearance-keyed cache for prepaint (B8).
try {
let nextCache: ThemeTokenCache = {
themeId: payload.theme_id,
activeScheme: payload.active_scheme ?? '',
}
const prevRaw = localStorage.getItem(THEME_CACHE_KEY)
if (prevRaw) {
const prev = JSON.parse(prevRaw) as ThemeTokenCache
if (prev && prev.themeId === nextCache.themeId && prev.activeScheme === nextCache.activeScheme) {
nextCache = { ...prev }
}
}
nextCache[appearance] = sanitizedTokens
localStorage.setItem(THEME_CACHE_KEY, JSON.stringify(nextCache))
} catch {
// ignore storage quota
}
// 5. Tier 3: lazy-load UI SDK ONLY when an approved interactive theme script is present (§8.1).
if (nextScriptURL && nextScriptURL !== activeUIScriptURL) {
try {
const { mountInteractiveThemeScript } = await import('./uiSdk')
if (gen !== applyGeneration) return
const cleanup = await mountInteractiveThemeScript(nextScriptURL, getState, actions)
if (gen !== applyGeneration) {
try { cleanup() } catch {}
return
}
activeUIScriptCleanup = cleanup
activeUIScriptURL = nextScriptURL
} catch {
if (gen === applyGeneration) {
// Fallback gracefully to the scriptless style/token theme (§4.2).
activeUIScriptCleanup = null
activeUIScriptURL = ''
}
}
}
}
/** Plays a theme-configured sound for an event if present (fail-silent). */
export function playThemeSound(payload: ActiveThemePayload | null, eventName: string): void {
const file = payload?.theme?.sounds?.[eventName]
if (!file || !payload?.asset_base_url) return
const safe = sanitizeRelativeAssetPath(file)
if (!safe) return
try {
const audio = new Audio(payload.asset_base_url + safe)
audio.volume = 0.35
void audio.play().catch(() => {})
} catch {
// ignore audio decode/autoplay errors
}
}
+187
View File
@@ -0,0 +1,187 @@
// Lazy-loaded Tier-3 Interactive Theme UI SDK (docs/plugin-architecture.md §5.1).
// Loaded ONLY when a trusted interactive theme with `ui:script` is enabled (§8.1).
import { UI_API_VERSION, UI_CONTRACT_PARTS, UI_CONTRACT_SLOTS, type UIContractPart, type UIContractSlot } from '../styles/ui-contract'
import { hideWailsGlobals } from '../wails'
import type { ThemeSDKHostActions, UIStateSnapshot } from './themeEngine'
export interface ReimsUISDK {
readonly uiApi: string
/** Registers a cleanup callback run in LIFO order on theme switch/disable. */
onDispose: (fn: () => void) => void
/** Runs a named feature isolated so errors disable only that feature. */
feature: (name: string, setup: (dispose: (fn: () => void) => void) => void) => void
/** Read-only non-sensitive state snapshot & subscription. */
getState: () => UIStateSnapshot
subscribeState: (cb: (snap: UIStateSnapshot) => void) => () => void
/** Queries elements strictly by contract part class (`rg-p-*`). */
queryPart: (part: UIContractPart) => HTMLElement | null
/** Shared MutationObserver bus scoped to a contract part. */
observePart: (part: UIContractPart, cb: () => void) => () => void
/** Shared RAF read/write batch pipeline to avoid layout thrashing. */
scheduleRead: (fn: () => void) => void
scheduleWrite: (fn: () => void) => void
/** Framework-agnostic DOM mounting into a declared slot anchor. */
mountSlot: (slot: UIContractSlot, node: HTMLElement) => () => void
/** Restricted non-destructive UI actions only (no start/stop/delete/config write). */
actions: ThemeSDKHostActions
}
const stateListeners = new Set<(snap: UIStateSnapshot) => void>()
export function notifyThemeSDKState(snap: UIStateSnapshot): void {
if (stateListeners.size === 0) return
for (const cb of stateListeners) {
try { cb(snap) } catch {}
}
}
// Shared RAF read/write pipeline.
let readQueue: Array<() => void> = []
let writeQueue: Array<() => void> = []
let rafScheduled = false
function flushFrame() {
rafScheduled = false
const reads = readQueue
const writes = writeQueue
readQueue = []
writeQueue = []
for (const r of reads) { try { r() } catch {} }
for (const w of writes) { try { w() } catch {} }
}
function scheduleRAF() {
if (rafScheduled) return
rafScheduled = true
requestAnimationFrame(flushFrame)
}
export async function mountInteractiveThemeScript(
scriptURL: string,
getState: () => UIStateSnapshot,
actions: ThemeSDKHostActions,
): Promise<() => void> {
if (!scriptURL.startsWith('/plugin-assets/') || scriptURL.includes('..')) {
throw new Error('Refused to load theme script outside /plugin-assets/')
}
let disposed = false
const disposers = new Set<() => void>()
const partSet = new Set<string>(UI_CONTRACT_PARTS)
const slotSet = new Set<string>(UI_CONTRACT_SLOTS)
const addDisposer = (fn: () => void) => {
if (disposed) return
disposers.add(fn)
}
const disposeAll = () => {
if (disposed) return
disposed = true
const list = Array.from(disposers).reverse()
disposers.clear()
for (const fn of list) {
try { fn() } catch {}
}
}
const sdk: ReimsUISDK = {
uiApi: UI_API_VERSION,
onDispose: addDisposer,
feature: (_name, setup) => {
if (disposed) return
const localDisposers: Array<() => void> = []
const localDispose = () => {
while (localDisposers.length > 0) {
try { localDisposers.pop()?.() } catch {}
}
}
addDisposer(localDispose)
try {
setup((fn) => localDisposers.push(fn))
} catch {
// Feature-isolated error: tear down only this feature (§4.2, §5.1).
localDispose()
}
},
getState: () => {
const s = getState()
return { ...s, vms: s.vms.map((v) => ({ ...v })) }
},
subscribeState: (cb) => {
if (disposed) return () => {}
stateListeners.add(cb)
const off = () => {
stateListeners.delete(cb)
disposers.delete(off)
}
addDisposer(off)
return off
},
queryPart: (part) => {
if (disposed || !partSet.has(part)) return null
return document.querySelector<HTMLElement>(`.${part}`)
},
observePart: (part, cb) => {
if (disposed || !partSet.has(part)) return () => {}
const target = document.querySelector<HTMLElement>(`.${part}`)
if (!target) return () => {}
const obs = new MutationObserver(() => {
if (disposed) return
try { cb() } catch {}
})
obs.observe(target, { attributes: true, childList: true, subtree: false })
const off = () => {
obs.disconnect()
disposers.delete(off)
}
addDisposer(off)
return off
},
scheduleRead: (fn) => {
if (disposed) return
readQueue.push(() => { if (!disposed) fn() })
scheduleRAF()
},
scheduleWrite: (fn) => {
if (disposed) return
writeQueue.push(() => { if (!disposed) fn() })
scheduleRAF()
},
mountSlot: (slot, node) => {
if (disposed || !slotSet.has(slot)) return () => {}
const host = document.querySelector<HTMLElement>(`[data-rg-slot="${CSS.escape(slot)}"]`)
if (!host) return () => {}
host.appendChild(node)
const off = () => {
node.remove()
disposers.delete(off)
}
addDisposer(off)
return off
},
actions: {
toggleSidebar: actions.toggleSidebar,
openSettings: actions.openSettings,
focusVMWindow: actions.focusVMWindow,
},
}
// Hide Wails binding globals from `window` before executing any theme script,
// and shadow bridge identifiers inside its closure (§5.1, B6). Note: scripts
// in the main window still run in the same DOM realm, so `ui:script` remains
// a high-trust permission requiring explicit user approval.
hideWailsGlobals()
const resp = await fetch(scriptURL, { credentials: 'same-origin' })
if (!resp.ok) throw new Error(`Failed to fetch theme script (${resp.status})`)
const source = await resp.text()
const runner = new Function('sdk', 'go', 'runtime', 'WailsInvoke', 'wails', `"use strict";\n${source}`)
try {
runner(sdk, undefined, undefined, undefined, undefined)
} catch (err) {
disposeAll()
throw err
}
return disposeAll
}
+4
View File
@@ -1,8 +1,12 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { App } from './App'
import { applyCachedThemeTokensSync } from './lib/themeEngine'
import './styles/app.css'
// Inline cached theme tokens before first paint to prevent FOUC (§5.1).
applyCachedThemeTokensSync()
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
+46
View File
@@ -1,5 +1,10 @@
/* Layer order: host-guard first so its !important usability invariants beat all
normal and !important rules in base/theme/user (CSS Cascade 5); normal rules
follow base -> theme -> user (§5.1, B7/M15). */
@layer host-guard, base, theme, user;
@import "./tokens.css";
@layer base {
* { box-sizing: border-box; }
html, body, #root {
@@ -1458,3 +1463,44 @@ button.status-issue + .status-metric { margin-left: 6px; }
}
.welcome-card h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; }
.welcome-card p { font-size: var(--fs-13); color: var(--text-2); max-width: 380px; }
/* Plugin system & UI Contract v1 (docs/plugin-architecture.md §5.1, §7.3, §9) */
.safe-mode-banner {
display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3);
padding: 6px var(--sp-4); font-size: var(--fs-12);
background: var(--warn-soft); color: var(--warn-text);
border-bottom: 1px solid var(--notice-border);
}
.rg-slot-anchor:empty { display: none; }
.rg-slot-inline { display: inline-flex; align-items: center; gap: 6px; }
.rg-slot-inline:empty { display: none; }
.rg-preview-anchor { position: absolute; z-index: 2; pointer-events: none; }
.rg-preview-anchor:empty { display: none; }
.rg-preview-anchor.tl { top: 6px; left: 6px; }
.rg-preview-anchor.tr { top: 6px; right: 6px; }
.rg-preview-anchor.bl { bottom: 6px; left: 6px; }
.rg-preview-anchor.br { bottom: 6px; right: 6px; }
.plugin-panel-wrap {
border: 1px solid var(--border); border-radius: var(--r-lg);
overflow: hidden; background: var(--surface-1); margin-bottom: var(--sp-3);
}
.plugin-panel-head {
padding: 8px 12px; font-size: var(--fs-12); font-weight: var(--fw-medium);
color: var(--text-2); border-bottom: 1px solid var(--border);
}
.plugin-panel-frame { display: block; width: 100%; border: 0; background: transparent; }
.plugin-panel-error {
display: flex; align-items: center; justify-content: space-between;
padding: 12px 14px; border: 1px solid var(--danger-border); border-radius: var(--r-md);
background: var(--danger-soft); color: var(--danger-text); font-size: var(--fs-12);
}
}
/* Host usability invariants locked with !important in earliest layer so themes
cannot override them even with !important (§5.1, B7/M15). */
@layer host-guard {
.rg-p-titlebar { --wails-draggable: drag !important; }
:focus-visible { box-shadow: var(--focus-ring) !important; }
.icon-btn, .win-btn { min-width: 28px !important; min-height: 28px !important; }
}
+2
View File
@@ -40,6 +40,7 @@
}
/* Design tokens — macOS Tahoe aesthetic with Windows platform craft (Light default, Dark & System supported). */
@layer base {
:root {
color-scheme: light;
@@ -244,3 +245,4 @@
--text-3: #a6a6b0;
}
}
}
+83
View File
@@ -0,0 +1,83 @@
// Single source of truth for UI Contract v1 (docs/plugin-architecture.md §5.1).
// Renaming or removing any part, state attribute, or token here is a uiApi major bump.
export const UI_API_VERSION = '1.0.0' as const
export const UI_CONTRACT_PARTS = [
'rg-p-shell',
'rg-p-titlebar',
'rg-p-brand',
'rg-p-workspace',
'rg-p-sidebar',
'rg-p-sidebar-head',
'rg-p-nav',
'rg-p-main',
'rg-p-vm-page',
'rg-p-vm-header',
'rg-p-vm-preview',
'rg-p-vm-summary',
'rg-p-statusbar',
'rg-p-logpanel',
'rg-p-settings',
'rg-p-empty',
] as const
export type UIContractPart = (typeof UI_CONTRACT_PARTS)[number]
export const UI_CONTRACT_STATE_ATTRS = [
'data-theme',
'data-motion',
'data-view',
'data-vm-state',
'data-busy',
'data-has-error',
'data-sidebar-collapsed',
'data-safe-mode',
] as const
export const UI_CONTRACT_SLOTS = [
'sidebar.footer',
'statusbar.right',
'vm.toolbar',
'vm.card',
'settings.plugin',
'vm.preview.tl',
'vm.preview.tr',
'vm.preview.bl',
'vm.preview.br',
'empty.state',
] as const
export type UIContractSlot = (typeof UI_CONTRACT_SLOTS)[number]
export const UI_CONTRACT_TOKENS = [
'--font-sans', '--font-mono',
'--fs-11', '--fs-12', '--fs-13', '--fs-14', '--fs-15', '--fs-16', '--fs-20', '--fs-24',
'--fw-regular', '--fw-medium', '--fw-strong',
'--sp-1', '--sp-2', '--sp-3', '--sp-4', '--sp-5', '--sp-6', '--sp-8',
'--r-sm', '--r-md', '--r-lg', '--r-xl',
'--surface-0', '--surface-canvas', '--surface-sidebar-rail', '--surface-sidebar',
'--surface-sidebar-border', '--surface-sidebar-shadow', '--surface-chrome',
'--surface-statusbar', '--surface-1', '--surface-card-elevated', '--surface-2',
'--surface-input', '--surface-hover', '--surface-active',
'--border', '--border-strong', '--highlight-top', '--scrim',
'--shadow-btn', '--shadow-card', '--shadow-overlay',
'--blur-chrome', '--blur-overlay',
'--text', '--text-2', '--text-3', '--text-code',
'--accent', '--accent-hover', '--accent-text', '--accent-soft', '--accent-soft-text', '--focus-ring',
'--status-running', '--status-busy', '--status-error', '--status-idle',
'--ok-soft', '--ok-text', '--warn-soft', '--warn-text',
'--danger', '--danger-soft', '--danger-border', '--danger-text',
'--notice-soft', '--notice-border', '--seg-thumb',
'--ease-out', '--ease-in-out', '--ease-spring',
'--dur-press', '--dur-fast', '--dur', '--dur-modal', '--dur-toast',
'--titlebar-h', '--logbar-h', '--sidebar-w', '--page-max',
] as const
export const UI_CONTRACT = {
uiApi: UI_API_VERSION,
parts: [...UI_CONTRACT_PARTS],
stateAttrs: [...UI_CONTRACT_STATE_ATTRS],
slots: [...UI_CONTRACT_SLOTS],
tokens: [...UI_CONTRACT_TOKENS],
}
+23 -1
View File
@@ -1,7 +1,7 @@
// Backend types come from the Wails-generated models (wailsjs/go/models.ts,
// regenerated by `wails dev` / `wails build`). This file only adds what Go
// cannot say: string unions, and `| null` for slices Go may send as nil.
import { app, config, host, installer, reims, runtime, version } from '../wailsjs/go/models'
import { app, config, driver, host, installer, plugin, reims, runtime, version } from '../wailsjs/go/models'
/** A generated class as a plain data shape (no convertValues helper). */
type Model<T> = Omit<T, 'convertValues'>
@@ -116,6 +116,28 @@ export type CachedInstaller = Model<installer.Cached> & {
export type DataRootChoice = app.DataRootChoice
export type DataRootCheck = app.DataRootCheck
export type LocalizedText = plugin.LocalizedText
export type PermissionSpec = plugin.PermissionSpec
export type SettingProperty = plugin.SettingProperty
export type SettingsSchema = plugin.SettingsSchema
export type PluginInfo = plugin.PluginInfo
export type DoctorFinding = plugin.DoctorFinding
export type TokenDeriveRule = plugin.TokenDeriveRule
export type ThemeScheme = plugin.ThemeScheme
export type ThemeDecoration = plugin.ThemeDecoration
export type ThemeDecorationState = plugin.ThemeDecorationState
export type ThemeContribution = plugin.ThemeContribution
export type CustomThemeScheme = plugin.CustomThemeScheme
export type ActiveThemePayload = plugin.ActiveThemePayload
export type MenuContribution = plugin.MenuContribution
export type VMCardContribution = plugin.VMCardContribution
export type PanelContribution = plugin.PanelContribution
export type StatusItemContribution = plugin.StatusItemContribution
export type PluginUIContributions = app.PluginUIContributions
export type DriverSummary = driver.DriverSummary
export type DriverCreateRequest = driver.CreateRequest
export type RuntimeKindSpec = runtime.KindSpec
/** A "reims:log" event (internal/app/app.go emitLog); not a Go struct, so not generated. */
export interface LogEntry {
ts: string
+136 -15
View File
@@ -1,26 +1,147 @@
// Backend calls are the Wails-generated bindings (wailsjs/go/app/App). Only
// the calls whose results carry the unions or nil slices added in types.ts are
// re-typed here; everything else passes through unchanged.
//
// At module boot we privately capture `window.go.app.App` and `window.runtime`
// so `hideWailsGlobals()` can remove them from `window` before running any
// Tier-3 interactive theme script without breaking the app's own calls (§5.1, B6).
import * as Go from '../wailsjs/go/app/App'
import { EventsOn } from '../wailsjs/runtime/runtime'
import type { AppState, CachedInstaller, DataRootChoice, LogEntry, RemoteRuntime, Task, VMAffinityStatus, VMAffinityUpdate } from './types'
import {
EventsOn as RawEventsOn,
OnFileDrop as RawOnFileDrop,
OnFileDropOff as RawOnFileDropOff,
WindowMinimise as RawWindowMinimise,
WindowToggleMaximise as RawWindowToggleMaximise,
} from '../wailsjs/runtime/runtime'
import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, PluginInfo, PluginUIContributions, RemoteRuntime, RuntimeKindSpec,
Task, VMAffinityStatus, VMAffinityUpdate,
} from './types'
type AnyFn = (...args: never[]) => unknown
interface WailsWindow {
go?: { app?: { App?: Record<string, AnyFn> } }
runtime?: Record<string, AnyFn>
}
const wailsWin = window as unknown as WailsWindow
const capturedGoApp: Record<string, AnyFn> = wailsWin.go?.app?.App ? { ...wailsWin.go.app.App } : {}
const capturedRuntime: Record<string, AnyFn> = wailsWin.runtime ? { ...wailsWin.runtime } : {}
let globalsHidden = false
const boundGo = {} as typeof Go
for (const key of Object.keys(Go) as Array<keyof typeof Go>) {
const fn = capturedGoApp[key as string]
;(boundGo as Record<string, unknown>)[key as string] = fn
? (...args: never[]) => fn(...args)
: Go[key]
}
/**
* Hides Wails binding globals (`window.go` and unsafe `window.runtime` methods)
* before mounting an interactive theme script (§5.1, B6). Only `ResolveFilePaths`
* (required internally by Wails's native drag-and-drop bridge) is retained on a
* frozen runtime stub.
*/
export function hideWailsGlobals(): void {
if (globalsHidden) return
globalsHidden = true
try {
delete wailsWin.go
Object.defineProperty(window, 'go', {
value: undefined,
writable: false,
configurable: false,
enumerable: false,
})
} catch {
// non-configurable in some test environments
}
try {
const minimalRuntime = typeof capturedRuntime.ResolveFilePaths === 'function'
? Object.freeze({ ResolveFilePaths: capturedRuntime.ResolveFilePaths })
: undefined
delete wailsWin.runtime
Object.defineProperty(window, 'runtime', {
value: minimalRuntime,
writable: false,
configurable: false,
enumerable: false,
})
} catch {
// ignore if non-configurable
}
}
export function OnFileDrop(
callback: (x: number, y: number, paths: string[]) => void,
useDropTarget: boolean,
): void {
if (typeof capturedRuntime.OnFileDrop === 'function') {
;(capturedRuntime.OnFileDrop as (cb: typeof callback, useTarget: boolean) => void)(callback, useDropTarget)
return
}
RawOnFileDrop(callback, useDropTarget)
}
export function OnFileDropOff(): void {
if (typeof capturedRuntime.OnFileDropOff === 'function') {
;(capturedRuntime.OnFileDropOff as () => void)()
return
}
RawOnFileDropOff()
}
export function WindowMinimise(): void {
if (typeof capturedRuntime.WindowMinimise === 'function') {
;(capturedRuntime.WindowMinimise as () => void)()
return
}
RawWindowMinimise()
}
export function WindowToggleMaximise(): void {
if (typeof capturedRuntime.WindowToggleMaximise === 'function') {
;(capturedRuntime.WindowToggleMaximise as () => void)()
return
}
RawWindowToggleMaximise()
}
function eventsOn<T>(eventName: string, cb: (data: T) => void): () => void {
if (typeof capturedRuntime.EventsOnMultiple === 'function') {
return (capturedRuntime.EventsOnMultiple as (name: string, fn: (data: T) => void, max: number) => () => void)(
eventName,
cb,
-1,
)
}
return RawEventsOn(eventName, cb)
}
export const api = {
...Go,
GetState: Go.GetState as () => Promise<AppState>,
GetTasks: Go.GetTasks as () => Promise<Task[]>,
GetVMAffinity: Go.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
SetVMAffinity: Go.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
ListInstallers: Go.ListInstallers as () => Promise<CachedInstaller[] | null>,
ListRemoteRuntimes: Go.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: Go.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
...boundGo,
GetState: boundGo.GetState as () => Promise<AppState>,
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
ListInstallers: boundGo.ListInstallers as () => Promise<CachedInstaller[] | null>,
ListRemoteRuntimes: boundGo.ListRemoteRuntimes as () => Promise<RemoteRuntime[] | null>,
SuggestDataRoots: boundGo.SuggestDataRoots as () => Promise<DataRootChoice[] | null>,
ListPlugins: boundGo.ListPlugins as () => Promise<PluginInfo[] | null>,
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
ListDrivers: boundGo.ListDrivers as () => Promise<DriverSummary[] | null>,
ListRuntimeKinds: boundGo.ListRuntimeKinds as () => Promise<RuntimeKindSpec[] | null>,
}
export const events = {
onTask: (cb: (task: Task) => void) => EventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => EventsOn('reims:state-changed', cb),
onLog: (cb: (entry: LogEntry) => void) => EventsOn('reims:log', cb),
onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb),
onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb),
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
onTraySelectVM: (cb: (name: string) => void) => EventsOn('reims:tray-select-vm', cb),
onTrayNewVM: (cb: () => void) => EventsOn('reims:tray-new-vm', cb),
onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb),
onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb),
}
+129
View File
@@ -0,0 +1,129 @@
{
"uiApi": "1.0.0",
"tokens": [
"--font-sans",
"--font-mono",
"--fs-11",
"--fs-12",
"--fs-13",
"--fs-14",
"--fs-15",
"--fs-16",
"--fs-20",
"--fs-24",
"--fw-regular",
"--fw-medium",
"--fw-strong",
"--sp-1",
"--sp-2",
"--sp-3",
"--sp-4",
"--sp-5",
"--sp-6",
"--sp-8",
"--r-sm",
"--r-md",
"--r-lg",
"--r-xl",
"--surface-0",
"--surface-canvas",
"--surface-sidebar-rail",
"--surface-sidebar",
"--surface-sidebar-border",
"--surface-sidebar-shadow",
"--surface-chrome",
"--surface-statusbar",
"--surface-1",
"--surface-card-elevated",
"--surface-2",
"--surface-input",
"--surface-hover",
"--surface-active",
"--border",
"--border-strong",
"--highlight-top",
"--scrim",
"--shadow-btn",
"--shadow-card",
"--shadow-overlay",
"--blur-chrome",
"--blur-overlay",
"--text",
"--text-2",
"--text-3",
"--text-code",
"--accent",
"--accent-hover",
"--accent-text",
"--accent-soft",
"--accent-soft-text",
"--focus-ring",
"--status-running",
"--status-busy",
"--status-error",
"--status-idle",
"--ok-soft",
"--ok-text",
"--warn-soft",
"--warn-text",
"--danger",
"--danger-soft",
"--danger-border",
"--danger-text",
"--notice-soft",
"--notice-border",
"--seg-thumb",
"--ease-out",
"--ease-in-out",
"--ease-spring",
"--dur-press",
"--dur-fast",
"--dur",
"--dur-modal",
"--dur-toast",
"--titlebar-h",
"--logbar-h",
"--sidebar-w",
"--page-max"
],
"parts": [
"rg-p-shell",
"rg-p-titlebar",
"rg-p-brand",
"rg-p-workspace",
"rg-p-sidebar",
"rg-p-sidebar-head",
"rg-p-nav",
"rg-p-main",
"rg-p-vm-page",
"rg-p-vm-header",
"rg-p-vm-preview",
"rg-p-vm-summary",
"rg-p-statusbar",
"rg-p-logpanel",
"rg-p-settings",
"rg-p-empty"
],
"stateAttrs": [
"data-theme",
"data-motion",
"data-view",
"data-vm-state",
"data-busy",
"data-has-error",
"data-sidebar-collapsed",
"data-safe-mode"
],
"slots": [
"sidebar.footer",
"statusbar.right",
"vm.toolbar",
"vm.card",
"settings.plugin",
"vm.preview.tl",
"vm.preview.tr",
"vm.preview.bl",
"vm.preview.br",
"empty.state"
]
}
+47
View File
@@ -3,8 +3,11 @@
import {reims} from '../models';
import {version} from '../models';
import {app} from '../models';
import {driver} from '../models';
import {plugin} from '../models';
import {runtime} from '../models';
import {installer} from '../models';
import {http} from '../models';
export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
@@ -30,6 +33,10 @@ export function CreateSnapshot(arg1:string,arg2:string):Promise<void>;
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
export function CreateVMWithDriver(arg1:driver.CreateRequest):Promise<void>;
export function DeleteCustomThemeScheme(arg1:string):Promise<void>;
export function DeleteInstaller(arg1:string):Promise<void>;
export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
@@ -42,14 +49,20 @@ export function DeliverPathsToGuest(arg1:string,arg2:Array<string>):Promise<Arra
export function DetachGuestTools(arg1:string):Promise<void>;
export function DisablePlugin(arg1:string):Promise<void>;
export function DismissTask(arg1:string):Promise<void>;
export function DoctorPlugin(arg1:string):Promise<Array<plugin.DoctorFinding>>;
export function DownloadAndAttachOnlineRecovery(arg1:string,arg2:string):Promise<string>;
export function DownloadInstaller(arg1:string):Promise<string>;
export function EjectInstaller(arg1:string):Promise<void>;
export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
export function EnableWHPX():Promise<void>;
export function EnterRecovery(arg1:string):Promise<void>;
@@ -60,6 +73,12 @@ export function FinishInstall(arg1:string):Promise<void>;
export function FocusVMWindow(arg1:string):Promise<void>;
export function GetActiveTheme():Promise<plugin.ActiveThemePayload>;
export function GetPluginSettings(arg1:string,arg2:string):Promise<Record<string, any>>;
export function GetPluginUIContributions():Promise<app.PluginUIContributions>;
export function GetState():Promise<app.AppState>;
export function GetStorageBreakdown():Promise<app.StorageBreakdown>;
@@ -76,22 +95,36 @@ export function GetVMMacOS(arg1:string):Promise<string>;
export function GetVMNote(arg1:string):Promise<string>;
export function GetVMPluginSettings(arg1:string):Promise<Record<string, Record<string, any>>>;
export function GetVMSSHUser(arg1:string):Promise<string>;
export function GetVMStats(arg1:string):Promise<app.VMStats>;
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
export function InstallPluginArchive(arg1:string):Promise<plugin.PluginInfo>;
export function InstallRuntimeArchive(arg1:string):Promise<runtime.Installed>;
export function InstallRuntimeOnline(arg1:string):Promise<string>;
export function InvokePluginCommand(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
export function LinkPluginDev(arg1:string):Promise<plugin.PluginInfo>;
export function ListDrivers():Promise<Array<driver.DriverSummary>>;
export function ListInstallers():Promise<Array<installer.Cached>>;
export function ListOfflineReleases():Promise<Array<installer.Release>>;
export function ListPlugins():Promise<Array<plugin.PluginInfo>>;
export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
export function ListRuntimeKinds():Promise<Array<runtime.KindSpec>>;
export function ListSnapshots(arg1:string):Promise<Array<reims.DiskSnapshot>>;
export function OpenProcessorScheduling():Promise<void>;
@@ -106,16 +139,24 @@ export function OpenVMFolder(arg1:string):Promise<void>;
export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
export function PanelBridgeCall(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
export function PickDirectory(arg1:string):Promise<string>;
export function PickFile(arg1:string,arg2:string):Promise<string>;
export function PluginAssetHandler():Promise<http.Handler>;
export function PreviewCreate(arg1:reims.CreateOpts):Promise<string>;
export function QuitApp():Promise<void>;
export function ReadPluginLog(arg1:string):Promise<string>;
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
export function RequestClose():Promise<void>;
export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeResult>;
@@ -124,6 +165,10 @@ export function RestartVM(arg1:string):Promise<void>;
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
export function SetActiveTheme(arg1:string,arg2:string):Promise<void>;
export function SetAutoPinPCores(arg1:boolean):Promise<void>;
export function SetDataRoot(arg1:string):Promise<void>;
@@ -134,6 +179,8 @@ export function SetLocale(arg1:string):Promise<void>;
export function SetMinimizeToTray(arg1:boolean):Promise<void>;
export function SetPluginSettings(arg1:string,arg2:string,arg3:Record<string, any>):Promise<void>;
export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetRuntimeSource(arg1:string):Promise<void>;
+88
View File
@@ -50,6 +50,14 @@ export function CreateVM(arg1) {
return window['go']['app']['App']['CreateVM'](arg1);
}
export function CreateVMWithDriver(arg1) {
return window['go']['app']['App']['CreateVMWithDriver'](arg1);
}
export function DeleteCustomThemeScheme(arg1) {
return window['go']['app']['App']['DeleteCustomThemeScheme'](arg1);
}
export function DeleteInstaller(arg1) {
return window['go']['app']['App']['DeleteInstaller'](arg1);
}
@@ -74,10 +82,18 @@ export function DetachGuestTools(arg1) {
return window['go']['app']['App']['DetachGuestTools'](arg1);
}
export function DisablePlugin(arg1) {
return window['go']['app']['App']['DisablePlugin'](arg1);
}
export function DismissTask(arg1) {
return window['go']['app']['App']['DismissTask'](arg1);
}
export function DoctorPlugin(arg1) {
return window['go']['app']['App']['DoctorPlugin'](arg1);
}
export function DownloadAndAttachOnlineRecovery(arg1, arg2) {
return window['go']['app']['App']['DownloadAndAttachOnlineRecovery'](arg1, arg2);
}
@@ -90,6 +106,10 @@ export function EjectInstaller(arg1) {
return window['go']['app']['App']['EjectInstaller'](arg1);
}
export function EnablePlugin(arg1, arg2) {
return window['go']['app']['App']['EnablePlugin'](arg1, arg2);
}
export function EnableWHPX() {
return window['go']['app']['App']['EnableWHPX']();
}
@@ -110,6 +130,18 @@ export function FocusVMWindow(arg1) {
return window['go']['app']['App']['FocusVMWindow'](arg1);
}
export function GetActiveTheme() {
return window['go']['app']['App']['GetActiveTheme']();
}
export function GetPluginSettings(arg1, arg2) {
return window['go']['app']['App']['GetPluginSettings'](arg1, arg2);
}
export function GetPluginUIContributions() {
return window['go']['app']['App']['GetPluginUIContributions']();
}
export function GetState() {
return window['go']['app']['App']['GetState']();
}
@@ -142,6 +174,10 @@ export function GetVMNote(arg1) {
return window['go']['app']['App']['GetVMNote'](arg1);
}
export function GetVMPluginSettings(arg1) {
return window['go']['app']['App']['GetVMPluginSettings'](arg1);
}
export function GetVMSSHUser(arg1) {
return window['go']['app']['App']['GetVMSSHUser'](arg1);
}
@@ -154,6 +190,10 @@ export function GetVMThumbnail(arg1) {
return window['go']['app']['App']['GetVMThumbnail'](arg1);
}
export function InstallPluginArchive(arg1) {
return window['go']['app']['App']['InstallPluginArchive'](arg1);
}
export function InstallRuntimeArchive(arg1) {
return window['go']['app']['App']['InstallRuntimeArchive'](arg1);
}
@@ -162,6 +202,18 @@ export function InstallRuntimeOnline(arg1) {
return window['go']['app']['App']['InstallRuntimeOnline'](arg1);
}
export function InvokePluginCommand(arg1, arg2, arg3) {
return window['go']['app']['App']['InvokePluginCommand'](arg1, arg2, arg3);
}
export function LinkPluginDev(arg1) {
return window['go']['app']['App']['LinkPluginDev'](arg1);
}
export function ListDrivers() {
return window['go']['app']['App']['ListDrivers']();
}
export function ListInstallers() {
return window['go']['app']['App']['ListInstallers']();
}
@@ -170,10 +222,18 @@ export function ListOfflineReleases() {
return window['go']['app']['App']['ListOfflineReleases']();
}
export function ListPlugins() {
return window['go']['app']['App']['ListPlugins']();
}
export function ListRemoteRuntimes() {
return window['go']['app']['App']['ListRemoteRuntimes']();
}
export function ListRuntimeKinds() {
return window['go']['app']['App']['ListRuntimeKinds']();
}
export function ListSnapshots(arg1) {
return window['go']['app']['App']['ListSnapshots'](arg1);
}
@@ -202,6 +262,10 @@ export function OpenVSCodeSSH(arg1, arg2) {
return window['go']['app']['App']['OpenVSCodeSSH'](arg1, arg2);
}
export function PanelBridgeCall(arg1, arg2, arg3) {
return window['go']['app']['App']['PanelBridgeCall'](arg1, arg2, arg3);
}
export function PickDirectory(arg1) {
return window['go']['app']['App']['PickDirectory'](arg1);
}
@@ -210,6 +274,10 @@ export function PickFile(arg1, arg2) {
return window['go']['app']['App']['PickFile'](arg1, arg2);
}
export function PluginAssetHandler() {
return window['go']['app']['App']['PluginAssetHandler']();
}
export function PreviewCreate(arg1) {
return window['go']['app']['App']['PreviewCreate'](arg1);
}
@@ -218,10 +286,18 @@ export function QuitApp() {
return window['go']['app']['App']['QuitApp']();
}
export function ReadPluginLog(arg1) {
return window['go']['app']['App']['ReadPluginLog'](arg1);
}
export function ReadVMLogs(arg1, arg2) {
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2);
}
export function RemovePlugin(arg1, arg2) {
return window['go']['app']['App']['RemovePlugin'](arg1, arg2);
}
export function RequestClose() {
return window['go']['app']['App']['RequestClose']();
}
@@ -238,6 +314,14 @@ export function RestoreSnapshot(arg1, arg2) {
return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2);
}
export function SaveCustomThemeScheme(arg1) {
return window['go']['app']['App']['SaveCustomThemeScheme'](arg1);
}
export function SetActiveTheme(arg1, arg2) {
return window['go']['app']['App']['SetActiveTheme'](arg1, arg2);
}
export function SetAutoPinPCores(arg1) {
return window['go']['app']['App']['SetAutoPinPCores'](arg1);
}
@@ -258,6 +342,10 @@ export function SetMinimizeToTray(arg1) {
return window['go']['app']['App']['SetMinimizeToTray'](arg1);
}
export function SetPluginSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetPluginSettings'](arg1, arg2, arg3);
}
export function SetRuntimeChannel(arg1) {
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
}
File diff suppressed because it is too large. Load diff
+175 -38
View File
@@ -14,10 +14,13 @@ import (
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/tray"
@@ -43,8 +46,10 @@ type AppState struct {
Transitions map[string]string `json:"transitions"`
PendingChanges map[string][]PendingChange `json:"pending_changes"`
// NeedsSetup is true on first launch, until a data folder is chosen (setup.go).
NeedsSetup bool `json:"needs_setup"`
AppVersion string `json:"app_version"`
NeedsSetup bool `json:"needs_setup"`
AppVersion string `json:"app_version"`
SafeMode bool `json:"safe_mode,omitempty"`
PluginCrashDetected bool `json:"plugin_crash_detected,omitempty"`
}
type rebootWatcherEntry struct {
@@ -75,6 +80,9 @@ type App struct {
launch cli.WindowArgs // flags this window was started with (window_launch.go)
trayIcon []byte // embedded PNG passed in from package main
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
pluginMgr *plugin.Manager
driverRouter *driver.Router
runtimeKinds *rt.KindRegistry
}
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
@@ -116,7 +124,10 @@ func (a *App) startup(ctx context.Context) {
pollCtx, cancel := context.WithCancel(ctx)
a.stopPoll = cancel
a.startTray()
a.startIMEBridge()
a.initPlugins()
if a.getInputService() == nil {
a.startIMEBridge()
}
go a.registerExistingGuestTools(pollCtx)
go a.pollVMs(pollCtx)
a.afterStartup()
@@ -154,6 +165,7 @@ func (a *App) shutdown(ctx context.Context) {
}
tasks.cancelAll()
stopAllVMMonitors()
a.shutdownPlugins()
a.mu.Lock()
for name, entry := range a.rebootWatchers {
entry.cancel()
@@ -317,13 +329,12 @@ func (a *App) pollVMs(ctx context.Context) {
if ib != nil {
ib.SetTargets(imeTargets)
}
a.syncInputTargets(imeTargets)
if tm != nil {
if runningCount > 0 {
if loc == i18n.ZhCN {
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d 台虚拟机运行中", runningCount))
} else {
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d VM(s) running", runningCount))
}
if runningCount == 1 {
tm.UpdateTooltip(i18n.T(loc, "tray.running.one"))
} else if runningCount > 1 {
tm.UpdateTooltip(i18n.T(loc, "tray.running.many", runningCount))
} else {
tm.UpdateTooltip("Reims-Go")
}
@@ -537,17 +548,38 @@ func (a *App) GetState() AppState {
}
opts := host.EvaluateOptimizations(rep, activePatches)
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
safeMode := a.launch.SafeMode
crashDetected := false
if mgr != nil {
safeMode = mgr.SafeMode()
crashDetected = mgr.CrashDetected()
if mgr.Registry().Hooks().HasSubscribers(plugin.EventHostPreflight) {
var rtCaps []string
if active != nil {
rtCaps = active.Manifest.EffectiveCapabilities()
}
_ = mgr.Registry().Hooks().DispatchPreflight(context.Background(), plugin.PreflightPayload{
HostFacts: buildHostFacts(rep, rtCaps),
})
}
}
return AppState{
Config: &cfgCopy,
Host: rep,
Optimizations: opts,
Runtimes: runtimes,
ActiveRuntime: active,
VMs: vms,
Transitions: trCopy,
PendingChanges: pcCopy,
NeedsSetup: needsSetup,
AppVersion: version.Version,
Config: &cfgCopy,
Host: rep,
Optimizations: opts,
Runtimes: runtimes,
ActiveRuntime: active,
VMs: vms,
Transitions: trCopy,
PendingChanges: pcCopy,
NeedsSetup: needsSetup,
AppVersion: version.Version,
SafeMode: safeMode,
PluginCrashDetected: crashDetected,
}
}
@@ -811,13 +843,14 @@ func (a *App) UseRuntime(commit string) error {
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
a.mu.Lock()
root := a.cfg.DataRoot
loc := a.cfg.Locale
a.mu.Unlock()
issues := reims.ValidateCreate(opts, host.Inspect(root))
issues := reims.ValidateCreateLocalized(opts, host.Inspect(root), loc)
// reims-ctl refuses a name already registered; say so before the create runs.
if vms, err := a.listVMsInternal(context.Background()); err == nil {
for _, vm := range vms {
if strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: "A VM named " + vm.Name + " already exists"})
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: i18n.T(loc, "validate.name_taken", vm.Name)})
break
}
}
@@ -840,8 +873,9 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
}
a.mu.Lock()
root := a.cfg.DataRoot
loc := a.cfg.Locale
a.mu.Unlock()
return reims.ValidateSet(opts, cur, host.Inspect(root)), nil
return reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc), nil
}
func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
@@ -851,8 +885,9 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
}
a.mu.Lock()
root := a.cfg.DataRoot
loc := a.cfg.Locale
a.mu.Unlock()
if issues := reims.ValidateSet(opts, cur, host.Inspect(root)); len(issues) > 0 {
if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
c, err := a.client()
@@ -1018,6 +1053,17 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
}()
}
// stripLegacyManagedExtraArgs removes reims-go internally managed QEMU arg
// fragments (reimstools, reimshelp, and legacy managed Win10 QMP targets)
// before ledger reconciliation so pre-plugin VMs and out-of-band helpers never
// produce duplicate QEMU device IDs on upgrade.
func stripLegacyManagedExtraArgs(extraArgs string) string {
s := reims.StripGuestToolsArgs(extraArgs)
s = reims.StripOfflineHelperArgs(s)
s = qmp.StripLegacyWin10RebootArgs(s)
return strings.TrimSpace(s)
}
func (a *App) StartVM(name string) error {
prep, err := a.prep(name)
if err != nil {
@@ -1036,22 +1082,83 @@ func (a *App) StartVM(name string) error {
}
a.cancelRebootWatcher(name)
a.syncGuestTools(c, name, &curDetail)
if env := a.inputBridgeEnv(name, curDetail.Directory); len(env) > 0 {
c.Env = append(c.Env, env...)
}
prep.Prepare(context.Background(), name, rep, &curDetail)
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
var qmpAddr string
if rep.NeedsColdRebootWorkaround {
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
_ = os.Remove(sockPath)
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
a.emitLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
if mgr != nil {
// Unified plugin-kernel start pipeline (§4.4): collect all vm.beforeStart
// intents (builtin + L1 rule hooks + L3 code hooks) and write merged
// extra-args via AT MOST ONE `reims-ctl set --extra-args` call.
rtCaps := prep.Runtime.Manifest.EffectiveCapabilities()
intents, blockErr := mgr.Registry().Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
VMName: name,
VMDir: curDetail.Directory,
DriverID: builtin.IDDriverReimsMacOS,
ExtraArgs: curDetail.ExtraArgs,
HasInstaller: curDetail.HasInstaller,
InstallerPath: curDetail.InstallerPath,
RuntimeKind: prep.Runtime.Manifest.EffectiveKind(),
RuntimeCaps: rtCaps,
HostFacts: buildHostFacts(rep, rtCaps),
VMCaps: driver.ReimsMacOSCapabilities,
State: curDetail.State,
})
if blockErr != nil {
a.emitLog(name, "Start blocked: "+blockErr.Error())
return blockErr
}
ledger, ledgerErr := plugin.LoadArgLedger(curDetail.Directory)
if ledgerErr != nil {
a.emitLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error())
ledger = &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
}
// Adopt/strip pre-ledger or out-of-band managed fragments before reconciling
// so upgrading existing VMs never duplicates QEMU device IDs (B1).
// BeforeStartPayload above already saw the original curDetail.ExtraArgs.
baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs)
reconciled := plugin.ReconcileStartIntents(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), intents)
reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs
for _, warn := range reconciled.Warnings {
a.emitLog(name, "[plugin] "+warn)
}
if len(reconciled.Env) > 0 {
c.Env = append(c.Env, reconciled.Env...)
}
if reconciled.Changed {
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
a.emitLog(name, "Warning: could not apply reconciled start extra-args: "+err.Error())
} else {
curDetail.ExtraArgs = reconciled.ExtraArgs
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
}
} else {
qmpAddr = "unix:" + sockPath
curDetail.ExtraArgs = merged
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
}
for _, act := range reconciled.PostStart {
if act.Kind == "qmp.watch_cold_reboot" {
if addr, ok := act.Params["qmp_addr"].(string); ok && addr != "" {
qmpAddr = addr
}
}
}
} else {
a.syncGuestTools(c, name, &curDetail)
if env := a.inputBridgeEnv(name, curDetail.Directory); len(env) > 0 {
c.Env = append(c.Env, env...)
}
prep.Prepare(context.Background(), name, rep, &curDetail)
if rep.NeedsColdRebootWorkaround {
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
_ = os.Remove(sockPath)
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
a.emitLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
} else {
qmpAddr = "unix:" + sockPath
curDetail.ExtraArgs = merged
}
}
}
@@ -1075,9 +1182,17 @@ func (a *App) StartVM(name string) error {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
return err
}
if qmpAddr != "" {
if qmpAddr != "" && mgr == nil {
a.watchWin10ColdReboot(name, qmpAddr)
}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
VMName: name,
VMDir: curDetail.Directory,
DriverID: builtin.IDDriverReimsMacOS,
QMPAddr: qmpAddr,
})
}
a.startVMMonitor(name, curDetail, startAt)
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
@@ -1092,8 +1207,15 @@ func (a *App) StopVM(name string, force bool) error {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.mu.Lock()
mgr := a.pluginMgr
a.transitions[name] = "stopping"
a.mu.Unlock()
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
@@ -1113,6 +1235,12 @@ func (a *App) StopVM(name string, force bool) error {
a.mu.Lock()
delete(a.pendingChanges, name)
a.mu.Unlock()
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
return nil
@@ -1166,6 +1294,15 @@ func (a *App) DeleteVM(name string, keepFiles bool) error {
if gt != nil {
gt.UnregisterVM(name)
}
a.mu.Lock()
delMgr := a.pluginMgr
a.mu.Unlock()
if delMgr != nil {
delMgr.Registry().Hooks().DispatchObserve(plugin.EventVMDeleted, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
return nil
+21 -11
View File
@@ -12,17 +12,19 @@ import (
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
type diagnosticsBundle struct {
HostReport host.Report
Optimizations []host.Optimization
Runtime *rt.Installed
VMDetail *reims.VMDetail
SerialLog string
QEMULog string
AppLogs []string
HostReport host.Report
Optimizations []host.Optimization
Runtime *rt.Installed
VMDetail *reims.VMDetail
SerialLog string
QEMULog string
AppLogs []string
PluginDiagnostics []plugin.DiagnosticsEntry
}
func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
@@ -98,6 +100,13 @@ func writeDiagnosticsZip(zipPath string, b diagnosticsBundle) error {
return err
}
}
if len(b.PluginDiagnostics) > 0 {
if err := addJSON("plugin-diagnostics.json", b.PluginDiagnostics); err != nil {
_ = zw.Close()
_ = f.Close()
return err
}
}
if err := zw.Close(); err != nil {
_ = f.Close()
return err
@@ -124,10 +133,11 @@ func (a *App) ExportDiagnostics(name string) (string, error) {
}
}
bundle := diagnosticsBundle{
HostReport: rep,
Optimizations: host.EvaluateOptimizations(rep, patchNames),
Runtime: active,
AppLogs: appLogs,
HostReport: rep,
Optimizations: host.EvaluateOptimizations(rep, patchNames),
Runtime: active,
AppLogs: appLogs,
PluginDiagnostics: a.collectPluginDiagnostics(context.Background(), name),
}
label := "host"
+5 -1
View File
@@ -37,7 +37,11 @@ func (a *App) ensureGuestToolsBridge() (*guesttools.Server, int, error) {
a.mu.Lock()
srv := a.guestTools
if srv == nil {
srv = guesttools.NewServer(nil)
if a.pluginMgr != nil {
srv = guesttools.NewTransportServer(nil)
} else {
srv = guesttools.NewServer(nil)
}
srv.SetHostTextHandler(func(vmName, text string) {
a.injectRemoteText(vmName, "", text)
})
+82
View File
@@ -0,0 +1,82 @@
package app
import (
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/qmp"
)
func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
// Simulate an existing pre-plugin VM whose vm.toml already contains:
// user arg + REIMSTOOLS + REIMSHELP + Win10 managed QMP args, with NO ledger file yet.
legacy := "-cpu host"
legacy = reims.MergeGuestToolsArgs(legacy, `D:\Data\cache\tools.img`)
legacy = reims.MergeOfflineHelperArgs(legacy, `D:\Data\cache\reimshelp.img`)
legacy = qmp.MergeWin10RebootUnixArgs(legacy, `D:\Data\vms\mac\reims-go-reboot.sock`)
ledger := &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
active := map[string]bool{
builtin.IDGuestTools: true,
builtin.IDOfflineHelper: true,
builtin.IDWin10ColdReboot: true,
}
intents := []plugin.StartIntent{
{
PluginID: builtin.IDGuestTools,
Args: []plugin.ArgFragment{{
PluginID: builtin.IDGuestTools, Key: "reimstools", Builtin: true, Priority: 80,
Tokens: plugin.SplitShellTokens(reims.MergeGuestToolsArgs("", `D:\Data\cache\tools.img`)),
}},
},
{
PluginID: builtin.IDOfflineHelper,
Args: []plugin.ArgFragment{{
PluginID: builtin.IDOfflineHelper, Key: "reimshelp", Builtin: true, Priority: 85,
Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", `D:\Data\cache\reimshelp.img`)),
}},
},
{
PluginID: builtin.IDWin10ColdReboot,
Args: []plugin.ArgFragment{{
PluginID: builtin.IDWin10ColdReboot, Key: "win10-cold-reboot", Builtin: true, Priority: 95,
Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", `D:\Data\vms\mac\reims-go-reboot.sock`)),
}},
},
}
base := stripLegacyManagedExtraArgs(legacy)
res := plugin.ReconcileStartIntents(base, ledger, active, intents)
if !strings.Contains(res.ExtraArgs, "-cpu host") {
t.Fatalf("user arg lost: %s", res.ExtraArgs)
}
for _, needle := range []string{"id=reimstools,", "id=reimstools-dev,", "id=reimshelp,", "id=reimshelp-dev,", "-no-reboot", "-qmp"} {
if got := strings.Count(res.ExtraArgs, needle); got != 1 {
t.Errorf("expected exactly 1 occurrence of %q, got %d in: %s", needle, got, res.ExtraArgs)
}
}
// Simulate detaching Guest Tools & ejecting offline installer on next start.
nextIntents := []plugin.StartIntent{
{PluginID: builtin.IDGuestTools, ClearKeys: []string{"reimstools"}},
{PluginID: builtin.IDOfflineHelper, ClearKeys: []string{"reimshelp"}},
{PluginID: builtin.IDWin10ColdReboot, ClearKeys: []string{"win10-cold-reboot"}},
}
base2 := stripLegacyManagedExtraArgs(res.ExtraArgs)
res2 := plugin.ReconcileStartIntents(base2, ledger, active, nextIntents)
if res2.ExtraArgs != "-cpu host" {
t.Fatalf("expected only user arg after clearing managed keys, got: %q", res2.ExtraArgs)
}
}
func TestStripLegacyPreservesUserNoReboot(t *testing.T) {
// A user hand-wrote `-no-reboot` without any reims-go managed QMP target.
got := stripLegacyManagedExtraArgs("-cpu host -no-reboot")
if got != "-cpu host -no-reboot" {
t.Fatalf("user -no-reboot was stripped unexpectedly: %q", got)
}
}
+792
View File
@@ -0,0 +1,792 @@
package app
import (
"context"
"errors"
"fmt"
"io"
"math"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/plugin/bundled"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// PluginUIContributions aggregates all active declarative plugin UI contributions
// for the frontend in a single round-trip (§4.2, §10).
type PluginUIContributions struct {
SafeMode bool `json:"safe_mode"`
CrashDetected bool `json:"crash_detected"`
Menus []plugin.MenuContribution `json:"menus,omitempty"`
VMCards []plugin.VMCardContribution `json:"vm_cards,omitempty"`
SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"`
StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"`
Panels []plugin.PanelContribution `json:"panels,omitempty"`
VMTemplates []plugin.VMTemplateContribution `json:"vm_templates,omitempty"`
Themes []plugin.ThemeContribution `json:"themes,omitempty"`
RuntimeSources []plugin.RuntimeSourceContribution `json:"runtime_sources,omitempty"`
RuntimeKinds []rt.KindSpec `json:"runtime_kinds,omitempty"`
Drivers []driver.DriverSummary `json:"drivers,omitempty"`
AssetToken string `json:"asset_token,omitempty"`
}
func (a *App) initPlugins() {
a.mu.Lock()
dataRoot := a.cfg.DataRoot
safeMode := a.launch.SafeMode
a.mu.Unlock()
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: version.Version,
SafeMode: safeMode,
RedactFn: reims.RedactText,
Logger: func(source, line string) {
a.emitLog(source, line)
},
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
return driver.NewSidecarDriver(contrib, sup)
},
OnSettingsChanged: func(pluginID, vmName string) {
a.onPluginSettingsChanged(pluginID, vmName)
},
})
if err != nil {
a.emitLog("plugin", "Plugin state warning: "+err.Error())
if mgr == nil {
return
}
}
kindReg := rt.NewKindRegistry()
drvRouter := driver.NewRouter(mgr.Registry(), func() string {
a.mu.Lock()
dir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms")
a.mu.Unlock()
return dir
})
mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) {
// Must not call Registry.Info/List here: both invoke this checker,
// which recursed until the goroutine stack overflowed at startup.
if pluginID == builtin.IDDriverReimsMacOS {
return drvRouter.CheckDriverInUse(context.Background(), builtin.IDDriverReimsMacOS)
}
// Check all guest driver IDs declared by this plugin (even when disabled) plus pluginID itself.
seen := map[string]bool{}
candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...)
for _, did := range candidates {
if did == "" || seen[did] {
continue
}
seen[did] = true
if inUse, reason, err := drvRouter.CheckDriverInUse(context.Background(), did); err != nil || inUse {
return inUse, reason, err
}
}
return false, "", nil
})
mgr.Broker().SetNotifier(func(pluginID, title, body string) {
a.emitLog("plugin:"+pluginID, title+": "+body)
})
cb := builtin.HostCallbacks{
GetConfig: func() config.Config {
a.mu.Lock()
cp := *a.cfg
a.mu.Unlock()
return cp
},
Log: func(source, line string) {
a.emitLog(source, line)
},
EnsureGuestTools: func() (*guesttools.Server, int, error) {
return a.ensureGuestToolsBridge()
},
OnIMEText: func(target host.IMETarget, text string) {
go a.injectRemoteText(target.VMName, target.VMDir, text)
},
StartColdReboot: func(vmName, qmpAddr string) {
a.watchWin10ColdReboot(vmName, qmpAddr)
},
CancelColdReboot: func(vmName string) {
a.cancelRebootWatcher(vmName)
},
VMSharedDir: func(vmName string) string {
return a.vmSharedDir(vmName)
},
GuestToolsImg: func(vmName string) string {
return a.guestToolsImagePath(vmName)
},
}
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
a.emitLog("plugin", "Builtin extension register error: "+err.Error())
}
if bundledList, err := bundled.BundledManifests(); err == nil {
if err := mgr.LoadBundled(bundledList); err != nil {
a.emitLog("plugin", "Bundled plugin load error: "+err.Error())
}
}
if err := mgr.LoadExternal(); err != nil {
a.emitLog("plugin", "External plugin load warning: "+err.Error())
}
// Sync runtime kinds and input filters whenever registry state changes.
mgr.Registry().OnChange(func() {
a.syncRuntimeKinds(kindReg, mgr.Registry())
a.syncInputFilters()
a.syncClipboardPolicies()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
})
a.mu.Lock()
a.pluginMgr = mgr
a.driverRouter = drvRouter
a.runtimeKinds = kindReg
a.mu.Unlock()
mgr.Registry().Reconcile(context.Background())
a.syncInputFilters()
a.syncClipboardPolicies()
}
func (a *App) shutdownPlugins() {
a.mu.Lock()
mgr := a.pluginMgr
a.pluginMgr = nil
a.mu.Unlock()
if mgr != nil {
mgr.Close()
}
}
func (a *App) syncRuntimeKinds(kr *rt.KindRegistry, reg *plugin.Registry) {
if kr == nil || reg == nil {
return
}
activeKinds := map[string]bool{rt.DefaultKind: true}
for _, rk := range reg.RuntimeKinds() {
activeKinds[rk.Kind] = true
_ = kr.Register(rt.KindSpec{
Kind: rk.Kind,
NameZh: rk.Name.ZhCN,
NameEn: rk.Name.EnUS,
RequiredFiles: rk.RequiredFiles,
DefaultAPIVersion: rk.DefaultAPIVer,
PluginID: rk.PluginID,
})
}
for _, existing := range kr.List() {
if !existing.Builtin && !activeKinds[existing.Kind] {
kr.Unregister(existing.Kind, "")
}
}
}
func (a *App) getInputService() *host.InputService {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil
}
raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput)
if !ok {
return nil
}
svc, _ := raw.(*host.InputService)
return svc
}
func (a *App) syncInputTargets(targets []host.IMETarget) {
if svc := a.getInputService(); svc != nil {
svc.SetTargets(targets)
}
}
func (a *App) syncInputFilters() {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return
}
svc := a.getInputService()
if svc == nil {
return
}
contribs := mgr.Registry().InputFilters()
var rules []host.InputFilterRule
for _, flt := range contribs {
if flt.Event != "mouse_wheel" {
continue
}
settingKey := flt.SettingKey
if settingKey == "" {
settingKey = "enabled"
}
vmNames := mgr.ActiveVMNamesWithSetting(flt.PluginID, settingKey)
if len(vmNames) == 0 {
continue
}
for _, vmName := range vmNames {
vals := mgr.GetSettings(flt.PluginID, vmName, false)
vert := true
if flt.VertKey != "" {
if v, ok := vals[flt.VertKey].(bool); ok {
vert = v
}
}
horiz := false
if flt.HorizKey != "" {
if h, ok := vals[flt.HorizKey].(bool); ok {
horiz = h
}
}
if !vert && !horiz {
continue
}
axis := flt.Axis
if flt.VertKey != "" || flt.HorizKey != "" {
// Explicit per-axis booleans govern; clear Axis so vertical=false is respected.
axis = ""
}
rules = append(rules, host.InputFilterRule{
ID: flt.ID + ":" + vmName,
PluginID: flt.PluginID,
Event: flt.Event,
Axis: axis,
Transform: flt.Transform,
Scope: flt.Scope,
VMNames: map[string]bool{vmName: true},
Vertical: vert,
Horizontal: horiz,
})
}
}
svc.SetFilterRules(rules)
}
func (a *App) syncClipboardPolicies() {
a.mu.Lock()
mgr := a.pluginMgr
gt := a.guestTools
a.mu.Unlock()
if mgr == nil || gt == nil {
return
}
if !mgr.Registry().IsActive(builtin.IDClipboard) {
return
}
globalVals := mgr.GetSettings(builtin.IDClipboard, "", false)
gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals))
for vmName, vmVals := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) {
pol := clipboardPolicyFromMap(vmVals)
gt.SetVMClipboardPolicy(vmName, &pol)
}
}
func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
a.syncInputFilters()
if pluginID == builtin.IDClipboard {
a.mu.Lock()
mgr := a.pluginMgr
gt := a.guestTools
a.mu.Unlock()
if mgr != nil && gt != nil {
vals := mgr.GetSettings(builtin.IDClipboard, vmName, false)
pol := clipboardPolicyFromMap(vals)
if vmName == "" {
gt.SetGlobalClipboardPolicy(pol)
} else {
gt.SetVMClipboardPolicy(vmName, &pol)
}
}
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
}
func clipboardPolicyFromMap(vals map[string]any) guesttools.ClipboardPolicy {
p := guesttools.DefaultClipboardPolicy()
if v, ok := vals["enabled"].(bool); ok {
p.Enabled = v
}
if v, ok := vals["direction"].(string); ok && v != "" {
p.Direction = guesttools.ClipboardDirection(v)
}
if v, ok := vals["sync_images"].(bool); ok {
p.SyncImages = v
}
switch v := vals["max_image_mb"].(type) {
case float64:
if v > 0 && !math.IsNaN(v) && !math.IsInf(v, 0) {
mb := int(math.Round(v))
if mb < 1 {
mb = 1
}
if mb > 16 {
mb = 16
}
p.MaxImageBytes = mb << 20
}
case int:
if v > 0 {
if v > 16 {
v = 16
}
p.MaxImageBytes = v << 20
}
}
return p
}
// PluginAssetHandler returns the HTTP handler mounted on Wails AssetServer for
// `/plugin-assets/<runToken>/<pluginID>/<relPath>` (§7.3).
func (a *App) PluginAssetHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.URL.Path, "/plugin-assets/") {
http.NotFound(w, r)
return
}
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil || mgr.Assets() == nil {
http.NotFound(w, r)
return
}
mgr.Assets().ServeHTTP(w, r)
})
}
func (a *App) emitPluginLogLine(vmName, source, line string) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
mgr.Registry().Hooks().EmitLogLine(vmName, source, line)
}
}
func (a *App) collectPluginDiagnostics(ctx context.Context, vmName string) []plugin.DiagnosticsEntry {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil
}
return mgr.Registry().CollectDiagnostics(ctx, vmName, reims.RedactText)
}
func buildHostFacts(rep host.Report, rtCaps []string) map[string]any {
gpuKind := "unknown"
if rep.RecommendedGPU != nil {
gpuKind = string(rep.RecommendedGPU.Kind)
}
return map[string]any{
"host.os": rep.OS,
"host.arch": rep.Arch,
"host.whpx": string(rep.WHPX),
"host.whpx_irqchip": rep.WHPXCaps.KernelIrqchipAvailable,
"host.whpx_nested_virt": rep.WHPXCaps.NestedVirtProperty,
"host.needs_cold_reboot": rep.NeedsColdRebootWorkaround,
"host.gpu_kind": gpuKind,
"runtime.capabilities": rtCaps,
}
}
// --- Wails-bound Plugin & Driver APIs (§10) ---
func (a *App) ListPlugins() []plugin.PluginInfo {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil
}
return mgr.Registry().List()
}
func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
info, err := mgr.InstallLocalArchive(context.Background(), archivePath, plugin.PackageInstallOptions{})
if err == nil && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return info, err
}
func (a *App) LinkPluginDev(dir string) (*plugin.PluginInfo, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
info, err := mgr.LinkDev(context.Background(), dir)
if err == nil && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return info, err
}
func (a *App) EnablePlugin(id string, approveHighRisk bool) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.Enable(context.Background(), id, approveHighRisk)
}
func (a *App) DisablePlugin(id string) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.Disable(context.Background(), id)
}
func (a *App) RemovePlugin(id string, purgeData bool) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.Remove(context.Background(), id, purgeData)
}
func (a *App) GetPluginSettings(pluginID, vmName string) map[string]any {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return map[string]any{}
}
return mgr.GetSettings(pluginID, vmName, true)
}
func (a *App) SetPluginSettings(pluginID, vmName string, values map[string]any) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.SetSettings(pluginID, vmName, values)
}
func (a *App) GetVMPluginSettings(vmName string) map[string]map[string]any {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return map[string]map[string]any{}
}
return mgr.GetAllVMSettings(vmName)
}
func (a *App) GetPluginUIContributions() PluginUIContributions {
a.mu.Lock()
mgr := a.pluginMgr
kr := a.runtimeKinds
dr := a.driverRouter
a.mu.Unlock()
if mgr == nil {
return PluginUIContributions{}
}
reg := mgr.Registry()
out := PluginUIContributions{
SafeMode: mgr.SafeMode(),
CrashDetected: mgr.CrashDetected(),
Menus: reg.Menus(""),
VMCards: reg.VMCards(),
SettingsPages: reg.SettingsPages(),
StatusItems: reg.StatusItems(),
Panels: reg.Panels(""),
VMTemplates: reg.VMTemplates(),
Themes: reg.Themes(),
RuntimeSources: reg.RuntimeSources(),
AssetToken: mgr.Assets().Token(),
}
if kr != nil {
out.RuntimeKinds = kr.List()
}
if dr != nil {
out.Drivers = dr.Summaries()
}
return out
}
func (a *App) InvokePluginCommand(pluginID, commandID string, args map[string]any) (any, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
return mgr.Registry().InvokeCommand(context.Background(), pluginID, commandID, args)
}
func (a *App) GetActiveTheme() plugin.ActiveThemePayload {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return plugin.ActiveThemePayload{ThemeID: builtin.IDThemeDefault}
}
return mgr.ActiveThemePayload()
}
func (a *App) SetActiveTheme(themeID, schemeID string) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
err := mgr.SetActiveTheme(themeID, schemeID)
if err == nil && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return err
}
func (a *App) SaveCustomThemeScheme(scheme plugin.CustomThemeScheme) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.SaveCustomThemeScheme(scheme)
}
func (a *App) DeleteCustomThemeScheme(schemeID string) error {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return errors.New("plugin manager not initialized")
}
return mgr.DeleteCustomThemeScheme(schemeID)
}
func (a *App) ListDrivers() []driver.DriverSummary {
a.mu.Lock()
dr := a.driverRouter
a.mu.Unlock()
if dr == nil {
return nil
}
return dr.Summaries()
}
func (a *App) ListRuntimeKinds() []rt.KindSpec {
a.mu.Lock()
kr := a.runtimeKinds
a.mu.Unlock()
if kr == nil {
return rt.NewKindRegistry().List()
}
return kr.List()
}
func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
a.mu.Lock()
dr := a.driverRouter
mgr := a.pluginMgr
a.mu.Unlock()
if dr == nil {
return errors.New("driver router not initialized")
}
drv, err := dr.DriverByID(req.DriverID)
if err != nil {
return err
}
ctx := context.Background()
if mgr != nil {
res := mgr.Registry().Hooks().DispatchBeforeCreate(ctx, plugin.BeforeCreatePayload{
VMName: req.Name,
DriverID: drv.ID(),
Options: req.Options,
})
if len(res.Errors) > 0 {
return errors.New(res.Errors[0])
}
if len(res.Patches) > 0 {
if req.Options == nil {
req.Options = map[string]any{}
}
for k, v := range res.Patches {
if _, exists := req.Options[k]; !exists {
req.Options[k] = v
}
}
}
}
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return errors.New(issues[0].Message)
}
w := vmstart.LineWriter(func(line string) { a.emitLog(req.Name, line) })
if err := drv.Create(ctx, req, w, w); err != nil {
return err
}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterCreate, plugin.VMEventPayload{
VMName: req.Name,
DriverID: drv.ID(),
})
}
a.wakePoll()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return nil
}
func (a *App) ReadPluginLog(pluginID string) (string, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return "", nil
}
if pluginID == "" || strings.ContainsAny(pluginID, `/\`) || strings.Contains(pluginID, "..") {
return "", errors.New("invalid plugin id")
}
if _, ok := mgr.Registry().Info(pluginID); !ok {
return "", fmt.Errorf("plugin %q not found", pluginID)
}
logsDir := filepath.Clean(mgr.Layout().LogsDir())
logPath := filepath.Clean(mgr.Layout().LogPath(pluginID))
if !strings.HasPrefix(strings.ToLower(logPath), strings.ToLower(logsDir+string(os.PathSeparator))) {
return "", errors.New("invalid plugin log path")
}
f, err := os.Open(logPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
return "", err
}
defer f.Close()
const maxLogReadBytes = 2 << 20
if st, statErr := f.Stat(); statErr == nil && st.Size() > maxLogReadBytes {
_, _ = f.Seek(st.Size()-maxLogReadBytes, io.SeekStart)
}
raw, err := io.ReadAll(io.LimitReader(f, maxLogReadBytes))
if err != nil {
return "", err
}
return reims.RedactText(string(raw)), nil
}
func (a *App) DoctorPlugin(pluginID string) []plugin.DoctorFinding {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil
}
info, ok := mgr.Registry().Info(pluginID)
if !ok {
return []plugin.DoctorFinding{{
Severity: "error",
Check: "lookup",
Message: fmt.Sprintf("plugin %q not found", pluginID),
}}
}
if info.InstallDir == "" {
return []plugin.DoctorFinding{{
Severity: "ok",
Check: "builtin",
Message: fmt.Sprintf("%s@%s (%s)", info.ID, info.Version, info.State),
}}
}
return plugin.DoctorDirectory(info.InstallDir, version.Version, nil)
}
// PanelBridgeCall handles permission-checked, rate-limited, redacted Host API
// reads from sandboxed L4 iframe panels (§7.3).
func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (any, error) {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
return nil, errors.New("plugin manager not initialized")
}
hasPanel := false
for _, p := range mgr.Registry().Panels("") {
if p.PluginID == pluginID {
hasPanel = true
break
}
}
if !hasPanel {
return nil, fmt.Errorf("plugin %q has no active panel", pluginID)
}
switch method {
case "vm.list":
if err := mgr.Broker().Authorize(pluginID, "vm:read"); err != nil {
return nil, err
}
vms, err := a.polledVMs(context.Background())
if err != nil {
return nil, err
}
out := make([]map[string]any, 0, len(vms))
for _, v := range vms {
out = append(out, map[string]any{
"name": v.Name,
"state": v.State,
})
}
return out, nil
case "notify":
title, _ := params["title"].(string)
body, _ := params["body"].(string)
if err := mgr.Broker().Notify(pluginID, title, body); err != nil {
return nil, err
}
return map[string]any{"ok": true}, nil
case "command.invoke":
if err := mgr.Broker().Authorize(pluginID, "ui:slot"); err != nil {
return nil, err
}
cmdID, _ := params["command"].(string)
cmdArgs, _ := params["args"].(map[string]any)
mgr.Broker().Audit(pluginID, "PANEL_CMD", cmdID)
return mgr.Registry().InvokeCommand(context.Background(), pluginID, cmdID, cmdArgs)
default:
return nil, fmt.Errorf("panel bridge method %q is not allowed", method)
}
}
+2
View File
@@ -108,12 +108,14 @@ func (a *App) startVMMonitor(name string, detail reims.VMDetail, startAt time.Ti
return
case <-logTicker.C:
for _, line := range serial.read(serialPath) {
a.emitPluginLogLine(name, "serial", line)
if key, msg := parseSerialMilestone(loc, line); msg != "" && !seenEvents[key] {
seenEvents[key] = true
a.emitLog(name, msg)
}
}
for _, line := range qemu.read(qemuPath) {
a.emitPluginLogLine(name, "qemu", line)
if key, msg := parseQemuMilestone(loc, line); msg != "" {
if key != "" && seenEvents[key] {
continue
+60 -11
View File
@@ -11,6 +11,7 @@ import (
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
@@ -81,6 +82,8 @@ func run(args []string) error {
return cmdVM(cfg, loc, rest[1:], *dataRootFlag == "")
case "installer":
return cmdInstaller(cfg, loc, rest[1:])
case "plugin":
return cmdPlugin(cfg, loc, rest[1:])
case "version", "-v", "--version":
fmt.Printf("reims-go %s\n", version.Version)
return nil
@@ -118,6 +121,8 @@ func printUsage(loc i18n.Locale) {
fmt.Println(" installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)")
fmt.Println(" installer cached 查看已下载的安装包及占用空间")
fmt.Println(" installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)")
fmt.Println(" plugin list|install|link|enable|disable|remove|info|doctor|run")
fmt.Println(" 管理内置扩展与第三方插件(含主题与驱动)")
fmt.Println(" version 查看当前版本")
return
}
@@ -147,6 +152,8 @@ func printUsage(loc i18n.Locale) {
fmt.Println(" installer download <ver> Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)")
fmt.Println(" installer cached List downloaded installers and the space they take")
fmt.Println(" installer delete <name> Delete a downloaded installer (refused if in use or downloading)")
fmt.Println(" plugin list|install|link|enable|disable|remove|info|doctor|run")
fmt.Println(" Manage built-in extensions and third-party plugins")
fmt.Println(" version Show current version")
}
@@ -174,11 +181,11 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
fmt.Printf("%-36s: %s/%s\n", i18n.T(loc, "doctor.os"), rep.OS, rep.Arch)
fmt.Printf("%-36s: %dC / %dT\n", i18n.T(loc, "doctor.cpu"), rep.PhysicalCores, rep.LogicalCPUs)
if rep.HasHybridCores {
fmt.Printf("%-36s: %d cores, mask %s (CPUs %v)\n", i18n.T(loc, "doctor.pcores"), rep.PCoreCount, rep.PCoreMaskHex, rep.PCoreLogicalCPUs)
fmt.Printf("%-36s: %d cores (CPUs %v)\n", i18n.T(loc, "doctor.ecores"), rep.ECoreCount, rep.ECoreLogicalCPUs)
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.pcores"), i18n.T(loc, "doctor.pcores.detail", rep.PCoreCount, rep.PCoreMaskHex, rep.PCoreLogicalCPUs))
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ecores"), i18n.T(loc, "doctor.ecores.detail", rep.ECoreCount, rep.ECoreLogicalCPUs))
}
if rep.TotalRAMGB > 0 {
fmt.Printf("%-36s: %.1f GB total / %.1f GB avail\n", i18n.T(loc, "doctor.ram"), rep.TotalRAMGB, rep.AvailRAMGB)
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ram"), i18n.T(loc, "doctor.ram.detail", rep.TotalRAMGB, rep.AvailRAMGB))
}
if rep.FreeDiskGB > 0 {
fmt.Printf("%-36s: %.1f GB (%s)\n", i18n.T(loc, "doctor.disk"), rep.FreeDiskGB, rep.DataRoot)
@@ -249,7 +256,16 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if item.Active {
mark = "*"
}
fmt.Printf("%s %s %s (%s)\n", mark, item.Commit, item.Manifest.QemuVersion, item.Dir)
kind := item.Kind
if kind == "" {
kind = item.Manifest.EffectiveKind()
}
apiVer := item.Manifest.EffectiveRuntimeAPI()
caps := strings.Join(item.Manifest.EffectiveCapabilities(), ",")
if caps != "" {
caps = " [" + caps + "]"
}
fmt.Printf("%s %-11s %-12s api=%-6s %s%s (%s)\n", mark, kind, item.Commit, apiVer, item.Manifest.QemuVersion, caps, item.Dir)
}
return nil
case "use":
@@ -270,7 +286,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
return nil
}
}
return fmt.Errorf("runtime %q not found", args[1])
return fmt.Errorf("%s", i18n.T(loc, "runtime.not_found", args[1]))
case "available":
return cmdRuntimeAvailable(cfg, loc, args[1:])
case "fetch":
@@ -306,6 +322,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
return enc.Encode(vms)
case "create":
fs := flag.NewFlagSet("vm create", flag.ContinueOnError)
driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID (default: builtin.driver.reims-macos)")
dir := fs.String("dir", "", "Custom VM directory")
macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)")
cpus := fs.Int("cpus", 8, "vCPU count")
@@ -323,6 +340,38 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
}
name := fs.Arg(0)
// Route non-reims guest drivers through the plugin Driver Router (§5.3, §10).
if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
drv, err := router.DriverByID(*driverID)
if err != nil {
return err
}
req := driver.CreateRequest{
DriverID: drv.ID(),
Name: name,
Dir: *dir,
Options: map[string]any{
"cpus": *cpus,
"memory": *mem,
"disk_size": *diskSize,
},
}
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil {
return err
}
if *start {
return drv.Start(ctx, name, os.Stdout, os.Stderr)
}
return nil
}
startAfterCreate := *start
opts := reims.CreateOpts{
Name: name,
@@ -460,15 +509,15 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
return err
}
if d.State == "running" {
return fmt.Errorf("stop %s before resizing its disk", args[1])
return fmt.Errorf("%s", i18n.T(loc, "vm.resize.stop_first", args[1]))
}
diskPath := resolveCLIDiskPath(d)
res, err := reims.ResizeDisk(ctx, active.QemuImgPath(), client.Env, diskPath, args[2], os.Stdout, os.Stderr)
if err != nil {
return err
}
fmt.Printf("%s: expanded disk %.0f GB -> %.0f GB\nRun inside macOS Terminal to expand APFS:\n %s\n",
args[1], float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30), res.GuestExpandCmd)
fmt.Println(i18n.T(loc, "vm.resize.done",
args[1], float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30), res.GuestExpandCmd))
return nil
case "compact":
if len(args) < 2 {
@@ -479,15 +528,15 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
return err
}
if d.State == "running" {
return fmt.Errorf("stop %s before compacting its disk", args[1])
return fmt.Errorf("%s", i18n.T(loc, "vm.compact.stop_first", args[1]))
}
diskPath := resolveCLIDiskPath(d)
res, err := reims.CompactDisk(ctx, active.QemuImgPath(), client.Env, diskPath, os.Stdout, os.Stderr)
if err != nil {
return err
}
fmt.Printf("%s: compacted disk %.2f GB -> %.2f GB (reclaimed %.2f GB)\n",
args[1], float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30))
fmt.Println(i18n.T(loc, "vm.compact.done",
args[1], float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30)))
return nil
default:
return fmt.Errorf("unknown vm subcommand %q", strings.Join(args, " "))
+321
View File
@@ -0,0 +1,321 @@
package cli
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/plugin/bundled"
"github.com/Nwflower/reims-go/internal/version"
)
func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *driver.Router, error) {
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: cfg.DataRoot,
HostVersion: version.Version,
SafeMode: safeMode,
RedactFn: reims.RedactText,
Logger: func(source, line string) {
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
},
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
return driver.NewSidecarDriver(contrib, sup)
},
})
if err != nil {
return nil, nil, err
}
cb := builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
Log: func(source, line string) {
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
},
}
router := driver.NewRouter(mgr.Registry(), func() string {
return filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms")
})
mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) {
if pluginID == builtin.IDDriverReimsMacOS {
return router.CheckDriverInUse(context.Background(), builtin.IDDriverReimsMacOS)
}
seen := map[string]bool{}
candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...)
for _, did := range candidates {
if did == "" || seen[did] {
continue
}
seen[did] = true
if inUse, reason, err := router.CheckDriverInUse(context.Background(), did); err != nil || inUse {
return inUse, reason, err
}
}
return false, "", nil
})
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
mgr.Close()
return nil, nil, err
}
if list, err := bundled.BundledManifests(); err == nil {
_ = mgr.LoadBundled(list)
}
_ = mgr.LoadExternal()
mgr.Registry().Reconcile(context.Background())
return mgr, router, nil
}
func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go plugin <list|install|link|enable|disable|remove|info|doctor|run>")
}
ctx := context.Background()
switch args[0] {
case "list":
fs := flag.NewFlagSet("plugin list", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output JSON")
if err := fs.Parse(args[1:]); err != nil {
return err
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
list := mgr.Registry().List()
if *asJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(list)
}
for _, p := range list {
mark := " "
if p.State == plugin.StateActive {
mark = "*"
} else if p.State == plugin.StateDegraded || p.State == plugin.StateFailed {
mark = "!"
}
fmt.Printf("%s %-34s %-8s %-8s %-9s %-8s %s\n",
mark, p.ID, p.Version, p.Tier, p.Trust, p.State, p.Name.Get(string(loc)))
}
return nil
case "install":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go plugin install <archive.zip>")
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
info, err := mgr.InstallLocalArchive(ctx, args[1], plugin.PackageInstallOptions{})
if err != nil {
return err
}
fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier))
if info.NeedsApproval {
fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID))
}
return nil
case "link":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go plugin link <dir>")
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
info, err := mgr.LinkDev(ctx, args[1])
if err != nil {
return err
}
fmt.Println(i18n.T(loc, "plugin.linked", info.ID, info.Version, info.InstallDir))
return nil
case "enable":
fs := flag.NewFlagSet("plugin enable", flag.ContinueOnError)
approve := fs.Bool("approve-high-risk", false, "Explicitly approve high-risk permissions or community L3 execution")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go plugin enable [--approve-high-risk] <id>")
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
if err := mgr.Enable(ctx, fs.Arg(0), *approve); err != nil {
return err
}
fmt.Println(i18n.T(loc, "plugin.enabled", fs.Arg(0)))
return nil
case "disable":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go plugin disable <id>")
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
if err := mgr.Disable(ctx, args[1]); err != nil {
return err
}
fmt.Println(i18n.T(loc, "plugin.disabled", args[1]))
return nil
case "remove":
fs := flag.NewFlagSet("plugin remove", flag.ContinueOnError)
purge := fs.Bool("purge", false, "Also delete plugin private data and logs")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() != 1 {
return fmt.Errorf("usage: reims-go plugin remove [--purge] <id>")
}
mgr, _, err := openCLIPluginManager(cfg, true)
if err != nil {
return err
}
defer mgr.Close()
if err := mgr.Remove(ctx, fs.Arg(0), *purge); err != nil {
return err
}
fmt.Println(i18n.T(loc, "plugin.removed", fs.Arg(0), *purge))
return nil
case "info":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go plugin info <id>")
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
info, ok := mgr.Registry().Info(args[1])
if !ok {
return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", args[1]))
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(info)
case "doctor":
fs := flag.NewFlagSet("plugin doctor", flag.ContinueOnError)
contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation")
if err := fs.Parse(args[1:]); err != nil {
return err
}
var contract *plugin.UIContract
if *contractPath != "" {
raw, err := os.ReadFile(*contractPath)
if err != nil {
return err
}
var c plugin.UIContract
if err := json.Unmarshal(raw, &c); err != nil {
return fmt.Errorf("parse ui-contract.json: %w", err)
}
contract = &c
}
target := ""
if fs.NArg() > 0 {
target = fs.Arg(0)
}
// If target is an existing directory, validate it directly (developer workflow, §5.1).
if target != "" {
if st, err := os.Stat(target); err == nil && st.IsDir() {
findings := plugin.DoctorDirectory(target, version.Version, contract)
return printDoctorFindings(loc, findings)
}
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
if target != "" {
info, ok := mgr.Registry().Info(target)
if !ok {
return fmt.Errorf("%s", i18n.T(loc, "plugin.target_not_found", target))
}
if info.InstallDir == "" {
fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State)
return nil
}
return printDoctorFindings(loc, plugin.DoctorDirectory(info.InstallDir, version.Version, contract))
}
// Audit all installed external plugins.
var allFindings []plugin.DoctorFinding
for _, info := range mgr.Registry().List() {
if info.InstallDir != "" {
allFindings = append(allFindings, plugin.DoctorDirectory(info.InstallDir, version.Version, contract)...)
} else {
allFindings = append(allFindings, plugin.DoctorFinding{
Severity: "ok",
Check: info.ID,
Message: fmt.Sprintf("%s@%s state=%s", info.ID, info.Version, info.State),
})
}
}
return printDoctorFindings(loc, allFindings)
case "run":
if len(args) < 3 {
return fmt.Errorf("usage: reims-go plugin run <id> <command> [key=value...]")
}
mgr, _, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
cmdArgs := map[string]any{}
for _, kv := range args[3:] {
k, v, ok := strings.Cut(kv, "=")
if !ok || strings.TrimSpace(k) == "" {
return fmt.Errorf("invalid argument %q (expected key=value)", kv)
}
cmdArgs[k] = v
}
res, err := mgr.Registry().InvokeCommand(ctx, args[1], args[2], cmdArgs)
if err != nil {
return err
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(res)
default:
return fmt.Errorf("unknown plugin subcommand %q", args[0])
}
}
func printDoctorFindings(loc i18n.Locale, findings []plugin.DoctorFinding) error {
hasErr := false
for _, f := range findings {
fmt.Printf("[%s] (%s) %s\n", f.Severity, f.Check, f.Message)
if f.Severity == "error" {
hasErr = true
}
}
if hasErr {
return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors"))
}
return nil
}
+46
View File
@@ -0,0 +1,46 @@
package cli
import (
"os"
"path/filepath"
"testing"
)
func TestCLIPluginListEnableDisableAndDoctor(t *testing.T) {
dataRoot := t.TempDir()
// `plugin list` should succeed and include builtins + bundled wheel-invert.
if code := Main([]string{"--data-root", dataRoot, "plugin", "list", "--json"}); code != 0 {
t.Fatalf("plugin list exited %d", code)
}
// Enable and disable bundled wheel-invert plugin via CLI.
if code := Main([]string{"--data-root", dataRoot, "plugin", "enable", "reims.input.wheel-invert"}); code != 0 {
t.Fatalf("plugin enable wheel-invert exited %d", code)
}
if code := Main([]string{"--data-root", dataRoot, "plugin", "disable", "reims.input.wheel-invert"}); code != 0 {
t.Fatalf("plugin disable wheel-invert exited %d", code)
}
// Builtin/bundled cannot be removed.
if code := Main([]string{"--data-root", dataRoot, "plugin", "remove", "reims.input.wheel-invert"}); code == 0 {
t.Fatal("expected removing bundled plugin to fail")
}
// Safe mode window flag round-trips cleanly.
w, ok := ParseWindowArgs([]string{"--safe-mode"})
if !ok || !w.SafeMode {
t.Fatalf("ParseWindowArgs(--safe-mode) = %+v, %v", w, ok)
}
// Dev link + doctor on a local directory.
devDir := t.TempDir()
_ = os.WriteFile(filepath.Join(devDir, "plugin.json"), []byte(`{
"schema": 1,
"id": "dev.sample.theme",
"version": "0.1.0",
"name": {"en-US": "Dev Theme"},
"engines": {"pluginApi": "^1.0.0"}
}`), 0o644)
if code := Main([]string{"--data-root", dataRoot, "plugin", "link", devDir}); code != 0 {
t.Fatalf("plugin link exited %d", code)
}
if code := Main([]string{"--data-root", dataRoot, "plugin", "doctor", devDir}); code != 0 {
t.Fatalf("plugin doctor dir exited %d", code)
}
}
+8
View File
@@ -8,6 +8,7 @@ import "strings"
// argument (`--name=value`) so a stray value is never taken for a command.
const (
flagBackground = "--background"
flagSafeMode = "--safe-mode"
flagStartVM = "--start-vm="
flagStartResult = "--start-result="
)
@@ -17,6 +18,8 @@ const (
type WindowArgs struct {
// Background keeps the window hidden; Reims-Go lives in the tray.
Background bool
// SafeMode skips all third-party plugins and reverts to the built-in theme (§9).
SafeMode bool
// StartVM is a VM to start as the GUI's StartVM would (Guest Tools and
// the Win10 cold-reboot watcher included).
StartVM string
@@ -33,6 +36,8 @@ func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
switch {
case a == flagBackground:
w.Background = true
case a == flagSafeMode:
w.SafeMode = true
case strings.HasPrefix(a, flagStartVM):
w.StartVM = strings.TrimPrefix(a, flagStartVM)
case strings.HasPrefix(a, flagStartResult):
@@ -50,6 +55,9 @@ func (w WindowArgs) Args() []string {
if w.Background {
out = append(out, flagBackground)
}
if w.SafeMode {
out = append(out, flagSafeMode)
}
if w.StartVM != "" {
out = append(out, flagStartVM+w.StartVM)
}
+343
View File
@@ -0,0 +1,343 @@
// Package driver defines the generic guest VM driver abstraction and router
// (docs/plugin-architecture.md §5.3). Existing macOS/reims VMs are served by
// builtin.driver.reims-macos with zero migration.
package driver
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/Nwflower/reims-go/internal/plugin"
)
const (
// BuiltinReimsMacOSDriverID is the default driver for all unmarked/existing VMs.
BuiltinReimsMacOSDriverID = "builtin.driver.reims-macos"
// OwnerMarkerFile persists the owning driver ID inside a VM directory.
OwnerMarkerFile = ".reims-go-driver"
)
// Standard VM capability bits (§5.3). UI and CLI gate actions by these bits.
const (
CapSnapshot = "snapshot"
CapCowClone = "cow_clone"
CapResize = "resize"
CapQMP = "qmp"
CapSSH = "ssh"
CapGuestTools = "guest_tools"
CapAffinity = "affinity"
CapOpenCore = "opencore"
CapRecovery = "recovery"
CapCloudInit = "cloud_init"
CapUEFIISO = "uefi_iso"
)
// ValidationIssue reports a field-level validation error before Create/Set.
type ValidationIssue struct {
Field string `json:"field"`
Message string `json:"message"`
}
// VMInfo is the generic cross-driver VM model (§5.3).
type VMInfo struct {
Name string `json:"name"`
DriverID string `json:"driver_id"`
DriverName string `json:"driver_name,omitempty"`
State string `json:"state"` // "stopped" | "running" | "broken" | "driver_unavailable"
PID *int `json:"pid,omitempty"`
CPUs int `json:"cpus,omitempty"`
Memory string `json:"memory,omitempty"`
DiskSummary string `json:"disk_summary,omitempty"`
Directory string `json:"directory,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
DriverData map[string]any `json:"driver_data,omitempty"`
DriverUnavailable bool `json:"driver_unavailable,omitempty"`
}
// DriverSummary exposes metadata and schemas for the creation wizard and UI.
type DriverSummary struct {
ID string `json:"id"`
Name plugin.LocalizedText `json:"name"`
RuntimeKind string `json:"runtime_kind"`
RuntimeAPIRange string `json:"runtime_api_range,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
CreateSchema *plugin.SettingsSchema `json:"create_schema,omitempty"`
SettingsSchema *plugin.SettingsSchema `json:"settings_schema,omitempty"`
Builtin bool `json:"builtin,omitempty"`
}
// CreateRequest is a driver-agnostic VM creation request.
type CreateRequest struct {
DriverID string `json:"driver_id"`
Name string `json:"name"`
Dir string `json:"dir,omitempty"`
Options map[string]any `json:"options,omitempty"`
}
// SetRequest is a driver-agnostic VM settings update request.
type SetRequest struct {
Name string `json:"name"`
Changes map[string]any `json:"changes,omitempty"`
}
// Driver is the core contract implemented by both builtin.driver.reims-macos
// and external L3 Sidecar guest drivers (such as Linux) (§5.3).
type Driver interface {
ID() string
DisplayName() plugin.LocalizedText
RuntimeKind() string
RuntimeAPIRange() string
Capabilities() []string
CreateSchema() *plugin.SettingsSchema
SettingsSchema() *plugin.SettingsSchema
List(ctx context.Context) ([]VMInfo, error)
Show(ctx context.Context, name string) (VMInfo, error)
ValidateCreate(ctx context.Context, req CreateRequest) []ValidationIssue
Create(ctx context.Context, req CreateRequest, stdout, stderr io.Writer) error
ValidateSet(ctx context.Context, req SetRequest) []ValidationIssue
Set(ctx context.Context, req SetRequest, stdout, stderr io.Writer) error
Start(ctx context.Context, name string, stdout, stderr io.Writer) error
Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error
Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error
}
// ActionDriver is an optional interface for driver-specific commands (snapshots,
// clones, custom actions) (§5.3).
type ActionDriver interface {
InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error)
}
// ReadOwnerDriver returns the owning driver ID recorded in `<vmDir>/.reims-go-driver`.
// Unmarked legacy VMs automatically belong to builtin.driver.reims-macos (§5.3).
func ReadOwnerDriver(vmDir string) string {
if strings.TrimSpace(vmDir) == "" {
return BuiltinReimsMacOSDriverID
}
raw, err := os.ReadFile(filepath.Join(vmDir, OwnerMarkerFile))
if err != nil {
return BuiltinReimsMacOSDriverID
}
id := strings.TrimSpace(string(raw))
if id == "" {
return BuiltinReimsMacOSDriverID
}
return id
}
// WriteOwnerDriver records driverID in `<vmDir>/.reims-go-driver`.
func WriteOwnerDriver(vmDir, driverID string) error {
if strings.TrimSpace(vmDir) == "" || strings.TrimSpace(driverID) == "" {
return nil
}
if err := os.MkdirAll(vmDir, 0o755); err != nil {
return err
}
return os.WriteFile(filepath.Join(vmDir, OwnerMarkerFile), []byte(strings.TrimSpace(driverID)+"\n"), 0o644)
}
// Router aggregates active guest drivers from the plugin Registry and routes
// VM operations by ownership (§5.3).
type Router struct {
reg *plugin.Registry
vmRootDir func() string // optional directory to scan orphaned/unavailable driver VMs
}
// NewRouter creates a driver Router backed by reg.
func NewRouter(reg *plugin.Registry, vmRootDir func() string) *Router {
return &Router{reg: reg, vmRootDir: vmRootDir}
}
// Drivers returns all active Guest Drivers sorted with builtin first.
func (rt *Router) Drivers() []Driver {
if rt == nil || rt.reg == nil {
return nil
}
raw := rt.reg.GuestDrivers()
var out []Driver
for _, v := range raw {
if d, ok := v.(Driver); ok && d != nil {
out = append(out, d)
}
}
sort.Slice(out, func(i, j int) bool {
bi := out[i].ID() == BuiltinReimsMacOSDriverID
bj := out[j].ID() == BuiltinReimsMacOSDriverID
if bi != bj {
return bi
}
return out[i].ID() < out[j].ID()
})
return out
}
// Summaries returns DriverSummary metadata for every active driver.
func (rt *Router) Summaries() []DriverSummary {
drvs := rt.Drivers()
out := make([]DriverSummary, 0, len(drvs))
for _, d := range drvs {
out = append(out, DriverSummary{
ID: d.ID(),
Name: d.DisplayName(),
RuntimeKind: d.RuntimeKind(),
RuntimeAPIRange: d.RuntimeAPIRange(),
Capabilities: d.Capabilities(),
CreateSchema: d.CreateSchema(),
SettingsSchema: d.SettingsSchema(),
Builtin: d.ID() == BuiltinReimsMacOSDriverID,
})
}
return out
}
// DriverByID returns the active driver for id, or an error if unavailable.
func (rt *Router) DriverByID(id string) (Driver, error) {
if strings.TrimSpace(id) == "" {
id = BuiltinReimsMacOSDriverID
}
if rt == nil || rt.reg == nil {
return nil, fmt.Errorf("driver %q unavailable: registry not initialized", id)
}
raw, ok := rt.reg.GuestDriver(id)
if !ok {
return nil, fmt.Errorf("driver %q is unavailable or disabled", id)
}
d, ok := raw.(Driver)
if !ok || d == nil {
return nil, fmt.Errorf("registered driver %q does not implement Driver", id)
}
return d, nil
}
// ListAllVMs merges VM listings from all active drivers and appends any VM
// directory under vmRootDir whose owning driver is currently unavailable (§4.2, §5.3).
func (rt *Router) ListAllVMs(ctx context.Context) ([]VMInfo, error) {
seen := make(map[string]bool)
var out []VMInfo
for _, d := range rt.Drivers() {
vms, err := d.List(ctx)
if err != nil {
continue
}
for _, vm := range vms {
key := strings.ToLower(vm.Name)
if seen[key] {
continue
}
vm.DriverID = d.ID()
if len(vm.Capabilities) == 0 {
vm.Capabilities = d.Capabilities()
}
seen[key] = true
out = append(out, vm)
}
}
// Scan vmRootDir for VMs whose driver is disabled/missing so they show as
// driver_unavailable without breaking other VMs (§4.2).
if rt.vmRootDir != nil {
root := rt.vmRootDir()
if root != "" {
if entries, err := os.ReadDir(root); err == nil {
for _, e := range entries {
if !e.IsDir() || seen[strings.ToLower(e.Name())] {
continue
}
vmDir := filepath.Join(root, e.Name())
markerPath := filepath.Join(vmDir, OwnerMarkerFile)
if _, err := os.Stat(markerPath); err != nil {
continue
}
owner := ReadOwnerDriver(vmDir)
if _, ok := rt.reg.GuestDriver(owner); !ok {
out = append(out, VMInfo{
Name: e.Name(),
DriverID: owner,
State: "driver_unavailable",
Directory: vmDir,
DriverUnavailable: true,
})
}
}
}
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out, nil
}
// ResolveVM finds the active driver owning vmName.
func (rt *Router) ResolveVM(ctx context.Context, vmName string) (Driver, VMInfo, error) {
for _, d := range rt.Drivers() {
vms, err := d.List(ctx)
if err != nil {
continue
}
for _, vm := range vms {
if vm.Name == vmName {
vm.DriverID = d.ID()
return d, vm, nil
}
}
}
// Check whether it exists as an unavailable-driver VM.
if rt.vmRootDir != nil && vmName != "" && vmName != "." && vmName != ".." && !strings.ContainsAny(vmName, `/\`) && filepath.Base(vmName) == vmName {
if root := rt.vmRootDir(); root != "" {
vmDir := filepath.Join(root, vmName)
if _, err := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); err == nil {
owner := ReadOwnerDriver(vmDir)
return nil, VMInfo{
Name: vmName,
DriverID: owner,
State: "driver_unavailable",
Directory: vmDir,
DriverUnavailable: true,
}, fmt.Errorf("VM %q requires driver %q which is currently unavailable", vmName, owner)
}
}
}
return nil, VMInfo{}, fmt.Errorf("VM %q not found in any active driver", vmName)
}
// CheckDriverInUse returns true if any VM belongs to driverID (fail-closed on list error, §4.1).
func (rt *Router) CheckDriverInUse(ctx context.Context, driverID string) (bool, string, error) {
if rt == nil || rt.reg == nil {
return false, "", errors.New("driver router not initialized")
}
if raw, ok := rt.reg.GuestDriver(driverID); ok {
if d, ok := raw.(Driver); ok && d != nil {
vms, err := d.List(ctx)
if err != nil {
return true, "", err
}
if len(vms) > 0 {
return true, fmt.Sprintf("%d VM(s) owned by %s", len(vms), driverID), nil
}
}
}
if rt.vmRootDir != nil {
if root := rt.vmRootDir(); root != "" {
if entries, err := os.ReadDir(root); err == nil {
for _, e := range entries {
if !e.IsDir() {
continue
}
vmDir := filepath.Join(root, e.Name())
if _, err := os.Stat(filepath.Join(vmDir, OwnerMarkerFile)); err == nil {
if ReadOwnerDriver(vmDir) == driverID {
return true, fmt.Sprintf("VM %s owned by %s", e.Name(), driverID), nil
}
}
}
}
}
}
return false, "", nil
}
+89
View File
@@ -0,0 +1,89 @@
package driver
import (
"context"
"io"
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/plugin"
)
type fakeDriver struct {
id string
vms []VMInfo
}
func (f *fakeDriver) ID() string { return f.id }
func (f *fakeDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: f.id} }
func (f *fakeDriver) RuntimeKind() string { return "qemu-ovmf" }
func (f *fakeDriver) RuntimeAPIRange() string { return "^1.0.0" }
func (f *fakeDriver) Capabilities() []string { return []string{CapCloudInit, CapSSH} }
func (f *fakeDriver) CreateSchema() *plugin.SettingsSchema { return nil }
func (f *fakeDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
func (f *fakeDriver) List(context.Context) ([]VMInfo, error) { return f.vms, nil }
func (f *fakeDriver) Show(_ context.Context, n string) (VMInfo, error) { return VMInfo{Name: n, DriverID: f.id}, nil }
func (f *fakeDriver) ValidateCreate(context.Context, CreateRequest) []ValidationIssue { return nil }
func (f *fakeDriver) Create(context.Context, CreateRequest, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) ValidateSet(context.Context, SetRequest) []ValidationIssue { return nil }
func (f *fakeDriver) Set(context.Context, SetRequest, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) Start(context.Context, string, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil }
func TestOwnerMarkerZeroMigrationAndRouterUnavailable(t *testing.T) {
vmRoot := t.TempDir()
legacyVM := filepath.Join(vmRoot, "macos-tahoe")
_ = os.MkdirAll(legacyVM, 0o755)
if got := ReadOwnerDriver(legacyVM); got != BuiltinReimsMacOSDriverID {
t.Fatalf("unmarked VM owner = %q, want %q", got, BuiltinReimsMacOSDriverID)
}
linuxVM := filepath.Join(vmRoot, "ubuntu-dev")
if err := WriteOwnerDriver(linuxVM, "reims.driver.linux"); err != nil {
t.Fatal(err)
}
if got := ReadOwnerDriver(linuxVM); got != "reims.driver.linux" {
t.Fatalf("marked VM owner = %q, want reims.driver.linux", got)
}
reg := plugin.NewRegistry(nil)
_ = reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "builtin.driver.reims-macos", Version: "1.0.0"},
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, BuiltinReimsMacOSDriverID, &fakeDriver{
id: BuiltinReimsMacOSDriverID,
vms: []VMInfo{{Name: "macos-tahoe", State: "stopped"}},
})
return nil
},
})
reg.Reconcile(context.Background())
router := NewRouter(reg, func() string { return vmRoot })
all, err := router.ListAllVMs(context.Background())
if err != nil {
t.Fatal(err)
}
if len(all) != 2 {
t.Fatalf("expected 2 VMs (1 active + 1 unavailable), got %+v", all)
}
foundUnavail := false
for _, vm := range all {
if vm.Name == "ubuntu-dev" {
foundUnavail = vm.DriverUnavailable && vm.State == "driver_unavailable" && vm.DriverID == "reims.driver.linux"
}
}
if !foundUnavail {
t.Fatalf("ubuntu-dev should be marked driver_unavailable: %+v", all)
}
// CheckDriverInUse must detect ubuntu-dev even when driver is disabled.
inUse, _, err := router.CheckDriverInUse(context.Background(), "reims.driver.linux")
if err != nil || !inUse {
t.Fatalf("expected reims.driver.linux in use, got inUse=%v err=%v", inUse, err)
}
}
+229
View File
@@ -0,0 +1,229 @@
package driver
import (
"context"
"encoding/json"
"fmt"
"io"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
// ReimsMacOSCapabilities lists all capabilities supported by builtin.driver.reims-macos.
var ReimsMacOSCapabilities = []string{
CapSnapshot,
CapCowClone,
CapResize,
CapQMP,
CapSSH,
CapGuestTools,
CapAffinity,
CapOpenCore,
CapRecovery,
}
// ReimsMacOSDriver adapts internal/driver/reims into the generic Driver interface
// as the compiled-in `builtin.driver.reims-macos` extension (§3.2, §5.3).
type ReimsMacOSDriver struct {
getConfig func() config.Config
}
// NewReimsMacOSDriver creates the built-in macOS driver adapter.
func NewReimsMacOSDriver(getConfig func() config.Config) *ReimsMacOSDriver {
return &ReimsMacOSDriver{getConfig: getConfig}
}
func (d *ReimsMacOSDriver) ID() string { return BuiltinReimsMacOSDriverID }
func (d *ReimsMacOSDriver) DisplayName() plugin.LocalizedText {
return plugin.LocalizedText{ZhCN: "macOS (Reims vGPU)", EnUS: "macOS (Reims vGPU)"}
}
func (d *ReimsMacOSDriver) RuntimeKind() string { return rt.DefaultKind }
func (d *ReimsMacOSDriver) RuntimeAPIRange() string { return "^1.0.0" }
func (d *ReimsMacOSDriver) Capabilities() []string { return append([]string(nil), ReimsMacOSCapabilities...) }
func (d *ReimsMacOSDriver) CreateSchema() *plugin.SettingsSchema {
return nil // Uses the native macOS CreateWizard UI
}
func (d *ReimsMacOSDriver) SettingsSchema() *plugin.SettingsSchema {
return nil // Uses the native macOS SettingsModal UI
}
func (d *ReimsMacOSDriver) client() (*reims.Client, error) {
cfg := d.getConfig()
active, err := rt.ResolveForKind(&cfg, d.RuntimeKind())
if err != nil {
return nil, err
}
if err := rt.CheckCompatibility(d.RuntimeKind(), d.RuntimeAPIRange(), *active); err != nil {
return nil, err
}
return reims.NewClient(&cfg, *active), nil
}
func (d *ReimsMacOSDriver) List(ctx context.Context) ([]VMInfo, error) {
c, err := d.client()
if err != nil {
return nil, err
}
items, err := c.List(ctx)
if err != nil {
return nil, err
}
out := make([]VMInfo, 0, len(items))
for _, it := range items {
out = append(out, VMInfo{
Name: it.Name,
DriverID: d.ID(),
DriverName: "macOS (Reims vGPU)",
State: it.State,
PID: it.PID,
Capabilities: d.Capabilities(),
})
}
return out, nil
}
func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (VMInfo, error) {
c, err := d.client()
if err != nil {
return VMInfo{}, err
}
det, err := c.Show(ctx, name)
if err != nil {
return VMInfo{}, err
}
rawBytes, _ := json.Marshal(det)
var data map[string]any
_ = json.Unmarshal(rawBytes, &data)
return VMInfo{
Name: det.Name,
DriverID: d.ID(),
DriverName: "macOS (Reims vGPU)",
State: det.State,
CPUs: det.CPUs,
Memory: det.Memory,
DiskSummary: det.Disk,
Directory: det.Directory,
Capabilities: d.Capabilities(),
DriverData: data,
}, nil
}
func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req CreateRequest) []ValidationIssue {
var opts reims.CreateOpts
if err := decodeMap(req.Options, &opts); err != nil {
return []ValidationIssue{{Field: "options", Message: err.Error()}}
}
if opts.Name == "" {
opts.Name = req.Name
}
if opts.Dir == "" {
opts.Dir = req.Dir
}
cfg := d.getConfig()
rep := host.Inspect(cfg.DataRoot)
issues := reims.ValidateCreateLocalized(opts, rep, cfg.Locale)
out := make([]ValidationIssue, 0, len(issues))
for _, is := range issues {
out = append(out, ValidationIssue{Field: is.Field, Message: is.Message})
}
return out
}
func (d *ReimsMacOSDriver) Create(ctx context.Context, req CreateRequest, stdout, stderr io.Writer) error {
c, err := d.client()
if err != nil {
return err
}
var opts reims.CreateOpts
if err := decodeMap(req.Options, &opts); err != nil {
return err
}
if opts.Name == "" {
opts.Name = req.Name
}
if opts.Dir == "" {
opts.Dir = req.Dir
}
return c.Create(ctx, opts, stdout, stderr)
}
func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req SetRequest) []ValidationIssue {
var opts reims.SetOpts
if err := decodeMap(req.Changes, &opts); err != nil {
return []ValidationIssue{{Field: "changes", Message: err.Error()}}
}
opts.Name = req.Name
var cur reims.VMDetail
if c, err := d.client(); err == nil {
if det, err := c.Show(ctx, req.Name); err == nil {
cur = det
}
}
cfg := d.getConfig()
rep := host.Inspect(cfg.DataRoot)
issues := reims.ValidateSetLocalized(opts, cur, rep, cfg.Locale)
out := make([]ValidationIssue, 0, len(issues))
for _, is := range issues {
out = append(out, ValidationIssue{Field: is.Field, Message: is.Message})
}
return out
}
func (d *ReimsMacOSDriver) Set(ctx context.Context, req SetRequest, stdout, stderr io.Writer) error {
c, err := d.client()
if err != nil {
return err
}
var opts reims.SetOpts
if err := decodeMap(req.Changes, &opts); err != nil {
return err
}
opts.Name = req.Name
return c.Set(ctx, opts, stdout, stderr)
}
func (d *ReimsMacOSDriver) Start(ctx context.Context, name string, stdout, stderr io.Writer) error {
c, err := d.client()
if err != nil {
return err
}
return c.StartWithCompat(ctx, name, stdout, stderr, nil)
}
func (d *ReimsMacOSDriver) Stop(ctx context.Context, name string, force bool, stdout, stderr io.Writer) error {
c, err := d.client()
if err != nil {
return err
}
if force {
return c.StopForce(ctx, name, stdout, stderr)
}
return c.Stop(ctx, name, stdout, stderr)
}
func (d *ReimsMacOSDriver) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error {
c, err := d.client()
if err != nil {
return err
}
return c.Delete(ctx, name, keepFiles, stdout, stderr)
}
func decodeMap(m map[string]any, dst any) error {
if len(m) == 0 {
return nil
}
raw, err := json.Marshal(m)
if err != nil {
return fmt.Errorf("marshal options: %w", err)
}
return json.Unmarshal(raw, dst)
}
+193
View File
@@ -0,0 +1,193 @@
package driver
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/plugin"
)
// SidecarDriver adapts an L3 Sidecar guest driver plugin into the unified
// driver.Driver + driver.ActionDriver interfaces over JSON-RPC 2.0 (§5.3, §8).
// Because VM processes are spawned via the reverse Host API (`host/vm.spawn`),
// a Sidecar crash or restart never terminates running VMs.
type SidecarDriver struct {
contrib plugin.GuestDriverContribution
sup *plugin.SidecarSupervisor
}
// NewSidecarDriver constructs a JSON-RPC proxy driver backed by sup.
func NewSidecarDriver(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) *SidecarDriver {
return &SidecarDriver{
contrib: contrib,
sup: sup,
}
}
func (d *SidecarDriver) ID() string { return d.contrib.ID }
func (d *SidecarDriver) DisplayName() plugin.LocalizedText { return d.contrib.Name }
func (d *SidecarDriver) RuntimeKind() string { return d.contrib.RuntimeKind }
func (d *SidecarDriver) RuntimeAPIRange() string { return d.contrib.RuntimeAPIRange }
func (d *SidecarDriver) Capabilities() []string { return append([]string(nil), d.contrib.Capabilities...) }
func (d *SidecarDriver) CreateSchema() *plugin.SettingsSchema { return d.contrib.CreateSchema }
func (d *SidecarDriver) SettingsSchema() *plugin.SettingsSchema { return d.contrib.SettingsSchema }
func (d *SidecarDriver) List(ctx context.Context) ([]VMInfo, error) {
var resp struct {
VMs []VMInfo `json:"vms"`
}
if err := d.sup.Call(ctx, "driver/list", nil, &resp); err != nil {
return nil, err
}
for i := range resp.VMs {
resp.VMs[i].DriverID = d.contrib.ID
if len(resp.VMs[i].Capabilities) == 0 {
resp.VMs[i].Capabilities = d.Capabilities()
}
}
return resp.VMs, nil
}
func (d *SidecarDriver) Show(ctx context.Context, name string) (VMInfo, error) {
var info VMInfo
if err := d.sup.Call(ctx, "driver/show", map[string]any{"name": name}, &info); err != nil {
return VMInfo{}, err
}
info.DriverID = d.contrib.ID
if len(info.Capabilities) == 0 {
info.Capabilities = d.Capabilities()
}
return info, nil
}
func (d *SidecarDriver) ValidateCreate(ctx context.Context, req CreateRequest) []ValidationIssue {
var resp struct {
Issues []ValidationIssue `json:"issues"`
}
if err := d.sup.Call(ctx, "driver/validateCreate", req, &resp); err != nil {
return []ValidationIssue{{Field: "driver", Message: err.Error()}}
}
return resp.Issues
}
func (d *SidecarDriver) Create(ctx context.Context, req CreateRequest, stdout, _ io.Writer) error {
var resp struct {
Directory string `json:"directory"`
Logs []string `json:"logs"`
}
if err := d.sup.Call(ctx, "driver/create", req, &resp); err != nil {
return err
}
for _, l := range resp.Logs {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, l)
}
}
if resp.Directory != "" {
cleanDir := filepath.Clean(resp.Directory)
// Only stamp ownership inside an existing directory returned for this VM,
// and refuse to hijack a directory already owned by a different driver.
if req.Dir != "" {
cleanReq := filepath.Clean(req.Dir)
if !strings.EqualFold(cleanDir, cleanReq) && !strings.HasPrefix(strings.ToLower(cleanDir), strings.ToLower(cleanReq+string(os.PathSeparator))) {
return fmt.Errorf("sidecar driver returned directory %q outside requested %q", resp.Directory, req.Dir)
}
}
if st, err := os.Stat(cleanDir); err == nil && st.IsDir() {
markerPath := filepath.Join(cleanDir, OwnerMarkerFile)
if _, mErr := os.Stat(markerPath); mErr == nil {
if existing := ReadOwnerDriver(cleanDir); existing != d.contrib.ID {
return fmt.Errorf("refusing to overwrite VM owner marker %q with %q", existing, d.contrib.ID)
}
}
if err := WriteOwnerDriver(cleanDir, d.contrib.ID); err != nil {
return fmt.Errorf("write driver owner marker: %w", err)
}
}
}
return nil
}
func (d *SidecarDriver) ValidateSet(ctx context.Context, req SetRequest) []ValidationIssue {
var resp struct {
Issues []ValidationIssue `json:"issues"`
}
if err := d.sup.Call(ctx, "driver/validateSet", req, &resp); err != nil {
return []ValidationIssue{{Field: "driver", Message: err.Error()}}
}
return resp.Issues
}
func (d *SidecarDriver) Set(ctx context.Context, req SetRequest, stdout, _ io.Writer) error {
var resp struct {
Logs []string `json:"logs"`
}
if err := d.sup.Call(ctx, "driver/set", req, &resp); err != nil {
return err
}
for _, l := range resp.Logs {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, l)
}
}
return nil
}
func (d *SidecarDriver) Start(ctx context.Context, name string, stdout, _ io.Writer) error {
var resp struct {
Logs []string `json:"logs"`
}
if err := d.sup.Call(ctx, "driver/start", map[string]any{"name": name}, &resp); err != nil {
return err
}
for _, l := range resp.Logs {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, l)
}
}
return nil
}
func (d *SidecarDriver) Stop(ctx context.Context, name string, force bool, stdout, _ io.Writer) error {
var resp struct {
Logs []string `json:"logs"`
}
if err := d.sup.Call(ctx, "driver/stop", map[string]any{"name": name, "force": force}, &resp); err != nil {
return err
}
for _, l := range resp.Logs {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, l)
}
}
return nil
}
func (d *SidecarDriver) Delete(ctx context.Context, name string, keepFiles bool, stdout, _ io.Writer) error {
var resp struct {
Logs []string `json:"logs"`
}
if err := d.sup.Call(ctx, "driver/delete", map[string]any{"name": name, "keep_files": keepFiles}, &resp); err != nil {
return err
}
for _, l := range resp.Logs {
if stdout != nil {
_, _ = fmt.Fprintln(stdout, l)
}
}
return nil
}
func (d *SidecarDriver) InvokeAction(ctx context.Context, vmName, action string, params map[string]any) (any, error) {
var resp any
err := d.sup.Call(ctx, "driver/invokeAction", map[string]any{
"vm_name": vmName,
"action": action,
"params": params,
}, &resp)
return resp, err
}
+113 -33
View File
@@ -20,6 +20,7 @@ import (
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
@@ -196,32 +197,46 @@ type registeredVM struct {
// Server serves the token-authenticated host ↔ guest bridge over 127.0.0.1
// (reachable from QEMU SLIRP guests as http://10.0.2.2:<port>).
type Server struct {
mu sync.RWMutex
clip Clipboard
vms map[string]*registeredVM // keyed by VM name
davHandlers map[string]*webdav.Handler
davRoots map[string]string
port int
listener net.Listener
httpSrv *http.Server
watchCancel context.CancelFunc
clipNotify chan struct{}
onHostText func(vmName, text string)
mu sync.RWMutex
clip Clipboard
vms map[string]*registeredVM // keyed by VM name
davHandlers map[string]*webdav.Handler
davRoots map[string]string
dynamicRoutes map[string]http.HandlerFunc
clipboardActive bool
globalClipPolicy ClipboardPolicy
vmClipPolicies map[string]ClipboardPolicy
watcherCount atomic.Int32
clipStatsH2G uint64
clipStatsG2H uint64
clipStatsErr uint64
port int
listener net.Listener
httpSrv *http.Server
watchCancel context.CancelFunc
clipNotify chan struct{}
onHostText func(vmName, text string)
}
// NewServer constructs a Guest Tools HTTP bridge. Pass nil for clip to use the
// host OS clipboard.
// NewServer constructs a Guest Tools HTTP bridge with clipboard active by default.
// Pass nil for clip to use the host OS clipboard.
func NewServer(clip Clipboard) *Server {
if clip == nil {
clip = &OSClipboard{}
}
return &Server{
clip: clip,
vms: make(map[string]*registeredVM),
davHandlers: make(map[string]*webdav.Handler),
davRoots: make(map[string]string),
clipNotify: make(chan struct{}),
s := &Server{
clip: clip,
vms: make(map[string]*registeredVM),
davHandlers: make(map[string]*webdav.Handler),
davRoots: make(map[string]string),
dynamicRoutes: make(map[string]http.HandlerFunc),
clipboardActive: true,
globalClipPolicy: DefaultClipboardPolicy(),
vmClipPolicies: make(map[string]ClipboardPolicy),
clipNotify: make(chan struct{}),
}
s.dynamicRoutes["/v1/clipboard"] = s.handleClipboard
return s
}
// Start binds the bridge on 127.0.0.1 starting from preferredPort (default
@@ -265,7 +280,7 @@ func (s *Server) Start(preferredPort int) (int, error) {
mux.HandleFunc("/v1/ping", s.handlePing)
mux.HandleFunc("/v1/config", s.handleConfig)
mux.HandleFunc("/v1/status", s.handleStatus)
mux.HandleFunc("/v1/clipboard", s.handleClipboard)
mux.HandleFunc("/v1/clipboard", s.dispatchDynamicRoute("/v1/clipboard", "clipboard"))
mux.HandleFunc("/v1/text-input", s.handleTextInput)
mux.HandleFunc("/v1/text-input/ack", s.handleTextInputAck)
mux.HandleFunc("/v1/host-text", s.handleHostText)
@@ -273,19 +288,36 @@ func (s *Server) Start(preferredPort int) (int, error) {
mux.HandleFunc("/v1/file", s.handleFile)
mux.HandleFunc("/dav/", s.handleWebDAV)
s.httpSrv = &http.Server{
Handler: mux,
Handler: localSecurityMiddleware(mux),
ReadHeaderTimeout: 10 * time.Second,
}
watchCtx, watchCancel := context.WithCancel(context.Background())
s.watchCancel = watchCancel
go s.watchClipboardLoop(watchCtx)
if s.clipboardActive {
watchCtx, watchCancel := context.WithCancel(context.Background())
s.watchCancel = watchCancel
s.watcherCount.Add(1)
go s.watchClipboardLoop(watchCtx)
}
go func() {
_ = s.httpSrv.Serve(ln)
}()
return s.port, nil
}
func (s *Server) dispatchDynamicRoute(routePath, feature string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
h := s.dynamicRoutes[routePath]
s.mu.RUnlock()
if h == nil {
writeFeatureDisabled(w, feature)
return
}
h(w, r)
}
}
func (s *Server) watchClipboardLoop(ctx context.Context) {
defer s.watcherCount.Add(-1)
ticker := time.NewTicker(150 * time.Millisecond)
defer ticker.Stop()
lastSeq := s.clip.SequenceNumber()
@@ -646,12 +678,19 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
caps := []string{"webdav", "prevent-sleep", "text-input", "drive-shares-readonly"}
if policy := s.EffectiveClipboardPolicy(vm.name); policy.Enabled {
caps = append([]string{"clipboard-text", "clipboard-longpoll"}, caps...)
if policy.SyncImages {
caps = append([]string{"clipboard-png"}, caps...)
}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"ok": true,
"vm": vm.name,
"version": DriveShareAgentVersion,
"capabilities": []string{"clipboard-text", "clipboard-png", "clipboard-longpoll", "webdav", "prevent-sleep", "text-input", "drive-shares-readonly"},
"capabilities": caps,
})
}
@@ -665,12 +704,17 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
policy := s.EffectiveClipboardPolicy(vm.name)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"vm": vm.name,
"prevent_sleep": vm.preventSleep,
"webdav_path": "/dav/" + vm.name + "/",
"shared_drives": enabledDriveLetters(vm),
"vm": vm.name,
"prevent_sleep": vm.preventSleep,
"webdav_path": "/dav/" + vm.name + "/",
"shared_drives": enabledDriveLetters(vm),
"clipboard_enabled": policy.Enabled,
"clipboard_direction": policy.Direction,
"clipboard_sync_images": policy.SyncImages,
"clipboard_max_bytes": policy.MaxImageBytes,
})
}
@@ -729,10 +773,19 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
policy := s.EffectiveClipboardPolicy(vm.name)
if !policy.Enabled {
writeFeatureDisabled(w, "clipboard")
return
}
switch r.Method {
case http.MethodGet:
acceptImage := strings.EqualFold(r.URL.Query().Get("accept"), "image") ||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")
if policy.Direction == ClipboardGuestToHost {
w.WriteHeader(http.StatusNoContent)
return
}
acceptImage := policy.SyncImages && (strings.EqualFold(r.URL.Query().Get("accept"), "image") ||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png"))
since := r.URL.Query().Get("since")
waitSec := 0
if rawWait := r.URL.Query().Get("wait"); rawWait != "" {
@@ -746,8 +799,13 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
deadline := time.Now().Add(time.Duration(waitSec) * time.Second)
for {
if !s.EffectiveClipboardPolicy(vm.name).Enabled {
writeFeatureDisabled(w, "clipboard")
return
}
if ov := s.takeClipOverride(vm.name); ov != nil {
s.touchLastSeen(vm.name)
atomic.AddUint64(&s.clipStatsH2G, 1)
w.Header().Set("X-Clip-Hash", ov.hash)
w.Header().Set("X-Clip-Kind", string(ClipText))
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
@@ -757,12 +815,17 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
}
payload, err := s.readClipboardPayload(acceptImage)
if err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if payload.Kind == ClipPNG && len(payload.Data) > policy.MaxImageBytes {
payload = ClipPayload{Kind: ClipText, Data: nil}
}
h := payloadHash(payload)
if since == "" || since != h {
s.touchLastSeen(vm.name)
atomic.AddUint64(&s.clipStatsH2G, 1)
w.Header().Set("X-Clip-Hash", h)
if payload.Kind == ClipPNG {
w.Header().Set("X-Clip-Kind", string(ClipPNG))
@@ -807,17 +870,30 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
}
case http.MethodPost, http.MethodPut:
body, err := io.ReadAll(io.LimitReader(r.Body, MaxClipboardBytes+1))
if policy.Direction == ClipboardHostToGuest {
w.WriteHeader(http.StatusNoContent)
return
}
limit := policy.MaxImageBytes
if limit <= 0 || limit > MaxClipboardBytes {
limit = MaxClipboardBytes
}
body, err := io.ReadAll(io.LimitReader(r.Body, int64(limit)+1))
if err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(body) > MaxClipboardBytes {
if len(body) > limit {
http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge)
return
}
ct := strings.ToLower(r.Header.Get("Content-Type"))
if strings.Contains(ct, "image/png") {
if !policy.SyncImages {
w.WriteHeader(http.StatusNoContent)
return
}
if !IsPNG(body) {
http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest)
return
@@ -825,9 +901,11 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
h := payloadHash(ClipPayload{Kind: ClipPNG, Data: body})
if cur, err := s.clip.Read(); err != nil || payloadHash(cur) != h {
if err := s.clip.WritePNG(body); err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
atomic.AddUint64(&s.clipStatsG2H, 1)
s.broadcastClipChange()
}
w.Header().Set("X-Clip-Kind", string(ClipPNG))
@@ -844,9 +922,11 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
h := textHash(text)
if cur, err := s.clip.ReadText(); err != nil || textHash(cur) != h {
if err := s.clip.WriteText(text); err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
atomic.AddUint64(&s.clipStatsG2H, 1)
s.broadcastClipChange()
}
w.Header().Set("X-Clip-Kind", string(ClipText))
+226
View File
@@ -0,0 +1,226 @@
package guesttools
import (
"context"
"encoding/json"
"net/http"
"net/url"
"strings"
"sync/atomic"
)
// ClipboardDirection controls which way host <-> guest clipboard sync flows (§5.4).
type ClipboardDirection string
const (
ClipboardBidirectional ClipboardDirection = "bidirectional"
ClipboardHostToGuest ClipboardDirection = "host-to-guest"
ClipboardGuestToHost ClipboardDirection = "guest-to-host"
)
// ClipboardPolicy configures clipboard sync globally or per VM (§5.4).
type ClipboardPolicy struct {
Enabled bool `json:"enabled"`
Direction ClipboardDirection `json:"direction"`
SyncImages bool `json:"sync_images"`
MaxImageBytes int `json:"max_image_bytes"`
}
// DefaultClipboardPolicy returns the default bidirectional text+image policy.
func DefaultClipboardPolicy() ClipboardPolicy {
return ClipboardPolicy{
Enabled: true,
Direction: ClipboardBidirectional,
SyncImages: true,
MaxImageBytes: MaxClipboardBytes,
}
}
// ClipboardStats tracks privacy-safe counters (never clipboard content, §5.4).
type ClipboardStats struct {
HostToGuestCount uint64 `json:"host_to_guest_count"`
GuestToHostCount uint64 `json:"guest_to_host_count"`
ErrorCount uint64 `json:"error_count"`
Active bool `json:"active"`
WatcherRunning bool `json:"watcher_running"`
}
// NewTransportServer constructs a Guest Tools HTTP transport server with
// clipboard disabled until the builtin.bridge.clipboard extension activates it (§5.4).
func NewTransportServer(clip Clipboard) *Server {
s := NewServer(clip)
s.clipboardActive = false
delete(s.dynamicRoutes, "/v1/clipboard")
s.globalClipPolicy = DefaultClipboardPolicy()
s.globalClipPolicy.Enabled = false
return s
}
// RegisterRoute dynamically mounts an HTTP handler on the Guest Tools bridge
// and returns an unregister function for Scope.OnDispose (§5.4).
func (s *Server) RegisterRoute(routePath string, handler http.HandlerFunc) func() {
s.mu.Lock()
if s.dynamicRoutes == nil {
s.dynamicRoutes = make(map[string]http.HandlerFunc)
}
s.dynamicRoutes[routePath] = handler
s.mu.Unlock()
return func() {
s.mu.Lock()
delete(s.dynamicRoutes, routePath)
s.mu.Unlock()
}
}
// HasRoute reports whether routePath is currently registered on the bridge.
func (s *Server) HasRoute(routePath string) bool {
s.mu.RLock()
_, ok := s.dynamicRoutes[routePath]
s.mu.RUnlock()
return ok
}
// SetClipboardActive enables or disables the clipboard extension on this bridge.
// Enabling registers /v1/clipboard and starts the host clipboard watcher;
// disabling removes the route and stops the watcher with zero residue (§5.4).
func (s *Server) SetClipboardActive(active bool) {
s.mu.Lock()
s.clipboardActive = active
if s.dynamicRoutes == nil {
s.dynamicRoutes = make(map[string]http.HandlerFunc)
}
if active {
s.globalClipPolicy.Enabled = true
s.dynamicRoutes["/v1/clipboard"] = s.handleClipboard
if s.listener != nil && s.watchCancel == nil {
watchCtx, watchCancel := context.WithCancel(context.Background())
s.watchCancel = watchCancel
s.watcherCount.Add(1)
go s.watchClipboardLoop(watchCtx)
}
s.mu.Unlock()
return
}
s.globalClipPolicy.Enabled = false
delete(s.dynamicRoutes, "/v1/clipboard")
cancel := s.watchCancel
s.watchCancel = nil
s.mu.Unlock()
if cancel != nil {
cancel()
}
s.broadcastClipChange()
}
// IsClipboardActive reports whether the clipboard feature is currently active.
func (s *Server) IsClipboardActive() bool {
s.mu.RLock()
defer s.mu.RUnlock()
return s.clipboardActive
}
// IsClipboardWatcherRunning reports whether the host clipboard polling goroutine is active.
func (s *Server) IsClipboardWatcherRunning() bool {
return s.watcherCount.Load() > 0
}
// SetGlobalClipboardPolicy updates the global clipboard policy immediately.
func (s *Server) SetGlobalClipboardPolicy(p ClipboardPolicy) {
p = normalizeClipboardPolicy(p)
s.mu.Lock()
s.globalClipPolicy = p
s.mu.Unlock()
s.broadcastClipChange()
}
// SetVMClipboardPolicy sets or clears a per-VM clipboard policy override immediately.
func (s *Server) SetVMClipboardPolicy(vmName string, p *ClipboardPolicy) {
s.mu.Lock()
if s.vmClipPolicies == nil {
s.vmClipPolicies = make(map[string]ClipboardPolicy)
}
if p == nil {
delete(s.vmClipPolicies, vmName)
} else {
s.vmClipPolicies[vmName] = normalizeClipboardPolicy(*p)
}
s.mu.Unlock()
s.broadcastClipChange()
}
// EffectiveClipboardPolicy returns the resolved policy for vmName.
func (s *Server) EffectiveClipboardPolicy(vmName string) ClipboardPolicy {
s.mu.RLock()
defer s.mu.RUnlock()
if !s.clipboardActive {
p := s.globalClipPolicy
p.Enabled = false
return p
}
if ov, ok := s.vmClipPolicies[vmName]; ok {
return ov
}
return s.globalClipPolicy
}
// ClipboardDiagnostics returns privacy-safe clipboard metrics (counts/errors only, §5.4).
func (s *Server) ClipboardDiagnostics() ClipboardStats {
return ClipboardStats{
HostToGuestCount: atomic.LoadUint64(&s.clipStatsH2G),
GuestToHostCount: atomic.LoadUint64(&s.clipStatsG2H),
ErrorCount: atomic.LoadUint64(&s.clipStatsErr),
Active: s.IsClipboardActive(),
WatcherRunning: s.IsClipboardWatcherRunning(),
}
}
func normalizeClipboardPolicy(p ClipboardPolicy) ClipboardPolicy {
switch p.Direction {
case ClipboardBidirectional, ClipboardHostToGuest, ClipboardGuestToHost:
default:
p.Direction = ClipboardBidirectional
}
if p.MaxImageBytes <= 0 || p.MaxImageBytes > MaxClipboardBytes {
p.MaxImageBytes = MaxClipboardBytes
}
return p
}
func writeFeatureDisabled(w http.ResponseWriter, feature string) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Retry-After", "5")
w.WriteHeader(http.StatusServiceUnavailable)
_ = json.NewEncoder(w).Encode(map[string]any{
"error": "feature_disabled",
"feature": feature,
})
}
// localSecurityMiddleware blocks sandboxed iframes and cross-origin web pages
// from calling the local Guest Tools HTTP API (docs/plugin-architecture.md §7.3).
func localSecurityMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.EqualFold(strings.TrimSpace(r.Header.Get("Sec-Fetch-Dest")), "iframe") {
http.Error(w, "forbidden: iframe access denied", http.StatusForbidden)
return
}
if origin := strings.TrimSpace(r.Header.Get("Origin")); origin != "" {
if strings.EqualFold(origin, "null") {
http.Error(w, "forbidden: null origin denied", http.StatusForbidden)
return
}
u, err := url.Parse(origin)
if err != nil || !strings.EqualFold(u.Scheme, "http") || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" {
http.Error(w, "forbidden: cross-origin denied", http.StatusForbidden)
return
}
host := strings.ToLower(u.Hostname())
if host != "127.0.0.1" && host != "localhost" && host != "10.0.2.2" {
http.Error(w, "forbidden: cross-origin denied", http.StatusForbidden)
return
}
}
next.ServeHTTP(w, r)
})
}
+125
View File
@@ -0,0 +1,125 @@
package guesttools
import (
"context"
"encoding/json"
"net/http"
"path/filepath"
"strings"
"testing"
"time"
)
func TestTransportClipboardToggleZeroResidueAndPolicy(t *testing.T) {
tmp := t.TempDir()
vmDir := filepath.Join(tmp, "vm")
sharedDir := filepath.Join(tmp, "shared")
clip := &memClipboard{kind: ClipText, data: []byte("initial")}
srv := NewTransportServer(clip)
port, err := srv.Start(-1)
if err != nil {
t.Fatal(err)
}
defer func() { _ = srv.Close(context.Background()) }()
cfg, err := LoadOrCreateVMConfig(vmDir, "mac1", sharedDir, port)
if err != nil {
t.Fatal(err)
}
srv.RegisterVM(cfg)
baseURL := "http://127.0.0.1:" + strconvItoa(port)
doReq := func(method, path string, headers map[string]string, body string) *http.Response {
req, err := http.NewRequest(method, baseURL+path, strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+cfg.Token)
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
return resp
}
// Initially disabled: zero route, zero watcher, 503 feature_disabled response.
if srv.HasRoute("/v1/clipboard") || srv.IsClipboardWatcherRunning() {
t.Fatal("expected clipboard route and watcher inactive on NewTransportServer")
}
resp := doReq(http.MethodGet, "/v1/clipboard", nil, "")
if resp.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("disabled clipboard status = %d, want 503", resp.StatusCode)
}
_ = resp.Body.Close()
// Enable clipboard live while server is running.
srv.SetClipboardActive(true)
if !srv.HasRoute("/v1/clipboard") {
t.Fatal("expected /v1/clipboard route active")
}
// Verify /v1/config advertises clipboard_enabled=true.
resp = doReq(http.MethodGet, "/v1/config", nil, "")
var cfgResp map[string]any
_ = json.NewDecoder(resp.Body).Decode(&cfgResp)
_ = resp.Body.Close()
if cfgResp["clipboard_enabled"] != true {
t.Fatalf("config clipboard_enabled = %v, want true", cfgResp["clipboard_enabled"])
}
// Per-VM direction override: host-to-guest blocks POST from guest.
srv.SetVMClipboardPolicy("mac1", &ClipboardPolicy{
Enabled: true,
Direction: ClipboardHostToGuest,
SyncImages: false,
MaxImageBytes: 1024,
})
resp = doReq(http.MethodPost, "/v1/clipboard", nil, "from-guest")
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("host-to-guest POST status = %d, want 204", resp.StatusCode)
}
_ = resp.Body.Close()
// Disable clipboard live: route gone, watcher stops cleanly, 503 returned.
srv.SetClipboardActive(false)
if srv.HasRoute("/v1/clipboard") {
t.Fatal("expected /v1/clipboard route removed after disable")
}
deadline := time.Now().Add(2 * time.Second)
for srv.IsClipboardWatcherRunning() && time.Now().Before(deadline) {
time.Sleep(20 * time.Millisecond)
}
if srv.IsClipboardWatcherRunning() {
t.Fatal("expected clipboard watcher goroutine stopped after disable")
}
// Security middleware (§7.3): block Origin: null, cross-origin, Sec-Fetch-Dest: iframe.
for _, hdr := range []map[string]string{
{"Origin": "null"},
{"Origin": "https://evil.example"},
{"Sec-Fetch-Dest": "iframe"},
} {
r := doReq(http.MethodGet, "/v1/ping", hdr, "")
if r.StatusCode != http.StatusForbidden {
t.Fatalf("security header %v status = %d, want 403", hdr, r.StatusCode)
}
_ = r.Body.Close()
}
}
func strconvItoa(n int) string {
if n == 0 {
return "0"
}
var digits [20]byte
i := len(digits)
for n > 0 {
i--
digits[i] = byte('0' + n%10)
n /= 10
}
return string(digits[i:])
}
+220
View File
@@ -0,0 +1,220 @@
package host
import (
"strings"
"sync"
"sync/atomic"
)
// InputFilterRule is a host-evaluated declarative input filter contributed by
// L1 plugins (e.g. reims.input.wheel-invert). No plugin code ever runs inside
// the low-level Win32 hook callback (docs/plugin-architecture.md §5.4).
type InputFilterRule struct {
ID string `json:"id"`
PluginID string `json:"plugin_id"`
Event string `json:"event"` // "mouse_wheel"
Axis string `json:"axis"` // "vertical" | "horizontal" | "both"
Transform string `json:"transform"` // "invert"
Scope string `json:"scope"` // "vm_foreground"
VMNames map[string]bool `json:"vm_names,omitempty"` // empty = all VMs; non-empty = targeted VMs
Vertical bool `json:"vertical"`
Horizontal bool `json:"horizontal"`
}
// EvalWheelFilter evaluates declarative wheel-invert rules for vmName and axis.
// Pure Go function so rule evaluation is deterministically unit-tested on every OS.
func EvalWheelFilter(rules []InputFilterRule, vmName string, horizontal bool, delta int16) (int16, bool) {
if delta == 0 || len(rules) == 0 {
return delta, false
}
for _, r := range rules {
if !strings.EqualFold(r.Event, "mouse_wheel") || !strings.EqualFold(r.Transform, "invert") {
continue
}
if len(r.VMNames) > 0 && !r.VMNames[vmName] {
continue
}
axis := strings.ToLower(strings.TrimSpace(r.Axis))
matchAxis := false
if horizontal {
matchAxis = r.Horizontal || axis == "horizontal" || axis == "both"
} else {
matchAxis = r.Vertical || axis == "vertical" || axis == "both" || (axis == "" && !r.Horizontal)
}
if matchAxis {
// Guard against int16(-32768) overflow on negation.
if delta == -32768 {
return 32767, true
}
return -delta, true
}
}
return delta, false
}
// hasMatchingWheelTarget returns true when at least one running target VM is
// matched by at least one active mouse_wheel filter rule (§5.4 on-demand hook).
func hasMatchingWheelTarget(rules []InputFilterRule, targets []IMETarget) bool {
if len(rules) == 0 || len(targets) == 0 {
return false
}
for _, t := range targets {
if t.PID == 0 {
continue
}
for _, r := range rules {
if !strings.EqualFold(r.Event, "mouse_wheel") || !strings.EqualFold(r.Transform, "invert") {
continue
}
if !r.Vertical && !r.Horizontal && r.Axis == "" {
continue
}
if len(r.VMNames) == 0 || r.VMNames[t.VMName] {
return true
}
}
}
return false
}
// InputService unifies low-level keyboard (IME bridge) and on-demand low-level
// mouse (declarative inputFilters) hooks behind one reversible host service (§5.4).
type InputService struct {
mu sync.Mutex
onIMEText func(target IMETarget, text string)
imeEnabled bool
imeBridge *IMEBridge
targets []IMETarget
targetByPID atomic.Pointer[map[uint32]IMETarget]
rules atomic.Pointer[[]InputFilterRule]
mouseHook *mouseWheelHook
closed bool
}
// NewInputService constructs an inactive InputService. No OS hooks are installed
// until EnableIME or SetFilterRules + matching targets require them (§8.1).
func NewInputService(onIMEText func(target IMETarget, text string)) *InputService {
s := &InputService{
onIMEText: onIMEText,
}
emptyTargets := make(map[uint32]IMETarget)
s.targetByPID.Store(&emptyTargets)
emptyRules := []InputFilterRule{}
s.rules.Store(&emptyRules)
return s
}
// EnableIME starts or stops the low-level keyboard hook for remote IME bridging.
func (s *InputService) EnableIME(enabled bool) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil
}
s.imeEnabled = enabled
if enabled {
if s.imeBridge == nil {
b, err := StartIMEBridge(s.onIMEText)
if err != nil {
return err
}
b.SetTargets(s.targets)
s.imeBridge = b
}
return nil
}
if s.imeBridge != nil {
s.imeBridge.Close()
s.imeBridge = nil
}
return nil
}
// SetTargets updates the active running VM PIDs and reconciles the on-demand
// mouse hook so it is installed ONLY while a matching VM is running (§5.4).
func (s *InputService) SetTargets(targets []IMETarget) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return
}
cp := append([]IMETarget(nil), targets...)
s.targets = cp
m := make(map[uint32]IMETarget, len(cp))
for _, t := range cp {
if t.PID > 0 {
m[t.PID] = t
}
}
s.targetByPID.Store(&m)
if s.imeBridge != nil {
s.imeBridge.SetTargets(cp)
}
s.reconcileMouseHookLocked()
}
// SetFilterRules replaces the active declarative input filters and installs or
// uninstalls the low-level mouse hook on demand (§5.4).
func (s *InputService) SetFilterRules(rules []InputFilterRule) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return
}
cp := append([]InputFilterRule(nil), rules...)
s.rules.Store(&cp)
s.reconcileMouseHookLocked()
}
// IsKeyboardHookInstalled reports whether the IME keyboard hook is active.
func (s *InputService) IsKeyboardHookInstalled() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.imeBridge != nil
}
// IsMouseHookInstalled reports whether the on-demand mouse wheel hook is active.
func (s *InputService) IsMouseHookInstalled() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.mouseHook != nil
}
func (s *InputService) reconcileMouseHookLocked() {
rulesPtr := s.rules.Load()
var rules []InputFilterRule
if rulesPtr != nil {
rules = *rulesPtr
}
need := hasMatchingWheelTarget(rules, s.targets)
if need && s.mouseHook == nil {
if mh, err := startMouseWheelHook(s); err == nil {
s.mouseHook = mh
}
} else if !need && s.mouseHook != nil {
s.mouseHook.Close()
s.mouseHook = nil
}
}
// Close tears down both keyboard and mouse hooks cleanly with zero residue.
func (s *InputService) Close() {
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return
}
s.closed = true
ib := s.imeBridge
mh := s.mouseHook
s.imeBridge = nil
s.mouseHook = nil
s.mu.Unlock()
if ib != nil {
ib.Close()
}
if mh != nil {
mh.Close()
}
}
+11
View File
@@ -0,0 +1,11 @@
//go:build !windows
package host
type mouseWheelHook struct{}
func startMouseWheelHook(_ *InputService) (*mouseWheelHook, error) {
return &mouseWheelHook{}, nil
}
func (h *mouseWheelHook) Close() {}
+59
View File
@@ -0,0 +1,59 @@
package host
import "testing"
func TestEvalWheelFilterAndOnDemandLifecycle(t *testing.T) {
rules := []InputFilterRule{{
ID: "wheel-invert",
PluginID: "reims.input.wheel-invert",
Event: "mouse_wheel",
Axis: "vertical",
Transform: "invert",
Scope: "vm_foreground",
VMNames: map[string]bool{"mac1": true},
Vertical: true,
Horizontal: false,
}}
// Matching VM + vertical axis -> inverted.
if d, ok := EvalWheelFilter(rules, "mac1", false, 120); !ok || d != -120 {
t.Fatalf("vertical mac1 = (%d, %v), want (-120, true)", d, ok)
}
// Non-matching horizontal axis -> untouched.
if d, ok := EvalWheelFilter(rules, "mac1", true, 120); ok || d != 120 {
t.Fatalf("horizontal mac1 = (%d, %v), want (120, false)", d, ok)
}
// Non-matching VM -> untouched.
if d, ok := EvalWheelFilter(rules, "mac2", false, 120); ok || d != 120 {
t.Fatalf("vertical mac2 = (%d, %v), want (120, false)", d, ok)
}
// Overflow guard for -32768.
if d, ok := EvalWheelFilter(rules, "mac1", false, -32768); !ok || d != 32767 {
t.Fatalf("overflow guard = (%d, %v), want (32767, true)", d, ok)
}
// On-demand hook lifecycle: no hook installed until BOTH rule AND matching target exist.
svc := NewInputService(nil)
defer svc.Close()
if svc.IsMouseHookInstalled() {
t.Fatal("mouse hook must NOT be installed when no rules exist")
}
svc.SetFilterRules(rules)
if svc.IsMouseHookInstalled() {
t.Fatal("mouse hook must NOT be installed when no matching VM is running")
}
svc.SetTargets([]IMETarget{{PID: 1234, VMName: "mac2"}})
if svc.IsMouseHookInstalled() {
t.Fatal("mouse hook must NOT be installed when running VM does not match rule")
}
svc.SetTargets([]IMETarget{{PID: 1234, VMName: "mac1"}})
if !svc.IsMouseHookInstalled() {
t.Fatal("mouse hook SHOULD be installed when matching VM is running")
}
// Disable plugin (clear rules) -> hook immediately uninstalled.
svc.SetFilterRules(nil)
if svc.IsMouseHookInstalled() {
t.Fatal("mouse hook MUST be uninstalled when filter rules are cleared")
}
}
+202
View File
@@ -0,0 +1,202 @@
//go:build windows
package host
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"syscall"
"unsafe"
)
const (
whMouseLL = 14
wmMouseWheel = 0x020A
wmMouseHWheel = 0x020E
inputMouse = 0
mouseEventfWheel = 0x0800
mouseEventfHWheel = 0x01000
llmhfInjected = 0x00000001
gaRoot = 2
// reimsInjectedInputMagic tags re-emitted wheel events so the hook ignores
// its own inverted events and never loops (§5.4).
reimsInjectedInputMagic uintptr = 0x5245494D // "REIM"
)
var (
procSendInput = user32.NewProc("SendInput")
procWindowFromPoint = user32.NewProc("WindowFromPoint")
procGetAncestor = user32.NewProc("GetAncestor")
activeMouseInputService atomic.Pointer[InputService]
mouseHookCBOnce sync.Once
mouseHookCB uintptr
)
type point struct {
X int32
Y int32
}
type msLLHookStruct struct {
pt point
mouseData uint32
flags uint32
time uint32
dwExtraInfo uintptr
}
// winMouseInput mirrors Win32 INPUT for INPUT_MOUSE on amd64 (40 bytes total).
type winMouseInput struct {
inputType uint32
_pad uint32
dx int32
dy int32
mouseData uint32
dwFlags uint32
time uint32
_pad2 uint32
dwExtraInfo uintptr
}
func getMouseHookCallback() uintptr {
mouseHookCBOnce.Do(func() {
mouseHookCB = syscall.NewCallback(mouseLowLevelProc)
})
return mouseHookCB
}
func mouseLowLevelProc(nCode int32, wParam uintptr, ms *msLLHookStruct) uintptr {
if nCode == hcAction && ms != nil && (wParam == wmMouseWheel || wParam == wmMouseHWheel) {
// Pass through our own injected events without recursion.
if !((ms.flags&llmhfInjected) != 0 && ms.dwExtraInfo == reimsInjectedInputMagic) {
if svc := activeMouseInputService.Load(); svc != nil {
if target, ok := svc.matchTargetAtPoint(ms.pt); ok {
delta := int16(ms.mouseData >> 16)
horizontal := wParam == wmMouseHWheel
rulesPtr := svc.rules.Load()
if rulesPtr != nil {
if newDelta, transformed := EvalWheelFilter(*rulesPtr, target.VMName, horizontal, delta); transformed {
if injectWheelEvent(horizontal, newDelta) {
return 1
}
}
}
}
}
}
}
r, _, _ := procCallNextHookEx.Call(0, uintptr(nCode), wParam, uintptr(unsafe.Pointer(ms)))
return r
}
func injectWheelEvent(horizontal bool, delta int16) bool {
flags := uint32(mouseEventfWheel)
if horizontal {
flags = mouseEventfHWheel
}
in := winMouseInput{
inputType: inputMouse,
mouseData: uint32(int32(delta)),
dwFlags: flags,
dwExtraInfo: reimsInjectedInputMagic,
}
r, _, _ := procSendInput.Call(1, uintptr(unsafe.Pointer(&in)), unsafe.Sizeof(in))
return r == 1
}
func (s *InputService) matchTargetAtPoint(pt point) (IMETarget, bool) {
m := s.targetByPID.Load()
if m == nil || len(*m) == 0 {
return IMETarget{}, false
}
var hwnd uintptr
if unsafe.Sizeof(uintptr(0)) == 8 {
packed := uintptr(uint32(pt.X)) | (uintptr(uint32(pt.Y)) << 32)
hwnd, _, _ = procWindowFromPoint.Call(packed)
if hwnd != 0 {
if root, _, _ := procGetAncestor.Call(hwnd, gaRoot); root != 0 {
hwnd = root
}
}
}
if hwnd == 0 {
hwnd, _, _ = procGetForegroundWindow.Call()
}
if hwnd == 0 {
return IMETarget{}, false
}
var pid uint32
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
if pid == 0 {
return IMETarget{}, false
}
t, ok := (*m)[pid]
return t, ok
}
type mouseWheelHook struct {
svc *InputService
threadID uint32
done chan struct{}
closeOnce sync.Once
}
func startMouseWheelHook(svc *InputService) (*mouseWheelHook, error) {
h := &mouseWheelHook{
svc: svc,
done: make(chan struct{}),
}
activeMouseInputService.Store(svc)
ready := make(chan error, 1)
go h.hookThread(ready)
if err := <-ready; err != nil {
activeMouseInputService.CompareAndSwap(svc, nil)
return nil, err
}
return h, nil
}
func (h *mouseWheelHook) hookThread(ready chan<- error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer close(h.done)
tid, _, _ := procGetCurrentThreadId.Call()
h.threadID = uint32(tid)
var msg winMsg
_, _, _ = procPeekMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, pmNoRemove)
hMod, _, _ := procGetModuleHandleW.Call(0)
hhook, _, err := procSetWindowsHookExW.Call(whMouseLL, getMouseHookCallback(), hMod, 0)
if hhook == 0 {
ready <- fmt.Errorf("SetWindowsHookExW(WH_MOUSE_LL): %w", err)
return
}
defer procUnhookWindowsHookEx.Call(hhook)
ready <- nil
for {
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(ret) <= 0 {
return
}
}
}
func (h *mouseWheelHook) Close() {
if h == nil {
return
}
h.closeOnce.Do(func() {
activeMouseInputService.CompareAndSwap(h.svc, nil)
if h.threadID != 0 {
_, _, _ = procPostThreadMessageW.Call(uintptr(h.threadID), wmQuit, 0, 0)
}
<-h.done
})
}
+187
View File
@@ -0,0 +1,187 @@
package plugin
import (
"bytes"
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"encoding/xml"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strings"
)
// AssetServer serves static assets for installed/linked plugins over a
// per-run random token prefix: `/plugin-assets/<runToken>/<pluginID>/<relPath>`
// with path-traversal protection, nosniff, strict CSP, and SVG script blocking (§7.3).
type AssetServer struct {
token string
lookup func(pluginID string) (installDir string, ok bool)
}
// NewAssetServer constructs a plugin static asset handler with a fresh 128-bit run token.
func NewAssetServer(lookup func(pluginID string) (string, bool)) *AssetServer {
var raw [16]byte
_, _ = rand.Read(raw[:])
return &AssetServer{
token: hex.EncodeToString(raw[:]),
lookup: lookup,
}
}
// Token returns the per-run random URL token.
func (a *AssetServer) Token() string { return a.token }
// AssetURL returns the safe URL for relPath inside pluginID.
func (a *AssetServer) AssetURL(pluginID, relPath string) string {
rel := strings.TrimPrefix(filepath.ToSlash(filepath.Clean(relPath)), "/")
return "/plugin-assets/" + a.token + "/" + pluginID + "/" + rel
}
// Prefix returns the route prefix handled by this AssetServer.
func (a *AssetServer) Prefix() string { return "/plugin-assets/" }
// ServeHTTP serves `/plugin-assets/<token>/<pluginID>/<relPath>` with strict security headers.
func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
trimmed := strings.TrimPrefix(r.URL.Path, "/plugin-assets/")
parts := strings.SplitN(trimmed, "/", 3)
if len(parts) < 3 || subtle.ConstantTimeCompare([]byte(parts[0]), []byte(a.token)) != 1 {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
pluginID, relPath := parts[1], parts[2]
if strings.Contains(relPath, "..") || strings.ContainsRune(relPath, '\\') {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
if a.lookup == nil {
http.NotFound(w, r)
return
}
rootDir, ok := a.lookup(pluginID)
if !ok || rootDir == "" {
http.NotFound(w, r)
return
}
fullPath, err := safeJoin(rootDir, relPath)
if err != nil {
http.Error(w, "forbidden path", http.StatusForbidden)
return
}
info, err := os.Stat(fullPath)
if err != nil || info.IsDir() {
http.NotFound(w, r)
return
}
data, err := os.ReadFile(fullPath)
if err != nil {
http.Error(w, "read error", http.StatusInternalServerError)
return
}
ext := strings.ToLower(filepath.Ext(fullPath))
ct := mime.TypeByExtension(ext)
if ct == "" {
ct = "application/octet-stream"
}
// Hardening headers (§7.3).
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "no-store")
if ext == ".html" || ext == ".htm" {
// Sandboxed L4 iframe panel CSP: no external network connections (§7.3).
w.Header().Set("Content-Security-Policy", "default-src 'self' 'unsafe-inline'; connect-src 'none'; img-src 'self' data:; font-src 'self'; object-src 'none'; base-uri 'none'")
} else {
w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; font-src 'self'; sandbox")
}
// Strip any embedded script/event handlers from SVG assets (§7.3).
if ext == ".svg" {
ct = "image/svg+xml; charset=utf-8"
data = SanitizeSVG(data)
}
// Verify CSS files remain safe (including relative asset containment, B5).
if ext == ".css" {
if err := ValidateThemeCSSSafetyInDir(string(data), filepath.Dir(fullPath)); err != nil {
http.Error(w, "unsafe stylesheet blocked", http.StatusForbidden)
return
}
}
w.Header().Set("Content-Type", ct)
w.WriteHeader(http.StatusOK)
if r.Method == http.MethodGet {
_, _ = w.Write(data)
}
}
// SanitizeSVG parses SVG XML and strips <script>/<foreignObject> subtrees,
// inline on* event attributes, and dangerous URI schemes (javascript:/vbscript:/data:text/html) (§7.3).
func SanitizeSVG(raw []byte) []byte {
dec := xml.NewDecoder(bytes.NewReader(raw))
var out bytes.Buffer
enc := xml.NewEncoder(&out)
skipDepth := 0
for {
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
// Malformed XML: fail closed rather than passing raw markup through.
return nil
}
switch t := tok.(type) {
case xml.StartElement:
local := strings.ToLower(t.Name.Local)
if skipDepth > 0 || local == "script" || local == "foreignobject" {
skipDepth++
continue
}
filtered := make([]xml.Attr, 0, len(t.Attr))
for _, attr := range t.Attr {
name := strings.ToLower(attr.Name.Local)
if strings.HasPrefix(name, "on") {
continue
}
val := strings.ToLower(strings.TrimSpace(attr.Value))
if name == "href" || name == "values" || name == "from" || name == "to" || name == "by" {
if strings.HasPrefix(val, "javascript:") || strings.HasPrefix(val, "vbscript:") || strings.HasPrefix(val, "data:text/html") || strings.Contains(val, "javascript:") {
continue
}
}
filtered = append(filtered, attr)
}
t.Attr = filtered
if err := enc.EncodeToken(t); err != nil {
return nil
}
case xml.EndElement:
if skipDepth > 0 {
skipDepth--
continue
}
if err := enc.EncodeToken(t); err != nil {
return nil
}
default:
if skipDepth > 0 {
continue
}
if err := enc.EncodeToken(tok); err != nil {
return nil
}
}
}
if err := enc.Flush(); err != nil {
return nil
}
return out.Bytes()
}
+210
View File
@@ -0,0 +1,210 @@
package plugin
import (
"archive/zip"
"context"
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestSemVerRejectsPathTraversal(t *testing.T) {
bad := []string{
"1.0.0-a/../../../x",
"1.0.0+a/../b",
"1.0.0-a\\b",
"1.0.0-a..b",
"1.0.0-",
"1.0.0+",
"1.0.0-alpha beta",
"1.0.0-../evil",
}
for _, v := range bad {
if _, err := ParseSemVer(v); err == nil {
t.Errorf("ParseSemVer(%q) expected error, got nil", v)
}
}
good := []string{"1.0.0", "v0.2.6", "1.2.3-alpha.1", "1.2.3-rc-1+build.42"}
for _, v := range good {
if _, err := ParseSemVer(v); err != nil {
t.Errorf("ParseSemVer(%q) unexpected error: %v", v, err)
}
}
}
func TestInstallArchiveRejectsTraversalVersion(t *testing.T) {
tmp := t.TempDir()
zipPath := filepath.Join(tmp, "evil.zip")
manifest := `{"schema":1,"id":"evil.pkg","version":"1.0.0-a/../../../escaped","name":{"en-US":"Evil"}}`
sum := sha256.Sum256([]byte(manifest))
sums := hex.EncodeToString(sum[:]) + " plugin.json\n"
f, err := os.Create(zipPath)
if err != nil {
t.Fatal(err)
}
zw := zip.NewWriter(f)
for name, body := range map[string]string{"plugin.json": manifest, "SHA256SUMS": sums} {
w, err := zw.Create(name)
if err != nil {
t.Fatal(err)
}
if _, err := w.Write([]byte(body)); err != nil {
t.Fatal(err)
}
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
_ = f.Close()
layout := NewPluginsLayout(tmp)
_, err = InstallArchive(layout, zipPath, PackageInstallOptions{HostVersion: "0.3.0", AllowUnsigned: true})
if err == nil {
t.Fatal("expected InstallArchive to reject traversal version")
}
}
func TestValidateArgFragmentBlocksInjection(t *testing.T) {
bad := [][]string{
{"-device", "x -smbios type=1,serial=SECRET"},
{"-device", `"x" -smbios type=1`},
{"-device", "x\n-smbios"},
{"-drive", "file=a.img -smbios type=1"},
{"positional", "-no-reboot"},
{"-no-reboot", "extra"},
{"-smbios", "type=1"},
{"-device", `"unterminated`},
}
for _, toks := range bad {
if err := ValidateArgFragment(ArgFragment{Tokens: toks}); err == nil {
t.Errorf("ValidateArgFragment(%q) expected error, got nil", toks)
}
}
good := [][]string{
{"-machine", "kernel-irqchip=off"},
{"-no-reboot", "-qmp", "unix:D:/Data/reims-go-reboot.sock,server=on,wait=off"},
{"-drive", `"id=reimshelp,if=none,format=raw,readonly=on,file=D:/My VMs/reimshelp.img"`, "-device", "usb-storage,id=reimshelp-dev,drive=reimshelp,bus=xhci.0"},
}
for _, toks := range good {
if err := ValidateArgFragment(ArgFragment{Tokens: toks}); err != nil {
t.Errorf("ValidateArgFragment(%q) unexpected error: %v", toks, err)
}
}
}
func TestBuiltinBeforeStartExemptFromExternalTimeout(t *testing.T) {
reg := NewRegistry(nil)
var completed bool
if err := reg.Register(PluginDef{
Manifest: Manifest{
Schema: 1, ID: "builtin.slow.prep", Version: "1.0.0",
Name: LocalizedText{EnUS: "Slow Builtin"},
},
Source: SourceBuiltin, Trust: TrustOfficial, Desired: true,
Activate: func(_ context.Context, sc *Scope) error {
sc.Registry().Hooks().Subscribe(sc, HookRegistration{
Event: EventVMBeforeStart,
Builtin: true,
Handler: func(ctx context.Context, _ any) (any, error) {
// Longer than the 2s external plugin timeout.
select {
case <-time.After(2200 * time.Millisecond):
completed = true
return StartIntent{
PluginID: "builtin.slow.prep",
Args: []ArgFragment{{Key: "k", Tokens: []string{"-machine", "kernel-irqchip=off"}, Builtin: true}},
}, nil
case <-ctx.Done():
return nil, ctx.Err()
}
},
})
return nil
},
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(context.Background())
intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), BeforeStartPayload{VMName: "test"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !completed || len(intents) != 1 {
t.Fatalf("builtin prep hook did not finish synchronously: completed=%v intents=%d", completed, len(intents))
}
if st := reg.StateOf("builtin.slow.prep"); st != StateActive {
t.Fatalf("builtin state = %s, want active", st)
}
}
func TestValidateThemeCSSAndContributionBlocksBypasses(t *testing.T) {
badCSS := []struct {
name string
css string
}{
{"css-escaped-url", `.rg-p-shell { background: u\72l("https://evil.test/x.png"); }`},
{"escaped-scheme", `.rg-p-shell { background: url("\68ttps://evil.test/x.png"); }`},
{"image-set-remote", `.rg-p-shell { background-image: image-set("https://evil.test/a.png" 1x); }`},
{"data-svg", `.rg-p-shell { background: url("data:image/svg+xml,<svg onload=alert(1)>"); }`},
{"data-html", `.rg-p-shell { background: url("data:text/html,<script>alert(1)</script>"); }`},
{"escaped-import", `@\69mport "https://evil.test/x.css";`},
{"unbalanced-close", `.rg-p-shell { color: red; } } .evil { display: none; }`},
{"unbalanced-open", `.rg-p-shell { color: red;`},
{"expression", `.rg-p-shell { width: expression(alert(1)); }`},
{"style-tag-breakout", `.rg-p-shell { content: "</style><script>alert(1)</script>"; }`},
{"traversal-url", `.rg-p-shell { background: url("../../secret.png"); }`},
}
for _, tc := range badCSS {
if err := ValidateThemeCSSSafety(tc.css); err == nil {
t.Errorf("ValidateThemeCSSSafety(%s) expected error, got nil", tc.name)
}
}
// Verify asset containment when rootDir is provided.
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "assets"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "assets", "bg.png"), []byte("png"), 0o644); err != nil {
t.Fatal(err)
}
if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/bg.png"); }`, dir); err != nil {
t.Errorf("valid local asset rejected: %v", err)
}
if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/missing.png"); }`, dir); err == nil {
t.Error("missing local asset should be rejected")
}
// Verify token & font injection checks.
badTokens := []ThemeContribution{
{ID: "t1", Tokens: map[string]string{"--accent": "red; } .evil { color: blue"}},
{ID: "t2", Tokens: map[string]string{"--accent": `u\72l(https://evil.test/x)`}},
{ID: "t3", Tokens: map[string]string{"not-a-var": "red"}},
{ID: "t4", Background: "https://evil.test/bg.png"},
{ID: "t5", Fonts: []ThemeFont{{Family: `Evil"; } body { display:none`, File: "assets/bg.png"}}},
}
for _, th := range badTokens {
if err := ValidateThemeContribution(th, dir); err == nil {
t.Errorf("ValidateThemeContribution(%s) expected error, got nil", th.ID)
}
}
goodTheme := ThemeContribution{
ID: "ok",
Tokens: map[string]string{"--accent": "#d97757"},
Background: "assets/bg.png",
Fonts: []ThemeFont{{Family: "CustomSans", File: "assets/bg.png", Weight: "400 700", Style: "normal"}},
}
if err := ValidateThemeContribution(goodTheme, dir); err != nil {
t.Errorf("valid theme rejected: %v", err)
}
if !strings.Contains(goodTheme.Background, "assets/") {
t.Fatal("sanity")
}
}
+311
View File
@@ -0,0 +1,311 @@
package plugin
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
)
const maxPluginLogBytes = 2 << 20 // 2 MiB log rotation threshold (§6.1)
// ManagedProcess represents a host-spawned VM process requested by an L3 driver
// so the VM process lives OUTSIDE the Sidecar's Job Object (§5.3).
type ManagedProcess struct {
PID int
PluginID string
VMName string
cmd *exec.Cmd
done chan struct{}
}
// Broker mediates all Host API calls from plugins (L3 Sidecar, L4 iframe bridge):
// permission checking, sensitive field redaction, per-plugin rate limiting,
// rotating audit log, and host-managed process launching (§3.1, §5.3, §7).
type Broker struct {
mu sync.Mutex
layout PluginsLayout
reg *Registry
redactFn func(string) string
// Rate limiting: sliding window counter per plugin.
rates map[string]*rateWindow
// Managed VM processes spawned on behalf of drivers (decoupled from Sidecar Job Object).
procs map[int]*ManagedProcess
onNotify func(pluginID, title, body string)
}
type rateWindow struct {
windowStart time.Time
count int
}
func NewBroker(layout PluginsLayout, reg *Registry, redactFn func(string) string) *Broker {
if redactFn == nil {
redactFn = func(s string) string { return s }
}
return &Broker{
layout: layout,
reg: reg,
redactFn: redactFn,
rates: make(map[string]*rateWindow),
procs: make(map[int]*ManagedProcess),
}
}
func (b *Broker) SetNotifier(fn func(pluginID, title, body string)) {
b.mu.Lock()
b.onNotify = fn
b.mu.Unlock()
}
// Authorize verifies that pluginID is active, holds perm (and has approved it
// when medium/high risk), and is within its rate limit (§7.1, §7.3).
func (b *Broker) Authorize(pluginID, perm string) error {
if ClassifyPermission(perm) == PermForbidden {
b.Audit(pluginID, "DENY", fmt.Sprintf("forbidden permission %q", perm))
return fmt.Errorf("permission %q does not exist or is forbidden", perm)
}
if b.reg == nil {
return errors.New("registry unavailable")
}
info, ok := b.reg.Info(pluginID)
if !ok {
return fmt.Errorf("unknown plugin %q", pluginID)
}
if info.State != StateActive && info.State != StateDegraded {
return fmt.Errorf("plugin %q is not active (state=%s)", pluginID, info.State)
}
if info.NeedsApproval {
b.Audit(pluginID, "DENY", fmt.Sprintf("unapproved plugin attempted %q", perm))
return fmt.Errorf("plugin %q requires high-risk permission approval", pluginID)
}
declared := false
for _, p := range info.Permissions {
if p.Name == perm {
declared = true
break
}
}
if !declared {
b.Audit(pluginID, "DENY", fmt.Sprintf("undeclared permission %q", perm))
return fmt.Errorf("plugin %q lacks permission %q", pluginID, perm)
}
if ClassifyPermission(perm) == PermHigh && info.Trust != TrustOfficial && info.Source != SourceBuiltin {
approved := false
for _, ap := range info.ApprovedPermissions {
if ap == perm {
approved = true
break
}
}
if !approved {
b.Audit(pluginID, "DENY", fmt.Sprintf("unapproved high-risk permission %q", perm))
return fmt.Errorf("plugin %q has not approved high-risk permission %q", pluginID, perm)
}
}
// Rate limit: max 120 Host API calls / second per plugin.
if !b.allowRate(pluginID, 120) {
b.Audit(pluginID, "RATE_LIMIT", perm)
return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID)
}
return nil
}
func (b *Broker) allowRate(pluginID string, limitPerSec int) bool {
b.mu.Lock()
defer b.mu.Unlock()
now := time.Now()
rw := b.rates[pluginID]
if rw == nil || now.Sub(rw.windowStart) >= time.Second {
b.rates[pluginID] = &rateWindow{windowStart: now, count: 1}
return true
}
if rw.count >= limitPerSec {
return false
}
rw.count++
return true
}
// Audit appends a redacted audit or stderr line to `<DataRoot>/plugins/logs/<id>.log`
// with automatic rotation at 2 MiB (§6.1).
func (b *Broker) Audit(pluginID, tag, msg string) {
if b == nil || b.layout.Root == "" || pluginID == "" {
return
}
if strings.ContainsAny(pluginID, `/\`) || strings.Contains(pluginID, "..") {
return
}
trimmed := strings.TrimSpace(msg)
if len(trimmed) > 4096 {
trimmed = trimmed[:4096] + "…"
}
safeMsg := b.redactFn(trimmed)
line := fmt.Sprintf("%s [%s] %s\n", time.Now().UTC().Format(time.RFC3339), tag, safeMsg)
b.mu.Lock()
defer b.mu.Unlock()
if err := os.MkdirAll(b.layout.LogsDir(), 0o755); err != nil {
return
}
logPath := b.layout.LogPath(pluginID)
if info, err := os.Stat(logPath); err == nil && info.Size() >= maxPluginLogBytes {
_ = os.Rename(logPath, logPath+".1")
}
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return
}
_, _ = f.WriteString(line)
_ = f.Close()
}
// StripSensitiveFields returns a copy of m with forbidden/sensitive keys removed (§1.2, §7.1).
func StripSensitiveFields(m map[string]any) map[string]any {
if m == nil {
return nil
}
blocked := map[string]bool{
"serial": true, "serial_number": true, "mlb": true, "uuid": true,
"rom": true, "mac": true, "mac_address": true, "osk": true,
"token": true, "bearer": true,
}
out := make(map[string]any, len(m))
for k, v := range m {
if blocked[strings.ToLower(k)] {
continue
}
if sub, ok := v.(map[string]any); ok {
out[k] = StripSensitiveFields(sub)
} else {
out[k] = v
}
}
return out
}
// Notify emits a host notification on behalf of a plugin with `ui:notify`.
func (b *Broker) Notify(pluginID, title, body string) error {
if err := b.Authorize(pluginID, "ui:notify"); err != nil {
return err
}
b.Audit(pluginID, "NOTIFY", title+": "+body)
b.mu.Lock()
fn := b.onNotify
b.mu.Unlock()
if fn != nil {
fn(pluginID, b.redactFn(title), b.redactFn(body))
}
return nil
}
// SpawnManagedVMProcess spawns an external VM executable (e.g. qemu-system-x86_64)
// owned by the HOST rather than the Sidecar's Job Object, so Sidecar crashes or
// restarts never kill running VMs (§5.3).
func (b *Broker) SpawnManagedVMProcess(ctx context.Context, pluginID, vmName, exePath string, args []string, workDir string, env []string) (int, error) {
if err := b.Authorize(pluginID, "process:spawn"); err != nil {
return 0, err
}
if err := ctx.Err(); err != nil {
return 0, err
}
if strings.TrimSpace(exePath) == "" {
return 0, errors.New("executable path required")
}
// Ensure executable path exists and is a regular file.
st, err := os.Stat(exePath)
if err != nil {
return 0, fmt.Errorf("executable not found: %w", err)
}
if st.IsDir() {
return 0, errors.New("executable path must be a file, not a directory")
}
cmd := exec.Command(exePath, args...)
if workDir != "" {
cmd.Dir = workDir
}
if len(env) > 0 {
cmd.Env = append(os.Environ(), env...)
}
configureDetachedVMProcess(cmd)
if err := cmd.Start(); err != nil {
b.Audit(pluginID, "SPAWN_ERR", fmt.Sprintf("vm=%s exe=%s err=%v", vmName, filepath.Base(exePath), err))
return 0, err
}
pid := cmd.Process.Pid
mp := &ManagedProcess{
PID: pid,
PluginID: pluginID,
VMName: vmName,
cmd: cmd,
done: make(chan struct{}),
}
b.mu.Lock()
b.procs[pid] = mp
b.mu.Unlock()
b.Audit(pluginID, "SPAWN", fmt.Sprintf("vm=%s pid=%d exe=%s", vmName, pid, filepath.Base(exePath)))
go func() {
_ = cmd.Wait()
close(mp.done)
b.mu.Lock()
delete(b.procs, pid)
b.mu.Unlock()
b.Audit(pluginID, "EXIT", fmt.Sprintf("vm=%s pid=%d", vmName, pid))
}()
return pid, nil
}
// StopManagedVMProcess terminates a host-managed VM process by PID.
func (b *Broker) StopManagedVMProcess(pluginID string, pid int) error {
if err := b.Authorize(pluginID, "vm:control"); err != nil {
return err
}
b.mu.Lock()
mp := b.procs[pid]
b.mu.Unlock()
if mp == nil || mp.cmd == nil || mp.cmd.Process == nil {
return nil
}
if mp.PluginID != pluginID {
return fmt.Errorf("PID %d is not owned by plugin %q", pid, pluginID)
}
return mp.cmd.Process.Kill()
}
// IsManagedProcessRunning reports whether pid is still alive in the broker.
func (b *Broker) IsManagedProcessRunning(pid int) bool {
b.mu.Lock()
mp := b.procs[pid]
b.mu.Unlock()
if mp == nil {
return false
}
select {
case <-mp.done:
return false
default:
return true
}
}
// IsManagedProcessRunningForPlugin reports whether pid is owned by pluginID and alive.
func (b *Broker) IsManagedProcessRunningForPlugin(pluginID string, pid int) bool {
b.mu.Lock()
mp := b.procs[pid]
b.mu.Unlock()
if mp == nil || mp.PluginID != pluginID {
return false
}
select {
case <-mp.done:
return false
default:
return true
}
}
+762
View File
@@ -0,0 +1,762 @@
// Package builtin registers compiled-in Reims-Go extensions onto the unified
// plugin Registry (docs/plugin-architecture.md §3.2, §5.4). Every builtin
// extension runs through the same reversible Scope, service dependency graph,
// and HookBus as external plugins so disabling any extension leaves zero residue.
package builtin
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/opencore"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// Builtin plugin IDs (§3.2, §5.4).
const (
IDThemeDefault = "builtin.theme.default"
IDDriverReimsMacOS = driver.BuiltinReimsMacOSDriverID
IDGuestTools = "builtin.bridge.guest-tools"
IDClipboard = "builtin.bridge.clipboard"
IDInput = "builtin.input"
IDWin10ColdReboot = "builtin.compat.win10-cold-reboot"
IDWHPXFallback = "builtin.compat.whpx-fallback"
IDOfflineHelper = "builtin.prep.offline-helper"
IDRecoveryBoot = "builtin.prep.recovery-boot"
IDGuestLang = "builtin.prep.guest-lang"
)
// Service names provided by builtin extensions.
const (
ServiceGuestToolsTransport = "guest-tools.transport"
ServiceHostInput = "host.input"
)
// HostCallbacks connects builtin extensions to host runtime services without
// creating an import cycle with internal/app.
type HostCallbacks struct {
GetConfig func() config.Config
Log func(source, line string)
EnsureGuestTools func() (*guesttools.Server, int, error)
OnIMEText func(target host.IMETarget, text string)
StartColdReboot func(vmName, qmpAddr string)
CancelColdReboot func(vmName string)
VMSharedDir func(vmName string) string
GuestToolsImg func(vmName string) string
// GetSetting returns a saved plugin setting value (empty vmName = app scope).
GetSetting func(pluginID, vmName, key string) (any, bool)
}
func appVersion() string {
v := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
if v == "" || v == "dev" {
return "0.2.6"
}
return v
}
// RegisterAll registers all Phase 0 builtin extensions into reg.
// desiredFn optionally overrides defaultEnabled (e.g. from state.json).
func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id string, defaultEnabled bool) bool) error {
if desiredFn == nil {
desiredFn = func(_ string, def bool) bool { return def }
}
ver := appVersion()
defs := []plugin.PluginDef{
defThemeDefault(ver, desiredFn),
defDriverReimsMacOS(ver, cb, desiredFn),
defGuestTools(ver, cb, desiredFn),
defClipboard(ver, cb, desiredFn),
defInput(ver, cb, desiredFn),
defWin10ColdReboot(ver, cb, desiredFn),
defWHPXFallback(ver, cb, desiredFn),
defOfflineHelper(ver, cb, desiredFn),
defRecoveryBoot(ver, cb, desiredFn),
defGuestLang(ver, cb, desiredFn),
}
for _, d := range defs {
if err := reg.Register(d); err != nil {
return err
}
}
return nil
}
func defThemeDefault(ver string, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDThemeDefault,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "默认浅色 / 深色主题", EnUS: "Default Light / Dark Theme"},
Description: plugin.LocalizedText{
ZhCN: "内置 macOS Tahoe 风格浅色与深色主题,零额外样式注入",
EnUS: "Built-in macOS Tahoe light and dark themes with zero extra CSS overhead",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
DefaultEnabled: true,
Contributes: plugin.Contributes{
Themes: []plugin.ThemeContribution{{
ID: IDThemeDefault,
Name: plugin.LocalizedText{ZhCN: "默认主题", EnUS: "Default"},
Appearance: "both",
}},
},
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDThemeDefault, true),
}
}
func defDriverReimsMacOS(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDDriverReimsMacOS,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "macOS 虚拟机驱动 (Reims vGPU)", EnUS: "macOS VM Driver (Reims vGPU)"},
Description: plugin.LocalizedText{
ZhCN: "内置 reims-ctl / reims-vgpu macOS 虚拟机驱动,支持 Metal Vulkan 加速、OpenCore 与快照",
EnUS: "Built-in reims-ctl / reims-vgpu macOS VM driver with Metal-to-Vulkan acceleration, OpenCore, and snapshots",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"driver:vm", "vm:control", "qmp:write"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDDriverReimsMacOS, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
drv := driver.NewReimsMacOSDriver(cb.GetConfig)
sc.Registry().RegisterGuestDriver(sc, IDDriverReimsMacOS, drv)
return nil
},
}
}
func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDGuestTools,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "Guest Tools 传输服务", EnUS: "Guest Tools Transport"},
Description: plugin.LocalizedText{
ZhCN: "提供本地回环鉴权宿客传输通道、REIMSTOOLS 辅助盘挂载、共享目录与防休眠支持",
EnUS: "Provides localhost token-authenticated host-guest transport, REIMSTOOLS helper disk, shared folders, and prevent-sleep",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Provides: []plugin.ServiceProvision{{Service: ServiceGuestToolsTransport, Version: "1.0.0"}},
Permissions: []string{"vm:intent", "fs:shared", "ui:slot"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDGuestTools, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
var srv *guesttools.Server
if cb.EnsureGuestTools != nil {
s, _, err := cb.EnsureGuestTools()
if err != nil {
return err
}
srv = s
} else {
srv = guesttools.NewTransportServer(nil)
}
sc.Provide(ServiceGuestToolsTransport, "1.0.0", srv)
sc.Registry().RegisterVMCard(sc, plugin.VMCardContribution{
ID: "guest-tools-transport",
Title: plugin.LocalizedText{ZhCN: "宿客协作通道", EnUS: "Guest Tools Bridge"},
Value: plugin.LocalizedText{ZhCN: "已就绪", EnUS: "Ready"},
Badge: "ok",
When: "capability:guest_tools",
})
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
if cb.EnsureGuestTools == nil {
return nil, nil
}
s, port, err := cb.EnsureGuestTools()
if err != nil || port <= 0 {
return nil, nil
}
sharedDir := ""
if cb.VMSharedDir != nil {
sharedDir = cb.VMSharedDir(p.VMName)
}
intent := plugin.StartIntent{
PluginID: IDGuestTools,
Env: map[string]string{},
}
gtCfg, err := guesttools.LoadOrCreateVMConfig(p.VMDir, p.VMName, sharedDir, port)
if err == nil && gtCfg.Token != "" {
s.RegisterVM(gtCfg)
intent.Env["REIMS_GO_INPUT_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-text", port)
intent.Env["REIMS_GO_INPUT_TOKEN"] = gtCfg.Token
}
if reims.HasGuestToolsArgs(p.ExtraArgs) && cb.GuestToolsImg != nil && err == nil {
imgPath := cb.GuestToolsImg(p.VMName)
if bErr := guesttools.BuildToolsDiskImage(imgPath, gtCfg); bErr == nil {
tokens := plugin.SplitShellTokens(reims.MergeGuestToolsArgs("", imgPath))
intent.Args = append(intent.Args, plugin.ArgFragment{
PluginID: IDGuestTools,
Key: "reimstools",
Tokens: tokens,
Builtin: true,
Priority: 80,
})
} else {
intent.Warnings = append(intent.Warnings, "guest tools image skipped: "+bErr.Error())
}
} else if !reims.HasGuestToolsArgs(p.ExtraArgs) {
intent.ClearKeys = append(intent.ClearKeys, "reimstools")
}
return intent, nil
},
})
return nil
},
}
}
func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
minMB := 1.0
maxMB := 16.0
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDClipboard,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Description: plugin.LocalizedText{
ZhCN: "在 Windows 宿主与 macOS 虚拟机之间同步文本与截图;支持按方向与大小限制即时开关",
EnUS: "Sync text and screenshots between Windows host and macOS VMs with per-VM direction and size controls",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Requires: []plugin.ServiceRequirement{{Service: ServiceGuestToolsTransport, Version: "^1.0.0"}},
Permissions: []string{"host:clipboard", "ui:slot"},
DefaultEnabled: true,
Settings: &plugin.SettingsSchema{
Title: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Group: "collaboration",
Scope: "vm",
Order: []string{"enabled", "direction", "sync_images", "max_image_mb"},
Properties: map[string]plugin.SettingProperty{
"enabled": {
Type: "boolean",
Title: plugin.LocalizedText{ZhCN: "启用剪贴板互通", EnUS: "Enable clipboard sync"},
Default: true,
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
},
"direction": {
Type: "string",
Title: plugin.LocalizedText{ZhCN: "同步方向", EnUS: "Sync direction"},
Enum: []string{"bidirectional", "host-to-guest", "guest-to-host"},
EnumLabels: []plugin.LocalizedText{
{ZhCN: "双向同步", EnUS: "Bidirectional"},
{ZhCN: "仅宿主到虚拟机", EnUS: "Host to guest only"},
{ZhCN: "仅虚拟机到宿主", EnUS: "Guest to host only"},
},
Default: "bidirectional",
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
},
"sync_images": {
Type: "boolean",
Title: plugin.LocalizedText{ZhCN: "同步剪贴板图片", EnUS: "Sync clipboard images"},
Default: true,
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
},
"max_image_mb": {
Type: "integer",
Title: plugin.LocalizedText{ZhCN: "图片大小上限 (MB)", EnUS: "Max image size (MB)"},
Default: 16,
Minimum: &minMB,
Maximum: &maxMB,
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
},
},
},
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDClipboard, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
rawSvc, ok := sc.Lookup(ServiceGuestToolsTransport)
if !ok {
return fmt.Errorf("required service %q not available", ServiceGuestToolsTransport)
}
srv, ok := rawSvc.(*guesttools.Server)
if !ok || srv == nil {
return fmt.Errorf("invalid %q service instance", ServiceGuestToolsTransport)
}
srv.SetClipboardActive(true)
sc.OnDispose(func() {
srv.SetClipboardActive(false)
})
sc.Registry().RegisterVMCard(sc, plugin.VMCardContribution{
ID: "clipboard-sync",
Title: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Value: plugin.LocalizedText{ZhCN: "已启用", EnUS: "Active"},
Badge: "ok",
When: "capability:guest_tools",
})
sc.Registry().RegisterDiagnostics(sc, plugin.DiagnosticsContribution{
ID: "clipboard-stats",
Title: plugin.LocalizedText{ZhCN: "剪贴板同步统计", EnUS: "Clipboard Sync Counters"},
}, func(_ context.Context, _ string) (plugin.DiagnosticsEntry, error) {
stats := srv.ClipboardDiagnostics()
// Privacy rule (§5.4): record counters and errors only, NEVER clipboard content.
return plugin.DiagnosticsEntry{
PluginID: IDClipboard,
Title: "Clipboard Sync Counters",
Data: map[string]any{
"active": stats.Active,
"watcher_running": stats.WatcherRunning,
"host_to_guest_count": stats.HostToGuestCount,
"guest_to_host_count": stats.GuestToHostCount,
"error_count": stats.ErrorCount,
},
}, nil
})
return nil
},
}
}
func defInput(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDInput,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "宿主输入服务与 IME 桥接", EnUS: "Host Input Service & IME Bridge"},
Description: plugin.LocalizedText{
ZhCN: "管理远程输入法键入钩子与声明式鼠标输入过滤器,停用后立即卸载钩子线程",
EnUS: "Manages the remote IME keyboard hook and declarative mouse input filters; unloads hook threads on disable",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Provides: []plugin.ServiceProvision{{Service: ServiceHostInput, Version: "1.0.0"}},
Permissions: []string{"input:filter"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDInput, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
svc := host.NewInputService(cb.OnIMEText)
if cb.OnIMEText != nil {
if err := svc.EnableIME(true); err != nil && cb.Log != nil {
cb.Log("app", "Remote IME hook unavailable: "+err.Error())
}
}
sc.Provide(ServiceHostInput, "1.0.0", svc)
sc.OnDispose(func() {
svc.Close()
})
return nil
},
}
}
func defWin10ColdReboot(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDWin10ColdReboot,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "Windows 10 冷重启补偿", EnUS: "Windows 10 Cold-Reboot Workaround"},
Description: plugin.LocalizedText{
ZhCN: "在缺少 WHvResetPartition 的 Windows 10 上通过独立 QMP 通道监听客体重启并自动重新拉起",
EnUS: "Uses an isolated QMP channel with -no-reboot on Windows 10 to restart guests cleanly in a new Hyper-V partition",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent", "qmp:write"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDWin10ColdReboot, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
needs, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
if !needs {
return plugin.StartIntent{
PluginID: IDWin10ColdReboot,
ClearKeys: []string{"win10-cold-reboot"},
}, nil
}
tmpDir := ""
if cb.GetConfig != nil {
cfg := cb.GetConfig()
tmpDir = cfg.TempDir()
}
sockPath := qmp.RebootSocketPath(p.VMDir, tmpDir, p.VMName)
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
_ = os.Remove(sockPath)
tokens := plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", sockPath))
return plugin.StartIntent{
PluginID: IDWin10ColdReboot,
Args: []plugin.ArgFragment{{
PluginID: IDWin10ColdReboot,
Key: "win10-cold-reboot",
Tokens: tokens,
Builtin: true,
Priority: 95,
}},
PostStart: []plugin.PostStartAction{{
PluginID: IDWin10ColdReboot,
Kind: "qmp.watch_cold_reboot",
Params: map[string]any{"qmp_addr": "unix:" + sockPath},
}},
}, nil
},
})
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMAfterStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
ev, ok := raw.(plugin.VMEventPayload)
if ok && ev.QMPAddr != "" && cb.StartColdReboot != nil {
cb.StartColdReboot(ev.VMName, ev.QMPAddr)
}
return nil, nil
},
})
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMAfterStop,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
ev, ok := raw.(plugin.VMEventPayload)
if ok && cb.CancelColdReboot != nil {
cb.CancelColdReboot(ev.VMName)
}
return nil, nil
},
})
return nil
},
}
}
func defWHPXFallback(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDWHPXFallback,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "WHPX 兼容降级", EnUS: "WHPX Compatibility Fallback"},
Description: plugin.LocalizedText{
ZhCN: "根据宿主嵌套虚拟化探测与运行时能力自动应用 kernel-irqchip=off 避免首次启动崩溃",
EnUS: "Automatically applies kernel-irqchip=off based on host nested-virt probes and runtime capabilities",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDWHPXFallback, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventHostPreflight,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.PreflightPayload)
if !ok {
return nil, nil
}
needsCold, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
irqAvail, _ := p.HostFacts["host.whpx_irqchip"].(bool)
nestedOK, _ := p.HostFacts["host.whpx_nested_virt"].(bool)
hasCap := false
if caps, ok := p.HostFacts["runtime.capabilities"].([]string); ok {
for _, c := range caps {
if strings.EqualFold(c, "nested-virt-nonfatal") {
hasCap = true
break
}
}
}
if !needsCold && irqAvail && !nestedOK && !hasCap {
return plugin.PreflightResult{
Advices: []string{"Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied"},
}, nil
}
return nil, nil
},
})
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
needsCold, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
irqAvail, _ := p.HostFacts["host.whpx_irqchip"].(bool)
nestedOK, _ := p.HostFacts["host.whpx_nested_virt"].(bool)
if needsCold || !irqAvail || nestedOK {
return plugin.StartIntent{
PluginID: IDWHPXFallback,
ClearKeys: []string{"kernel-irqchip"},
}, nil
}
for _, c := range p.RuntimeCaps {
if strings.EqualFold(c, "nested-virt-nonfatal") {
return plugin.StartIntent{
PluginID: IDWHPXFallback,
ClearKeys: []string{"kernel-irqchip"},
}, nil
}
}
if reims.HasKernelIrqchipArg(p.ExtraArgs) {
return nil, nil
}
return plugin.StartIntent{
PluginID: IDWHPXFallback,
Args: []plugin.ArgFragment{{
PluginID: IDWHPXFallback,
Key: "kernel-irqchip",
Tokens: []string{"-machine", "kernel-irqchip=off"},
Builtin: true,
Priority: 90,
}},
Warnings: []string{"Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically"},
}, nil
},
})
return nil
},
}
}
func defOfflineHelper(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDOfflineHelper,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "离线安装辅助盘", EnUS: "Offline Installer Helper Disk"},
Description: plugin.LocalizedText{
ZhCN: "在挂载离线安装器时自动准备并注入 REIMSHELP 辅助盘,弹出安装盘后自动剥离",
EnUS: "Automatically prepares and attaches the REIMSHELP helper disk for offline installers and strips it on eject",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDOfflineHelper, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
if p.HasInstaller && reims.IsOfflineInstallerPath(p.InstallerPath) && cb.GetConfig != nil {
cfg := cb.GetConfig()
helperPath, err := installer.EnsureOfflineHelperImage(cfg.XDGCacheDir(), p.InstallerPath)
if err != nil {
return plugin.StartIntent{
PluginID: IDOfflineHelper,
Warnings: []string{"offline install helper disk skipped: " + err.Error()},
}, nil
}
tokens := plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", helperPath))
return plugin.StartIntent{
PluginID: IDOfflineHelper,
Args: []plugin.ArgFragment{{
PluginID: IDOfflineHelper,
Key: "reimshelp",
Tokens: tokens,
Builtin: true,
Priority: 85,
}},
}, nil
}
return plugin.StartIntent{
PluginID: IDOfflineHelper,
ClearKeys: []string{"reimshelp"},
}, nil
},
})
return nil
},
}
}
func defRecoveryBoot(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDRecoveryBoot,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "恢复模式引导切换", EnUS: "Recovery Boot Picker Sync"},
Description: plugin.LocalizedText{
ZhCN: "在虚拟机启动前根据标记自动更新 OpenCore 引导菜单以进入或退出恢复模式",
EnUS: "Updates OpenCore boot picker before start when entering or exiting macOS Recovery mode",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDRecoveryBoot, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(ctx context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS || cb.GetConfig == nil {
return nil, nil
}
marker := vmstart.ReadRecoveryMarker(p.VMDir)
if marker != "want" && marker != "restore" {
return nil, nil
}
cfg := cb.GetConfig()
active, err := rt.ResolveActive(&cfg)
if err != nil || active == nil {
return nil, nil
}
c := reims.NewClient(&cfg, *active)
show := marker == "want"
nextMarker := ""
if show {
nextMarker = "on"
}
logFn := func(line string) {
if cb.Log != nil {
cb.Log(p.VMName, line)
}
}
w := vmstart.LineWriter(logFn)
if err := c.UpdateOpenCore(ctx, p.VMName, show, w, w); err != nil {
return plugin.StartIntent{
PluginID: IDRecoveryBoot,
Warnings: []string{"could not update OpenCore boot picker: " + err.Error()},
}, nil
}
vmstart.WriteRecoveryMarker(p.VMDir, nextMarker)
return nil, nil
},
})
return nil
},
}
}
func defGuestLang(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDGuestLang,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "macOS 引导语言重放", EnUS: "macOS Boot Language Replay"},
Description: plugin.LocalizedText{
ZhCN: "在启动前与 OpenCore 重建后自动写入已保存的 prev-lang:kbd 客体语言偏好",
EnUS: "Replays the saved prev-lang:kbd language preference into OpenCore NVRAM before start",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDGuestLang, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
// Lower priority so it replays AFTER recovery-boot rebuilds OpenCore (§11.2).
Priority: -10,
Handler: func(ctx context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS || cb.GetConfig == nil {
return nil, nil
}
saved := opencore.ReadSavedGuestLang(p.VMDir)
if saved == "" {
return nil, nil
}
ocPath := opencore.ResolveOpenCorePath(p.VMDir)
if ocPath == "" {
return nil, nil
}
cfg := cb.GetConfig()
active, err := rt.ResolveActive(&cfg)
if err != nil || active == nil {
return nil, nil
}
env := rt.BuildChildEnv(&cfg, *active)
if _, err := opencore.PatchImagePrevLang(ctx, ocPath, saved, active.QemuImgPath(), env); err != nil {
return plugin.StartIntent{
PluginID: IDGuestLang,
Warnings: []string{"could not apply macOS language to OpenCore: " + err.Error()},
}, nil
}
return nil, nil
},
})
return nil
},
}
}
+123
View File
@@ -0,0 +1,123 @@
package builtin
import (
"context"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/bundled"
)
func TestBuiltinClipboardAndInputLifecycleZeroResidue(t *testing.T) {
reg := plugin.NewRegistry(nil)
gtSrv := guesttools.NewTransportServer(nil)
if _, err := gtSrv.Start(-1); err != nil {
t.Fatal(err)
}
defer func() { _ = gtSrv.Close(context.Background()) }()
cb := HostCallbacks{
GetConfig: func() config.Config { return config.Config{DataRoot: t.TempDir()} },
EnsureGuestTools: func() (*guesttools.Server, int, error) {
return gtSrv, gtSrv.Port(), nil
},
}
if err := RegisterAll(reg, cb, nil); err != nil {
t.Fatalf("RegisterAll: %v", err)
}
reg.Reconcile(context.Background())
// Clipboard extension should be active and have mounted /v1/clipboard + watcher.
if !reg.IsActive(IDGuestTools) || !reg.IsActive(IDClipboard) {
t.Fatalf("expected guest-tools and clipboard active")
}
if !gtSrv.HasRoute("/v1/clipboard") || !gtSrv.IsClipboardActive() {
t.Fatal("expected clipboard route mounted while builtin.bridge.clipboard is active")
}
// Disable clipboard live -> route removed, watcher stopped, zero residue!
if err := reg.SetDesired(context.Background(), IDClipboard, false); err != nil {
t.Fatal(err)
}
if gtSrv.HasRoute("/v1/clipboard") || gtSrv.IsClipboardActive() {
t.Fatal("expected zero clipboard route residue after disabling builtin.bridge.clipboard")
}
deadline := time.Now().Add(2 * time.Second)
for gtSrv.IsClipboardWatcherRunning() && time.Now().Before(deadline) {
time.Sleep(20 * time.Millisecond)
}
if gtSrv.IsClipboardWatcherRunning() {
t.Fatal("expected clipboard watcher stopped after disable")
}
// Re-enable clipboard -> active again.
if err := reg.SetDesired(context.Background(), IDClipboard, true); err != nil {
t.Fatal(err)
}
if !gtSrv.HasRoute("/v1/clipboard") {
t.Fatal("expected clipboard route restored on re-enable")
}
// Disabling transport service cascades and disables clipboard cleanly.
if err := reg.SetDesired(context.Background(), IDGuestTools, false); err != nil {
t.Fatal(err)
}
if reg.IsActive(IDClipboard) || gtSrv.HasRoute("/v1/clipboard") {
t.Fatal("disabling guest-tools transport must cascade-unload clipboard")
}
// Input service disables cleanly with zero hook residue.
if raw, ok := reg.LookupService(ServiceHostInput); !ok || raw == nil {
t.Fatal("expected host.input service provided")
}
if err := reg.SetDesired(context.Background(), IDInput, false); err != nil {
t.Fatal(err)
}
if _, ok := reg.LookupService(ServiceHostInput); ok {
t.Fatal("expected host.input service removed after disable")
}
// Bundled wheel-invert manifest parses cleanly and defaults to disabled.
manifests, err := bundled.BundledManifests()
if err != nil || len(manifests) != 1 {
t.Fatalf("BundledManifests = %d, err=%v", len(manifests), err)
}
if manifests[0].ID != bundled.WheelInvertPluginID || manifests[0].DefaultEnabled {
t.Fatalf("unexpected wheel-invert manifest: %+v", manifests[0])
}
if manifests[0].InferTier(false) != plugin.TierL1 {
t.Fatalf("wheel-invert tier = %s, want L1", manifests[0].InferTier(false))
}
// WHPX fallback hook uses runtime capability rather than patch name substring.
intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
VMName: "mac1",
DriverID: IDDriverReimsMacOS,
RuntimeCaps: []string{},
HostFacts: map[string]any{
"host.needs_cold_reboot": false,
"host.whpx_irqchip": true,
"host.whpx_nested_virt": false,
},
})
if err != nil {
t.Fatal(err)
}
foundIrq := false
for _, in := range intents {
if in.PluginID == IDWHPXFallback && len(in.Args) == 1 {
foundIrq = true
}
}
if !foundIrq {
t.Fatalf("expected WHPX fallback intent, got %+v", intents)
}
}
func TestInputServiceTypeCheck(t *testing.T) {
_ = host.NewInputService(nil)
}
+47
View File
@@ -0,0 +1,47 @@
// Package bundled embeds official L1 plugin packages shipped inside reims-go.exe
// (docs/plugin-architecture.md §5.4, §9). They exercise the exact same manifest
// parsing, permission checking, settings rendering, and enable/disable lifecycle
// as external packages, with trust=official and removable=false.
package bundled
import (
"embed"
"encoding/json"
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/version"
)
//go:embed wheel-invert/plugin.json
var bundledFS embed.FS
// WheelInvertPluginID is the ID of the bundled mouse-wheel inversion L1 plugin.
const WheelInvertPluginID = "reims.input.wheel-invert"
// BundledManifests returns all official bundled L1 plugin manifests embedded in
// the binary, with version aligned to the host application version.
func BundledManifests() ([]plugin.Manifest, error) {
paths := []string{
"wheel-invert/plugin.json",
}
out := make([]plugin.Manifest, 0, len(paths))
appVer := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
if appVer == "" || appVer == "dev" {
appVer = "0.2.6"
}
for _, p := range paths {
raw, err := bundledFS.ReadFile(p)
if err != nil {
return nil, fmt.Errorf("read bundled manifest %s: %w", p, err)
}
var m plugin.Manifest
if err := json.Unmarshal(raw, &m); err != nil {
return nil, fmt.Errorf("parse bundled manifest %s: %w", p, err)
}
m.Version = appVer
out = append(out, m)
}
return out, nil
}
@@ -0,0 +1,100 @@
{
"schema": 1,
"id": "reims.input.wheel-invert",
"version": "1.0.0",
"name": {
"zh-CN": "滚轮方向反转",
"en-US": "Mouse wheel invert"
},
"description": {
"zh-CN": "针对 macOS 自然滚动方向,在前台为目标虚拟机窗口时反转鼠标滚轮增量",
"en-US": "Invert mouse wheel scroll deltas when a target macOS VM window is focused"
},
"publisher": "Reims-Go",
"license": "Apache-2.0",
"homepage": "https://github.com/Nwflower/reims-go",
"engines": {
"pluginApi": "^1.0.0"
},
"platforms": ["windows-x64"],
"permissions": ["input:filter"],
"activation": ["onStartup"],
"defaultEnabled": false,
"contributes": {
"inputFilters": [
{
"id": "wheel-invert-rule",
"event": "mouse_wheel",
"axis": "vertical",
"transform": "invert",
"scope": "vm_foreground",
"settingKey": "enabled",
"verticalKey": "vertical",
"horizontalKey": "horizontal",
"name": {
"zh-CN": "反转滚轮",
"en-US": "Invert wheel"
}
}
],
"settingsPages": [
{
"id": "wheel-invert-vm-settings",
"title": {
"zh-CN": "滚轮反转",
"en-US": "Wheel invert"
},
"group": "keyboard",
"scope": "vm"
}
]
},
"settings": {
"title": {
"zh-CN": "滚轮反转",
"en-US": "Wheel invert"
},
"x-group": "keyboard",
"x-scope": "vm",
"x-order": ["enabled", "vertical", "horizontal"],
"properties": {
"enabled": {
"type": "boolean",
"title": {
"zh-CN": "为此虚拟机反转滚轮方向",
"en-US": "Invert mouse wheel for this VM"
},
"description": {
"zh-CN": "仅在前台窗口属于该虚拟机时生效,停用后立即卸载钩子",
"en-US": "Active only while this VM window is focused; hook unloads when disabled"
},
"default": false,
"x-effect": "immediate",
"x-scope": "vm",
"x-group": "keyboard"
},
"vertical": {
"type": "boolean",
"title": {
"zh-CN": "反转垂直滚轮",
"en-US": "Invert vertical scroll"
},
"default": true,
"x-effect": "immediate",
"x-scope": "vm",
"x-group": "keyboard"
},
"horizontal": {
"type": "boolean",
"title": {
"zh-CN": "反转水平滚轮",
"en-US": "Invert horizontal scroll"
},
"default": false,
"x-effect": "immediate",
"x-scope": "vm",
"x-group": "keyboard"
}
}
}
}
+457
View File
@@ -0,0 +1,457 @@
package plugin
import (
"context"
"fmt"
"sort"
"sync"
"sync/atomic"
"time"
)
// Lifecycle hook event names (§4.3).
const (
EventHostPreflight = "host.preflight"
EventVMBeforeCreate = "vm.beforeCreate"
EventVMAfterCreate = "vm.afterCreate"
EventVMBeforeStart = "vm.beforeStart"
EventVMAfterStart = "vm.afterStart"
EventVMBeforeStop = "vm.beforeStop"
EventVMAfterStop = "vm.afterStop"
EventVMDeleted = "vm.deleted"
EventLogOnLine = "log.onLine"
)
// HookHandler is invoked when an event fires. Its payload and return type depend
// on the event contract (§4.3).
type HookHandler func(ctx context.Context, payload any) (any, error)
// HookRegistration configures one subscribed handler on the HookBus.
type HookRegistration struct {
PluginID string
Event string
Builtin bool
Priority int
Blocking bool // only honored on vm.beforeStart if BlockingAllowed is true
BlockingAllowed bool
Handler HookHandler
}
// PreflightPayload is passed to host.preflight handlers.
type PreflightPayload struct {
HostFacts map[string]any `json:"host_facts"`
}
// PreflightResult is returned by host.preflight handlers.
type PreflightResult struct {
Warnings []string `json:"warnings,omitempty"`
Advices []string `json:"advices,omitempty"`
}
// BeforeCreatePayload is passed to vm.beforeCreate handlers.
type BeforeCreatePayload struct {
VMName string `json:"vm_name"`
DriverID string `json:"driver_id"`
Options map[string]any `json:"options,omitempty"`
}
// BeforeCreateResult is returned by vm.beforeCreate handlers.
type BeforeCreateResult struct {
Errors []string `json:"errors,omitempty"`
Patches map[string]any `json:"patches,omitempty"`
}
// BeforeStartPayload is passed to vm.beforeStart handlers.
type BeforeStartPayload struct {
VMName string `json:"vm_name"`
VMDir string `json:"vm_dir"`
DriverID string `json:"driver_id"`
ExtraArgs string `json:"extra_args"`
HasInstaller bool `json:"has_installer"`
InstallerPath string `json:"installer_path,omitempty"`
RuntimeKind string `json:"runtime_kind"`
RuntimeCaps []string `json:"runtime_caps,omitempty"`
HostFacts map[string]any `json:"host_facts,omitempty"`
VMCaps []string `json:"vm_caps,omitempty"`
State string `json:"state,omitempty"`
}
// VMEventPayload is passed to vm.afterCreate / vm.afterStart / vm.beforeStop / vm.afterStop / vm.deleted.
type VMEventPayload struct {
VMName string `json:"vm_name"`
VMDir string `json:"vm_dir,omitempty"`
DriverID string `json:"driver_id,omitempty"`
PID int `json:"pid,omitempty"`
QMPAddr string `json:"qmp_addr,omitempty"`
SSHPort int `json:"ssh_port,omitempty"`
Extra map[string]any `json:"extra,omitempty"`
}
// LogLineEvent is one log line queued for log.onLine batch subscribers.
type LogLineEvent struct {
VMName string `json:"vm_name"`
Source string `json:"source"` // "serial" | "qemu" | "app"
Line string `json:"line"`
}
// HookBus dispatches lifecycle events respecting builtin-first ordering,
// per-event timeouts, fail-open/blocking policies, and zero-cost fast paths (§4.3, §8.1).
type HookBus struct {
reg *Registry
mu sync.RWMutex
handlers map[string][]*HookRegistration
seq uint64
// Zero-overhead counter for log.onLine (§8.1): checked with atomic load
// before constructing LogLineEvent objects.
logSubCount atomic.Int32
logCh chan LogLineEvent
logOnce sync.Once
}
func NewHookBus(reg *Registry) *HookBus {
return &HookBus{
reg: reg,
handlers: make(map[string][]*HookRegistration),
}
}
// Subscribe attaches a hook handler to scope so disposal unregisters it cleanly.
func (b *HookBus) Subscribe(sc *Scope, hr HookRegistration) {
if sc == nil || hr.Event == "" || hr.Handler == nil {
return
}
hr.PluginID = sc.PluginID()
ptr := &hr
b.mu.Lock()
b.handlers[hr.Event] = append(b.handlers[hr.Event], ptr)
b.sortLocked(hr.Event)
if hr.Event == EventLogOnLine {
b.logSubCount.Add(1)
b.startLogBatcherLocked()
}
b.mu.Unlock()
sc.OnDispose(func() {
b.mu.Lock()
list := b.handlers[hr.Event]
kept := list[:0]
for _, item := range list {
if item != ptr {
kept = append(kept, item)
}
}
if len(kept) == 0 {
delete(b.handlers, hr.Event)
} else {
b.handlers[hr.Event] = kept
}
if hr.Event == EventLogOnLine {
b.logSubCount.Add(-1)
}
b.mu.Unlock()
})
}
func (b *HookBus) sortLocked(event string) {
list := b.handlers[event]
sort.SliceStable(list, func(i, j int) bool {
if list[i].Builtin != list[j].Builtin {
return list[i].Builtin
}
if list[i].Priority != list[j].Priority {
return list[i].Priority > list[j].Priority
}
return list[i].PluginID < list[j].PluginID
})
}
// HasSubscribers returns whether any plugin is subscribed to event (zero-cost gate, §8.1).
func (b *HookBus) HasSubscribers(event string) bool {
if event == EventLogOnLine {
return b.logSubCount.Load() > 0
}
b.mu.RLock()
n := len(b.handlers[event])
b.mu.RUnlock()
return n > 0
}
func (b *HookBus) snapshot(event string) []*HookRegistration {
b.mu.RLock()
list := b.handlers[event]
if len(list) == 0 {
b.mu.RUnlock()
return nil
}
cp := make([]*HookRegistration, len(list))
copy(cp, list)
b.mu.RUnlock()
return cp
}
// DispatchPreflight runs host.preflight (collect; builtin runs synchronously on
// parent ctx, external plugins get 500ms timeout and fail-open).
func (b *HookBus) DispatchPreflight(ctx context.Context, payload PreflightPayload) PreflightResult {
subs := b.snapshot(EventHostPreflight)
if len(subs) == 0 {
return PreflightResult{}
}
var merged PreflightResult
for _, hr := range subs {
var (
res any
err error
)
if hr.Builtin {
res, err = b.invokeBuiltin(ctx, hr, payload)
} else {
res, err = b.invokeWithTimeout(ctx, hr, payload, 500*time.Millisecond)
}
if err != nil {
continue
}
if pr, ok := res.(PreflightResult); ok {
merged.Warnings = append(merged.Warnings, pr.Warnings...)
merged.Advices = append(merged.Advices, pr.Advices...)
} else if prp, ok := res.(*PreflightResult); ok && prp != nil {
merged.Warnings = append(merged.Warnings, prp.Warnings...)
merged.Advices = append(merged.Advices, prp.Advices...)
}
}
return merged
}
// DispatchBeforeCreate runs vm.beforeCreate (intercept; builtin runs
// synchronously on parent ctx, external plugins get 2s timeout and fail-open).
func (b *HookBus) DispatchBeforeCreate(ctx context.Context, payload BeforeCreatePayload) BeforeCreateResult {
subs := b.snapshot(EventVMBeforeCreate)
if len(subs) == 0 {
return BeforeCreateResult{}
}
out := BeforeCreateResult{Patches: map[string]any{}}
for _, hr := range subs {
var (
res any
err error
)
if hr.Builtin {
res, err = b.invokeBuiltin(ctx, hr, payload)
} else {
res, err = b.invokeWithTimeout(ctx, hr, payload, 2*time.Second)
}
if err != nil {
continue
}
var r BeforeCreateResult
switch v := res.(type) {
case BeforeCreateResult:
r = v
case *BeforeCreateResult:
if v != nil {
r = *v
}
default:
continue
}
out.Errors = append(out.Errors, r.Errors...)
for k, v := range r.Patches {
out.Patches[k] = v
}
}
return out
}
// DispatchBeforeStart runs vm.beforeStart (intercept). Builtin prep hooks run
// synchronously on parent ctx without external timeouts so disk/OpenCore I/O
// always completes before QEMU starts (B2). External plugin hooks share a 10s
// chain budget with 2s per plugin (§4.3).
func (b *HookBus) DispatchBeforeStart(ctx context.Context, payload BeforeStartPayload) ([]StartIntent, error) {
subs := b.snapshot(EventVMBeforeStart)
if len(subs) == 0 {
return nil, nil
}
hasExternal := false
for _, hr := range subs {
if !hr.Builtin {
hasExternal = true
break
}
}
extChainCtx := ctx
if hasExternal {
var extChainCancel context.CancelFunc
extChainCtx, extChainCancel = context.WithTimeout(ctx, 10*time.Second)
defer extChainCancel()
}
var intents []StartIntent
for _, hr := range subs {
var (
res any
err error
)
if hr.Builtin {
res, err = b.invokeBuiltin(ctx, hr, payload)
} else {
if extChainCtx.Err() != nil {
break
}
res, err = b.invokeWithTimeout(extChainCtx, hr, payload, 2*time.Second)
}
if err != nil {
continue
}
var intent StartIntent
switch v := res.(type) {
case StartIntent:
intent = v
case *StartIntent:
if v != nil {
intent = *v
} else {
continue
}
default:
continue
}
intent.PluginID = hr.PluginID
if intent.BlockReason != "" && hr.Blocking && hr.BlockingAllowed {
return intents, fmt.Errorf("blocked by %s: %s", hr.PluginID, intent.BlockReason)
}
intents = append(intents, intent)
}
return intents, nil
}
// DispatchObserve asynchronously fires observation events (vm.afterCreate,
// vm.afterStart, vm.beforeStop, vm.afterStop, vm.deleted), logging errors only.
func (b *HookBus) DispatchObserve(event string, payload VMEventPayload) {
subs := b.snapshot(event)
if len(subs) == 0 {
return
}
timeout := 10 * time.Second
if event == EventVMAfterCreate {
timeout = 30 * time.Second
}
go func() {
for _, hr := range subs {
_, _ = b.invokeWithTimeout(context.Background(), hr, payload, timeout)
}
}()
}
// EmitLogLine queues a log line for batched log.onLine delivery. When no
// subscribers exist, this is a single atomic load (zero allocation, §8.1).
// Under backpressure, lines are dropped silently so logging is never blocked.
func (b *HookBus) EmitLogLine(vmName, source, line string) {
if b.logSubCount.Load() <= 0 {
return
}
b.mu.RLock()
ch := b.logCh
b.mu.RUnlock()
if ch == nil {
return
}
select {
case ch <- LogLineEvent{VMName: vmName, Source: source, Line: line}:
default:
// Backpressure: drop without blocking VM log pipeline (§4.3).
}
}
func (b *HookBus) startLogBatcherLocked() {
b.logOnce.Do(func() {
ch := make(chan LogLineEvent, 256)
b.logCh = ch
go b.runLogBatcher(ch)
})
}
func (b *HookBus) runLogBatcher(ch <-chan LogLineEvent) {
const maxBatch = 32
ticker := time.NewTicker(150 * time.Millisecond)
defer ticker.Stop()
var batch []LogLineEvent
flush := func() {
if len(batch) == 0 {
return
}
subs := b.snapshot(EventLogOnLine)
if len(subs) == 0 {
batch = batch[:0]
return
}
deliver := make([]LogLineEvent, len(batch))
copy(deliver, batch)
batch = batch[:0]
for _, hr := range subs {
_, _ = b.invokeWithTimeout(context.Background(), hr, deliver, 500*time.Millisecond)
}
}
for {
select {
case ev := <-ch:
batch = append(batch, ev)
if len(batch) >= maxBatch {
flush()
}
case <-ticker.C:
flush()
}
}
}
// invokeBuiltin runs a trusted built-in handler synchronously on parent ctx
// (with panic recovery) so I/O-heavy prep steps never time out or race QEMU.
func (b *HookBus) invokeBuiltin(ctx context.Context, hr *HookRegistration, payload any) (val any, err error) {
defer func() {
if rec := recover(); rec != nil {
val = nil
err = fmt.Errorf("hook panic: %v", rec)
}
if b.reg != nil {
b.reg.RecordHookOutcome(hr.PluginID, err)
}
}()
return hr.Handler(ctx, payload)
}
func (b *HookBus) invokeWithTimeout(parent context.Context, hr *HookRegistration, payload any, limit time.Duration) (any, error) {
callCtx, cancel := context.WithTimeout(parent, limit)
defer cancel()
type result struct {
val any
err error
}
done := make(chan result, 1)
go func() {
defer func() {
if rec := recover(); rec != nil {
done <- result{err: fmt.Errorf("hook panic: %v", rec)}
}
}()
v, err := hr.Handler(callCtx, payload)
done <- result{val: v, err: err}
}()
select {
case r := <-done:
if b.reg != nil {
b.reg.RecordHookOutcome(hr.PluginID, r.err)
}
return r.val, r.err
case <-callCtx.Done():
err := fmt.Errorf("hook %s/%s timed out (%v)", hr.PluginID, hr.Event, limit)
if b.reg != nil {
b.reg.RecordHookOutcome(hr.PluginID, err)
}
return nil, err
}
}
+45
View File
@@ -0,0 +1,45 @@
//go:build !windows
package plugin
import (
"os/exec"
"sync"
"syscall"
)
func configureSidecarCmd(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}
func configureDetachedVMProcess(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}
type sidecarJob struct {
pgid int
closeOnce sync.Once
}
func newSidecarJob(_ uintptr) (*sidecarJob, error) {
return &sidecarJob{}, nil
}
func (j *sidecarJob) Assign(pid int) error {
if j != nil {
j.pgid = pid
}
return nil
}
func (j *sidecarJob) Close() {
if j == nil {
return
}
j.closeOnce.Do(func() {
if j.pgid > 0 {
_ = syscall.Kill(-j.pgid, syscall.SIGKILL)
j.pgid = 0
}
})
}
+90
View File
@@ -0,0 +1,90 @@
//go:build windows
package plugin
import (
"fmt"
"os/exec"
"sync"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
const (
createNoWindow = 0x08000000
createBreakawayFromJob = 0x01000000
createNewProcessGroup = 0x00000200
)
func configureSidecarCmd(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: createNoWindow | createNewProcessGroup,
}
}
func configureDetachedVMProcess(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: createNoWindow | createNewProcessGroup | createBreakawayFromJob,
}
}
type sidecarJob struct {
handle windows.Handle
closeOnce sync.Once
}
// newSidecarJob creates a Windows Job Object with KILL_ON_JOB_CLOSE so that
// closing the job (or host exit/crash) reclaims the entire Sidecar process tree
// with zero orphan processes (§8). Optional memLimitBytes caps process memory (L2).
func newSidecarJob(memLimitBytes uintptr) (*sidecarJob, error) {
h, err := windows.CreateJobObject(nil, nil)
if err != nil {
return nil, fmt.Errorf("CreateJobObject: %w", err)
}
info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{}
info.BasicLimitInformation.LimitFlags = windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
if memLimitBytes > 0 {
info.BasicLimitInformation.LimitFlags |= windows.JOB_OBJECT_LIMIT_PROCESS_MEMORY
info.ProcessMemoryLimit = memLimitBytes
}
if _, err := windows.SetInformationJobObject(
h,
windows.JobObjectExtendedLimitInformation,
uintptr(unsafe.Pointer(&info)),
uint32(unsafe.Sizeof(info)),
); err != nil {
_ = windows.CloseHandle(h)
return nil, fmt.Errorf("SetInformationJobObject: %w", err)
}
return &sidecarJob{handle: h}, nil
}
func (j *sidecarJob) Assign(pid int) error {
if j == nil || j.handle == 0 || pid <= 0 {
return nil
}
proc, err := windows.OpenProcess(windows.PROCESS_SET_QUOTA|windows.PROCESS_TERMINATE, false, uint32(pid))
if err != nil {
return fmt.Errorf("OpenProcess(%d): %w", pid, err)
}
defer windows.CloseHandle(proc)
return windows.AssignProcessToJobObject(j.handle, proc)
}
func (j *sidecarJob) Close() {
if j == nil {
return
}
j.closeOnce.Do(func() {
if j.handle == 0 {
return
}
_ = windows.TerminateJobObject(j.handle, 1)
_ = windows.CloseHandle(j.handle)
j.handle = 0
})
}
+451
View File
@@ -0,0 +1,451 @@
package plugin
import (
"context"
"errors"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestSemVerMatchesRange(t *testing.T) {
cases := []struct {
ver string
expr string
want bool
}{
{"1.0.0", "^1.0.0", true},
{"1.5.2", "^1.0.0", true},
{"2.0.0", "^1.0.0", false},
{"1.2.5", "~1.2.0", true},
{"1.3.0", "~1.2.0", false},
{"0.2.6", ">=0.2.0 <0.3.0", true},
{"0.3.0", ">=0.2.0 <0.3.0", false},
{"1.0.0", "1.x", true},
{"2.0.0", "1.x || >=2.0.0", true},
{"0.9.0", "", true},
{"1.0.0-alpha.1", ">=1.0.0", false},
}
for _, tc := range cases {
if got := MatchesRange(tc.ver, tc.expr); got != tc.want {
t.Errorf("MatchesRange(%q, %q) = %v, want %v", tc.ver, tc.expr, got, tc.want)
}
}
}
func TestScopeLIFODisposeAndPanicSafety(t *testing.T) {
reg := NewRegistry(nil)
sc := newScope("test.plugin", reg)
var order []int
sc.OnDispose(func() { order = append(order, 1) })
sc.OnDispose(func() { panic("cleanup boom") })
sc.OnDispose(func() { order = append(order, 3) })
sc.Dispose()
sc.Dispose() // idempotent
want := []int{3, 1}
if !reflect.DeepEqual(order, want) {
t.Fatalf("dispose order = %v, want %v", order, want)
}
}
func TestRegistryDependencyReconcileAndCascade(t *testing.T) {
reg := NewRegistry(nil)
var log []string
_ = reg.Register(PluginDef{
Manifest: Manifest{
ID: "builtin.transport",
Version: "1.0.0",
Provides: []ServiceProvision{{Service: "transport", Version: "1.0.0"}},
},
Source: SourceBuiltin,
Trust: TrustOfficial,
Desired: true,
Activate: func(_ context.Context, sc *Scope) error {
log = append(log, "up:transport")
sc.Provide("transport", "1.0.0", "svc-instance")
sc.OnDispose(func() { log = append(log, "down:transport") })
return nil
},
})
_ = reg.Register(PluginDef{
Manifest: Manifest{
ID: "builtin.clipboard",
Version: "1.0.0",
Requires: []ServiceRequirement{{Service: "transport", Version: "^1.0.0"}},
},
Source: SourceBuiltin,
Trust: TrustOfficial,
Desired: true,
Activate: func(_ context.Context, sc *Scope) error {
svc, ok := sc.Lookup("transport")
if !ok || svc != "svc-instance" {
return errors.New("missing transport service")
}
log = append(log, "up:clipboard")
sc.OnDispose(func() { log = append(log, "down:clipboard") })
return nil
},
})
reg.Reconcile(context.Background())
if !reg.IsActive("builtin.transport") || !reg.IsActive("builtin.clipboard") {
t.Fatalf("expected both active, got transport=%s clipboard=%s", reg.StateOf("builtin.transport"), reg.StateOf("builtin.clipboard"))
}
// Disabling provider must cascade-dispose dependent and leave it pending.
if err := reg.SetDesired(context.Background(), "builtin.transport", false); err != nil {
t.Fatalf("disable transport: %v", err)
}
if reg.IsActive("builtin.transport") {
t.Fatal("transport should be off")
}
if reg.IsActive("builtin.clipboard") {
t.Fatal("clipboard should have been cascade-disposed")
}
if reg.StateOf("builtin.clipboard") != StatePending {
t.Fatalf("clipboard state = %s, want pending", reg.StateOf("builtin.clipboard"))
}
// Re-enabling provider automatically reactivates pending dependent.
if err := reg.SetDesired(context.Background(), "builtin.transport", true); err != nil {
t.Fatalf("re-enable transport: %v", err)
}
if !reg.IsActive("builtin.clipboard") {
t.Fatalf("clipboard should auto-reactivate, got %s", reg.StateOf("builtin.clipboard"))
}
}
func TestRegistryPanicRollbackAndInUseFailClosed(t *testing.T) {
reg := NewRegistry(nil)
rolledBack := false
_ = reg.Register(PluginDef{
Manifest: Manifest{ID: "bad.panic", Version: "1.0.0"},
Source: SourceLocal,
Desired: true,
Activate: func(_ context.Context, sc *Scope) error {
sc.OnDispose(func() { rolledBack = true })
sc.Provide("temp.svc", "1.0.0", 42)
panic("boom")
},
})
_ = reg.Register(PluginDef{
Manifest: Manifest{
ID: "bad.api",
Version: "1.0.0",
Engines: Engines{PluginAPI: "^9.0.0"},
},
Source: SourceLocal,
Desired: true,
})
reg.Reconcile(context.Background())
if !rolledBack {
t.Fatal("expected activation panic to roll back scope")
}
if _, ok := reg.LookupService("temp.svc"); ok {
t.Fatal("expected provided service to be rolled back on panic")
}
if reg.StateOf("bad.panic") != StateFailed {
t.Fatalf("bad.panic state = %s, want failed", reg.StateOf("bad.panic"))
}
if reg.StateOf("bad.api") != StateFailed {
t.Fatalf("bad.api state = %s, want failed", reg.StateOf("bad.api"))
}
// InUse fail-closed guard.
_ = reg.Register(PluginDef{
Manifest: Manifest{ID: "drv.test", Version: "1.0.0"},
Source: SourceLocal,
Desired: true,
})
reg.Reconcile(context.Background())
reg.SetInUseChecker(func(id string) (bool, string, error) {
if id == "drv.test" {
return false, "", errors.New("probe error")
}
return false, "", nil
})
if err := reg.SetDesired(context.Background(), "drv.test", false); err == nil {
t.Fatal("expected fail-closed error when InUseChecker fails")
}
}
func TestHookBusOrderingTimeoutDegradeAndBlocking(t *testing.T) {
reg := NewRegistry(nil)
var seq []string
_ = reg.Register(PluginDef{
Manifest: Manifest{ID: "user.hook", Version: "1.0.0"},
Source: SourceLocal,
Desired: true,
Activate: func(_ context.Context, sc *Scope) error {
reg.Hooks().Subscribe(sc, HookRegistration{
Event: EventVMBeforeStart,
Handler: func(_ context.Context, _ any) (any, error) {
seq = append(seq, "user")
return StartIntent{Warnings: []string{"user-warn"}}, nil
},
})
return nil
},
})
_ = reg.Register(PluginDef{
Manifest: Manifest{ID: "builtin.hook", Version: "1.0.0"},
Source: SourceBuiltin,
Desired: true,
Activate: func(_ context.Context, sc *Scope) error {
reg.Hooks().Subscribe(sc, HookRegistration{
Event: EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, _ any) (any, error) {
seq = append(seq, "builtin")
return StartIntent{Warnings: []string{"builtin-warn"}}, nil
},
})
return nil
},
})
var failCalls atomic.Int32
_ = reg.Register(PluginDef{
Manifest: Manifest{ID: "flaky.hook", Version: "1.0.0"},
Source: SourceLocal,
Desired: true,
Activate: func(_ context.Context, sc *Scope) error {
reg.Hooks().Subscribe(sc, HookRegistration{
Event: EventHostPreflight,
Handler: func(_ context.Context, _ any) (any, error) {
failCalls.Add(1)
return nil, errors.New("boom")
},
})
return nil
},
})
reg.Reconcile(context.Background())
intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), BeforeStartPayload{VMName: "vm1"})
if err != nil {
t.Fatalf("DispatchBeforeStart error: %v", err)
}
if !reflect.DeepEqual(seq, []string{"builtin", "user"}) {
t.Fatalf("hook order = %v, want [builtin user]", seq)
}
if len(intents) != 2 {
t.Fatalf("intents len = %d, want 2", len(intents))
}
// 3 consecutive failures degrade the plugin.
for i := 0; i < 3; i++ {
reg.Hooks().DispatchPreflight(context.Background(), PreflightPayload{})
}
if reg.StateOf("flaky.hook") != StateDegraded {
t.Fatalf("flaky.hook state = %s, want degraded", reg.StateOf("flaky.hook"))
}
// Blocking guard honored only when Blocking && BlockingAllowed.
_ = reg.Register(PluginDef{
Manifest: Manifest{ID: "guard.block", Version: "1.0.0"},
Source: SourceLocal,
Desired: true,
Activate: func(_ context.Context, sc *Scope) error {
reg.Hooks().Subscribe(sc, HookRegistration{
Event: EventVMBeforeStart,
Blocking: true,
BlockingAllowed: true,
Handler: func(_ context.Context, _ any) (any, error) {
return StartIntent{BlockReason: "policy check failed"}, nil
},
})
return nil
},
})
reg.Reconcile(context.Background())
if _, err := reg.Hooks().DispatchBeforeStart(context.Background(), BeforeStartPayload{VMName: "vm1"}); err == nil || !strings.Contains(err.Error(), "policy check failed") {
t.Fatalf("expected blocking error, got %v", err)
}
// Zero-overhead log.onLine check.
if reg.Hooks().HasSubscribers(EventLogOnLine) {
t.Fatal("expected no log.onLine subscribers")
}
reg.Hooks().EmitLogLine("vm1", "qemu", "fast path")
}
func TestArgLedgerReconcilePreserveUserArgsAndStripOnDisable(t *testing.T) {
dir := t.TempDir()
ledger, err := LoadArgLedger(dir)
if err != nil {
t.Fatalf("LoadArgLedger: %v", err)
}
// User has hand-written args that must NEVER be stripped.
userArgs := `-device virtio-rng-pci -rtc base=utc`
active := map[string]bool{
"builtin.compat.whpx-fallback": true,
"thirdparty.tweak": true,
}
intents := []StartIntent{
{
PluginID: "builtin.compat.whpx-fallback",
Args: []ArgFragment{{
Key: "kernel-irqchip",
Tokens: []string{"-machine", "kernel-irqchip=off"},
Builtin: true,
Priority: 100,
}},
},
{
PluginID: "thirdparty.tweak",
Args: []ArgFragment{
{
Key: "kernel-irqchip", // conflicts with builtin; builtin wins!
Tokens: []string{"-machine", "kernel-irqchip=on"},
Priority: 999,
},
{
Key: "disallowed",
Tokens: []string{"-smbios", "type=1,serial=FAKE"}, // rejected by allowlist
},
{
Key: "custom-dev",
Tokens: []string{"-device", "usb-tablet,id=my-tab"},
},
},
Env: map[string]string{
"REIMS_PLUGIN_THIRDPARTY_TWEAK_DEBUG": "1",
"PATH": "/hijack", // rejected
},
},
}
res := ReconcileStartIntents(userArgs, ledger, active, intents)
if !strings.Contains(res.ExtraArgs, "-device virtio-rng-pci -rtc base=utc") {
t.Fatalf("user args lost: %q", res.ExtraArgs)
}
if !strings.Contains(res.ExtraArgs, "-machine kernel-irqchip=off") {
t.Fatalf("builtin winning arg missing: %q", res.ExtraArgs)
}
if strings.Contains(res.ExtraArgs, "kernel-irqchip=on") {
t.Fatalf("losing conflict arg should not appear: %q", res.ExtraArgs)
}
if strings.Contains(res.ExtraArgs, "-smbios") {
t.Fatalf("disallowed -smbios arg should be rejected: %q", res.ExtraArgs)
}
if !strings.Contains(res.ExtraArgs, "-device usb-tablet,id=my-tab") {
t.Fatalf("valid plugin arg missing: %q", res.ExtraArgs)
}
if len(res.Env) != 1 || res.Env[0] != "REIMS_PLUGIN_THIRDPARTY_TWEAK_DEBUG=1" {
t.Fatalf("unexpected env: %v", res.Env)
}
if len(res.Warnings) < 3 {
t.Fatalf("expected conflict, disallowed arg, and disallowed env warnings, got %v", res.Warnings)
}
if err := SaveArgLedger(dir, ledger); err != nil {
t.Fatalf("SaveArgLedger: %v", err)
}
reloaded, err := LoadArgLedger(dir)
if err != nil {
t.Fatalf("reload ledger: %v", err)
}
// Disable thirdparty.tweak -> its fragment is stripped cleanly, user + builtin remain.
stripped, changed := StripPluginFromArgs(res.ExtraArgs, reloaded, "thirdparty.tweak")
if !changed {
t.Fatal("expected change on strip")
}
if strings.Contains(stripped, "usb-tablet") {
t.Fatalf("plugin fragment not stripped: %q", stripped)
}
if !strings.Contains(stripped, "-device virtio-rng-pci -rtc base=utc") || !strings.Contains(stripped, "-machine kernel-irqchip=off") {
t.Fatalf("user or builtin args damaged: %q", stripped)
}
}
func TestL1RuleHooks(t *testing.T) {
reg := NewRegistry(nil)
_ = reg.Register(PluginDef{
Manifest: Manifest{
ID: "l1.rule.sample",
Version: "1.0.0",
Contributes: Contributes{
RuleHooks: []RuleHook{{
ID: "rtc-rule",
Event: EventVMBeforeStart,
Conditions: []RuleCondition{
{Fact: "vm.driver", Operator: "eq", Value: "builtin.driver.reims-macos"},
{Fact: "runtime.capabilities", Operator: "not_contains", Value: "rtc-fix"},
},
Actions: []RuleAction{
{Kind: "append_args", Key: "rtc", Tokens: []string{"-rtc", "base=localtime"}},
{Kind: "warn", Message: "applied rtc rule"},
},
}},
},
},
Source: SourceLocal,
Desired: true,
})
reg.Reconcile(context.Background())
intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), BeforeStartPayload{
VMName: "vm1",
DriverID: "builtin.driver.reims-macos",
RuntimeCaps: []string{"win10-compat"},
})
if err != nil || len(intents) != 1 || len(intents[0].Args) != 1 {
t.Fatalf("expected 1 rule intent with 1 arg, got intents=%+v err=%v", intents, err)
}
// Now with runtime having "rtc-fix", rule should not match.
intents2, _ := reg.Hooks().DispatchBeforeStart(context.Background(), BeforeStartPayload{
VMName: "vm1",
DriverID: "builtin.driver.reims-macos",
RuntimeCaps: []string{"rtc-fix"},
})
if len(intents2) != 0 {
t.Fatalf("expected 0 intents when cap present, got %+v", intents2)
}
}
func TestLogLineBatchDelivery(t *testing.T) {
reg := NewRegistry(nil)
received := make(chan []LogLineEvent, 1)
_ = reg.Register(PluginDef{
Manifest: Manifest{ID: "log.sub", Version: "1.0.0"},
Source: SourceLocal,
Desired: true,
Activate: func(_ context.Context, sc *Scope) error {
reg.Hooks().Subscribe(sc, HookRegistration{
Event: EventLogOnLine,
Handler: func(_ context.Context, raw any) (any, error) {
if batch, ok := raw.([]LogLineEvent); ok {
select {
case received <- batch:
default:
}
}
return nil, nil
},
})
return nil
},
})
reg.Reconcile(context.Background())
if !reg.Hooks().HasSubscribers(EventLogOnLine) {
t.Fatal("expected log subscriber")
}
reg.Hooks().EmitLogLine("vm1", "serial", "hello kernel")
select {
case batch := <-received:
if len(batch) != 1 || batch[0].Line != "hello kernel" {
t.Fatalf("unexpected batch: %+v", batch)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for batched log.onLine")
}
}
+546
View File
@@ -0,0 +1,546 @@
package plugin
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
)
const ArgLedgerFileName = ".reims-go-arg-ledger.json"
// AllowedQEMUOptionFamilies lists the QEMU argument families plugins are
// allowed to contribute via StartIntent (§4.4).
var AllowedQEMUOptionFamilies = map[string]bool{
"-drive": true,
"-device": true,
"-machine": true,
"-qmp": true,
"-no-reboot": true,
"-chardev": true,
"-netdev": true,
"-audiodev": true,
"-display": true,
"-usb": true,
"-fw_cfg": true,
"-smbios": false, // never allow overriding SMBIOS
"-rtc": true,
"-global": true,
"-object": true,
}
// AllowedHostEnvVars lists non-namespaced environment variables permitted in
// builtin/plugin StartIntents (§4.4).
var AllowedHostEnvVars = map[string]bool{
"REIMS_GO_INPUT_URL": true,
"REIMS_GO_INPUT_TOKEN": true,
"REIMS_VGPU_LOG": true,
"VK_ICD_FILENAMES": true,
"SDL_VIDEODRIVER": true,
}
// ArgFragment is one QEMU argument group contributed by a plugin.
type ArgFragment struct {
PluginID string `json:"plugin_id"`
Key string `json:"key"` // logical group key (e.g. "reimshelp", "reimstools", "kernel-irqchip", "win10-reboot")
Tokens []string `json:"tokens"` // tokenized QEMU args (e.g. ["-machine", "kernel-irqchip=off"])
Priority int `json:"priority"` // higher priority wins conflicts
Builtin bool `json:"builtin,omitempty"`
}
// PostStartAction represents a host-controlled action requested by vm.beforeStart.
type PostStartAction struct {
PluginID string `json:"plugin_id"`
Kind string `json:"kind"` // e.g. "qmp.watch_cold_reboot", "guesttools.sync", "notify"
Params map[string]any `json:"params,omitempty"`
}
// StartIntent is the structured output of a vm.beforeStart hook (§4.4).
// Plugins never call `reims-ctl` directly; they return intents merged by host.
type StartIntent struct {
PluginID string `json:"plugin_id"`
Args []ArgFragment `json:"args,omitempty"`
ClearKeys []string `json:"clear_keys,omitempty"` // explicitly clear owned fragments
Env map[string]string `json:"env,omitempty"`
Warnings []string `json:"warnings,omitempty"`
BlockReason string `json:"block_reason,omitempty"`
PostStart []PostStartAction `json:"post_start,omitempty"`
}
// ArgLedger persists plugin-owned QEMU arg fragments in a VM directory so that
// disabling/uninstalling a plugin strips its exact fragments while NEVER
// touching unowned user `--extra-args` (§4.4).
type ArgLedger struct {
Version int `json:"version"`
Owners map[string][]ArgFragment `json:"owners"` // pluginID -> fragments
}
// LoadArgLedger reads `<vmDir>/.reims-go-arg-ledger.json`. Missing file returns empty ledger.
func LoadArgLedger(vmDir string) (*ArgLedger, error) {
if strings.TrimSpace(vmDir) == "" {
return &ArgLedger{Version: 1, Owners: map[string][]ArgFragment{}}, nil
}
p := filepath.Join(vmDir, ArgLedgerFileName)
raw, err := os.ReadFile(p)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return &ArgLedger{Version: 1, Owners: map[string][]ArgFragment{}}, nil
}
return nil, err
}
var ledger ArgLedger
if err := json.Unmarshal(raw, &ledger); err != nil {
return nil, fmt.Errorf("parse arg ledger: %w", err)
}
if ledger.Owners == nil {
ledger.Owners = map[string][]ArgFragment{}
}
if ledger.Version == 0 {
ledger.Version = 1
}
return &ledger, nil
}
// SaveArgLedger atomically writes `<vmDir>/.reims-go-arg-ledger.json`.
func SaveArgLedger(vmDir string, ledger *ArgLedger) error {
if strings.TrimSpace(vmDir) == "" || ledger == nil {
return nil
}
if err := os.MkdirAll(vmDir, 0o755); err != nil {
return err
}
ledger.Version = 1
raw, err := json.MarshalIndent(ledger, "", " ")
if err != nil {
return err
}
target := filepath.Join(vmDir, ArgLedgerFileName)
f, err := os.CreateTemp(vmDir, ArgLedgerFileName+".*.tmp")
if err != nil {
return err
}
tmp := f.Name()
if _, err := f.Write(append(raw, '\n')); err != nil {
_ = f.Close()
_ = os.Remove(tmp)
return err
}
if err := f.Sync(); err != nil {
_ = f.Close()
_ = os.Remove(tmp)
return err
}
if err := f.Close(); err != nil {
_ = os.Remove(tmp)
return err
}
if err := os.Rename(tmp, target); err != nil {
_ = os.Remove(tmp)
return err
}
return nil
}
// ReconcileResult holds the merged extra-args, env vars, warnings, and post-start actions.
type ReconcileResult struct {
ExtraArgs string
Changed bool
Env []string
Warnings []string
PostStart []PostStartAction
}
// validateSingleShellToken ensures a fragment token cannot split into multiple
// QEMU arguments when joined with spaces (blocking whitespace/quote injection, B4).
func validateSingleShellToken(tok string) error {
if tok == "" {
return errors.New("empty QEMU argument token")
}
if strings.ContainsAny(tok, "\r\n\x00") {
return fmt.Errorf("QEMU argument token %q contains control characters", tok)
}
first := tok[0]
if first == '"' || first == '\'' {
if len(tok) < 2 || tok[len(tok)-1] != first {
return fmt.Errorf("QEMU argument token %q has unbalanced quotes", tok)
}
inner := tok[1 : len(tok)-1]
if first == '\'' {
if strings.ContainsRune(inner, '\'') {
return fmt.Errorf("QEMU argument token %q contains nested single quote", tok)
}
} else {
escaped := false
for i := 0; i < len(inner); i++ {
if escaped {
escaped = false
continue
}
if inner[i] == '\\' {
escaped = true
continue
}
if inner[i] == '"' {
return fmt.Errorf("QEMU argument token %q contains unescaped double quote", tok)
}
}
if escaped {
return fmt.Errorf("QEMU argument token %q ends with dangling escape", tok)
}
}
} else {
if strings.ContainsAny(tok, " \t\"'") {
return fmt.Errorf("QEMU argument token %q contains unquoted whitespace or quotes", tok)
}
}
resplit := SplitShellTokens(tok)
if len(resplit) != 1 || resplit[0] != tok {
return fmt.Errorf("QEMU argument token %q does not round-trip as a single token", tok)
}
return nil
}
// ValidateArgFragment checks that every token is a single shell-safe token and
// every flag belongs to the host allowlist (B4, §4.4).
func ValidateArgFragment(frag ArgFragment) error {
if len(frag.Tokens) == 0 {
return nil
}
for _, tok := range frag.Tokens {
if err := validateSingleShellToken(tok); err != nil {
return err
}
}
for i := 0; i < len(frag.Tokens); i++ {
tok := frag.Tokens[i]
if !strings.HasPrefix(tok, "-") {
return fmt.Errorf("unexpected positional QEMU argument %q", tok)
}
flagName := tok
if eq := strings.IndexByte(flagName, '='); eq > 0 {
flagName = flagName[:eq]
}
allowed, exists := AllowedQEMUOptionFamilies[flagName]
if !exists || !allowed {
return fmt.Errorf("QEMU option %q is not in plugin allowlist", flagName)
}
// Value-taking flags without '=' must carry their argument value in this fragment.
if flagName != "-no-reboot" && flagName != "-usb" && !strings.Contains(tok, "=") {
if i+1 >= len(frag.Tokens) || strings.HasPrefix(frag.Tokens[i+1], "-") {
return fmt.Errorf("QEMU option %q requires a value token", flagName)
}
i++
}
}
return nil
}
// ValidateEnvKey checks whether pluginID is allowed to set envKey (§4.4).
// Shared host env vars (e.g. VK_ICD_FILENAMES, REIMS_GO_INPUT_*) are restricted
// to built-in plugins; external plugins may only set their own REIMS_PLUGIN_<ID>_* namespace.
func ValidateEnvKey(pluginID, envKey string) bool {
if envKey == "" || strings.ContainsAny(envKey, "=\r\n\x00") {
return false
}
if strings.HasPrefix(pluginID, "builtin.") && AllowedHostEnvVars[envKey] {
return true
}
prefix := "REIMS_PLUGIN_" + sanitizeEnvPrefix(pluginID) + "_"
return strings.HasPrefix(envKey, prefix)
}
func sanitizeEnvPrefix(pluginID string) string {
var b strings.Builder
for _, r := range strings.ToUpper(pluginID) {
if (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') {
b.WriteRune(r)
} else {
b.WriteByte('_')
}
}
return b.String()
}
// ReconcileStartIntents strips previously owned fragments from currentExtraArgs
// (preserving ALL unowned user args), arbitrates conflicts across new intents,
// validates option allowlists & env prefixes, updates the ledger, and returns
// the single merged extra-args string ready for one `reims-ctl set` call (§4.4).
func ReconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlugins map[string]bool, intents []StartIntent) ReconcileResult {
if ledger == nil {
ledger = &ArgLedger{Version: 1, Owners: map[string][]ArgFragment{}}
}
if ledger.Owners == nil {
ledger.Owners = map[string][]ArgFragment{}
}
// 1. Extract user-owned (unmanaged) tokens by stripping all previously
// recorded ledger fragments from currentExtraArgs.
userTokens := stripOwnedTokens(SplitShellTokens(currentExtraArgs), ledger)
// 2. Drop ledger entries for plugins that are no longer active.
if activePlugins != nil {
for pid := range ledger.Owners {
if !activePlugins[pid] {
delete(ledger.Owners, pid)
}
}
}
var res ReconcileResult
// Track chosen fragments per logical key for conflict arbitration.
type winner struct {
frag ArgFragment
}
byKey := make(map[string]winner)
envMap := make(map[string]string)
// Carry forward existing active plugins' fragments unless replaced/cleared.
newOwners := make(map[string][]ArgFragment)
for pid, frags := range ledger.Owners {
cp := make([]ArgFragment, len(frags))
copy(cp, frags)
newOwners[pid] = cp
}
for _, intent := range intents {
pid := intent.PluginID
isBuiltin := strings.HasPrefix(pid, "builtin.")
res.Warnings = append(res.Warnings, intent.Warnings...)
for _, ps := range intent.PostStart {
if !isBuiltin && (ps.Kind == "qmp.watch_cold_reboot" || ps.Kind == "guesttools.sync") {
res.Warnings = append(res.Warnings, fmt.Sprintf("plugin %s post-start action %q rejected (builtin only)", pid, ps.Kind))
continue
}
ps.PluginID = pid
res.PostStart = append(res.PostStart, ps)
}
if len(intent.ClearKeys) > 0 {
clearSet := make(map[string]bool, len(intent.ClearKeys))
for _, k := range intent.ClearKeys {
clearSet[k] = true
}
kept := newOwners[pid][:0]
for _, f := range newOwners[pid] {
if !clearSet[f.Key] {
kept = append(kept, f)
}
}
if len(kept) == 0 {
delete(newOwners, pid)
} else {
newOwners[pid] = kept
}
}
if len(intent.Args) > 0 {
// Replace keys provided by this intent for pid.
providedKeys := make(map[string]bool, len(intent.Args))
var valid []ArgFragment
for _, frag := range intent.Args {
frag.PluginID = pid
if !isBuiltin {
frag.Builtin = false
}
if err := ValidateArgFragment(frag); err != nil {
res.Warnings = append(res.Warnings, fmt.Sprintf("plugin %s arg rejected: %v", pid, err))
continue
}
providedKeys[frag.Key] = true
valid = append(valid, frag)
}
var mergedOwner []ArgFragment
for _, existing := range newOwners[pid] {
if !providedKeys[existing.Key] {
mergedOwner = append(mergedOwner, existing)
}
}
mergedOwner = append(mergedOwner, valid...)
if len(mergedOwner) > 0 {
newOwners[pid] = mergedOwner
}
}
for k, v := range intent.Env {
if !ValidateEnvKey(pid, k) {
res.Warnings = append(res.Warnings, fmt.Sprintf("plugin %s env %q rejected (outside namespace/allowlist)", pid, k))
continue
}
envMap[k] = v
}
}
// 3. Arbitrate conflicts across plugins for the same logical key (builtin or higher priority wins).
pluginIDs := make([]string, 0, len(newOwners))
for pid := range newOwners {
pluginIDs = append(pluginIDs, pid)
}
sort.Strings(pluginIDs)
var unkeyed []ArgFragment
for _, pid := range pluginIDs {
for _, frag := range newOwners[pid] {
if frag.Key == "" {
unkeyed = append(unkeyed, frag)
continue
}
prev, exists := byKey[frag.Key]
if !exists {
byKey[frag.Key] = winner{frag: frag}
continue
}
// Conflict!
if fragWins(frag, prev.frag) {
res.Warnings = append(res.Warnings, fmt.Sprintf("QEMU option conflict on %q: %s overrode %s", frag.Key, frag.PluginID, prev.frag.PluginID))
byKey[frag.Key] = winner{frag: frag}
} else {
res.Warnings = append(res.Warnings, fmt.Sprintf("QEMU option conflict on %q: %s kept over %s", frag.Key, prev.frag.PluginID, frag.PluginID))
}
}
}
// Rebuild ledger.Owners with winning fragments only.
ledger.Owners = make(map[string][]ArgFragment)
keys := make([]string, 0, len(byKey))
for k := range byKey {
keys = append(keys, k)
}
sort.Strings(keys)
finalTokens := append([]string(nil), userTokens...)
for _, k := range keys {
w := byKey[k].frag
ledger.Owners[w.PluginID] = append(ledger.Owners[w.PluginID], w)
finalTokens = append(finalTokens, w.Tokens...)
}
for _, f := range unkeyed {
ledger.Owners[f.PluginID] = append(ledger.Owners[f.PluginID], f)
finalTokens = append(finalTokens, f.Tokens...)
}
// Format env slice deterministically.
if len(envMap) > 0 {
envKeys := make([]string, 0, len(envMap))
for k := range envMap {
envKeys = append(envKeys, k)
}
sort.Strings(envKeys)
for _, k := range envKeys {
res.Env = append(res.Env, k+"="+envMap[k])
}
}
res.ExtraArgs = strings.TrimSpace(strings.Join(finalTokens, " "))
res.Changed = strings.TrimSpace(currentExtraArgs) != res.ExtraArgs
return res
}
// StripPluginFromArgs removes all fragments owned by pluginID from currentExtraArgs
// and updates ledger, leaving user args and other plugins' args intact.
func StripPluginFromArgs(currentExtraArgs string, ledger *ArgLedger, pluginID string) (string, bool) {
if ledger == nil || len(ledger.Owners[pluginID]) == 0 {
return strings.TrimSpace(currentExtraArgs), false
}
sub := &ArgLedger{Owners: map[string][]ArgFragment{pluginID: ledger.Owners[pluginID]}}
tokens := stripOwnedTokens(SplitShellTokens(currentExtraArgs), sub)
delete(ledger.Owners, pluginID)
next := strings.TrimSpace(strings.Join(tokens, " "))
return next, next != strings.TrimSpace(currentExtraArgs)
}
func fragWins(candidate, existing ArgFragment) bool {
if candidate.Builtin != existing.Builtin {
return candidate.Builtin
}
if candidate.Priority != existing.Priority {
return candidate.Priority > existing.Priority
}
return candidate.PluginID < existing.PluginID
}
func stripOwnedTokens(tokens []string, ledger *ArgLedger) []string {
if len(tokens) == 0 || ledger == nil || len(ledger.Owners) == 0 {
return tokens
}
// Collect all owned token sequences to remove.
var seqs [][]string
for _, frags := range ledger.Owners {
for _, f := range frags {
if len(f.Tokens) > 0 {
seqs = append(seqs, f.Tokens)
}
}
}
if len(seqs) == 0 {
return tokens
}
// Match longest sequences first so composite fragments don't partially match.
sort.Slice(seqs, func(i, j int) bool {
return len(seqs[i]) > len(seqs[j])
})
out := make([]string, 0, len(tokens))
for i := 0; i < len(tokens); {
matched := false
for _, seq := range seqs {
if i+len(seq) <= len(tokens) && tokensEqual(tokens[i:i+len(seq)], seq) {
i += len(seq)
matched = true
break
}
}
if !matched {
out = append(out, tokens[i])
i++
}
}
return out
}
func tokensEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// SplitShellTokens splits a QEMU extra-args string preserving quoted tokens.
func SplitShellTokens(s string) []string {
var out []string
var cur strings.Builder
var quote byte
for i := 0; i < len(s); i++ {
c := s[i]
if quote != 0 {
cur.WriteByte(c)
if c == quote {
quote = 0
}
continue
}
if c == '\'' || c == '"' {
quote = c
cur.WriteByte(c)
continue
}
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
if cur.Len() > 0 {
out = append(out, cur.String())
cur.Reset()
}
continue
}
cur.WriteByte(c)
}
if cur.Len() > 0 {
out = append(out, cur.String())
}
return out
}
+999
View File
@@ -0,0 +1,999 @@
package plugin
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
// SidecarDriverFactory builds a guest driver proxy from a Sidecar contribution
// and supervisor without importing internal/driver into internal/plugin.
type SidecarDriverFactory func(contrib GuestDriverContribution, sup *SidecarSupervisor) any
// ManagerOptions configures the high-level Plugin Manager.
type ManagerOptions struct {
DataRoot string
HostVersion string
SafeMode bool
Keyring []SigningKey
RedactFn func(string) string
Logger func(source, line string)
SidecarDriverFactory SidecarDriverFactory
OnSettingsChanged func(pluginID, vmName string)
}
// ActiveThemePayload is sent to the frontend to apply L1/L2/Tier-3 themes (§5.1).
type ActiveThemePayload struct {
ThemeID string `json:"theme_id"`
PluginID string `json:"plugin_id,omitempty"`
ActiveScheme string `json:"active_scheme,omitempty"`
Theme *ThemeContribution `json:"theme,omitempty"`
CustomSchemes []CustomThemeScheme `json:"custom_schemes,omitempty"`
CSS string `json:"css,omitempty"`
AssetBaseURL string `json:"asset_base_url,omitempty"`
UIScriptURL string `json:"ui_script_url,omitempty"`
UIScriptTrust TrustLevel `json:"ui_script_trust,omitempty"`
}
// Manager coordinates Registry, StateStore, package installation, safe mode,
// settings, themes, AssetServer, Broker, and L3 Sidecar supervisors.
type Manager struct {
opts ManagerOptions
layout PluginsLayout
store *StateStore
registry *Registry
broker *Broker
assets *AssetServer
mu sync.RWMutex
state *StateFile
stateLoadErr error
safeMode bool
crashDetected bool
installDirs map[string]string // pluginID -> dir (for AssetServer)
supervisors map[string]*SidecarSupervisor
}
// NewManager initializes the Plugin Manager for DataRoot. If state.json is
// corrupt, stateLoadErr is recorded and returned on load rather than wiping state (§6.1).
func NewManager(opts ManagerOptions) (*Manager, error) {
layout := NewPluginsLayout(opts.DataRoot)
reg := NewRegistry(opts.Logger)
broker := NewBroker(layout, reg, opts.RedactFn)
m := &Manager{
opts: opts,
layout: layout,
store: NewStateStore(layout.Root),
registry: reg,
broker: broker,
safeMode: opts.SafeMode,
crashDetected: DidLastStartupCrash(layout.Root),
installDirs: make(map[string]string),
supervisors: make(map[string]*SidecarSupervisor),
}
m.assets = NewAssetServer(func(pluginID string) (string, bool) {
m.mu.RLock()
dir, ok := m.installDirs[pluginID]
m.mu.RUnlock()
return dir, ok
})
st, err := m.store.Load()
if err != nil {
m.stateLoadErr = err
return m, err
}
m.state = st
return m, nil
}
func (m *Manager) Registry() *Registry { return m.registry }
func (m *Manager) Broker() *Broker { return m.broker }
func (m *Manager) Assets() *AssetServer { return m.assets }
func (m *Manager) Layout() PluginsLayout { return m.layout }
func (m *Manager) SafeMode() bool { return m.safeMode }
func (m *Manager) CrashDetected() bool { return m.crashDetected }
// DesiredFor returns whether pluginID should be enabled according to state.json,
// falling back to defaultEnabled if no saved record exists.
func (m *Manager) DesiredFor(id string, defaultEnabled bool) bool {
m.mu.RLock()
defer m.mu.RUnlock()
if m.state != nil {
if rec, ok := m.state.Plugins[id]; ok {
return rec.Enabled
}
}
return defaultEnabled
}
// LoadBundled registers official L1 plugins embedded inside reims-go.exe (§9).
func (m *Manager) LoadBundled(manifests []Manifest) error {
for _, man := range manifests {
if err := ValidateManifest(man, m.opts.HostVersion, true); err != nil {
return fmt.Errorf("invalid bundled plugin %s: %w", man.ID, err)
}
desired := m.DesiredFor(man.ID, man.DefaultEnabled)
if m.safeMode {
// Bundled official L1 plugins obey safe mode too if non-builtin?
// §9: safe mode skips all third-party plugins; bundled official defaults to off anyway.
if !man.DefaultEnabled {
desired = false
}
}
if err := m.registry.Register(PluginDef{
Manifest: man,
Source: SourceBundled,
Trust: TrustOfficial,
Removable: false,
Desired: desired,
LogPath: m.layout.LogPath(man.ID),
}); err != nil {
return err
}
}
return nil
}
// LoadExternal loads all installed packages and dev links from state.json.
// In SafeMode, external plugins are registered as disabled (off) so the user
// can inspect and remove/disable faulty plugins safely (§9).
func (m *Manager) LoadExternal() error {
m.mu.RLock()
st := m.state
safe := m.safeMode
var devMode bool
var activeThemeID string
type extEntry struct {
id string
rec PluginRecord
}
var entries []extEntry
if st != nil {
devMode = st.DeveloperMode
activeThemeID = st.ActiveThemeID
for id, rec := range st.Plugins {
if rec == nil || rec.Source == SourceBuiltin || rec.Source == SourceBundled {
continue
}
cp := *rec
cp.ApprovedPermissions = append([]string(nil), rec.ApprovedPermissions...)
entries = append(entries, extEntry{id: id, rec: cp})
}
}
m.mu.RUnlock()
if st == nil {
return m.stateLoadErr
}
if !safe {
_ = BeginStartupInit(m.layout.Root)
defer EndStartupInit(m.layout.Root)
}
for _, item := range entries {
id := item.id
rec := item.rec
var dir string
switch rec.Source {
case SourceDevLink:
if !devMode {
continue
}
dir = rec.DevPath
default:
if rec.Version == "" || !reReverseDomainID.MatchString(id) {
continue
}
if _, err := ParseSemVer(rec.Version); err != nil {
continue
}
safeDir, err := safeJoin(m.layout.PkgsDir(), id+"/"+rec.Version)
if err != nil {
continue
}
dir = safeDir
}
if dir == "" {
continue
}
if err := m.registerExternalDir(dir, &rec, safe); err != nil && m.opts.Logger != nil {
m.opts.Logger("plugin", fmt.Sprintf("skipped external plugin %s: %v", id, err))
}
}
// Restore active theme unless in safe mode (§5.1: safe mode always reverts to builtin theme).
if !safe && activeThemeID != "" {
_ = m.registry.SetActiveTheme(activeThemeID)
}
return nil
}
func (m *Manager) registerExternalDir(dir string, rec *PluginRecord, safeMode bool) error {
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
if err != nil {
return err
}
var man Manifest
if err := json.Unmarshal(raw, &man); err != nil {
return err
}
if err := ValidateManifest(man, m.opts.HostVersion, false); err != nil {
return err
}
if rec.ID != "" && man.ID != rec.ID {
return fmt.Errorf("manifest plugin id %q does not match state record %q", man.ID, rec.ID)
}
trust := rec.Trust
if trust == "" {
trust = TrustCommunity
}
if rec.Source == SourceDevLink {
trust = TrustDev
}
entryRel := man.Entry.Sidecar
if entryRel == "" {
entryRel = man.Entry.UIScript
}
if entryRel == "" {
entryRel = man.Entry.Script
}
entryAbs := ""
entryHash := ""
if entryRel != "" {
full, err := safeJoin(dir, entryRel)
if err != nil {
return fmt.Errorf("invalid plugin entry path %q: %w", entryRel, err)
}
entryAbs = full
entryHash, _ = fileSHA256Hex(full)
}
needsApproval := computeNeedsApproval(man, trust, rec.ApprovedPermissions, rec.ApprovedEntryHash, entryHash)
desired := rec.Enabled && !safeMode && !needsApproval
m.mu.Lock()
m.installDirs[man.ID] = dir
m.mu.Unlock()
tier := man.InferTier(false)
var activate Activator
if tier == TierL3 && entryAbs != "" {
activate = m.buildSidecarActivator(man, entryAbs, rec.BlockingGuardOK)
}
return m.registry.Register(PluginDef{
Manifest: man,
Source: rec.Source,
Trust: trust,
InstallDir: dir,
EntryPath: entryAbs,
EntryHash: entryHash,
LogPath: m.layout.LogPath(man.ID),
Removable: true,
Desired: desired,
ApprovedPermissions: append([]string(nil), rec.ApprovedPermissions...),
NeedsApproval: needsApproval,
Activate: activate,
})
}
func computeNeedsApproval(m Manifest, trust TrustLevel, approvedPerms []string, approvedHash, currentHash string) bool {
if trust == TrustOfficial {
return false
}
approvedSet := make(map[string]bool, len(approvedPerms))
for _, p := range approvedPerms {
approvedSet[p] = true
}
// Any unapproved high-risk permission requires explicit confirmation (§7.1).
for _, hp := range HighRiskPermissions(m.Permissions) {
if !approvedSet[hp] {
return true
}
}
// Community L3 sidecar requires explicit hash approval (§7.2).
if trust == TrustCommunity && m.InferTier(false) == TierL3 {
if currentHash == "" || approvedHash != currentHash {
return true
}
}
return false
}
func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAllowed bool) Activator {
return func(ctx context.Context, sc *Scope) error {
pid := man.ID
sup := NewSidecarSupervisor(SidecarOptions{
PluginID: pid,
ExePath: exePath,
DataDir: m.layout.DataDir(pid),
Broker: m.broker,
Registry: m.registry,
IdleTimeout: 5 * time.Minute,
})
m.mu.Lock()
m.supervisors[pid] = sup
m.mu.Unlock()
sc.OnDispose(func() {
sup.Stop()
m.mu.Lock()
if m.supervisors[pid] == sup {
delete(m.supervisors, pid)
}
m.mu.Unlock()
})
// Wire Sidecar hooks.
for _, hk := range man.Contributes.Hooks {
h := hk
m.registry.Hooks().Subscribe(sc, HookRegistration{
PluginID: pid,
Event: h.Event,
Priority: h.Priority,
Blocking: h.Blocking,
BlockingAllowed: blockingAllowed,
Handler: func(hctx context.Context, payload any) (any, error) {
switch h.Event {
case EventVMBeforeStart:
var intent StartIntent
if err := sup.Call(hctx, "hook/"+h.Event, payload, &intent); err != nil {
return nil, err
}
intent.PluginID = pid
return intent, nil
case EventHostPreflight:
var pr PreflightResult
if err := sup.Call(hctx, "hook/"+h.Event, payload, &pr); err != nil {
return nil, err
}
return pr, nil
case EventVMBeforeCreate:
var bcr BeforeCreateResult
if err := sup.Call(hctx, "hook/"+h.Event, payload, &bcr); err != nil {
return nil, err
}
return bcr, nil
default:
var out any
err := sup.Call(hctx, "hook/"+h.Event, payload, &out)
return out, err
}
},
})
}
// Wire Sidecar commands.
for _, cmd := range man.Contributes.Commands {
c := cmd
m.registry.RegisterCommand(sc, c, func(cctx context.Context, args map[string]any) (any, error) {
var out any
err := sup.Call(cctx, "command/invoke", map[string]any{
"command": c.ID,
"args": args,
}, &out)
return out, err
})
}
// Wire Sidecar diagnostics collectors.
for _, diag := range man.Contributes.Diagnostics {
dg := diag
m.registry.RegisterDiagnostics(sc, dg, func(dctx context.Context, vmName string) (DiagnosticsEntry, error) {
var entry DiagnosticsEntry
err := sup.Call(dctx, "diagnostics/collect", map[string]any{
"id": dg.ID,
"vm_name": vmName,
}, &entry)
return entry, err
})
}
// Wire Sidecar guest drivers.
if m.opts.SidecarDriverFactory != nil {
for _, gd := range man.Contributes.GuestDrivers {
drv := m.opts.SidecarDriverFactory(gd, sup)
if drv != nil {
m.registry.RegisterGuestDriver(sc, gd.ID, drv)
}
}
}
// Eagerly start only if activation explicitly includes "onStartup" (§8).
for _, act := range man.Activation {
if strings.EqualFold(act, "onStartup") {
if err := sup.EnsureStarted(ctx); err != nil {
return err
}
break
}
}
return nil
}
}
// InstallLocalArchive transactionally installs a local .zip plugin package and
// records it in state.json (disabled by default until user enables/approves it).
func (m *Manager) InstallLocalArchive(ctx context.Context, archivePath string, opts PackageInstallOptions) (*PluginInfo, error) {
if opts.HostVersion == "" {
opts.HostVersion = m.opts.HostVersion
}
if len(opts.Keyring) == 0 {
opts.Keyring = m.opts.Keyring
}
opts.AllowUnsigned = true
installed, err := InstallArchive(m.layout, archivePath, opts)
if err != nil {
return nil, err
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return nil, errors.New("plugin state not loaded")
}
rec := m.state.Plugins[installed.Manifest.ID]
if rec == nil {
rec = &PluginRecord{
ID: installed.Manifest.ID,
Source: SourceLocal,
Enabled: false,
}
m.state.Plugins[installed.Manifest.ID] = rec
}
// Preserve previously installed versions for rollback (§9).
foundVer := false
for _, v := range rec.InstalledVersions {
if v == installed.Manifest.Version {
foundVer = true
break
}
}
if !foundVer {
rec.InstalledVersions = append(rec.InstalledVersions, installed.Manifest.Version)
}
rec.Version = installed.Manifest.Version
rec.Source = SourceLocal
rec.Trust = installed.Trust
rec.UpdatedAt = time.Now()
// If upgrade introduces unapproved high-risk permissions or changed binary hash, pause it (§7.1).
if computeNeedsApproval(installed.Manifest, installed.Trust, rec.ApprovedPermissions, rec.ApprovedEntryHash, installed.EntryHash) {
rec.Enabled = false
}
if err := m.store.Save(m.state); err != nil {
m.mu.Unlock()
return nil, err
}
recCopy := *rec
m.mu.Unlock()
if err := m.registerExternalDir(installed.InstallDir, &recCopy, m.safeMode); err != nil {
return nil, err
}
m.registry.Reconcile(ctx)
info, _ := m.registry.Info(installed.Manifest.ID)
return &info, nil
}
// LinkDev links a local plugin directory in developer mode (trust=dev, §5.1, §9).
func (m *Manager) LinkDev(ctx context.Context, dir string) (*PluginInfo, error) {
absDir, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
raw, err := os.ReadFile(filepath.Join(absDir, "plugin.json"))
if err != nil {
return nil, fmt.Errorf("read plugin.json: %w", err)
}
var man Manifest
if err := json.Unmarshal(raw, &man); err != nil {
return nil, fmt.Errorf("parse plugin.json: %w", err)
}
if err := ValidateManifest(man, m.opts.HostVersion, false); err != nil {
return nil, err
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return nil, m.stateNotLoadedErr()
}
m.state.DeveloperMode = true
rec := m.state.Plugins[man.ID]
if rec == nil {
rec = &PluginRecord{ID: man.ID}
m.state.Plugins[man.ID] = rec
}
rec.Source = SourceDevLink
rec.Trust = TrustDev
rec.Version = man.Version
rec.DevPath = absDir
rec.Enabled = false
rec.UpdatedAt = time.Now()
if err := m.store.Save(m.state); err != nil {
m.mu.Unlock()
return nil, err
}
recCopy := *rec
m.mu.Unlock()
if err := m.registerExternalDir(absDir, &recCopy, m.safeMode); err != nil {
return nil, err
}
m.registry.Reconcile(ctx)
info, _ := m.registry.Info(man.ID)
return &info, nil
}
// Enable activates a plugin, optionally recording high-risk permission approval (§7.1, §7.2).
func (m *Manager) Enable(ctx context.Context, id string, approveHighRisk bool) error {
info, ok := m.registry.Info(id)
if !ok {
return fmt.Errorf("plugin %q not found", id)
}
if m.safeMode && info.Source != SourceBuiltin {
return errors.New("cannot enable third-party plugins in safe mode")
}
if info.NeedsApproval && !approveHighRisk {
return fmt.Errorf("plugin %q requires explicit high-risk permission approval", id)
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
rec := m.state.Plugins[id]
if rec == nil {
rec = &PluginRecord{ID: id, Source: info.Source, Trust: info.Trust, Version: info.Version}
m.state.Plugins[id] = rec
}
prevEnabled := rec.Enabled
prevApprovedPerms := append([]string(nil), rec.ApprovedPermissions...)
prevApprovedHash := rec.ApprovedEntryHash
rec.Enabled = true
rec.UpdatedAt = time.Now()
if approveHighRisk {
perms := make([]string, 0, len(info.Permissions))
for _, p := range info.Permissions {
perms = append(perms, p.Name)
}
rec.ApprovedPermissions = perms
rec.ApprovedEntryHash = info.EntryHash
}
dir := info.InstallDir
recCopy := *rec
recCopy.ApprovedPermissions = append([]string(nil), rec.ApprovedPermissions...)
m.mu.Unlock()
if approveHighRisk && dir != "" && info.Source != SourceBuiltin && info.Source != SourceBundled {
if err := m.registerExternalDir(dir, &recCopy, false); err != nil {
m.mu.Lock()
rec.Enabled = prevEnabled
rec.ApprovedPermissions = prevApprovedPerms
rec.ApprovedEntryHash = prevApprovedHash
m.mu.Unlock()
return err
}
}
if err := m.registry.SetDesired(ctx, id, true); err != nil {
m.mu.Lock()
rec.Enabled = prevEnabled
rec.ApprovedPermissions = prevApprovedPerms
rec.ApprovedEntryHash = prevApprovedHash
m.mu.Unlock()
return err
}
m.mu.Lock()
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
// Disable turns off a plugin (if not in use) and persists the state.
func (m *Manager) Disable(ctx context.Context, id string) error {
if err := m.registry.SetDesired(ctx, id, false); err != nil {
return err
}
activeThemeNil := m.registry.ActiveTheme() == nil
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
rec := m.state.Plugins[id]
if rec == nil {
rec = &PluginRecord{ID: id}
m.state.Plugins[id] = rec
}
rec.Enabled = false
rec.UpdatedAt = time.Now()
if m.state.ActiveThemeID != "" && activeThemeNil {
// If disabling the active theme's plugin, fall back to builtin default theme (§5.1).
m.state.ActiveThemeID = ""
}
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
// Remove uninstalls a removable external plugin (refusing builtins/bundled or in-use plugins).
func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error {
info, ok := m.registry.Info(id)
if !ok {
return fmt.Errorf("plugin %q not found", id)
}
if !info.Removable {
return fmt.Errorf("plugin %q is built-in or bundled and cannot be uninstalled (disable it instead)", id)
}
if err := m.registry.Unregister(ctx, id); err != nil {
return err
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
delete(m.state.Plugins, id)
delete(m.installDirs, id)
err := m.store.Save(m.state)
m.mu.Unlock()
if err != nil {
return err
}
_ = os.RemoveAll(filepath.Join(m.layout.PkgsDir(), id))
if purgeData {
_ = os.RemoveAll(m.layout.DataDir(id))
_ = os.Remove(m.layout.LogPath(id))
}
return nil
}
func (m *Manager) stateNotLoadedErr() error {
if m.stateLoadErr != nil {
return m.stateLoadErr
}
return errors.New("plugin state not loaded")
}
// --- Settings store (app-scoped & vm-scoped, hiding x-secret on readback) ---
func (m *Manager) GetSettings(pluginID, vmName string, maskSecrets bool) map[string]any {
var schema *SettingsSchema
if info, ok := m.registry.Info(pluginID); ok {
schema = info.Settings
}
m.mu.RLock()
defer m.mu.RUnlock()
out := map[string]any{}
// Seed defaults from schema.
if schema != nil {
for k, prop := range schema.Properties {
if prop.Default != nil {
out[k] = prop.Default
}
}
}
if m.state != nil {
if rec := m.state.Plugins[pluginID]; rec != nil {
if vmName == "" {
for k, v := range rec.AppSettings {
out[k] = v
}
} else if vmMap := rec.VMSettings[vmName]; vmMap != nil {
for k, v := range vmMap {
out[k] = v
}
}
}
}
if maskSecrets && schema != nil {
for k, prop := range schema.Properties {
if prop.Secret {
if _, exists := out[k]; exists && out[k] != "" {
out[k] = "••••••••"
}
}
}
}
return out
}
func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) error {
info, hasInfo := m.registry.Info(pluginID)
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
rec := m.state.Plugins[pluginID]
if rec == nil {
rec = &PluginRecord{ID: pluginID}
if hasInfo {
rec.Source = info.Source
rec.Trust = info.Trust
rec.Enabled = info.Enabled
}
m.state.Plugins[pluginID] = rec
}
isSecretMask := func(k string, v any) bool {
if info.Settings == nil {
return false
}
prop, ok := info.Settings.Properties[k]
if !ok || !prop.Secret {
return false
}
s, ok := v.(string)
return ok && s == "••••••••"
}
if vmName == "" {
if rec.AppSettings == nil {
rec.AppSettings = map[string]any{}
}
for k, v := range values {
if isSecretMask(k, v) {
continue
}
rec.AppSettings[k] = v
}
} else {
if rec.VMSettings == nil {
rec.VMSettings = map[string]map[string]any{}
}
if rec.VMSettings[vmName] == nil {
rec.VMSettings[vmName] = map[string]any{}
}
for k, v := range values {
if isSecretMask(k, v) {
continue
}
rec.VMSettings[vmName][k] = v
}
}
rec.UpdatedAt = time.Now()
err := m.store.Save(m.state)
cb := m.opts.OnSettingsChanged
m.mu.Unlock()
if err == nil && cb != nil {
cb(pluginID, vmName)
}
return err
}
// SavedVMSettingsForPlugin returns a copy of all saved per-VM setting maps for pluginID.
func (m *Manager) SavedVMSettingsForPlugin(pluginID string) map[string]map[string]any {
m.mu.RLock()
defer m.mu.RUnlock()
if m.state == nil {
return nil
}
rec := m.state.Plugins[pluginID]
if rec == nil || len(rec.VMSettings) == 0 {
return nil
}
out := make(map[string]map[string]any, len(rec.VMSettings))
for vmName, kv := range rec.VMSettings {
cp := make(map[string]any, len(kv))
for k, v := range kv {
cp[k] = v
}
out[vmName] = cp
}
return out
}
// GetAllVMSettings returns pluginID -> settings map for vmName across active plugins.
func (m *Manager) GetAllVMSettings(vmName string) map[string]map[string]any {
out := map[string]map[string]any{}
for _, info := range m.registry.List() {
if info.State != StateActive && info.State != StateDegraded {
continue
}
if info.Settings == nil {
continue
}
hasVMProp := info.Settings.Scope == "vm"
if !hasVMProp {
for _, p := range info.Settings.Properties {
if p.Scope == "vm" {
hasVMProp = true
break
}
}
}
if hasVMProp {
out[info.ID] = m.GetSettings(info.ID, vmName, true)
}
}
return out
}
// --- Theme Management (§5.1) ---
func (m *Manager) SetActiveTheme(themeID, schemeID string) error {
if m.safeMode && themeID != "" && themeID != "builtin.theme.default" {
return errors.New("custom themes are disabled in safe mode")
}
if err := m.registry.SetActiveTheme(themeID); err != nil {
return err
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
m.state.ActiveThemeID = themeID
m.state.ActiveSchemeID = schemeID
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
func (m *Manager) SaveCustomThemeScheme(scheme CustomThemeScheme) error {
if strings.TrimSpace(scheme.ID) == "" || strings.TrimSpace(scheme.Name) == "" {
return errors.New("scheme id and name required")
}
for k, v := range scheme.Seeds {
if err := ValidateCSSTokenValue(v); err != nil {
return fmt.Errorf("invalid seed %q: %w", k, err)
}
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
updated := false
for i := range m.state.CustomSchemes {
if m.state.CustomSchemes[i].ID == scheme.ID {
m.state.CustomSchemes[i] = scheme
updated = true
break
}
}
if !updated {
m.state.CustomSchemes = append(m.state.CustomSchemes, scheme)
}
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
func (m *Manager) DeleteCustomThemeScheme(schemeID string) error {
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
kept := m.state.CustomSchemes[:0]
for _, s := range m.state.CustomSchemes {
if s.ID != schemeID {
kept = append(kept, s)
}
}
m.state.CustomSchemes = kept
if m.state.ActiveSchemeID == schemeID {
m.state.ActiveSchemeID = ""
}
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
// ActiveThemePayload builds the resolved theme bundle for the frontend (§5.1).
// Returns an empty/default payload when using the builtin theme (zero extra CSS).
func (m *Manager) ActiveThemePayload() ActiveThemePayload {
m.mu.RLock()
activeScheme := ""
var customSchemes []CustomThemeScheme
if m.state != nil {
activeScheme = m.state.ActiveSchemeID
customSchemes = append([]CustomThemeScheme(nil), m.state.CustomSchemes...)
}
m.mu.RUnlock()
if m.safeMode {
return ActiveThemePayload{ThemeID: "builtin.theme.default", CustomSchemes: customSchemes}
}
th := m.registry.ActiveTheme()
if th == nil || th.ID == "builtin.theme.default" {
return ActiveThemePayload{ThemeID: "builtin.theme.default", CustomSchemes: customSchemes}
}
payload := ActiveThemePayload{
ThemeID: th.ID,
PluginID: th.PluginID,
ActiveScheme: activeScheme,
Theme: th,
CustomSchemes: customSchemes,
AssetBaseURL: "/plugin-assets/" + m.assets.Token() + "/" + th.PluginID + "/",
}
m.mu.RLock()
installDir := m.installDirs[th.PluginID]
m.mu.RUnlock()
if installDir != "" && th.Stylesheet != "" {
if full, err := safeJoin(installDir, th.Stylesheet); err == nil {
if raw, err := os.ReadFile(full); err == nil {
if ValidateThemeCSSSafetyInDir(string(raw), filepath.Dir(full)) == nil {
payload.CSS = string(raw)
}
}
}
}
if th.UIScript != "" && validateSafeManifestAsset(th.UIScript, "") == nil {
if info, ok := m.registry.Info(th.PluginID); ok {
hasPerm := false
for _, p := range info.Permissions {
if p.Name == "ui:script" {
hasPerm = true
break
}
}
approved := info.Trust == TrustOfficial || info.Source == SourceBuiltin
if !approved && !info.NeedsApproval {
for _, ap := range info.ApprovedPermissions {
if ap == "ui:script" {
approved = true
break
}
}
}
// Enforce §5.1 trust boundary: ui:script requires declared and approved permission.
if hasPerm && approved {
payload.UIScriptURL = m.assets.AssetURL(th.PluginID, th.UIScript)
payload.UIScriptTrust = info.Trust
}
}
}
return payload
}
// ActiveVMNamesWithSetting scans saved VM settings for pluginID where key==true.
func (m *Manager) ActiveVMNamesWithSetting(pluginID, key string) []string {
m.mu.RLock()
defer m.mu.RUnlock()
if m.state == nil {
return nil
}
rec := m.state.Plugins[pluginID]
if rec == nil || len(rec.VMSettings) == 0 {
return nil
}
var out []string
for vmName, kv := range rec.VMSettings {
if b, ok := kv[key].(bool); ok && b {
out = append(out, vmName)
}
}
sort.Strings(out)
return out
}
// Close shuts down all active plugins and Sidecar supervisors cleanly.
func (m *Manager) Close() {
m.registry.DisposeAll()
m.mu.Lock()
sups := make([]*SidecarSupervisor, 0, len(m.supervisors))
for id, sup := range m.supervisors {
sups = append(sups, sup)
delete(m.supervisors, id)
}
m.mu.Unlock()
for _, sup := range sups {
sup.Stop()
}
}
+395
View File
@@ -0,0 +1,395 @@
package plugin_test
import (
"archive/zip"
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
// TestHelperSidecar acts as an external L3 Sidecar executable when invoked
// with REIMS_TEST_SIDECAR=1 (using the compiled test binary itself so zero
// extra build time is needed and Windows Job Object cleanup is tested live).
func TestHelperSidecar(t *testing.T) {
if os.Getenv("REIMS_TEST_SIDECAR") != "1" {
return
}
mode := os.Getenv("REIMS_TEST_SIDECAR_MODE")
if mode == "crash" {
os.Exit(42)
}
srv := pluginsdk.New()
srv.SetCapability("linux-driver", true)
srv.Handle("command/invoke", func(ctx context.Context, raw json.RawMessage) (any, error) {
var req struct {
Command string `json:"command"`
Args map[string]any `json:"args"`
}
_ = json.Unmarshal(raw, &req)
if req.Command == "hang" {
<-ctx.Done()
return nil, ctx.Err()
}
if req.Command == "notify-host" {
_ = srv.Notify(ctx, "hello", "from sidecar")
}
return map[string]any{"echo": req.Command, "args": req.Args}, nil
})
srv.Handle("hook/vm.beforeStart", func(_ context.Context, raw json.RawMessage) (any, error) {
return plugin.StartIntent{
Args: []plugin.ArgFragment{{
Key: "sidecar-rtc",
Tokens: []string{"-rtc", "base=utc"},
}},
}, nil
})
srv.Handle("diagnostics/collect", func(_ context.Context, _ json.RawMessage) (any, error) {
return plugin.DiagnosticsEntry{
Title: "Sidecar Diag",
Text: "mac=aa:bb:cc:dd:ee:ff serial=C02SECRET1234",
}, nil
})
srv.Handle("driver/list", func(_ context.Context, _ json.RawMessage) (any, error) {
return map[string]any{
"vms": []driver.VMInfo{{
Name: "ubuntu-24",
State: "stopped",
CPUs: 4,
Memory: "8G",
DriverName: "Linux (Test Sidecar)",
}},
}, nil
})
srv.Handle("driver/show", func(_ context.Context, raw json.RawMessage) (any, error) {
var req struct{ Name string }
_ = json.Unmarshal(raw, &req)
return driver.VMInfo{Name: req.Name, State: "stopped", CPUs: 4, Memory: "8G"}, nil
})
_ = srv.Serve(context.Background())
os.Exit(0)
}
func makePluginZip(t *testing.T, files map[string][]byte, priv ed25519.PrivateKey, corruptSum bool) string {
t.Helper()
zipPath := filepath.Join(t.TempDir(), "plugin.zip")
f, err := os.Create(zipPath)
if err != nil {
t.Fatal(err)
}
zw := zip.NewWriter(f)
var sumLines []string
for rel, content := range files {
w, err := zw.Create(rel)
if err != nil {
t.Fatal(err)
}
_, _ = w.Write(content)
h := sha256.Sum256(content)
hexSum := hex.EncodeToString(h[:])
if corruptSum {
hexSum = strings.Repeat("0", 64)
}
sumLines = append(sumLines, fmt.Sprintf("%s %s", hexSum, rel))
}
sumsBytes := []byte(strings.Join(sumLines, "\n") + "\n")
w, _ := zw.Create("SHA256SUMS")
_, _ = w.Write(sumsBytes)
if len(priv) > 0 {
sig := ed25519.Sign(priv, sumsBytes)
sw, _ := zw.Create("SHA256SUMS.sig")
_, _ = sw.Write([]byte(base64.StdEncoding.EncodeToString(sig)))
}
_ = zw.Close()
_ = f.Close()
return zipPath
}
func TestStateStoreRefusesCorruptJSON(t *testing.T) {
dir := t.TempDir()
_ = os.WriteFile(filepath.Join(dir, plugin.StateFileName), []byte("{corrupt"), 0o644)
store := plugin.NewStateStore(dir)
if _, err := store.Load(); err == nil {
t.Fatal("expected error loading corrupt state.json; MUST NOT treat as empty")
}
}
func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) {
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
dataRoot := t.TempDir()
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: "0.2.6",
Keyring: []plugin.SigningKey{{
KeyID: "official-1",
Publisher: "Reims-Go",
Trust: plugin.TrustOfficial,
PublicKey: pub,
}},
RedactFn: reims.RedactText,
})
if err != nil {
t.Fatal(err)
}
defer mgr.Close()
// 1. Valid signed L1 theme pack (token + style + decoration).
manifestJSON, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.aurora",
Version: "1.0.0",
Name: plugin.LocalizedText{ZhCN: "极光测试主题", EnUS: "Aurora Test Theme"},
Description: plugin.LocalizedText{EnUS: "Verifies token+style+decoration theme interface"},
Publisher: "Test",
License: "MIT",
Engines: plugin.Engines{PluginAPI: "^1.0.0", UIAPI: "^1.0.0"},
Contributes: plugin.Contributes{
Themes: []plugin.ThemeContribution{{
ID: "test.theme.aurora",
Name: plugin.LocalizedText{EnUS: "Aurora"},
Appearance: "both",
Seeds: map[string]string{"accent": "#7c3aed"},
Stylesheet: "theme.css",
Decorations: []plugin.ThemeDecoration{{
ID: "mascot",
Slot: "sidebar.footer",
States: []plugin.ThemeDecorationState{
{When: "vmState==running", Asset: "mascot.svg"},
},
}},
}},
},
})
validCSS := []byte(`.rg-p-sidebar { background: var(--surface-sidebar); }`)
svgWithScript := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><circle onclick="evil()" r="4"/></svg>`)
goodZip := makePluginZip(t, map[string][]byte{
"plugin.json": manifestJSON,
"theme.css": validCSS,
"mascot.svg": svgWithScript,
}, priv, false)
info, err := mgr.InstallLocalArchive(context.Background(), goodZip, plugin.PackageInstallOptions{})
if err != nil {
t.Fatalf("InstallLocalArchive valid theme: %v", err)
}
if info.Trust != plugin.TrustOfficial {
t.Fatalf("trust = %s, want official", info.Trust)
}
if err := mgr.Enable(context.Background(), "test.theme.aurora", false); err != nil {
t.Fatalf("enable theme: %v", err)
}
if err := mgr.SetActiveTheme("test.theme.aurora", ""); err != nil {
t.Fatalf("SetActiveTheme: %v", err)
}
payload := mgr.ActiveThemePayload()
if payload.ThemeID != "test.theme.aurora" || !strings.Contains(payload.CSS, ".rg-p-sidebar") {
t.Fatalf("unexpected active theme payload: %+v", payload)
}
// Verify AssetServer token gate, traversal block, and SVG script sanitization (§7.3).
reqBadTok := httptest.NewRequest(http.MethodGet, "/plugin-assets/wrongtoken/test.theme.aurora/mascot.svg", nil)
recBadTok := httptest.NewRecorder()
mgr.Assets().ServeHTTP(recBadTok, reqBadTok)
if recBadTok.Code != http.StatusForbidden {
t.Fatalf("wrong token status = %d, want 403", recBadTok.Code)
}
reqSVG := httptest.NewRequest(http.MethodGet, mgr.Assets().AssetURL("test.theme.aurora", "mascot.svg"), nil)
recSVG := httptest.NewRecorder()
mgr.Assets().ServeHTTP(recSVG, reqSVG)
if recSVG.Code != http.StatusOK {
t.Fatalf("SVG fetch status = %d, want 200", recSVG.Code)
}
if strings.Contains(recSVG.Body.String(), "<script") || strings.Contains(recSVG.Body.String(), "onclick") {
t.Fatalf("SVG was not sanitized: %s", recSVG.Body.String())
}
if recSVG.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Fatal("missing X-Content-Type-Options: nosniff")
}
// Verify plugin doctor validates CSS against UI contract (§5.1).
contract := &plugin.UIContract{
UIAPI: "1.0.0",
Parts: []string{"rg-p-sidebar"},
Tokens: []string{"--surface-sidebar"},
}
findings := plugin.DoctorDirectory(info.InstallDir, "0.2.6", contract)
for _, f := range findings {
if f.Severity == "error" || f.Severity == "warn" {
t.Fatalf("unexpected doctor finding on valid theme: %+v", f)
}
}
// 2. Corrupt checksum zip must be rejected before touching disk/state.
badSumZip := makePluginZip(t, map[string][]byte{"plugin.json": manifestJSON, "theme.css": validCSS}, nil, true)
if _, err := mgr.InstallLocalArchive(context.Background(), badSumZip, plugin.PackageInstallOptions{}); err == nil {
t.Fatal("expected corrupt SHA256SUMS zip to be rejected")
}
// 3. Incompatible pluginApi zip must be rejected before install.
incompatManifest, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.incompat.pkg",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Incompat"},
Engines: plugin.Engines{PluginAPI: "^9.0.0"},
})
incompatZip := makePluginZip(t, map[string][]byte{"plugin.json": incompatManifest}, nil, false)
if _, err := mgr.InstallLocalArchive(context.Background(), incompatZip, plugin.PackageInstallOptions{}); err == nil {
t.Fatal("expected incompatible pluginApi zip to be rejected")
}
// 4. Market redline: reject Apple .ipsw inside zip.
redlineZip := makePluginZip(t, map[string][]byte{
"plugin.json": manifestJSON,
"Universal.ipsw": []byte("nope"),
}, nil, false)
if _, err := mgr.InstallLocalArchive(context.Background(), redlineZip, plugin.PackageInstallOptions{}); err == nil {
t.Fatal("expected Apple .ipsw zip to be rejected by redline")
}
// 5. Anti-swap ID check.
if _, err := mgr.InstallLocalArchive(context.Background(), goodZip, plugin.PackageInstallOptions{ExpectedID: "other.id"}); err == nil {
t.Fatal("expected anti-swap ID mismatch error")
}
}
func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) {
exePath, err := os.Executable()
if err != nil {
t.Fatal(err)
}
dataRoot := t.TempDir()
layout := plugin.NewPluginsLayout(dataRoot)
reg := plugin.NewRegistry(nil)
broker := plugin.NewBroker(layout, reg, reims.RedactText)
notified := make(chan string, 1)
broker.SetNotifier(func(pid, title, body string) {
notified <- pid + ":" + title
})
t.Setenv("REIMS_TEST_SIDECAR", "1")
t.Setenv("REIMS_TEST_SIDECAR_MODE", "")
sup := plugin.NewSidecarSupervisor(plugin.SidecarOptions{
PluginID: "test.sidecar.linux",
ExePath: exePath,
Args: []string{"-test.run=^TestHelperSidecar$"},
DataDir: layout.DataDir("test.sidecar.linux"),
Broker: broker,
Registry: reg,
})
defer sup.Stop()
_ = reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{
ID: "test.sidecar.linux",
Version: "1.0.0",
Permissions: []string{"ui:notify", "driver:vm", "vm:intent"},
},
Source: plugin.SourceLocal,
Trust: plugin.TrustVerified,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.OnDispose(func() { sup.Stop() })
drv := driver.NewSidecarDriver(plugin.GuestDriverContribution{
ID: "test.driver.linux",
Name: plugin.LocalizedText{EnUS: "Linux"},
RuntimeKind: "qemu-ovmf",
}, sup)
reg.RegisterGuestDriver(sc, "test.driver.linux", drv)
reg.RegisterDiagnostics(sc, plugin.DiagnosticsContribution{
ID: "sidecar-diag",
Title: plugin.LocalizedText{EnUS: "Sidecar Diag"},
}, func(ctx context.Context, vm string) (plugin.DiagnosticsEntry, error) {
var e plugin.DiagnosticsEntry
err := sup.Call(ctx, "diagnostics/collect", map[string]any{"vm": vm}, &e)
return e, err
})
return nil
},
})
reg.Reconcile(context.Background())
// 1. Driver proxy lists VMs from Sidecar over JSON-RPC 2.0.
router := driver.NewRouter(reg, nil)
vms, err := router.ListAllVMs(context.Background())
if err != nil || len(vms) != 1 || vms[0].Name != "ubuntu-24" {
t.Fatalf("SidecarDriver ListAllVMs = %+v, err=%v", vms, err)
}
// 2. Command invocation + reverse Host API notification.
var cmdOut map[string]any
if err := sup.Call(context.Background(), "command/invoke", map[string]any{"command": "notify-host"}, &cmdOut); err != nil {
t.Fatalf("command/invoke: %v", err)
}
select {
case msg := <-notified:
if msg != "test.sidecar.linux:hello" {
t.Fatalf("unexpected notify msg: %q", msg)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for reverse Host API notification")
}
// 3. Diagnostics collection enforces host redaction of MAC & serial (§4.2, §7.1).
diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", reims.RedactText)
if len(diags) != 1 {
t.Fatalf("expected 1 diag entry, got %d", len(diags))
}
if strings.Contains(diags[0].Text, "aa:bb:cc") || strings.Contains(diags[0].Text, "C02SECRET") {
t.Fatalf("sensitive fields leaked in plugin diagnostics: %q", diags[0].Text)
}
// 4. Hung command is cancellable by timeout without hanging host!
hangCtx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
if err := sup.Call(hangCtx, "command/invoke", map[string]any{"command": "hang"}, nil); err == nil {
t.Fatal("expected hang call to time out cleanly")
}
// 5. Stop terminates Sidecar cleanly (zero orphan process).
sup.Stop()
if sup.IsRunning() {
t.Fatal("expected Sidecar stopped with zero orphan process")
}
// 6. Crashing Sidecar trips circuit breaker without crashing host.
t.Setenv("REIMS_TEST_SIDECAR_MODE", "crash")
crashSup := plugin.NewSidecarSupervisor(plugin.SidecarOptions{
PluginID: "test.sidecar.crash",
ExePath: exePath,
Args: []string{"-test.run=^TestHelperSidecar$"},
DataDir: layout.DataDir("test.sidecar.crash"),
Broker: broker,
Registry: reg,
MaxRestarts: 2,
})
defer crashSup.Stop()
if err := crashSup.EnsureStarted(context.Background()); err == nil {
t.Fatal("expected crashing sidecar handshake error")
}
}
+692
View File
@@ -0,0 +1,692 @@
package plugin
import (
"archive/zip"
"crypto/ed25519"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"time"
)
var (
reReverseDomainID = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*(\.[a-z0-9][a-z0-9_-]*)+$`)
)
// ForbiddenMarketPatterns enforces §1.3 & §9 market redlines: reject Apple
// proprietary payloads, closed firmware, and SMBIOS literal secrets.
var ForbiddenMarketPatterns = []string{
".ipsw",
"basesystem.dmg",
"installesd.dmg",
"apple-osk",
}
var reOSKAssignment = regexp.MustCompile(`(?i)\bosk\s*=\s*[^\s,"']{32,}`)
func containsForbiddenSMCKey(low string) bool {
if strings.Contains(low, "isa-applesmc") && strings.Contains(low, "osk=") {
return true
}
return reOSKAssignment.MatchString(low)
}
// SigningKeyring maps key IDs / publishers to ed25519 public keys and trust level.
type SigningKey struct {
KeyID string
Publisher string
Trust TrustLevel
PublicKey ed25519.PublicKey
}
// MarketEntry describes one plugin published in the remote/embedded market index (§9).
type MarketEntry struct {
ID string `json:"id"`
Version string `json:"version"`
Name LocalizedText `json:"name"`
Description LocalizedText `json:"description"`
Publisher string `json:"publisher"`
License string `json:"license"`
Channel string `json:"channel"` // "stable" | "alpha"
Trust TrustLevel `json:"trust"`
Engines Engines `json:"engines"`
DownloadURL string `json:"download_url"`
SHA256 string `json:"sha256"`
Signer string `json:"signer,omitempty"`
}
// MarketIndex is the static index.json structure (§9).
type MarketIndex struct {
Schema int `json:"schema"`
UpdatedAt string `json:"updated_at"`
Plugins []MarketEntry `json:"plugins"`
}
// EmbeddedFallbackMarketIndex is shipped as a zero-network fallback (§9).
var EmbeddedFallbackMarketIndex = MarketIndex{
Schema: 1,
UpdatedAt: "2026-11-29T00:00:00Z",
Plugins: []MarketEntry{},
}
// PackageInstallOptions controls optional expectations during transactional install.
type PackageInstallOptions struct {
ExpectedID string
ExpectedVersion string
HostVersion string
Keyring []SigningKey
AllowUnsigned bool
}
// InstalledPackage describes the verified result of a transactional package install.
type InstalledPackage struct {
Manifest Manifest `json:"manifest"`
InstallDir string `json:"install_dir"`
Trust TrustLevel `json:"trust"`
EntryPath string `json:"entry_path,omitempty"`
EntryHash string `json:"entry_hash,omitempty"`
}
// DoctorFinding is one diagnostic item produced by `reims-go plugin doctor`.
type DoctorFinding struct {
Severity string `json:"severity"` // "error" | "warn" | "ok"
Check string `json:"check"`
Message string `json:"message"`
}
// UIContract describes the exported frontend UI contract (`ui-contract.json`)
// used by `plugin doctor` to validate theme CSS selectors (§5.1).
type UIContract struct {
UIAPI string `json:"uiApi"`
Tokens []string `json:"tokens"`
Parts []string `json:"parts"`
StateAttrs []string `json:"stateAttrs"`
Slots []string `json:"slots"`
}
// PluginsLayout returns the standard directories under `<DataRoot>/plugins/` (§6.1).
type PluginsLayout struct {
Root string
}
func NewPluginsLayout(dataRoot string) PluginsLayout {
return PluginsLayout{Root: filepath.Join(dataRoot, "plugins")}
}
func (l PluginsLayout) StatePath() string { return filepath.Join(l.Root, StateFileName) }
func (l PluginsLayout) PkgsDir() string { return filepath.Join(l.Root, "pkgs") }
func (l PluginsLayout) PkgDir(id, ver string) string {
return filepath.Join(l.Root, "pkgs", id, ver)
}
func (l PluginsLayout) DataDir(id string) string { return filepath.Join(l.Root, "data", id) }
func (l PluginsLayout) LogsDir() string { return filepath.Join(l.Root, "logs") }
func (l PluginsLayout) LogPath(id string) string { return filepath.Join(l.Root, "logs", id+".log") }
func (l PluginsLayout) TmpDir() string { return filepath.Join(l.Root, "tmp") }
func (l PluginsLayout) IndexCachePath() string { return filepath.Join(l.Root, "index-cache.json") }
// ValidateManifest validates plugin.json schema, ID, SemVer, engines, platforms,
// permissions, and runtime provenance (§6.2, §7.1, §9).
func ValidateManifest(m Manifest, hostVersion string, isBuiltinOrBundled bool) error {
if m.Schema != 0 && m.Schema != ManifestSchemaVersion {
return fmt.Errorf("unsupported plugin manifest schema %d (expected %d)", m.Schema, ManifestSchemaVersion)
}
if !reReverseDomainID.MatchString(m.ID) {
return fmt.Errorf("invalid plugin id %q (must be reverse-domain lowercase, e.g. vendor.feature)", m.ID)
}
if !isBuiltinOrBundled && strings.HasPrefix(m.ID, "builtin.") {
return fmt.Errorf("plugin id %q uses reserved builtin. namespace", m.ID)
}
if _, err := ParseSemVer(m.Version); err != nil {
return fmt.Errorf("invalid plugin version %q: %w", m.Version, err)
}
if m.Name.ZhCN == "" && m.Name.EnUS == "" {
return errors.New("plugin manifest missing localized name")
}
if m.DefaultEnabled && !isBuiltinOrBundled {
return errors.New("only builtin or bundled plugins may set defaultEnabled=true")
}
if bad := ForbiddenPermissions(m.Permissions); len(bad) > 0 {
return fmt.Errorf("plugin requests forbidden or unknown permissions: %s", strings.Join(bad, ", "))
}
if reqAPI := strings.TrimSpace(m.Engines.PluginAPI); reqAPI != "" {
if !MatchesRange(PluginAPIVersion, reqAPI) {
return fmt.Errorf("incompatible pluginApi: plugin requires %s, host provides %s", reqAPI, PluginAPIVersion)
}
}
if reqUI := strings.TrimSpace(m.Engines.UIAPI); reqUI != "" {
if !MatchesRange(UIAPIVersion, reqUI) {
return fmt.Errorf("incompatible uiApi: plugin requires %s, host provides %s", reqUI, UIAPIVersion)
}
}
if reqHost := strings.TrimSpace(m.Engines.ReimsGo); reqHost != "" && hostVersion != "" && hostVersion != "dev" {
if !MatchesRange(hostVersion, reqHost) {
return fmt.Errorf("incompatible reims-go version: plugin requires %s, host is %s", reqHost, hostVersion)
}
}
if len(m.Platforms) > 0 {
curPlat := currentPlatformTag()
matched := false
for _, p := range m.Platforms {
if strings.EqualFold(p, curPlat) || p == "*" || strings.EqualFold(p, "any") {
matched = true
break
}
}
if !matched {
return fmt.Errorf("plugin does not support platform %s (supported: %s)", curPlat, strings.Join(m.Platforms, ", "))
}
}
if len(m.Contributes.Runtimes) > 0 {
if m.Provenance == nil || strings.TrimSpace(m.Provenance.SourcePackage) == "" || strings.TrimSpace(m.License) == "" {
return errors.New("runtime plugin packages must declare license and provenance.sourcePackage")
}
}
if !isBuiltinOrBundled {
permSet := make(map[string]bool, len(m.Permissions))
for _, p := range m.Permissions {
permSet[p] = true
}
hasThemeUIScript := false
for _, th := range m.Contributes.Themes {
if strings.TrimSpace(th.UIScript) != "" {
hasThemeUIScript = true
break
}
}
if (strings.TrimSpace(m.Entry.UIScript) != "" || len(m.Contributes.UIScripts) > 0 || hasThemeUIScript) && !permSet["ui:script"] {
return errors.New("plugin declaring uiScript must request permission \"ui:script\"")
}
if len(m.Contributes.RuleHooks) > 0 && !permSet["vm:intent"] {
return errors.New("plugin declaring ruleHooks must request permission \"vm:intent\"")
}
if len(m.Contributes.GuestDrivers) > 0 && !permSet["driver:vm"] {
return errors.New("plugin declaring guestDrivers must request permission \"driver:vm\"")
}
if len(m.Contributes.InputFilters) > 0 && !permSet["input:filter"] {
return errors.New("plugin declaring inputFilters must request permission \"input:filter\"")
}
if len(m.Contributes.Runtimes) > 0 && !permSet["runtime:provider"] {
return errors.New("plugin declaring runtimes must request permission \"runtime:provider\"")
}
}
for _, panel := range m.Contributes.Panels {
entry := strings.TrimSpace(panel.Entry)
if entry == "" {
entry = "index.html"
}
if err := validateSafeManifestAsset(entry, ""); err != nil {
return fmt.Errorf("invalid panel %q entry %q: %w", panel.ID, panel.Entry, err)
}
}
for _, th := range m.Contributes.Themes {
if err := ValidateThemeContribution(th, ""); err != nil {
return err
}
}
return nil
}
func currentPlatformTag() string {
arch := runtime.GOARCH
if arch == "amd64" {
arch = "x64"
}
return runtime.GOOS + "-" + arch
}
// InstallArchive transactionally verifies and installs a plugin .zip package (§9):
// 1. Extract into plugins/tmp/<stage> (rejecting zip-slip and market redline files)
// 2. Parse & validate plugin.json (engines, platforms, permissions, id/version anti-swap)
// 3. Verify SHA256SUMS covers every extracted file with matching hashes
// 4. Verify optional ed25519 signature over SHA256SUMS to derive TrustLevel
// 5. Atomically rename stage dir into plugins/pkgs/<id>/<version>
// Any error removes stage dir and leaves existing pkgs/ and state.json untouched.
func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstallOptions) (*InstalledPackage, error) {
if err := os.MkdirAll(layout.TmpDir(), 0o755); err != nil {
return nil, err
}
stageDir, err := os.MkdirTemp(layout.TmpDir(), "stage-*")
if err != nil {
return nil, err
}
cleanupStage := true
defer func() {
if cleanupStage {
_ = os.RemoveAll(stageDir)
}
}()
if err := extractPluginZip(archivePath, stageDir); err != nil {
return nil, err
}
// Enforce market redlines on extracted content.
if err := checkMarketRedlines(stageDir); err != nil {
return nil, err
}
manifestPath := filepath.Join(stageDir, "plugin.json")
rawManifest, err := os.ReadFile(manifestPath)
if err != nil {
return nil, fmt.Errorf("package missing plugin.json: %w", err)
}
var m Manifest
if err := json.Unmarshal(rawManifest, &m); err != nil {
return nil, fmt.Errorf("invalid plugin.json: %w", err)
}
if opts.ExpectedID != "" && m.ID != opts.ExpectedID {
return nil, fmt.Errorf("package id mismatch (anti-swap): expected %q, got %q", opts.ExpectedID, m.ID)
}
if opts.ExpectedVersion != "" && m.Version != opts.ExpectedVersion {
return nil, fmt.Errorf("package version mismatch (anti-swap): expected %q, got %q", opts.ExpectedVersion, m.Version)
}
if err := ValidateManifest(m, opts.HostVersion, false); err != nil {
return nil, err
}
// Verify SHA256SUMS.
sumsPath := filepath.Join(stageDir, "SHA256SUMS")
sumsRaw, err := os.ReadFile(sumsPath)
if err != nil {
return nil, fmt.Errorf("package missing SHA256SUMS: %w", err)
}
if err := verifyDirSHA256Sums(stageDir, sumsRaw); err != nil {
return nil, err
}
// Verify optional ed25519 signature over SHA256SUMS.
trust := TrustCommunity
sigPath := filepath.Join(stageDir, "SHA256SUMS.sig")
if sigRaw, sigErr := os.ReadFile(sigPath); sigErr == nil {
t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, opts.Keyring)
if vErr != nil {
return nil, fmt.Errorf("invalid package signature: %w", vErr)
}
trust = t
} else if !errors.Is(sigErr, os.ErrNotExist) {
return nil, sigErr
} else if !opts.AllowUnsigned && len(opts.Keyring) > 0 {
return nil, errors.New("unsigned plugin package rejected by policy")
}
// Validate entry file existence and compute entry hash for high-risk display.
entryRel := m.Entry.Sidecar
if entryRel == "" {
entryRel = m.Entry.UIScript
}
if entryRel == "" {
entryRel = m.Entry.Script
}
var entryHash string
if entryRel != "" {
entryFull, err := safeJoin(stageDir, entryRel)
if err != nil {
return nil, fmt.Errorf("invalid entry path %q: %w", entryRel, err)
}
h, err := fileSHA256Hex(entryFull)
if err != nil {
return nil, fmt.Errorf("entry file %q missing: %w", entryRel, err)
}
entryHash = h
}
// Validate all theme fields (tokens, seeds, fonts, background, stylesheet & asset refs, B5).
for _, th := range m.Contributes.Themes {
if err := ValidateThemeContribution(th, stageDir); err != nil {
return nil, err
}
}
// Atomic activation into pkgs/<id>/<version> with path-traversal guard (B3).
finalDir, err := safeJoin(layout.PkgsDir(), m.ID+"/"+m.Version)
if err != nil {
return nil, fmt.Errorf("invalid plugin install target: %w", err)
}
if err := os.MkdirAll(filepath.Dir(finalDir), 0o755); err != nil {
return nil, err
}
// If same version already exists, replace atomically via backup swap.
backupDir := ""
if _, err := os.Stat(finalDir); err == nil {
backupDir = finalDir + ".prev-" + fmt.Sprintf("%d", time.Now().UnixNano())
if err := os.Rename(finalDir, backupDir); err != nil {
return nil, fmt.Errorf("prepare upgrade swap: %w", err)
}
}
if err := os.Rename(stageDir, finalDir); err != nil {
if backupDir != "" {
_ = os.Rename(backupDir, finalDir)
}
return nil, fmt.Errorf("activate plugin package: %w", err)
}
cleanupStage = false
if backupDir != "" {
_ = os.RemoveAll(backupDir)
}
entryAbs := ""
if entryRel != "" {
entryAbs = filepath.Join(finalDir, filepath.FromSlash(entryRel))
}
return &InstalledPackage{
Manifest: m,
InstallDir: finalDir,
Trust: trust,
EntryPath: entryAbs,
EntryHash: entryHash,
}, nil
}
// DoctorDirectory validates a plugin directory (installed or local dev link),
// checking manifest, SHA256SUMS (if present), CSS safety, and UI contract compliance (§5.1, §10).
func DoctorDirectory(dir string, hostVersion string, contract *UIContract) []DoctorFinding {
var out []DoctorFinding
add := func(sev, check, msg string) {
out = append(out, DoctorFinding{Severity: sev, Check: check, Message: msg})
}
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
if err != nil {
add("error", "manifest", "cannot read plugin.json: "+err.Error())
return out
}
var m Manifest
if err := json.Unmarshal(raw, &m); err != nil {
add("error", "manifest", "invalid plugin.json JSON: "+err.Error())
return out
}
if err := ValidateManifest(m, hostVersion, false); err != nil {
add("error", "manifest", err.Error())
} else {
add("ok", "manifest", fmt.Sprintf("valid manifest %s@%s (tier=%s)", m.ID, m.Version, m.InferTier(false)))
}
if err := checkMarketRedlines(dir); err != nil {
add("error", "redline", err.Error())
} else {
add("ok", "redline", "no forbidden proprietary or secret files detected")
}
if sumsRaw, err := os.ReadFile(filepath.Join(dir, "SHA256SUMS")); err == nil {
if err := verifyDirSHA256Sums(dir, sumsRaw); err != nil {
add("error", "checksum", err.Error())
} else {
add("ok", "checksum", "SHA256SUMS verified")
}
} else {
add("warn", "checksum", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)")
}
// Validate theme manifest fields and stylesheets against safety rules and UI Contract v1 (§5.1, B5).
for _, th := range m.Contributes.Themes {
if err := ValidateThemeContribution(th, dir); err != nil {
add("error", "theme-css", err.Error())
} else if th.Stylesheet != "" {
add("ok", "theme-css", th.Stylesheet+" passed CSS safety & asset check")
}
if th.Stylesheet == "" {
continue
}
cssPath, err := safeJoin(dir, th.Stylesheet)
if err != nil {
continue
}
cssBytes, err := os.ReadFile(cssPath)
if err != nil {
continue
}
cssText := string(cssBytes)
if contract != nil {
for _, issue := range CheckCSSAgainstContract(cssText, *contract) {
add("warn", "ui-contract", issue)
}
}
}
return out
}
var (
reCSSClass = regexp.MustCompile(`\.([a-zA-Z_-][a-zA-Z0-9_-]*)`)
reCSSVar = regexp.MustCompile(`var\(\s*(--[a-zA-Z0-9_-]+)`)
)
// CheckCSSAgainstContract verifies that a theme stylesheet only references
// contract part classes (`rg-p-*`) and contract design tokens (§5.1).
func CheckCSSAgainstContract(css string, contract UIContract) []string {
partSet := make(map[string]bool, len(contract.Parts))
for _, p := range contract.Parts {
partSet[p] = true
}
tokenSet := make(map[string]bool, len(contract.Tokens))
for _, tk := range contract.Tokens {
tokenSet[tk] = true
}
var issues []string
seen := map[string]bool{}
for _, m := range reCSSClass.FindAllStringSubmatch(css, -1) {
cls := m[1]
if !partSet[cls] && !seen["cls:"+cls] {
seen["cls:"+cls] = true
issues = append(issues, fmt.Sprintf("selector class .%s is not in ui-contract parts", cls))
}
}
for _, m := range reCSSVar.FindAllStringSubmatch(css, -1) {
v := m[1]
if !tokenSet[v] && !strings.HasPrefix(v, "--theme-") && !seen["var:"+v] {
seen["var:"+v] = true
issues = append(issues, fmt.Sprintf("CSS variable %s is not in ui-contract tokens", v))
}
}
sort.Strings(issues)
return issues
}
func extractPluginZip(archivePath, destDir string) error {
r, err := zip.OpenReader(archivePath)
if err != nil {
return fmt.Errorf("open plugin zip: %w", err)
}
defer r.Close()
const (
maxZipFiles = 2048
maxZipFileBytes = int64(256 << 20)
maxZipTotalBytes = int64(512 << 20)
)
if len(r.File) > maxZipFiles {
return fmt.Errorf("plugin zip exceeds maximum file count (%d)", maxZipFiles)
}
var totalWritten int64
cleanDest := filepath.Clean(destDir) + string(os.PathSeparator)
for _, f := range r.File {
if f.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("symlink entries are forbidden in plugin zip: %s", f.Name)
}
target := filepath.Join(destDir, filepath.FromSlash(f.Name))
if !strings.HasPrefix(filepath.Clean(target), cleanDest) && filepath.Clean(target) != filepath.Clean(destDir) {
return fmt.Errorf("illegal path in plugin zip: %s", f.Name)
}
if f.FileInfo().IsDir() {
if err := os.MkdirAll(target, 0o755); err != nil {
return err
}
continue
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
rc, err := f.Open()
if err != nil {
return err
}
out, err := os.Create(target)
if err != nil {
_ = rc.Close()
return err
}
// Cap single extracted file and cumulative archive bytes to prevent zip bombs.
n, copyErr := io.Copy(out, io.LimitReader(rc, maxZipFileBytes+1))
_ = rc.Close()
closeErr := out.Close()
if copyErr != nil {
return copyErr
}
if closeErr != nil {
return closeErr
}
if n > maxZipFileBytes {
return fmt.Errorf("plugin zip entry %s exceeds max file size", f.Name)
}
totalWritten += n
if totalWritten > maxZipTotalBytes {
return errors.New("plugin zip exceeds maximum total extracted size")
}
}
return nil
}
func checkMarketRedlines(root string) error {
return filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return err
}
lowName := strings.ToLower(info.Name())
for _, pat := range ForbiddenMarketPatterns {
if strings.Contains(lowName, pat) {
return fmt.Errorf("forbidden proprietary file detected (%s)", info.Name())
}
}
// Quick scan of small text/json manifests for Apple OSK patterns.
if info.Size() <= 256*1024 && (strings.HasSuffix(lowName, ".json") || strings.HasSuffix(lowName, ".toml") || strings.HasSuffix(lowName, ".txt")) {
if b, rErr := os.ReadFile(p); rErr == nil {
low := strings.ToLower(string(b))
if containsForbiddenSMCKey(low) {
return fmt.Errorf("forbidden Apple SMC OSK detected in %s", info.Name())
}
}
}
return nil
})
}
func verifyDirSHA256Sums(root string, sumsRaw []byte) error {
expected := make(map[string]string)
for _, line := range strings.Split(string(sumsRaw), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
fields := strings.Fields(line)
if len(fields) < 2 {
return fmt.Errorf("malformed SHA256SUMS line: %q", line)
}
rel := filepath.ToSlash(strings.TrimPrefix(fields[1], "./"))
expected[rel] = strings.ToLower(fields[0])
}
if len(expected) == 0 {
return errors.New("SHA256SUMS is empty")
}
// Check every declared file matches its hash.
for rel, wantHash := range expected {
full, err := safeJoin(root, rel)
if err != nil {
return err
}
got, err := fileSHA256Hex(full)
if err != nil {
return fmt.Errorf("SHA256SUMS file missing %s: %w", rel, err)
}
if got != wantHash {
return fmt.Errorf("SHA256 mismatch for %s: expected %s, got %s", rel, wantHash, got)
}
}
// Ensure no unhashed extra files exist (except SHA256SUMS and SHA256SUMS.sig).
return filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return err
}
rel, err := filepath.Rel(root, p)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
if rel == "SHA256SUMS" || rel == "SHA256SUMS.sig" {
return nil
}
if _, ok := expected[rel]; !ok {
return fmt.Errorf("unverified file in package not listed in SHA256SUMS: %s", rel)
}
return nil
})
}
func verifyEd25519Signature(message, sigRaw []byte, keyring []SigningKey) (TrustLevel, error) {
sigBytes, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(sigRaw)))
if err != nil {
// Also accept raw 64-byte binary signature.
if len(sigRaw) == ed25519.SignatureSize {
sigBytes = sigRaw
} else {
return TrustCommunity, fmt.Errorf("decode signature: %w", err)
}
}
if len(sigBytes) != ed25519.SignatureSize {
return TrustCommunity, fmt.Errorf("unexpected ed25519 signature size %d", len(sigBytes))
}
for _, k := range keyring {
if len(k.PublicKey) == ed25519.PublicKeySize && ed25519.Verify(k.PublicKey, message, sigBytes) {
return k.Trust, nil
}
}
return TrustCommunity, errors.New("signature did not match any trusted signing key")
}
func pathWithinRoot(root, candidate string) bool {
if runtime.GOOS == "windows" {
r := strings.ToLower(root)
c := strings.ToLower(candidate)
return c == r || strings.HasPrefix(c, r+string(os.PathSeparator))
}
return candidate == root || strings.HasPrefix(candidate, root+string(os.PathSeparator))
}
func safeJoin(root, rel string) (string, error) {
cleanRoot := filepath.Clean(root)
joined := filepath.Clean(filepath.Join(cleanRoot, filepath.FromSlash(rel)))
if !pathWithinRoot(cleanRoot, joined) {
return "", fmt.Errorf("path traversal blocked: %q", rel)
}
// Guard against symlinks / NTFS junctions escaping rootDir.
evalRoot := cleanRoot
if r, err := filepath.EvalSymlinks(cleanRoot); err == nil {
evalRoot = filepath.Clean(r)
}
if evalJoined, err := filepath.EvalSymlinks(joined); err == nil {
evalJoined = filepath.Clean(evalJoined)
if !pathWithinRoot(evalRoot, evalJoined) {
return "", fmt.Errorf("symlink traversal blocked: %q", rel)
}
return evalJoined, nil
}
return joined, nil
}
func fileSHA256Hex(p string) (string, error) {
f, err := os.Open(p)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
File diff suppressed because it is too large. Load diff
+312
View File
@@ -0,0 +1,312 @@
package plugin
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"strings"
"sync"
"sync/atomic"
)
const maxRPCFrameBytes = 8 << 20 // 8 MiB per JSON-RPC frame (large blobs go via file paths, §8)
// RPCError is a JSON-RPC 2.0 error object.
type RPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func (e *RPCError) Error() string {
return fmt.Sprintf("rpc error %d: %s", e.Code, e.Message)
}
type rpcEnvelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *RPCError `json:"error,omitempty"`
}
// RPCRequestHandler handles inbound JSON-RPC requests from the peer.
type RPCRequestHandler func(ctx context.Context, params json.RawMessage) (any, error)
// RPCConn implements bidirectional Content-Length framed JSON-RPC 2.0 over
// stdio pipes with a single writer goroutine and bounded queue (§8).
type RPCConn struct {
r *bufio.Reader
w io.Writer
writeCh chan []byte
closeCh chan struct{}
closeOnce sync.Once
nextID atomic.Uint64
mu sync.Mutex
pending map[string]chan rpcEnvelope
handlers map[string]RPCRequestHandler
closed bool
doneCh chan struct{}
}
// NewRPCConn starts reader and single-writer goroutines over r and w.
func NewRPCConn(r io.Reader, w io.Writer) *RPCConn {
c := &RPCConn{
r: bufio.NewReaderSize(r, 64*1024),
w: w,
writeCh: make(chan []byte, 64),
closeCh: make(chan struct{}),
pending: make(map[string]chan rpcEnvelope),
handlers: make(map[string]RPCRequestHandler),
doneCh: make(chan struct{}),
}
go c.writeLoop()
go c.readLoop()
return c
}
// Handle registers a handler for inbound peer requests of method.
func (c *RPCConn) Handle(method string, h RPCRequestHandler) {
c.mu.Lock()
c.handlers[method] = h
c.mu.Unlock()
}
// Call sends a JSON-RPC 2.0 request and waits for the response or ctx cancellation.
func (c *RPCConn) Call(ctx context.Context, method string, params any, out any) error {
idNum := c.nextID.Add(1)
idKey := strconv.FormatUint(idNum, 10)
var rawParams json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = b
}
env := rpcEnvelope{
JSONRPC: "2.0",
ID: json.RawMessage(idKey),
Method: method,
Params: rawParams,
}
payload, err := json.Marshal(env)
if err != nil {
return err
}
respCh := make(chan rpcEnvelope, 1)
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return errors.New("rpc connection closed")
}
c.pending[idKey] = respCh
c.mu.Unlock()
defer func() {
c.mu.Lock()
delete(c.pending, idKey)
c.mu.Unlock()
}()
if err := c.enqueue(ctx, payload); err != nil {
return err
}
select {
case resp, ok := <-respCh:
if !ok {
return errors.New("rpc connection closed while awaiting response")
}
if resp.Error != nil {
return resp.Error
}
if out != nil && len(resp.Result) > 0 && string(resp.Result) != "null" {
return json.Unmarshal(resp.Result, out)
}
return nil
case <-ctx.Done():
return ctx.Err()
case <-c.closeCh:
return errors.New("rpc connection closed")
case <-c.doneCh:
return errors.New("rpc connection closed")
}
}
// Notify sends a JSON-RPC 2.0 notification (no response expected).
func (c *RPCConn) Notify(ctx context.Context, method string, params any) error {
var rawParams json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = b
}
env := rpcEnvelope{
JSONRPC: "2.0",
Method: method,
Params: rawParams,
}
payload, err := json.Marshal(env)
if err != nil {
return err
}
return c.enqueue(ctx, payload)
}
func (c *RPCConn) enqueue(ctx context.Context, payload []byte) error {
select {
case c.writeCh <- payload:
return nil
case <-ctx.Done():
return ctx.Err()
case <-c.closeCh:
return errors.New("rpc connection closed")
}
}
func (c *RPCConn) writeLoop() {
for {
select {
case payload := <-c.writeCh:
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(payload))
if _, err := io.WriteString(c.w, header); err != nil {
c.Close()
return
}
if _, err := c.w.Write(payload); err != nil {
c.Close()
return
}
case <-c.closeCh:
return
}
}
}
func (c *RPCConn) readLoop() {
defer func() {
c.Close()
close(c.doneCh)
}()
for {
frame, err := readContentLengthFrame(c.r)
if err != nil {
return
}
var env rpcEnvelope
if err := json.Unmarshal(frame, &env); err != nil {
continue
}
if env.Method != "" {
// Inbound request or notification from peer.
go c.dispatchInbound(env)
continue
}
if len(env.ID) > 0 {
key := strings.TrimSpace(string(env.ID))
c.mu.Lock()
ch := c.pending[key]
delete(c.pending, key)
if ch != nil {
select {
case ch <- env:
default:
}
}
c.mu.Unlock()
}
}
}
func (c *RPCConn) dispatchInbound(env rpcEnvelope) {
c.mu.Lock()
h := c.handlers[env.Method]
c.mu.Unlock()
if h == nil {
if len(env.ID) > 0 {
c.sendResponse(env.ID, nil, &RPCError{Code: -32601, Message: "method not found: " + env.Method})
}
return
}
res, err := h(context.Background(), env.Params)
if len(env.ID) == 0 {
return // notification
}
if err != nil {
c.sendResponse(env.ID, nil, &RPCError{Code: -32000, Message: err.Error()})
return
}
c.sendResponse(env.ID, res, nil)
}
func (c *RPCConn) sendResponse(id json.RawMessage, result any, rpcErr *RPCError) {
env := rpcEnvelope{
JSONRPC: "2.0",
ID: id,
Error: rpcErr,
}
if rpcErr == nil {
if result == nil {
env.Result = json.RawMessage("null")
} else if b, err := json.Marshal(result); err == nil {
env.Result = b
}
}
if b, err := json.Marshal(env); err == nil {
_ = c.enqueue(context.Background(), b)
}
}
// Close closes the RPC connection and fails all pending outbound calls.
func (c *RPCConn) Close() {
c.closeOnce.Do(func() {
close(c.closeCh)
c.mu.Lock()
c.closed = true
for id := range c.pending {
delete(c.pending, id)
}
c.mu.Unlock()
})
}
func readContentLengthFrame(r *bufio.Reader) ([]byte, error) {
contentLen := -1
for {
line, err := r.ReadString('\n')
if err != nil {
return nil, err
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
break
}
k, v, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil || n < 0 || n > maxRPCFrameBytes {
return nil, fmt.Errorf("invalid Content-Length %q", v)
}
contentLen = n
}
}
if contentLen < 0 {
return nil, errors.New("missing Content-Length header")
}
buf := make([]byte, contentLen)
if _, err := io.ReadFull(r, buf); err != nil {
return nil, err
}
return buf, nil
}
+199
View File
@@ -0,0 +1,199 @@
package plugin
import (
"context"
"fmt"
"strings"
)
// RuleCondition is a declarative, non-Turing-complete predicate over host, VM,
// and runtime facts (§5.4).
type RuleCondition struct {
Fact string `json:"fact"` // e.g. "host.needs_cold_reboot", "host.whpx", "vm.driver", "runtime.kind", "runtime.capabilities"
Operator string `json:"operator"` // "eq" | "neq" | "contains" | "not_contains" | "exists"
Value any `json:"value,omitempty"`
}
// RuleAction is a constrained action emitted when all conditions match (§5.4).
type RuleAction struct {
Kind string `json:"kind"` // "append_args" | "set_env" | "warn" | "post_start"
Key string `json:"key,omitempty"` // fragment key for append_args
Tokens []string `json:"tokens,omitempty"` // QEMU arg tokens
Env map[string]string `json:"env,omitempty"` // env overrides
Message string `json:"message,omitempty"` // warning text
Action string `json:"action,omitempty"` // post_start kind
Params map[string]any `json:"params,omitempty"`
}
// RuleHook is an L1 declarative hook rule contributed via plugin.json (§5.4).
type RuleHook struct {
ID string `json:"id"`
Event string `json:"event"` // "vm.beforeStart" | "host.preflight"
Priority int `json:"priority,omitempty"`
Conditions []RuleCondition `json:"conditions,omitempty"`
Actions []RuleAction `json:"actions"`
}
// EvaluateRuleConditions checks whether all declarative conditions hold against facts.
func EvaluateRuleConditions(conds []RuleCondition, facts map[string]any) bool {
for _, c := range conds {
val, exists := facts[c.Fact]
switch strings.ToLower(strings.TrimSpace(c.Operator)) {
case "exists":
if !exists || val == nil {
return false
}
case "eq", "==":
if !exists || !factEquals(val, c.Value) {
return false
}
case "neq", "!=":
if exists && factEquals(val, c.Value) {
return false
}
case "contains":
if !exists || !factContains(val, c.Value) {
return false
}
case "not_contains":
if exists && factContains(val, c.Value) {
return false
}
default:
return false
}
}
return true
}
func factEquals(actual, expected any) bool {
return strings.EqualFold(fmt.Sprint(actual), fmt.Sprint(expected))
}
func factContains(actual, needle any) bool {
sNeedle := strings.ToLower(fmt.Sprint(needle))
switch v := actual.(type) {
case []string:
for _, item := range v {
if strings.EqualFold(item, sNeedle) {
return true
}
}
return false
case []any:
for _, item := range v {
if strings.EqualFold(fmt.Sprint(item), sNeedle) {
return true
}
}
return false
default:
return strings.Contains(strings.ToLower(fmt.Sprint(actual)), sNeedle)
}
}
func (r *Registry) registerRuleHooks(sc *Scope, pluginID string, rules []RuleHook) {
for _, rule := range rules {
rl := rule
switch rl.Event {
case EventVMBeforeStart:
r.hooks.Subscribe(sc, HookRegistration{
PluginID: pluginID,
Event: EventVMBeforeStart,
Priority: rl.Priority,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(BeforeStartPayload)
if !ok {
return nil, nil
}
facts := buildStartFacts(p)
if !EvaluateRuleConditions(rl.Conditions, facts) {
return nil, nil
}
return buildRuleStartIntent(pluginID, rl), nil
},
})
case EventHostPreflight:
r.hooks.Subscribe(sc, HookRegistration{
PluginID: pluginID,
Event: EventHostPreflight,
Priority: rl.Priority,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(PreflightPayload)
if !ok {
return nil, nil
}
if !EvaluateRuleConditions(rl.Conditions, p.HostFacts) {
return nil, nil
}
var res PreflightResult
for _, act := range rl.Actions {
if act.Kind == "warn" && act.Message != "" {
res.Warnings = append(res.Warnings, act.Message)
}
}
return res, nil
},
})
}
}
}
func buildStartFacts(p BeforeStartPayload) map[string]any {
facts := make(map[string]any, len(p.HostFacts)+8)
for k, v := range p.HostFacts {
facts[k] = v
}
facts["vm.name"] = p.VMName
facts["vm.driver"] = p.DriverID
facts["vm.capabilities"] = p.VMCaps
facts["vm.state"] = p.State
facts["vm.has_installer"] = p.HasInstaller
facts["runtime.kind"] = p.RuntimeKind
facts["runtime.capabilities"] = p.RuntimeCaps
return facts
}
func buildRuleStartIntent(pluginID string, rule RuleHook) StartIntent {
intent := StartIntent{PluginID: pluginID}
for i, act := range rule.Actions {
switch act.Kind {
case "append_args":
if len(act.Tokens) == 0 {
continue
}
key := act.Key
if key == "" {
key = fmt.Sprintf("%s:%s:%d", pluginID, rule.ID, i)
}
intent.Args = append(intent.Args, ArgFragment{
PluginID: pluginID,
Key: key,
Tokens: append([]string(nil), act.Tokens...),
Priority: rule.Priority,
})
case "set_env":
if len(act.Env) > 0 {
if intent.Env == nil {
intent.Env = make(map[string]string, len(act.Env))
}
for k, v := range act.Env {
intent.Env[k] = v
}
}
case "warn":
if act.Message != "" {
intent.Warnings = append(intent.Warnings, act.Message)
}
case "post_start":
if act.Action != "" {
intent.PostStart = append(intent.PostStart, PostStartAction{
PluginID: pluginID,
Kind: act.Action,
Params: act.Params,
})
}
}
}
return intent
}
+101
View File
@@ -0,0 +1,101 @@
package plugin
import (
"sync"
)
// Scope tracks all reversible side effects registered by one activated plugin (§4.1).
// When the plugin is disabled, upgraded, or fails mid-activation, Dispose runs
// all registered cleanup callbacks in strict LIFO (reverse) order.
type Scope struct {
pluginID string
registry *Registry
mu sync.Mutex
disposers []func()
disposed bool
}
func newScope(pluginID string, reg *Registry) *Scope {
return &Scope{
pluginID: pluginID,
registry: reg,
}
}
// PluginID returns the owning plugin's identifier.
func (s *Scope) PluginID() string {
return s.pluginID
}
// Registry returns the parent plugin registry.
func (s *Scope) Registry() *Registry {
return s.registry
}
// OnDispose registers a cleanup function to be invoked in reverse order on disposal.
// If the scope is already disposed, fn is invoked immediately.
func (s *Scope) OnDispose(fn func()) {
if fn == nil {
return
}
s.mu.Lock()
if s.disposed {
s.mu.Unlock()
safeInvoke(fn)
return
}
s.disposers = append(s.disposers, fn)
s.mu.Unlock()
}
// Provide registers a named service with a SemVer version and auto-removes it on dispose.
func (s *Scope) Provide(name, version string, svc any) {
if s.registry == nil || name == "" {
return
}
s.registry.provideService(s.pluginID, name, version, svc)
s.OnDispose(func() {
s.registry.unprovideService(s.pluginID, name)
})
}
// Lookup fetches a provided service by name from the registry.
func (s *Scope) Lookup(name string) (any, bool) {
if s.registry == nil {
return nil, false
}
return s.registry.LookupService(name)
}
// Dispose runs all registered cleanup functions in reverse order, catching panics
// so one faulty cleanup never prevents remaining resources from being released.
func (s *Scope) Dispose() {
s.mu.Lock()
if s.disposed {
s.mu.Unlock()
return
}
s.disposed = true
fns := s.disposers
s.disposers = nil
s.mu.Unlock()
for i := len(fns) - 1; i >= 0; i-- {
safeInvoke(fns[i])
}
}
// Disposed reports whether Dispose has been called.
func (s *Scope) Disposed() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.disposed
}
func safeInvoke(fn func()) {
defer func() {
_ = recover()
}()
fn()
}
+208
View File
@@ -0,0 +1,208 @@
package plugin
import (
"fmt"
"strconv"
"strings"
)
// SemVer is a parsed MAJOR.MINOR.PATCH semantic version.
type SemVer struct {
Major int
Minor int
Patch int
Pre string
}
// ParseSemVer parses "v1.2.3", "1.2", or "1.2.3-alpha.1".
func ParseSemVer(raw string) (SemVer, error) {
s := strings.TrimSpace(raw)
s = strings.TrimPrefix(s, "v")
if s == "" {
return SemVer{}, fmt.Errorf("empty version")
}
if idx := strings.IndexByte(s, '+'); idx >= 0 {
build := s[idx+1:]
if !validSemVerDotIdents(build) {
return SemVer{}, fmt.Errorf("invalid semver build metadata in %q", raw)
}
s = s[:idx]
}
var pre string
if idx := strings.IndexByte(s, '-'); idx >= 0 {
pre = s[idx+1:]
if !validSemVerDotIdents(pre) {
return SemVer{}, fmt.Errorf("invalid semver prerelease in %q", raw)
}
s = s[:idx]
}
parts := strings.Split(s, ".")
if len(parts) < 1 || len(parts) > 3 {
return SemVer{}, fmt.Errorf("invalid semver %q", raw)
}
nums := [3]int{}
for i, p := range parts {
n, err := strconv.Atoi(p)
if err != nil || n < 0 {
return SemVer{}, fmt.Errorf("invalid semver %q", raw)
}
nums[i] = n
}
return SemVer{Major: nums[0], Minor: nums[1], Patch: nums[2], Pre: pre}, nil
}
// validSemVerDotIdents checks RFC SemVer 2.0.0 dot-separated prerelease/build
// identifiers: non-empty, each segment non-empty and strictly [0-9A-Za-z-],
// which prevents path separators, "..", or whitespace from slipping into PkgDir.
func validSemVerDotIdents(s string) bool {
if s == "" {
return false
}
for _, seg := range strings.Split(s, ".") {
if seg == "" {
return false
}
for i := 0; i < len(seg); i++ {
c := seg[i]
ok := (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-'
if !ok {
return false
}
}
}
return true
}
// Compare returns -1 if v < other, 0 if equal, +1 if v > other.
func (v SemVer) Compare(other SemVer) int {
if v.Major != other.Major {
if v.Major < other.Major {
return -1
}
return 1
}
if v.Minor != other.Minor {
if v.Minor < other.Minor {
return -1
}
return 1
}
if v.Patch != other.Patch {
if v.Patch < other.Patch {
return -1
}
return 1
}
if v.Pre == other.Pre {
return 0
}
// Release > prerelease.
if v.Pre == "" {
return 1
}
if other.Pre == "" {
return -1
}
if v.Pre < other.Pre {
return -1
}
return 1
}
// MatchesRange evaluates whether version satisfies a SemVer range expression.
// Supports empty/"*", "||" disjunctions, space/comma conjunctions, and
// operators: >=, <=, >, <, =, ^, ~.
func MatchesRange(version, expr string) bool {
expr = strings.TrimSpace(expr)
if expr == "" || expr == "*" {
return true
}
v, err := ParseSemVer(version)
if err != nil {
return false
}
for _, branch := range strings.Split(expr, "||") {
branch = strings.TrimSpace(branch)
if branch == "" {
continue
}
if matchesAndClauses(v, branch) {
return true
}
}
return false
}
func matchesAndClauses(v SemVer, clause string) bool {
// Normalize comma separators into spaces.
norm := strings.ReplaceAll(clause, ",", " ")
tokens := strings.Fields(norm)
if len(tokens) == 0 {
return true
}
for _, tok := range tokens {
if !matchesSingleConstraint(v, tok) {
return false
}
}
return true
}
func matchesSingleConstraint(v SemVer, tok string) bool {
tok = strings.TrimSpace(tok)
if tok == "" || tok == "*" {
return true
}
switch {
case strings.HasPrefix(tok, ">="):
target, err := ParseSemVer(tok[2:])
return err == nil && v.Compare(target) >= 0
case strings.HasPrefix(tok, "<="):
target, err := ParseSemVer(tok[2:])
return err == nil && v.Compare(target) <= 0
case strings.HasPrefix(tok, ">"):
target, err := ParseSemVer(tok[1:])
return err == nil && v.Compare(target) > 0
case strings.HasPrefix(tok, "<"):
target, err := ParseSemVer(tok[1:])
return err == nil && v.Compare(target) < 0
case strings.HasPrefix(tok, "="):
target, err := ParseSemVer(tok[1:])
return err == nil && v.Compare(target) == 0
case strings.HasPrefix(tok, "^"):
target, err := ParseSemVer(tok[1:])
if err != nil || v.Compare(target) < 0 {
return false
}
if target.Major > 0 {
return v.Major == target.Major
}
if target.Minor > 0 {
return v.Major == 0 && v.Minor == target.Minor
}
return v.Major == 0 && v.Minor == 0 && v.Patch == target.Patch
case strings.HasPrefix(tok, "~"):
target, err := ParseSemVer(tok[1:])
if err != nil || v.Compare(target) < 0 {
return false
}
return v.Major == target.Major && v.Minor == target.Minor
default:
// Allow "1.x" or exact match.
if strings.HasSuffix(tok, ".x") || strings.HasSuffix(tok, ".*") {
prefix := strings.TrimSuffix(strings.TrimSuffix(tok, ".x"), ".*")
parts := strings.Split(strings.TrimPrefix(prefix, "v"), ".")
if len(parts) == 1 {
maj, err := strconv.Atoi(parts[0])
return err == nil && v.Major == maj
}
if len(parts) == 2 {
maj, e1 := strconv.Atoi(parts[0])
min, e2 := strconv.Atoi(parts[1])
return e1 == nil && e2 == nil && v.Major == maj && v.Minor == min
}
}
target, err := ParseSemVer(tok)
return err == nil && v.Compare(target) == 0
}
}
+487
View File
@@ -0,0 +1,487 @@
package plugin
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"sync"
"sync/atomic"
"time"
)
// SidecarOptions configures an L3 (or future L2) supervised child process (§8).
type SidecarOptions struct {
PluginID string
ExePath string
Args []string
DataDir string
Broker *Broker
Registry *Registry
IdleTimeout time.Duration // 0 = no idle shutdown
MemLimitBytes uintptr // optional Windows Job Object memory cap (L2)
MaxRestarts int // circuit breaker threshold (default 3)
ExtraHandlers map[string]RPCRequestHandler
}
type sidecarInstance struct {
cmd *exec.Cmd
job *sidecarJob
rpc *RPCConn
stdin io.WriteCloser
exited chan struct{}
inFlight atomic.Int32
}
// SidecarSupervisor manages the lifecycle of one per-plugin Sidecar process:
// lazy start, Windows Job Object containment, Content-Length JSON-RPC 2.0
// handshake, stderr log collection, exponential backoff restart + circuit
// breaker, graceful reload, and idle reclamation (§8).
type SidecarSupervisor struct {
opts SidecarOptions
startMu sync.Mutex
mu sync.Mutex
cur *sidecarInstance
stopped bool
crashCount int
lastCrash time.Time
lastActivity time.Time
idleCancel context.CancelFunc
capabilities map[string]any
}
func NewSidecarSupervisor(opts SidecarOptions) *SidecarSupervisor {
if opts.MaxRestarts <= 0 {
opts.MaxRestarts = 3
}
return &SidecarSupervisor{
opts: opts,
lastActivity: time.Now(),
}
}
// EnsureStarted lazily launches the Sidecar process and performs the
// `plugin/initialize` handshake (§8).
func (s *SidecarSupervisor) EnsureStarted(ctx context.Context) error {
s.startMu.Lock()
defer s.startMu.Unlock()
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
return errors.New("sidecar supervisor stopped")
}
if s.cur != nil {
select {
case <-s.cur.exited:
s.cur = nil
default:
s.lastActivity = time.Now()
s.mu.Unlock()
return nil
}
}
if s.crashCount >= s.opts.MaxRestarts {
s.mu.Unlock()
return fmt.Errorf("sidecar %s circuit-broken after %d crashes", s.opts.PluginID, s.crashCount)
}
// Exponential backoff after prior crash.
backoff := time.Duration(0)
if s.crashCount > 0 {
backoff = time.Duration(200*(1<<(s.crashCount-1))) * time.Millisecond
if elapsed := time.Since(s.lastCrash); elapsed < backoff {
backoff -= elapsed
} else {
backoff = 0
}
}
s.mu.Unlock()
if backoff > 0 {
select {
case <-time.After(backoff):
case <-ctx.Done():
return ctx.Err()
}
}
inst, caps, err := s.spawnInstance(ctx)
if err != nil {
return err
}
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
s.terminateInstance(inst)
return errors.New("sidecar stopped during startup")
}
s.cur = inst
s.capabilities = caps
s.lastActivity = time.Now()
if s.opts.IdleTimeout > 0 && s.idleCancel == nil {
idleCtx, cancel := context.WithCancel(context.Background())
s.idleCancel = cancel
go s.idleWatchLoop(idleCtx)
}
s.mu.Unlock()
return nil
}
func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance, map[string]any, error) {
if s.opts.DataDir != "" {
if err := os.MkdirAll(s.opts.DataDir, 0o755); err != nil {
return nil, nil, err
}
}
cmd := exec.Command(s.opts.ExePath, s.opts.Args...)
cmd.Dir = s.opts.DataDir
configureSidecarCmd(cmd)
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
_ = stdin.Close()
return nil, nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
_ = stdin.Close()
_ = stdout.Close()
return nil, nil, err
}
job, err := newSidecarJob(s.opts.MemLimitBytes)
if err != nil {
_ = stdin.Close()
_ = stdout.Close()
_ = stderr.Close()
return nil, nil, err
}
if err := cmd.Start(); err != nil {
_ = stdin.Close()
_ = stdout.Close()
_ = stderr.Close()
job.Close()
return nil, nil, fmt.Errorf("start sidecar %s: %w", s.opts.PluginID, err)
}
if err := job.Assign(cmd.Process.Pid); err != nil {
_ = cmd.Process.Kill()
_ = cmd.Wait()
job.Close()
return nil, nil, fmt.Errorf("assign sidecar %s to job: %w", s.opts.PluginID, err)
}
rpcConn := NewRPCConn(stdout, stdin)
s.registerReverseHostAPI(rpcConn)
inst := &sidecarInstance{
cmd: cmd,
job: job,
rpc: rpcConn,
stdin: stdin,
exited: make(chan struct{}),
}
// Collect stderr into rotated plugin audit log (§8).
go func() {
sc := bufio.NewScanner(stderr)
sc.Buffer(make([]byte, 0, 16*1024), 64*1024)
for sc.Scan() {
if s.opts.Broker != nil {
s.opts.Broker.Audit(s.opts.PluginID, "STDERR", sc.Text())
}
}
}()
// Reap via process handle (cmd.Wait), NOT pipe EOF (§8).
go func() {
err := cmd.Wait()
rpcConn.Close()
job.Close()
close(inst.exited)
s.onInstanceExit(inst, err)
}()
// Handshake: plugin/initialize exchanging pluginApi version & capabilities.
initCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
var initResp struct {
PluginAPI string `json:"pluginApi"`
Capabilities map[string]any `json:"capabilities"`
}
err = rpcConn.Call(initCtx, "plugin/initialize", map[string]any{
"pluginId": s.opts.PluginID,
"pluginApi": PluginAPIVersion,
"dataDir": s.opts.DataDir,
}, &initResp)
if err != nil {
s.terminateInstance(inst)
return nil, nil, fmt.Errorf("sidecar %s handshake failed: %w", s.opts.PluginID, err)
}
return inst, initResp.Capabilities, nil
}
func (s *SidecarSupervisor) registerReverseHostAPI(conn *RPCConn) {
pid := s.opts.PluginID
broker := s.opts.Broker
conn.Handle("host/notify", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var req struct {
Title string `json:"title"`
Body string `json:"body"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
return map[string]any{"ok": true}, broker.Notify(pid, req.Title, req.Body)
})
conn.Handle("host/audit", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker != nil {
if !broker.allowRate(pid, 120) {
return nil, fmt.Errorf("plugin %q exceeded audit rate limit", pid)
}
var req struct {
Message string `json:"message"`
}
_ = json.Unmarshal(raw, &req)
broker.Audit(pid, "PLUGIN", req.Message)
}
return map[string]any{"ok": true}, nil
})
conn.Handle("host/vm.spawn", func(ctx context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var req struct {
VMName string `json:"vm_name"`
ExePath string `json:"exe_path"`
Args []string `json:"args"`
WorkDir string `json:"work_dir"`
Env []string `json:"env"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vmPID, err := broker.SpawnManagedVMProcess(ctx, pid, req.VMName, req.ExePath, req.Args, req.WorkDir, req.Env)
if err != nil {
return nil, err
}
return map[string]any{"pid": vmPID}, nil
})
conn.Handle("host/vm.stop", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var req struct {
PID int `json:"pid"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
return map[string]any{"ok": true}, broker.StopManagedVMProcess(pid, req.PID)
})
conn.Handle("host/vm.isRunning", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return map[string]any{"running": false}, nil
}
var req struct {
PID int `json:"pid"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
return map[string]any{"running": broker.IsManagedProcessRunningForPlugin(pid, req.PID)}, nil
})
for method, h := range s.opts.ExtraHandlers {
conn.Handle(method, h)
}
}
func (s *SidecarSupervisor) onInstanceExit(inst *sidecarInstance, exitErr error) {
s.mu.Lock()
isCurrent := s.cur == inst
stopped := s.stopped
if isCurrent {
s.cur = nil
}
if !stopped && isCurrent {
s.crashCount++
s.lastCrash = time.Now()
crashes := s.crashCount
s.mu.Unlock()
if s.opts.Broker != nil {
s.opts.Broker.Audit(s.opts.PluginID, "CRASH", fmt.Sprintf("sidecar exited unexpectedly (count=%d): %v", crashes, exitErr))
}
if crashes >= s.opts.MaxRestarts && s.opts.Registry != nil {
s.opts.Registry.MarkFailed(s.opts.PluginID, fmt.Sprintf("sidecar crashed %d times: %v", crashes, exitErr))
}
return
}
s.mu.Unlock()
}
// Call lazily starts the Sidecar if needed and invokes a JSON-RPC 2.0 method.
func (s *SidecarSupervisor) Call(ctx context.Context, method string, params any, out any) error {
if err := s.EnsureStarted(ctx); err != nil {
return err
}
s.mu.Lock()
inst := s.cur
s.lastActivity = time.Now()
s.mu.Unlock()
if inst == nil {
return errors.New("sidecar not running")
}
inst.inFlight.Add(1)
defer inst.inFlight.Add(-1)
return inst.rpc.Call(ctx, method, params, out)
}
// Reload performs zero-downtime replacement: spawns new Sidecar, swaps pointer,
// drains in-flight requests on old Sidecar, then terminates old Job Object (§8).
func (s *SidecarSupervisor) Reload(ctx context.Context) error {
s.startMu.Lock()
defer s.startMu.Unlock()
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
return errors.New("sidecar supervisor stopped")
}
s.mu.Unlock()
newInst, caps, err := s.spawnInstance(ctx)
if err != nil {
return err
}
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
s.terminateInstance(newInst)
return errors.New("sidecar stopped during reload")
}
old := s.cur
s.cur = newInst
s.capabilities = caps
s.crashCount = 0
s.lastActivity = time.Now()
if s.opts.IdleTimeout > 0 && s.idleCancel == nil {
idleCtx, cancel := context.WithCancel(context.Background())
s.idleCancel = cancel
go s.idleWatchLoop(idleCtx)
}
s.mu.Unlock()
if old != nil {
go func() {
deadline := time.Now().Add(5 * time.Second)
for old.inFlight.Load() > 0 && time.Now().Before(deadline) {
time.Sleep(25 * time.Millisecond)
}
s.terminateInstance(old)
}()
}
return nil
}
// IsRunning reports whether a Sidecar child process is currently alive.
func (s *SidecarSupervisor) IsRunning() bool {
s.mu.Lock()
inst := s.cur
s.mu.Unlock()
if inst == nil {
return false
}
select {
case <-inst.exited:
return false
default:
return true
}
}
// PID returns the current Sidecar child process ID (0 if not running).
func (s *SidecarSupervisor) PID() int {
s.mu.Lock()
inst := s.cur
s.mu.Unlock()
if inst == nil || inst.cmd == nil || inst.cmd.Process == nil {
return 0
}
return inst.cmd.Process.Pid
}
func (s *SidecarSupervisor) idleWatchLoop(ctx context.Context) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.mu.Lock()
inst := s.cur
idle := time.Since(s.lastActivity)
timeout := s.opts.IdleTimeout
if inst != nil && timeout > 0 && idle >= timeout && inst.inFlight.Load() == 0 {
s.cur = nil
s.mu.Unlock()
s.terminateInstance(inst)
} else {
s.mu.Unlock()
}
}
}
}
func (s *SidecarSupervisor) terminateInstance(inst *sidecarInstance) {
if inst == nil {
return
}
_ = inst.rpc.Notify(context.Background(), "plugin/shutdown", nil)
_ = inst.stdin.Close()
select {
case <-inst.exited:
case <-time.After(800 * time.Millisecond):
inst.job.Close()
select {
case <-inst.exited:
case <-time.After(1 * time.Second):
}
}
inst.job.Close()
inst.rpc.Close()
}
// Stop terminates the Sidecar and its entire Job Object process tree cleanly.
func (s *SidecarSupervisor) Stop() {
s.mu.Lock()
s.stopped = true
inst := s.cur
s.cur = nil
cancel := s.idleCancel
s.idleCancel = nil
s.mu.Unlock()
if cancel != nil {
cancel()
}
s.terminateInstance(inst)
}
+174
View File
@@ -0,0 +1,174 @@
package plugin
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
const (
StateFileName = "state.json"
StartupSentinel = ".startup-sentinel"
CurrentStateSchema = 1
)
// PluginRecord persists enablement, pinned version, approved permissions, and
// settings for one plugin in `<DataRoot>/plugins/state.json` (§6.1).
type PluginRecord struct {
ID string `json:"id"`
Version string `json:"version,omitempty"`
Source SourceKind `json:"source,omitempty"`
Trust TrustLevel `json:"trust,omitempty"`
Enabled bool `json:"enabled"`
Pinned bool `json:"pinned,omitempty"`
DevPath string `json:"dev_path,omitempty"`
ApprovedPermissions []string `json:"approved_permissions,omitempty"`
ApprovedEntryHash string `json:"approved_entry_hash,omitempty"`
BlockingGuardOK bool `json:"blocking_guard_ok,omitempty"`
AppSettings map[string]any `json:"app_settings,omitempty"`
VMSettings map[string]map[string]any `json:"vm_settings,omitempty"` // vmName -> key -> val
InstalledVersions []string `json:"installed_versions,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
// CustomThemeScheme stores a user-created or edited theme color scheme (§5.1).
type CustomThemeScheme struct {
ID string `json:"id"`
ThemeID string `json:"theme_id"`
Name string `json:"name"`
Appearance string `json:"appearance,omitempty"`
Seeds map[string]string `json:"seeds"`
}
// StateFile is the authoritative persisted plugin state at `<DataRoot>/plugins/state.json`.
type StateFile struct {
Schema int `json:"schema"`
DeveloperMode bool `json:"developer_mode,omitempty"`
ActiveThemeID string `json:"active_theme_id,omitempty"`
ActiveSchemeID string `json:"active_scheme_id,omitempty"`
CustomSchemes []CustomThemeScheme `json:"custom_schemes,omitempty"`
Plugins map[string]*PluginRecord `json:"plugins"`
}
// StateStore safely reads and atomically writes state.json with .bak fallback.
// Per §6.1: read/parse errors are NEVER treated as an empty plugin list!
type StateStore struct {
mu sync.Mutex
dir string
data *StateFile
}
func NewStateStore(pluginsDir string) *StateStore {
return &StateStore{dir: pluginsDir}
}
func (s *StateStore) Path() string { return filepath.Join(s.dir, StateFileName) }
// Load reads state.json. Missing file initializes a fresh StateFile; any read
// or JSON parse error is returned immediately (never wiped to empty, §6.1).
func (s *StateStore) Load() (*StateFile, error) {
s.mu.Lock()
defer s.mu.Unlock()
p := s.Path()
raw, err := os.ReadFile(p)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
st := &StateFile{
Schema: CurrentStateSchema,
Plugins: make(map[string]*PluginRecord),
}
s.data = st
return st, nil
}
return nil, fmt.Errorf("read plugin state %s: %w", p, err)
}
var st StateFile
if err := json.Unmarshal(raw, &st); err != nil {
return nil, fmt.Errorf("corrupt plugin state %s (refusing to overwrite): %w", p, err)
}
if st.Plugins == nil {
st.Plugins = make(map[string]*PluginRecord)
}
if st.Schema == 0 {
st.Schema = CurrentStateSchema
}
s.data = &st
return &st, nil
}
// Save atomically persists state.json via temp file + .bak backup + rename (§6.1).
func (s *StateStore) Save(st *StateFile) error {
s.mu.Lock()
defer s.mu.Unlock()
if st == nil {
return errors.New("nil plugin state")
}
if st.Plugins == nil {
st.Plugins = make(map[string]*PluginRecord)
}
st.Schema = CurrentStateSchema
if err := os.MkdirAll(s.dir, 0o755); err != nil {
return err
}
raw, err := json.MarshalIndent(st, "", " ")
if err != nil {
return err
}
raw = append(raw, '\n')
target := s.Path()
tmp := target + ".tmp"
if err := os.WriteFile(tmp, raw, 0o644); err != nil {
return err
}
// Preserve previous valid file as .bak before atomic swap.
if prev, err := os.ReadFile(target); err == nil {
_ = os.WriteFile(target+".bak", prev, 0o644)
}
if err := os.Rename(tmp, target); err != nil {
_ = os.Remove(tmp)
return err
}
s.data = st
return nil
}
// --- Safe-mode startup sentinel (§9) ---
// SentinelPath returns `<DataRoot>/plugins/.startup-sentinel`.
func SentinelPath(pluginsDir string) string {
return filepath.Join(pluginsDir, StartupSentinel)
}
// DidLastStartupCrash reports whether a startup sentinel from an unfinished
// plugin initialization is still on disk.
func DidLastStartupCrash(pluginsDir string) bool {
if strings.TrimSpace(pluginsDir) == "" {
return false
}
_, err := os.Stat(SentinelPath(pluginsDir))
return err == nil
}
// BeginStartupInit writes the startup sentinel before loading third-party plugins.
func BeginStartupInit(pluginsDir string) error {
if strings.TrimSpace(pluginsDir) == "" {
return nil
}
if err := os.MkdirAll(pluginsDir, 0o755); err != nil {
return err
}
return os.WriteFile(SentinelPath(pluginsDir), []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), 0o644)
}
// EndStartupInit removes the startup sentinel once plugin init succeeds.
func EndStartupInit(pluginsDir string) {
if strings.TrimSpace(pluginsDir) == "" {
return
}
_ = os.Remove(SentinelPath(pluginsDir))
}
+599
View File
@@ -0,0 +1,599 @@
package plugin
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"unicode"
)
var (
reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`)
reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`)
reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`)
reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`)
reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`)
reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`)
)
// ValidateThemeCSSSafety rejects unbalanced braces, unclosed strings/comments,
// CSS-escaped url()/image-set()/expression() bypasses, remote @import, and
// external or unsafe data: URLs (§5.1, B5).
func ValidateThemeCSSSafety(css string) error {
return ValidateThemeCSSSafetyInDir(css, "")
}
// ValidateThemeCSSSafetyInDir performs ValidateThemeCSSSafety and, when rootDir
// is non-empty, also verifies that every relative url()/@import resolves to an
// existing file inside rootDir.
func ValidateThemeCSSSafetyInDir(css, rootDir string) error {
if strings.Contains(strings.ToLower(css), "</style") {
return errors.New("theme stylesheet cannot contain </style")
}
n := len(css)
i := 0
braceDepth := 0
skipWSAndComments := func() error {
for i < n {
if css[i] == ' ' || css[i] == '\t' || css[i] == '\r' || css[i] == '\n' || css[i] == '\f' {
i++
continue
}
if i+1 < n && css[i] == '/' && css[i+1] == '*' {
end := strings.Index(css[i+2:], "*/")
if end < 0 {
return errors.New("unclosed CSS comment in theme stylesheet")
}
i += 2 + end + 2
continue
}
break
}
return nil
}
readString := func(quote byte) (string, error) {
i++ // consume opening quote
var b strings.Builder
for i < n {
c := css[i]
if c == '\n' || c == '\r' || c == '\f' {
return "", errors.New("unclosed CSS string literal")
}
if c == quote {
i++
return b.String(), nil
}
if c == '\\' {
i++
if i >= n {
return "", errors.New("dangling escape in CSS string")
}
if css[i] == '\n' || css[i] == '\r' || css[i] == '\f' {
if css[i] == '\r' && i+1 < n && css[i+1] == '\n' {
i += 2
} else {
i++
}
continue
}
r, next := decodeCSSEscape(css, i)
b.WriteRune(r)
i = next
continue
}
b.WriteByte(c)
i++
}
return "", errors.New("unclosed CSS string literal")
}
readIdent := func() string {
var b strings.Builder
for i < n {
c := css[i]
if c == '\\' && i+1 < n && css[i+1] != '\n' && css[i+1] != '\r' {
r, next := decodeCSSEscape(css, i+1)
b.WriteRune(r)
i = next
continue
}
if isCSSIdentChar(c) {
b.WriteByte(c)
i++
continue
}
break
}
return b.String()
}
readURLArg := func() (string, error) {
if err := skipWSAndComments(); err != nil {
return "", err
}
if i >= n {
return "", errors.New("unclosed url() in theme stylesheet")
}
if css[i] == '"' || css[i] == '\'' {
val, err := readString(css[i])
if err != nil {
return "", err
}
if err := skipWSAndComments(); err != nil {
return "", err
}
if i >= n || css[i] != ')' {
return "", errors.New("malformed url() in theme stylesheet")
}
i++ // consume ')'
return val, nil
}
var b strings.Builder
for i < n {
c := css[i]
if c == ')' {
i++
return strings.TrimSpace(b.String()), nil
}
if c == '(' || c == '"' || c == '\'' || c == '\n' || c == '\r' {
return "", errors.New("malformed unquoted url() in theme stylesheet")
}
if c == '\\' {
if i+1 >= n {
return "", errors.New("dangling escape in url()")
}
r, next := decodeCSSEscape(css, i+1)
b.WriteRune(r)
i = next
continue
}
b.WriteByte(c)
i++
}
return "", errors.New("unclosed url() in theme stylesheet")
}
for i < n {
if err := skipWSAndComments(); err != nil {
return err
}
if i >= n {
break
}
c := css[i]
switch {
case c == '{':
braceDepth++
i++
case c == '}':
braceDepth--
if braceDepth < 0 {
return errors.New("unbalanced '}' in theme stylesheet (layer breakout blocked)")
}
i++
case c == '"' || c == '\'':
if _, err := readString(c); err != nil {
return err
}
case c == '@':
i++
atName := strings.ToLower(readIdent())
if atName == "import" {
if err := skipWSAndComments(); err != nil {
return err
}
var target string
var err error
if i < n && (css[i] == '"' || css[i] == '\'') {
target, err = readString(css[i])
if err != nil {
return err
}
} else {
fn := strings.ToLower(readIdent())
if fn != "url" || i >= n || css[i] != '(' {
return errors.New("@import syntax not allowed in theme stylesheet")
}
i++ // '('
target, err = readURLArg()
if err != nil {
return err
}
}
if err := validateCSSResourceURL(target, rootDir, true); err != nil {
return fmt.Errorf("@import %q forbidden: %w", target, err)
}
}
case isCSSIdentStart(c) || c == '\\':
ident := strings.ToLower(readIdent())
if i < n && css[i] == '(' {
switch ident {
case "expression":
return errors.New("CSS expression() is forbidden in theme stylesheets")
case "url", "src":
i++ // consume '('
u, err := readURLArg()
if err != nil {
return err
}
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
return err
}
case "image-set", "-webkit-image-set":
i++ // consume '('
if err := validateImageSetArgs(css, &i, rootDir, skipWSAndComments, readString, readIdent, readURLArg); err != nil {
return err
}
default:
i++ // consume '('
}
}
default:
i++
}
}
if braceDepth != 0 {
return errors.New("unbalanced '{' in theme stylesheet")
}
return nil
}
func validateImageSetArgs(
css string,
idx *int,
rootDir string,
skipWS func() error,
readString func(byte) (string, error),
readIdent func() string,
readURLArg func() (string, error),
) error {
depth := 1
n := len(css)
for *idx < n && depth > 0 {
if err := skipWS(); err != nil {
return err
}
if *idx >= n {
break
}
c := css[*idx]
switch {
case c == ')':
depth--
*idx++
case c == '(':
depth++
*idx++
case c == '"' || c == '\'':
s, err := readString(c)
if err != nil {
return err
}
// Bare strings inside image-set() are URLs unless inside type("...").
if depth == 1 {
if err := validateCSSResourceURL(s, rootDir, false); err != nil {
return err
}
}
case isCSSIdentStart(c) || c == '\\':
fn := strings.ToLower(readIdent())
if *idx < n && css[*idx] == '(' {
if fn == "url" || fn == "src" {
*idx++
u, err := readURLArg()
if err != nil {
return err
}
if err := validateCSSResourceURL(u, rootDir, false); err != nil {
return err
}
} else if fn == "image-set" || fn == "-webkit-image-set" {
*idx++
if err := validateImageSetArgs(css, idx, rootDir, skipWS, readString, readIdent, readURLArg); err != nil {
return err
}
} else {
depth++
*idx++
}
}
default:
*idx++
}
}
if depth != 0 {
return errors.New("unclosed image-set() in theme stylesheet")
}
return nil
}
func validateCSSResourceURL(rawURL, rootDir string, isImport bool) error {
u := strings.TrimSpace(rawURL)
if u == "" {
if isImport {
return errors.New("empty @import URL")
}
return nil
}
if strings.ContainsAny(u, "\r\n\x00") {
return errors.New("control characters in CSS URL")
}
lower := strings.ToLower(u)
if strings.HasPrefix(lower, "//") {
return fmt.Errorf("external protocol-relative URL %q is forbidden", u)
}
if strings.HasPrefix(lower, "data:") {
if isImport {
return errors.New("data: URL forbidden in @import")
}
allowedData := []string{
"data:image/png;", "data:image/png,",
"data:image/jpeg;", "data:image/jpeg,",
"data:image/webp;", "data:image/webp,",
"data:image/gif;", "data:image/gif,",
"data:font/woff2;", "data:font/woff;",
}
for _, pfx := range allowedData {
if strings.HasPrefix(lower, pfx) {
return nil
}
}
return fmt.Errorf("unsafe data: URL %q is forbidden in theme stylesheets", u)
}
if reSchemePrefix.MatchString(u) {
return fmt.Errorf("external/scheme URL %q is forbidden in theme stylesheets", u)
}
// Strip query/fragment for path validation.
pathOnly := u
if q := strings.IndexAny(pathOnly, "?#"); q >= 0 {
pathOnly = pathOnly[:q]
}
if pathOnly == "" {
// Fragment-only URL like url(#clip) — allowed for SVG/local refs, not @import.
if isImport {
return errors.New("fragment URL forbidden in @import")
}
return nil
}
if strings.HasPrefix(pathOnly, "/") || strings.Contains(pathOnly, "\\") {
return fmt.Errorf("absolute or backslash path %q is forbidden in theme stylesheets", u)
}
for _, seg := range strings.Split(pathOnly, "/") {
if seg == ".." {
return fmt.Errorf("path traversal %q is forbidden in theme stylesheets", u)
}
}
if rootDir != "" {
full, err := safeJoin(rootDir, pathOnly)
if err != nil {
return err
}
st, err := os.Stat(full)
if err != nil || st.IsDir() {
return fmt.Errorf("theme CSS asset %q not found in package", pathOnly)
}
}
return nil
}
// ValidateCSSTokenValue checks a single CSS custom property or seed value to
// ensure it cannot break out of a declaration, close @layer, or load external URLs (B5).
func ValidateCSSTokenValue(val string) error {
if strings.ContainsAny(val, "\r\n\x00{};") || strings.HasSuffix(strings.TrimSpace(val), `\`) {
return fmt.Errorf("CSS token value %q contains forbidden characters", val)
}
if strings.Contains(val, "/*") || strings.Contains(val, "*/") {
return fmt.Errorf("CSS token value %q must not contain CSS comments", val)
}
decoded := strings.ToLower(decodeAllCSSEscapes(val))
for _, bad := range []string{"</style", "url(", "src(", "image-set(", "-webkit-image-set(", "expression(", "@import", "javascript:", "data:", "http://", "https://", "//"} {
if strings.Contains(decoded, bad) {
return fmt.Errorf("CSS token value %q contains forbidden construct %q", val, bad)
}
}
return nil
}
// ValidateThemeContribution validates all theme manifest fields (tokens, seeds,
// fonts, background, and stylesheet) so untrusted strings cannot inject CSS (B5).
func ValidateThemeContribution(th ThemeContribution, rootDir string) error {
for k, v := range th.Tokens {
if !reTokenKey.MatchString(k) {
return fmt.Errorf("invalid theme token key %q", k)
}
if err := ValidateCSSTokenValue(v); err != nil {
return fmt.Errorf("theme token %q: %w", k, err)
}
}
for k, v := range th.DarkTokens {
if !reTokenKey.MatchString(k) {
return fmt.Errorf("invalid theme darkToken key %q", k)
}
if err := ValidateCSSTokenValue(v); err != nil {
return fmt.Errorf("theme darkToken %q: %w", k, err)
}
}
for k, v := range th.Seeds {
if err := ValidateCSSTokenValue(v); err != nil {
return fmt.Errorf("theme seed %q: %w", k, err)
}
}
for _, sc := range th.Schemes {
for k, v := range sc.Seeds {
if err := ValidateCSSTokenValue(v); err != nil {
return fmt.Errorf("theme scheme %q seed %q: %w", sc.ID, k, err)
}
}
}
for _, r := range th.DeriveRules {
if !reTokenKey.MatchString(r.Token) {
return fmt.Errorf("invalid deriveRule token %q", r.Token)
}
}
if th.Background != "" {
if err := validateSafeManifestAsset(th.Background, rootDir); err != nil {
return fmt.Errorf("theme background %q: %w", th.Background, err)
}
}
if th.BrandMark != "" {
if err := validateSafeManifestAsset(th.BrandMark, rootDir); err != nil {
return fmt.Errorf("theme brandMark %q: %w", th.BrandMark, err)
}
}
if th.UIScript != "" {
if err := validateSafeManifestAsset(th.UIScript, rootDir); err != nil {
return fmt.Errorf("theme uiScript %q: %w", th.UIScript, err)
}
}
for k, asset := range th.Icons {
if err := validateSafeManifestAsset(asset, rootDir); err != nil {
return fmt.Errorf("theme icon %q (%q): %w", k, asset, err)
}
}
for k, asset := range th.Sounds {
if err := validateSafeManifestAsset(asset, rootDir); err != nil {
return fmt.Errorf("theme sound %q (%q): %w", k, asset, err)
}
}
for _, dec := range th.Decorations {
for _, st := range dec.States {
if st.Asset != "" {
if err := validateSafeManifestAsset(st.Asset, rootDir); err != nil {
return fmt.Errorf("theme decoration %q asset %q: %w", dec.ID, st.Asset, err)
}
}
for _, fr := range st.Frames {
if err := validateSafeManifestAsset(fr, rootDir); err != nil {
return fmt.Errorf("theme decoration %q frame %q: %w", dec.ID, fr, err)
}
}
}
}
for _, f := range th.Fonts {
if strings.TrimSpace(f.Family) == "" || strings.ContainsAny(f.Family, "\"'\\;{}\r\n\x00") || strings.Contains(strings.ToLower(f.Family), "</style") {
return fmt.Errorf("invalid theme font family %q", f.Family)
}
if err := validateSafeManifestAsset(f.File, rootDir); err != nil {
return fmt.Errorf("theme font file %q: %w", f.File, err)
}
if f.Weight != "" && !reFontWeight.MatchString(f.Weight) {
return fmt.Errorf("invalid theme font weight %q", f.Weight)
}
if f.Style != "" && !reFontStyle.MatchString(strings.TrimSpace(f.Style)) {
return fmt.Errorf("invalid theme font style %q", f.Style)
}
if f.UnicodeRange != "" && !reUnicodeRange.MatchString(f.UnicodeRange) {
return fmt.Errorf("invalid theme font unicodeRange %q", f.UnicodeRange)
}
}
if th.Stylesheet != "" {
if rootDir != "" {
cssPath, err := safeJoin(rootDir, th.Stylesheet)
if err != nil {
return fmt.Errorf("invalid theme stylesheet path: %w", err)
}
cssRaw, err := os.ReadFile(cssPath)
if err != nil {
return fmt.Errorf("missing theme stylesheet %q: %w", th.Stylesheet, err)
}
// Relative url() inside stylesheet resolves relative to stylesheet's dir;
// verify inside package rootDir as well.
if err := ValidateThemeCSSSafetyInDir(string(cssRaw), filepath.Dir(cssPath)); err != nil {
return fmt.Errorf("unsafe theme CSS %q: %w", th.Stylesheet, err)
}
}
}
return nil
}
func validateSafeManifestAsset(rel, rootDir string) error {
if rel == "" {
return errors.New("empty asset path")
}
if strings.ContainsAny(rel, "\"'\\;{}()\r\n\x00") || !reSafeAssetRel.MatchString(rel) {
return errors.New("asset path contains forbidden characters")
}
if strings.HasPrefix(rel, "/") || reSchemePrefix.MatchString(rel) {
return errors.New("asset path must be package-relative")
}
for _, seg := range strings.Split(rel, "/") {
if seg == ".." {
return errors.New("path traversal in asset path")
}
}
if rootDir != "" {
full, err := safeJoin(rootDir, rel)
if err != nil {
return err
}
st, err := os.Stat(full)
if err != nil || st.IsDir() {
return errors.New("asset file not found in package")
}
}
return nil
}
func decodeCSSEscape(s string, pos int) (rune, int) {
n := len(s)
if pos >= n {
return 0xFFFD, pos
}
if isHexByte(s[pos]) {
start := pos
for pos < n && pos-start < 6 && isHexByte(s[pos]) {
pos++
}
code, err := strconv.ParseInt(s[start:pos], 16, 32)
// CSS spec: one optional whitespace char after hex escape is consumed.
if pos < n {
if s[pos] == '\r' && pos+1 < n && s[pos+1] == '\n' {
pos += 2
} else if s[pos] == ' ' || s[pos] == '\t' || s[pos] == '\n' || s[pos] == '\r' || s[pos] == '\f' {
pos++
}
}
if err != nil || code <= 0 || code > unicode.MaxRune {
return 0xFFFD, pos
}
return rune(code), pos
}
return rune(s[pos]), pos + 1
}
func decodeAllCSSEscapes(s string) string {
if !strings.ContainsRune(s, '\\') {
return s
}
var b strings.Builder
for i := 0; i < len(s); {
if s[i] == '\\' && i+1 < len(s) {
r, next := decodeCSSEscape(s, i+1)
b.WriteRune(r)
i = next
continue
}
b.WriteByte(s[i])
i++
}
return b.String()
}
func isHexByte(c byte) bool {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}
func isCSSIdentStart(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-' || c >= 0x80
}
func isCSSIdentChar(c byte) bool {
return isCSSIdentStart(c) || (c >= '0' && c <= '9')
}
+570
View File
@@ -0,0 +1,570 @@
// Package plugin implements the Reims-Go plugin kernel: unified extension
// registry, reversible scopes, dependency-driven reconciliation, hook dispatch,
// start-intent argument ownership ledger, package lifecycle, security broker,
// L1 declarative rules, and L3 Sidecar supervision.
package plugin
import (
"encoding/json"
"strings"
"time"
)
const (
// PluginAPIVersion is the host plugin API contract version (SemVer).
PluginAPIVersion = "1.0.0"
// UIAPIVersion is the frontend UI contract version (SemVer).
UIAPIVersion = "1.0.0"
// ManifestSchemaVersion is the current plugin.json schema version.
ManifestSchemaVersion = 1
)
// State represents the runtime lifecycle state of a plugin (§4.1).
type State string
const (
StateOff State = "off"
StatePending State = "pending"
StateActive State = "active"
StateDegraded State = "degraded"
StateFailed State = "failed"
)
// TrustLevel classifies the provenance and signature trust of a plugin (§7.2).
type TrustLevel string
const (
TrustOfficial TrustLevel = "official"
TrustVerified TrustLevel = "verified"
TrustCommunity TrustLevel = "community"
TrustDev TrustLevel = "dev"
)
// Tier identifies the execution isolation layer derived from package contents (§3.1).
type Tier string
const (
TierBuiltin Tier = "builtin"
TierL1 Tier = "L1"
TierRuntime Tier = "runtime"
TierL2 Tier = "L2"
TierL3 Tier = "L3"
TierL4 Tier = "L4"
)
// SourceKind distinguishes where a plugin came from.
type SourceKind string
const (
SourceBuiltin SourceKind = "builtin"
SourceBundled SourceKind = "bundled"
SourceLocal SourceKind = "local"
SourceMarket SourceKind = "market"
SourceDevLink SourceKind = "dev"
)
// LocalizedText holds bilingual zh-CN / en-US strings readable without executing code (§6.2).
type LocalizedText struct {
ZhCN string `json:"zh-CN,omitempty"`
EnUS string `json:"en-US,omitempty"`
}
// Get returns the best localized string for locale, falling back cleanly.
func (lt LocalizedText) Get(locale string) string {
if strings.HasPrefix(strings.ToLower(locale), "zh") {
if lt.ZhCN != "" {
return lt.ZhCN
}
return lt.EnUS
}
if lt.EnUS != "" {
return lt.EnUS
}
return lt.ZhCN
}
// UnmarshalJSON accepts either a plain string or an object {"zh-CN": ..., "en-US": ...}.
func (lt *LocalizedText) UnmarshalJSON(data []byte) error {
var plain string
if err := json.Unmarshal(data, &plain); err == nil {
lt.ZhCN = plain
lt.EnUS = plain
return nil
}
type alias LocalizedText
var a alias
if err := json.Unmarshal(data, &a); err != nil {
return err
}
*lt = LocalizedText(a)
return nil
}
// Engines specifies host compatibility ranges checked before install (§6.2).
type Engines struct {
ReimsGo string `json:"reims-go,omitempty"`
PluginAPI string `json:"pluginApi,omitempty"`
UIAPI string `json:"uiApi,omitempty"`
}
// Entry declares executable/script/panel entrypoints. Tier is inferred from this (§6.2).
type Entry struct {
Sidecar string `json:"sidecar,omitempty"`
Script string `json:"script,omitempty"`
PanelDir string `json:"panelDir,omitempty"`
UIScript string `json:"uiScript,omitempty"`
}
// ServiceRequirement declares a service dependency with an optional SemVer range.
type ServiceRequirement struct {
Service string `json:"service"`
Version string `json:"version,omitempty"`
Optional bool `json:"optional,omitempty"`
}
// ServiceProvision declares a service provided by a plugin.
type ServiceProvision struct {
Service string `json:"service"`
Version string `json:"version"`
}
// Provenance records upstream build and source archive metadata (mandatory for runtime packages).
type Provenance struct {
UpstreamRepo string `json:"upstreamRepo,omitempty"`
Commit string `json:"commit,omitempty"`
Patches []string `json:"patches,omitempty"`
PatchHashes []string `json:"patchHashes,omitempty"`
SourcePackage string `json:"sourcePackage,omitempty"`
}
// Manifest is the declarative plugin.json descriptor (§6.2).
type Manifest struct {
Schema int `json:"schema"`
ID string `json:"id"`
Version string `json:"version"`
Name LocalizedText `json:"name"`
Description LocalizedText `json:"description"`
Publisher string `json:"publisher,omitempty"`
License string `json:"license,omitempty"`
Homepage string `json:"homepage,omitempty"`
Engines Engines `json:"engines,omitempty"`
Platforms []string `json:"platforms,omitempty"`
Entry Entry `json:"entry,omitempty"`
Contributes Contributes `json:"contributes,omitempty"`
Requires []ServiceRequirement `json:"requires,omitempty"`
Provides []ServiceProvision `json:"provides,omitempty"`
Permissions []string `json:"permissions,omitempty"`
Activation []string `json:"activation,omitempty"`
Settings *SettingsSchema `json:"settings,omitempty"`
DefaultEnabled bool `json:"defaultEnabled,omitempty"`
Provenance *Provenance `json:"provenance,omitempty"`
}
// InferTier derives the plugin's execution tier from manifest contents (never trusting self-claims).
func (m Manifest) InferTier(isBuiltin bool) Tier {
if isBuiltin {
return TierBuiltin
}
if strings.TrimSpace(m.Entry.Sidecar) != "" {
return TierL3
}
if strings.TrimSpace(m.Entry.Script) != "" {
return TierL2
}
if strings.TrimSpace(m.Entry.PanelDir) != "" || len(m.Contributes.Panels) > 0 {
return TierL4
}
if len(m.Contributes.Runtimes) > 0 {
return TierRuntime
}
return TierL1
}
// Contributes enumerates all extension-point declarations in plugin.json (§4.2).
type Contributes struct {
Themes []ThemeContribution `json:"themes,omitempty"`
UIScripts []UIScriptContribution `json:"uiScripts,omitempty"`
Locales []LocaleContribution `json:"locales,omitempty"`
InputFilters []InputFilterContribution `json:"inputFilters,omitempty"`
VMTemplates []VMTemplateContribution `json:"vmTemplates,omitempty"`
RuntimeSources []RuntimeSourceContribution `json:"runtimeSources,omitempty"`
RuntimeKinds []RuntimeKindContribution `json:"runtimeKinds,omitempty"`
Runtimes []RuntimePackContribution `json:"runtimes,omitempty"`
GuestDrivers []GuestDriverContribution `json:"guestDrivers,omitempty"`
Hooks []HookContribution `json:"hooks,omitempty"`
RuleHooks []RuleHook `json:"ruleHooks,omitempty"`
Commands []CommandContribution `json:"commands,omitempty"`
Menus []MenuContribution `json:"menus,omitempty"`
VMCards []VMCardContribution `json:"vmCards,omitempty"`
SettingsPages []SettingsPageContribution `json:"settingsPages,omitempty"`
StatusItems []StatusItemContribution `json:"statusItems,omitempty"`
Panels []PanelContribution `json:"panels,omitempty"`
Diagnostics []DiagnosticsContribution `json:"diagnostics,omitempty"`
}
// ThemeContribution describes a L1 token/style theme or tier-3 interactive theme (§5.1).
type ThemeContribution struct {
ID string `json:"id"`
Name LocalizedText `json:"name"`
Description LocalizedText `json:"description,omitempty"`
Appearance string `json:"appearance,omitempty"` // "light" | "dark" | "both"
Seeds map[string]string `json:"seeds,omitempty"`
Schemes []ThemeScheme `json:"schemes,omitempty"`
DeriveRules []TokenDeriveRule `json:"deriveRules,omitempty"`
Tokens map[string]string `json:"tokens,omitempty"`
DarkTokens map[string]string `json:"darkTokens,omitempty"`
Fonts []ThemeFont `json:"fonts,omitempty"`
Icons map[string]string `json:"icons,omitempty"`
BrandMark string `json:"brandMark,omitempty"`
Background string `json:"background,omitempty"`
Sounds map[string]string `json:"sounds,omitempty"`
Stylesheet string `json:"stylesheet,omitempty"` // relative path inside package
Decorations []ThemeDecoration `json:"decorations,omitempty"`
UIScript string `json:"uiScript,omitempty"` // requires ui:script
PluginID string `json:"pluginId,omitempty"`
}
// ThemeScheme is a named seed-color preset inside a theme pack.
type ThemeScheme struct {
ID string `json:"id"`
Name LocalizedText `json:"name"`
Appearance string `json:"appearance,omitempty"` // "light" | "dark" | "both"
Seeds map[string]string `json:"seeds"`
}
// TokenDeriveRule derives a CSS custom property from a seed color using
// declarative lightness/chroma/alpha adjustments per light/dark appearance.
type TokenDeriveRule struct {
Token string `json:"token"`
FromSeed string `json:"fromSeed"`
Appearance string `json:"appearance,omitempty"` // "" (both) | "light" | "dark"
Lightness float64 `json:"lightness,omitempty"` // delta in [-1, 1]
Chroma float64 `json:"chroma,omitempty"` // scale multiplier (0 = unchanged)
Alpha float64 `json:"alpha,omitempty"` // 0 = opaque / unchanged, (0,1] sets alpha
}
// ThemeFont declares a bundled font face.
type ThemeFont struct {
Family string `json:"family"`
File string `json:"file"`
Weight string `json:"weight,omitempty"`
Style string `json:"style,omitempty"`
UnicodeRange string `json:"unicodeRange,omitempty"`
}
// ThemeDecoration defines a declarative state-driven sprite/frame decoration anchored to a slot.
type ThemeDecoration struct {
ID string `json:"id"`
Slot string `json:"slot"` // e.g. "sidebar.footer", "vm.preview.br"
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Alt LocalizedText `json:"alt,omitempty"`
States []ThemeDecorationState `json:"states"`
}
// ThemeDecorationState maps a state expression (e.g. "vmState==running") to a static/animated asset.
type ThemeDecorationState struct {
When string `json:"when"` // "default", "vmState==running", "busy==true", etc.
Asset string `json:"asset,omitempty"`
Frames []string `json:"frames,omitempty"`
FPS int `json:"fps,omitempty"`
}
// UIScriptContribution registers a trusted interactive theme script.
type UIScriptContribution struct {
ID string `json:"id"`
ThemeID string `json:"themeId"`
Script string `json:"script"`
PluginID string `json:"pluginId,omitempty"`
}
// LocaleContribution registers additional UI translations.
type LocaleContribution struct {
Locale string `json:"locale"`
File string `json:"file,omitempty"`
Messages map[string]string `json:"messages,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// InputFilterContribution declares a host-side input filter rule (§5.4).
type InputFilterContribution struct {
ID string `json:"id"`
Event string `json:"event"` // "mouse_wheel"
Axis string `json:"axis,omitempty"` // "vertical" | "horizontal" | "both"
Transform string `json:"transform"` // "invert"
Scope string `json:"scope"` // "vm_foreground"
SettingKey string `json:"settingKey,omitempty"` // VM-scoped boolean key
HorizKey string `json:"horizontalKey,omitempty"`
VertKey string `json:"verticalKey,omitempty"`
Name LocalizedText `json:"name,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// VMTemplateContribution contributes a VM creation preset.
type VMTemplateContribution struct {
ID string `json:"id"`
DriverID string `json:"driverId,omitempty"`
Name LocalizedText `json:"name"`
Description LocalizedText `json:"description,omitempty"`
Defaults map[string]any `json:"defaults,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// RuntimeSourceContribution contributes an additional runtime download mirror/source.
type RuntimeSourceContribution struct {
ID string `json:"id"`
Kind string `json:"kind"`
Name LocalizedText `json:"name"`
IndexURL string `json:"indexUrl"`
Channel string `json:"channel,omitempty"`
License string `json:"license,omitempty"`
Publisher string `json:"publisher,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// RuntimeKindContribution registers a new runtime kind (e.g. "qemu-ovmf").
type RuntimeKindContribution struct {
Kind string `json:"kind"`
Name LocalizedText `json:"name"`
Description LocalizedText `json:"description,omitempty"`
RequiredFiles []string `json:"requiredFiles,omitempty"`
DefaultAPIVer string `json:"defaultApiVersion,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// RuntimePackContribution declares an archive/binary runtime package inside a plugin.
type RuntimePackContribution struct {
Kind string `json:"kind"`
Version string `json:"version"`
RuntimeAPI string `json:"runtimeApi"`
Capabilities []string `json:"capabilities,omitempty"`
Dir string `json:"dir,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// GuestDriverContribution declares a guest VM driver provided by an L3 Sidecar or builtin.
type GuestDriverContribution struct {
ID string `json:"id"`
Name LocalizedText `json:"name"`
Description LocalizedText `json:"description,omitempty"`
RuntimeKind string `json:"runtimeKind"`
RuntimeAPIRange string `json:"runtimeApiRange,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
CreateSchema *SettingsSchema `json:"createSchema,omitempty"`
SettingsSchema *SettingsSchema `json:"settingsSchema,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// HookContribution subscribes a Sidecar or L2 script to a lifecycle event.
type HookContribution struct {
Event string `json:"event"`
Priority int `json:"priority,omitempty"`
Blocking bool `json:"blocking,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// CommandContribution exposes a command callable via CLI (`plugin run`) or GUI menu.
type CommandContribution struct {
ID string `json:"id"`
Title LocalizedText `json:"title"`
Description LocalizedText `json:"description,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// MenuContribution contributes a button/menu item to a declared UI slot (e.g. vm.toolbar).
type MenuContribution struct {
ID string `json:"id"`
Slot string `json:"slot"` // "vm.toolbar"
Command string `json:"command"`
Title LocalizedText `json:"title"`
When string `json:"when,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// VMCardContribution contributes key-value info to `vm.card`.
type VMCardContribution struct {
ID string `json:"id"`
Title LocalizedText `json:"title"`
Value LocalizedText `json:"value,omitempty"`
Badge string `json:"badge,omitempty"` // "ok" | "warn" | "idle" | "error"
When string `json:"when,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// SettingsPageContribution declares a plugin settings group.
type SettingsPageContribution struct {
ID string `json:"id"`
Title LocalizedText `json:"title"`
Group string `json:"group,omitempty"` // e.g. "keyboard", "collaboration", "general"
Scope string `json:"scope,omitempty"` // "app" | "vm"
PluginID string `json:"pluginId,omitempty"`
}
// StatusItemContribution contributes an item to `statusbar.right`.
type StatusItemContribution struct {
ID string `json:"id"`
Slot string `json:"slot"` // "statusbar.right"
Text LocalizedText `json:"text"`
Tooltip LocalizedText `json:"tooltip,omitempty"`
Command string `json:"command,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// PanelContribution declares an L4 sandboxed iframe panel in a declared slot.
type PanelContribution struct {
ID string `json:"id"`
Slot string `json:"slot"` // "settings.plugin" | "vm.card" | "sidebar.footer"
Title LocalizedText `json:"title"`
Entry string `json:"entry"` // relative HTML file under entry.panelDir
Height int `json:"height,omitempty"`
PluginID string `json:"pluginId,omitempty"`
}
// DiagnosticsContribution declares a diagnostics collector.
type DiagnosticsContribution struct {
ID string `json:"id"`
Title LocalizedText `json:"title"`
PluginID string `json:"pluginId,omitempty"`
}
// SettingsSchema is a JSON Schema subset with Reims-Go extensions (§6.2).
type SettingsSchema struct {
Title LocalizedText `json:"title,omitempty"`
Group string `json:"x-group,omitempty"` // e.g. "keyboard", "collaboration"
Scope string `json:"x-scope,omitempty"` // "app" | "vm"
Properties map[string]SettingProperty `json:"properties"`
Order []string `json:"x-order,omitempty"`
}
// SettingProperty describes one configurable field.
type SettingProperty struct {
Type string `json:"type"` // "boolean" | "string" | "number" | "integer"
Title LocalizedText `json:"title"`
Description LocalizedText `json:"description,omitempty"`
Default any `json:"default,omitempty"`
Enum []string `json:"enum,omitempty"`
EnumLabels []LocalizedText `json:"x-enumLabels,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
Secret bool `json:"x-secret,omitempty"`
Effect string `json:"x-effect,omitempty"` // "immediate" | "next_start"
Scope string `json:"x-scope,omitempty"` // "app" | "vm"
Group string `json:"x-group,omitempty"` // VM settings section id
Required bool `json:"required,omitempty"`
}
// PermissionLevel categorizes permission risk (§7.1).
type PermissionLevel string
const (
PermLow PermissionLevel = "low"
PermMedium PermissionLevel = "medium"
PermHigh PermissionLevel = "high"
PermForbidden PermissionLevel = "forbidden"
)
// PermissionSpec classifies a declared permission string.
type PermissionSpec struct {
Name string `json:"name"`
Level PermissionLevel `json:"level"`
}
// ClassifyPermission returns the risk tier of a permission per §7.1.
func ClassifyPermission(perm string) PermissionLevel {
p := strings.TrimSpace(perm)
switch p {
case "vm:read", "ui:notify", "task:progress", "fs:plugin_data", "log:read":
return PermLow
case "vm:intent", "runtime:source", "ui:slot", "input:filter":
return PermMedium
case "driver:vm", "runtime:provider", "process:spawn", "vm:control",
"qmp:write", "fs:vm_dir", "fs:shared", "host:clipboard", "ui:script":
return PermHigh
}
if strings.HasPrefix(p, "net:") && len(p) > len("net:") {
return PermMedium
}
return PermForbidden
}
// HasHighRiskPermission returns all high-risk permissions in perms.
func HighRiskPermissions(perms []string) []string {
var out []string
for _, p := range perms {
if ClassifyPermission(p) == PermHigh {
out = append(out, p)
}
}
return out
}
// ForbiddenPermissions returns any unrecognized/forbidden permissions in perms.
func ForbiddenPermissions(perms []string) []string {
var out []string
for _, p := range perms {
if ClassifyPermission(p) == PermForbidden {
out = append(out, p)
}
}
return out
}
// DeclaredUISlots lists the host-declared UI slots and their max item caps (§4.2).
var DeclaredUISlots = map[string]int{
"vm.toolbar": 8,
"vm.card": 6,
"settings.plugin": 16,
"sidebar.footer": 2,
"statusbar.right": 4,
"create.source": 4,
"vm.preview.tl": 2,
"vm.preview.tr": 2,
"vm.preview.bl": 2,
"vm.preview.br": 2,
"empty.state": 2,
}
// IsDeclaredSlot checks whether slot is a host-recognized UI slot.
func IsDeclaredSlot(slot string) bool {
_, ok := DeclaredUISlots[slot]
return ok
}
// PluginInfo is the read-only UI/CLI view of an installed or builtin plugin.
type PluginInfo struct {
ID string `json:"id"`
Version string `json:"version"`
Name LocalizedText `json:"name"`
Description LocalizedText `json:"description"`
Publisher string `json:"publisher,omitempty"`
License string `json:"license,omitempty"`
Homepage string `json:"homepage,omitempty"`
Source SourceKind `json:"source"`
Trust TrustLevel `json:"trust"`
Tier Tier `json:"tier"`
State State `json:"state"`
Enabled bool `json:"enabled"`
Removable bool `json:"removable"`
InUse bool `json:"in_use"`
Error string `json:"error,omitempty"`
DegradedReason string `json:"degraded_reason,omitempty"`
Permissions []PermissionSpec `json:"permissions,omitempty"`
ApprovedPermissions []string `json:"approved_permissions,omitempty"`
NeedsApproval bool `json:"needs_approval"`
Requires []string `json:"requires,omitempty"`
Provides []string `json:"provides,omitempty"`
Settings *SettingsSchema `json:"settings,omitempty"`
InstallDir string `json:"install_dir,omitempty"`
EntryHash string `json:"entry_hash,omitempty"`
EntryPath string `json:"entry_path,omitempty"`
LogPath string `json:"log_path,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
// DiagnosticsEntry is one redacted diagnostic section contributed by a plugin.
type DiagnosticsEntry struct {
PluginID string `json:"plugin_id"`
Title string `json:"title"`
Data map[string]any `json:"data,omitempty"`
Text string `json:"text,omitempty"`
}
+30
View File
@@ -42,6 +42,36 @@ func RebootSocketPath(vmDir, tmpDir, vmName string) string {
return filepath.Join(vmDir, "q-"+short+".sock")
}
// StripLegacyWin10RebootArgs removes reims-go managed Win10 cold-reboot args
// (`-no-reboot` + `-qmp <managed>`) ONLY when a managed QMP target is present,
// preserving any user hand-written `-no-reboot` on hosts without managed QMP.
func StripLegacyWin10RebootArgs(existing string) string {
tokens := splitShellTokens(existing)
hasManagedQMP := false
for i := 0; i < len(tokens); i++ {
if tokens[i] == "-qmp" && i+1 < len(tokens) && isManagedQMPTarget(tokens[i+1]) {
hasManagedQMP = true
break
}
}
if !hasManagedQMP {
return strings.TrimSpace(existing)
}
cleaned := make([]string, 0, len(tokens))
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
if tok == "-no-reboot" {
continue
}
if tok == "-qmp" && i+1 < len(tokens) && isManagedQMPTarget(tokens[i+1]) {
i++
continue
}
cleaned = append(cleaned, tok)
}
return strings.Join(cleaned, " ")
}
// MergeWin10RebootUnixArgs idempotently merges `-no-reboot` and a local AF_UNIX
// `-qmp unix:<path>,server=on,wait=off` into existing extra_args while stripping
// any legacy managed TCP or Unix QMP arguments.
+251
View File
@@ -0,0 +1,251 @@
package runtime
import (
"errors"
"fmt"
"regexp"
"sort"
"strings"
"sync"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/plugin"
)
var reRuntimeKind = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
const (
// DefaultKind is the built-in macOS vGPU runtime kind.
DefaultKind = "reims-vgpu"
// DefaultRuntimeAPI is the baseline CLI/output contract version for reims-vgpu.
DefaultRuntimeAPI = "1.0.0"
)
// KindSpec describes a registered runtime kind (e.g. "reims-vgpu", "qemu-ovmf").
type KindSpec struct {
Kind string `json:"kind"`
NameZh string `json:"name_zh"`
NameEn string `json:"name_en"`
RequiredFiles []string `json:"required_files,omitempty"`
DefaultAPIVersion string `json:"default_api_version,omitempty"`
Builtin bool `json:"builtin,omitempty"`
PluginID string `json:"plugin_id,omitempty"`
}
// KindRegistry holds all registered runtime kinds (§5.2).
type KindRegistry struct {
mu sync.RWMutex
kinds map[string]KindSpec
}
// NewKindRegistry creates a registry pre-populated with the built-in reims-vgpu kind.
func NewKindRegistry() *KindRegistry {
kr := &KindRegistry{
kinds: make(map[string]KindSpec),
}
kr.kinds[DefaultKind] = KindSpec{
Kind: DefaultKind,
NameZh: "Reims vGPU 运行时",
NameEn: "Reims vGPU Runtime",
RequiredFiles: []string{"bin/reims-ctl.exe", "qemu/bin/qemu-system-x86_64.exe"},
DefaultAPIVersion: DefaultRuntimeAPI,
Builtin: true,
PluginID: "builtin.runtime.reims-vgpu",
}
return kr
}
// Register adds or updates a runtime kind.
func (kr *KindRegistry) Register(spec KindSpec) error {
spec.Kind = strings.TrimSpace(spec.Kind)
if spec.Kind == "" {
return errors.New("runtime kind cannot be empty")
}
if !reRuntimeKind.MatchString(spec.Kind) || strings.Contains(spec.Kind, "..") {
return fmt.Errorf("invalid runtime kind %q", spec.Kind)
}
kr.mu.Lock()
defer kr.mu.Unlock()
if cur, exists := kr.kinds[spec.Kind]; exists {
if cur.Builtin {
return fmt.Errorf("cannot overwrite built-in runtime kind %q", spec.Kind)
}
if cur.PluginID != "" && spec.PluginID != "" && cur.PluginID != spec.PluginID {
return fmt.Errorf("runtime kind %q is already owned by plugin %q", spec.Kind, cur.PluginID)
}
}
kr.kinds[spec.Kind] = spec
return nil
}
// Unregister removes a non-builtin runtime kind registered by pluginID.
func (kr *KindRegistry) Unregister(kind, pluginID string) {
kr.mu.Lock()
if cur, ok := kr.kinds[kind]; ok && !cur.Builtin && (pluginID == "" || cur.PluginID == pluginID) {
delete(kr.kinds, kind)
}
kr.mu.Unlock()
}
// Get returns a registered runtime kind.
func (kr *KindRegistry) Get(kind string) (KindSpec, bool) {
kr.mu.RLock()
spec, ok := kr.kinds[kind]
kr.mu.RUnlock()
return spec, ok
}
// List returns all registered runtime kinds sorted deterministically.
func (kr *KindRegistry) List() []KindSpec {
kr.mu.RLock()
defer kr.mu.RUnlock()
out := make([]KindSpec, 0, len(kr.kinds))
for _, s := range kr.kinds {
out = append(out, s)
}
sort.Slice(out, func(i, j int) bool {
if out[i].Builtin != out[j].Builtin {
return out[i].Builtin
}
return out[i].Kind < out[j].Kind
})
return out
}
// EffectiveKind returns Manifest.Kind, defaulting to "reims-vgpu" for legacy packages.
func (m Manifest) EffectiveKind() string {
if strings.TrimSpace(m.Kind) != "" {
return strings.TrimSpace(m.Kind)
}
return DefaultKind
}
// EffectiveRuntimeAPI returns Manifest.RuntimeAPI, defaulting to "1.0.0".
func (m Manifest) EffectiveRuntimeAPI() string {
if strings.TrimSpace(m.RuntimeAPI) != "" {
return strings.TrimSpace(m.RuntimeAPI)
}
return DefaultRuntimeAPI
}
// EffectiveCapabilities returns declared capabilities plus inferred legacy
// capabilities derived from Patches so callers no longer match raw patch filenames (§5.2).
func (m Manifest) EffectiveCapabilities() []string {
seen := make(map[string]bool, len(m.Capabilities)+len(m.Patches))
var out []string
add := func(c string) {
c = strings.TrimSpace(c)
if c != "" && !seen[c] {
seen[c] = true
out = append(out, c)
}
}
for _, c := range m.Capabilities {
add(c)
}
for _, p := range m.Patches {
low := strings.ToLower(p.Name)
switch {
case strings.Contains(low, "nested-virt-nonfatal"):
add("nested-virt-nonfatal")
case strings.Contains(low, "startup-ipis"):
add("win10-startup-ipis")
case strings.Contains(low, "win10-compat"):
add("win10-compat")
case strings.Contains(low, "coroutine-fiber"):
add("win32-coroutine-fiber")
}
}
return out
}
// HasCapability reports whether the runtime declares or infers capability capName.
func (m Manifest) HasCapability(capName string) bool {
for _, c := range m.EffectiveCapabilities() {
if strings.EqualFold(c, capName) {
return true
}
}
return false
}
// CheckCompatibility verifies that an installed runtime matches a driver's
// required runtime kind and runtime_api SemVer range (§5.2).
func CheckCompatibility(requiredKind, requiredAPIRange string, inst Installed) error {
if requiredKind == "" {
requiredKind = DefaultKind
}
gotKind := inst.Manifest.EffectiveKind()
if inst.Kind != "" {
gotKind = inst.Kind
}
if !strings.EqualFold(gotKind, requiredKind) {
return fmt.Errorf("runtime kind mismatch: driver requires %q, installed runtime %s is %q", requiredKind, inst.Commit, gotKind)
}
if strings.TrimSpace(requiredAPIRange) != "" {
gotAPI := inst.Manifest.EffectiveRuntimeAPI()
if !plugin.MatchesRange(gotAPI, requiredAPIRange) {
return fmt.Errorf("incompatible runtime_api: driver requires %s, runtime %s (%s) provides %s", requiredAPIRange, inst.Commit, gotKind, gotAPI)
}
}
return nil
}
// ValidateThirdPartyProvenance enforces GPL/compliance provenance rules for
// third-party runtime packages (§5.2): must declare license and source archive,
// and cannot enter the official "stable" channel.
func ValidateThirdPartyProvenance(m Manifest) error {
if strings.EqualFold(m.Channel, "stable") {
return errors.New("third-party runtime packages cannot claim the official stable channel")
}
if strings.TrimSpace(m.License) == "" {
return errors.New("third-party runtime manifest missing license declaration")
}
if strings.TrimSpace(m.SourcePackage) == "" {
return errors.New("third-party runtime manifest missing source_package (required for GPL compliance)")
}
return nil
}
// ListByKind returns installed runtimes matching kind.
func ListByKind(cfg *config.Config, kind string) ([]Installed, error) {
all, err := List(cfg)
if err != nil {
return nil, err
}
if kind == "" {
return all, nil
}
var out []Installed
for _, item := range all {
k := item.Kind
if k == "" {
k = item.Manifest.EffectiveKind()
}
if strings.EqualFold(k, kind) {
out = append(out, item)
}
}
return out, nil
}
// ResolveForKind returns the active runtime for kind, falling back to the
// newest installed runtime of that kind when only one exists (or for non-default kinds).
func ResolveForKind(cfg *config.Config, kind string) (*Installed, error) {
if kind == "" {
kind = DefaultKind
}
list, err := ListByKind(cfg, kind)
if err != nil {
return nil, err
}
for i := range list {
if list[i].Commit == cfg.ActiveRuntime || (kind+"/"+list[i].Commit) == cfg.ActiveRuntime {
return &list[i], nil
}
}
if len(list) == 1 || (kind != DefaultKind && len(list) > 0) {
return &list[0], nil
}
return nil, fmt.Errorf("no active %s runtime installed", kind)
}
+104
View File
@@ -0,0 +1,104 @@
package runtime
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/config"
)
func TestKindRegistryAndCapabilities(t *testing.T) {
kr := NewKindRegistry()
if _, ok := kr.Get(DefaultKind); !ok {
t.Fatal("missing builtin reims-vgpu kind")
}
if err := kr.Register(KindSpec{Kind: "qemu-ovmf", NameEn: "QEMU + OVMF", PluginID: "plugin.linux"}); err != nil {
t.Fatalf("register kind: %v", err)
}
if len(kr.List()) != 2 {
t.Fatalf("expected 2 kinds, got %d", len(kr.List()))
}
kr.Unregister("qemu-ovmf", "plugin.linux")
if _, ok := kr.Get("qemu-ovmf"); ok {
t.Fatal("expected qemu-ovmf to be unregistered")
}
// Legacy manifest infers capabilities from patches.
m := Manifest{
Commit: "abc1234",
Patches: []Patch{
{Name: "qemu-whpx-nested-virt-nonfatal.patch"},
{Name: "qemu-whpx-win10-startup-ipis.patch"},
},
}
if m.EffectiveKind() != DefaultKind {
t.Fatalf("EffectiveKind = %q", m.EffectiveKind())
}
if !m.HasCapability("nested-virt-nonfatal") || !m.HasCapability("win10-startup-ipis") {
t.Fatalf("expected inferred capabilities, got %v", m.EffectiveCapabilities())
}
}
func TestMultiKindCoexistenceAndCompatibility(t *testing.T) {
root := t.TempDir()
cfg := &config.Config{DataRoot: root, ActiveRuntime: "abc1234"}
if err := cfg.EnsureDirs(); err != nil {
t.Fatal(err)
}
// Legacy layout: runtimes/abc1234/manifest.json
legacyDir := filepath.Join(cfg.RuntimesDir(), "abc1234")
_ = os.MkdirAll(legacyDir, 0o755)
legacyM, _ := json.Marshal(Manifest{SchemaVersion: 2, Commit: "abc1234", BuiltAt: "2026-11-28T00:00:00Z"})
_ = os.WriteFile(filepath.Join(legacyDir, "manifest.json"), legacyM, 0o644)
// New kind layout: runtimes/qemu-ovmf/9.2.0/manifest.json
ovmfDir := filepath.Join(cfg.RuntimesDir(), "qemu-ovmf", "9.2.0")
_ = os.MkdirAll(ovmfDir, 0o755)
ovmfM, _ := json.Marshal(Manifest{
SchemaVersion: 2,
Kind: "qemu-ovmf",
RuntimeAPI: "2.0.0",
Commit: "9.2.0",
BuiltAt: "2026-11-29T00:00:00Z",
Capabilities: []string{"whpx", "virtio-gpu"},
})
_ = os.WriteFile(filepath.Join(ovmfDir, "manifest.json"), ovmfM, 0o644)
list, err := List(cfg)
if err != nil || len(list) != 2 {
t.Fatalf("List = %d (err=%v), want 2", len(list), err)
}
reimsRT, err := ResolveForKind(cfg, DefaultKind)
if err != nil || reimsRT.Commit != "abc1234" {
t.Fatalf("ResolveForKind(reims-vgpu) = %+v, err=%v", reimsRT, err)
}
ovmfRT, err := ResolveForKind(cfg, "qemu-ovmf")
if err != nil || ovmfRT.Commit != "9.2.0" {
t.Fatalf("ResolveForKind(qemu-ovmf) = %+v, err=%v", ovmfRT, err)
}
// Compatibility checks.
if err := CheckCompatibility("qemu-ovmf", "^2.0.0", *ovmfRT); err != nil {
t.Fatalf("expected compatible, got %v", err)
}
if err := CheckCompatibility("qemu-ovmf", "^1.0.0", *ovmfRT); err == nil {
t.Fatal("expected incompatible runtime_api error")
}
if err := CheckCompatibility("reims-vgpu", "^1.0.0", *ovmfRT); err == nil {
t.Fatal("expected kind mismatch error")
}
// Third-party provenance guard.
if err := ValidateThirdPartyProvenance(Manifest{Origin: "third-party", Channel: "stable", License: "GPL-2.0", SourcePackage: "src.tar.zst"}); err == nil {
t.Fatal("third-party cannot enter stable channel")
}
if err := ValidateThirdPartyProvenance(Manifest{Origin: "third-party", Channel: "community", License: "GPL-2.0"}); err == nil {
t.Fatal("third-party missing source_package should fail")
}
if err := ValidateThirdPartyProvenance(Manifest{Origin: "third-party", Channel: "community", License: "GPL-2.0", SourcePackage: "src.tar.zst"}); err != nil {
t.Fatalf("valid third-party provenance rejected: %v", err)
}
}
+71 -26
View File
@@ -41,6 +41,14 @@ type Manifest struct {
Patches []Patch `json:"patches,omitempty"`
Channel string `json:"channel,omitempty"` // channel at build time: alpha (older packages: candidate)
SourcePackage string `json:"source_package,omitempty"` // file name of the matching source archive
// Schema 2+ plugin runtime extensions (docs/plugin-architecture.md §5.2).
Kind string `json:"kind,omitempty"` // defaults to "reims-vgpu"
RuntimeAPI string `json:"runtime_api,omitempty"` // CLI/driver contract version, e.g. "1.0.0"
Capabilities []string `json:"capabilities,omitempty"` // explicit feature/patch capability IDs
License string `json:"license,omitempty"` // SPDX or license summary
Publisher string `json:"publisher,omitempty"` // official or third-party publisher
Origin string `json:"origin,omitempty"` // "official" | "third-party"
}
// ByteCount is an integer that also accepts a whole-number float ("962466926.0"),
@@ -64,6 +72,7 @@ type Patch struct {
}
type Installed struct {
Kind string `json:"kind,omitempty"`
Commit string `json:"commit"`
Dir string `json:"dir"`
Active bool `json:"active"`
@@ -103,6 +112,8 @@ func (r Installed) QemuImgPath() string {
}
// List returns all valid portable runtimes installed under cfg.RuntimesDir().
// Legacy layout `runtimes/<commit>/` is treated as kind "reims-vgpu" (zero
// migration); additional runtime kinds live under `runtimes/<kind>/<version>/`.
func List(cfg *config.Config) ([]Installed, error) {
entries, err := os.ReadDir(cfg.RuntimesDir())
if err != nil {
@@ -117,20 +128,52 @@ func List(cfg *config.Config) ([]Installed, error) {
continue
}
dir := filepath.Join(cfg.RuntimesDir(), e.Name())
m, err := readManifest(filepath.Join(dir, "manifest.json"))
if err != nil {
if m, err := readManifest(filepath.Join(dir, "manifest.json")); err == nil {
commit := m.Commit
if commit == "" {
commit = e.Name()
}
kind := m.EffectiveKind()
out = append(out, Installed{
Kind: kind,
Commit: commit,
Dir: dir,
Active: kind == DefaultKind && commit == cfg.ActiveRuntime,
Manifest: m,
})
continue
}
commit := m.Commit
if commit == "" {
commit = e.Name()
// Check nested kind directory: runtimes/<kind>/<version>/manifest.json
subEntries, subErr := os.ReadDir(dir)
if subErr != nil {
continue
}
for _, sub := range subEntries {
if !sub.IsDir() || strings.HasSuffix(sub.Name(), ".tmp") {
continue
}
subDir := filepath.Join(dir, sub.Name())
m, err := readManifest(filepath.Join(subDir, "manifest.json"))
if err != nil {
continue
}
commit := m.Commit
if commit == "" {
commit = sub.Name()
}
kind := m.EffectiveKind()
if m.Kind == "" {
kind = e.Name()
m.Kind = kind
}
out = append(out, Installed{
Kind: kind,
Commit: commit,
Dir: subDir,
Active: (kind == DefaultKind && commit == cfg.ActiveRuntime) || (kind+"/"+commit) == cfg.ActiveRuntime,
Manifest: m,
})
}
out = append(out, Installed{
Commit: commit,
Dir: dir,
Active: commit == cfg.ActiveRuntime,
Manifest: m,
})
}
sort.Slice(out, func(i, j int) bool {
return out[i].Manifest.BuiltAt > out[j].Manifest.BuiltAt
@@ -138,21 +181,9 @@ func List(cfg *config.Config) ([]Installed, error) {
return out, nil
}
// ResolveActive returns the currently active installed runtime.
// ResolveActive returns the currently active installed reims-vgpu runtime.
func ResolveActive(cfg *config.Config) (*Installed, error) {
list, err := List(cfg)
if err != nil {
return nil, err
}
for i := range list {
if list[i].Commit == cfg.ActiveRuntime {
return &list[i], nil
}
}
if len(list) == 1 {
return &list[0], nil
}
return nil, errors.New("no active runtime installed")
return ResolveForKind(cfg, DefaultKind)
}
// BuildChildEnv returns a clean, D-drive-isolated environment for invoking reims-ctl.
@@ -258,15 +289,29 @@ func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, err
}
}
kind := m.EffectiveKind()
if m.Origin == "third-party" {
if err := ValidateThirdPartyProvenance(m); err != nil {
return nil, err
}
}
finalDir := filepath.Join(cfg.RuntimesDir(), m.Commit)
if kind != DefaultKind {
kindDir := filepath.Join(cfg.RuntimesDir(), kind)
if err := os.MkdirAll(kindDir, 0o755); err != nil {
return nil, err
}
finalDir = filepath.Join(kindDir, m.Commit)
}
_ = os.RemoveAll(finalDir)
if err := os.Rename(bundleDir, finalDir); err != nil {
return nil, fmt.Errorf("activate runtime dir: %w", err)
}
return &Installed{
Kind: kind,
Commit: m.Commit,
Dir: finalDir,
Active: true,
Active: kind == DefaultKind,
Manifest: m,
}, nil
}
+2 -1
View File
@@ -49,7 +49,8 @@ func main() {
CSSDropValue: "drop",
},
AssetServer: &assetserver.Options{
Assets: assets,
Assets: assets,
Handler: desktopApp.PluginAssetHandler(),
},
BackgroundColour: &options.RGBA{R: 28, G: 28, B: 30, A: 255},
Windows: &windows.Options{
+314
View File
@@ -0,0 +1,314 @@
// Package pluginsdk provides a lightweight, zero-dependency Go SDK for writing
// external L3 Sidecar plugins (and guest VM drivers such as Linux) for Reims-Go.
// Communication uses Content-Length framed JSON-RPC 2.0 over stdin/stdout while
// diagnostics/logs write to stderr (docs/plugin-architecture.md §8, §12 Phase 3).
package pluginsdk
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
)
// PluginAPIVersion is the protocol version spoken by this SDK.
const PluginAPIVersion = "1.0.0"
// Handler handles one inbound JSON-RPC method from the Reims-Go host.
type Handler func(ctx context.Context, params json.RawMessage) (any, error)
// InitInfo contains initialization data received from the host during handshake.
type InitInfo struct {
PluginID string `json:"pluginId"`
PluginAPI string `json:"pluginApi"`
DataDir string `json:"dataDir"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type envelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
// Server runs inside a Sidecar executable, serving host requests over stdin/stdout
// and issuing reverse Host API calls back to Reims-Go.
type Server struct {
in *bufio.Reader
out io.Writer
mu sync.Mutex
handlers map[string]Handler
pending map[string]chan envelope
writeMu sync.Mutex
nextID atomic.Uint64
initInfo InitInfo
caps map[string]any
}
// New creates a Sidecar SDK server bound to os.Stdin / os.Stdout.
func New() *Server {
return NewWithIO(os.Stdin, os.Stdout)
}
// NewWithIO creates a Sidecar SDK server over custom streams (useful for tests).
func NewWithIO(r io.Reader, w io.Writer) *Server {
s := &Server{
in: bufio.NewReaderSize(r, 64*1024),
out: w,
handlers: make(map[string]Handler),
pending: make(map[string]chan envelope),
caps: map[string]any{},
}
s.Handle("plugin/initialize", func(_ context.Context, raw json.RawMessage) (any, error) {
var info InitInfo
if err := json.Unmarshal(raw, &info); err != nil {
return nil, err
}
s.mu.Lock()
s.initInfo = info
caps := s.caps
s.mu.Unlock()
return map[string]any{
"pluginApi": PluginAPIVersion,
"capabilities": caps,
}, nil
})
return s
}
// SetCapability advertises a capability in the handshake response.
func (s *Server) SetCapability(k string, v any) {
s.mu.Lock()
s.caps[k] = v
s.mu.Unlock()
}
// InitInfo returns the handshake metadata sent by the host.
func (s *Server) InitInfo() InitInfo {
s.mu.Lock()
defer s.mu.Unlock()
return s.initInfo
}
// Handle registers a JSON-RPC method handler (e.g. "hook/vm.beforeStart",
// "command/invoke", "diagnostics/collect", "driver/list", ...).
func (s *Server) Handle(method string, h Handler) {
s.mu.Lock()
s.handlers[method] = h
s.mu.Unlock()
}
// CallHost invokes a reverse Host API method on Reims-Go (e.g. "host/notify",
// "host/vm.spawn", "host/vm.stop", "host/audit").
func (s *Server) CallHost(ctx context.Context, method string, params any, out any) error {
idStr := strconv.FormatUint(s.nextID.Add(1), 10)
var rawParams json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = b
}
ch := make(chan envelope, 1)
s.mu.Lock()
s.pending[idStr] = ch
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.pending, idStr)
s.mu.Unlock()
}()
if err := s.writeFrame(envelope{
JSONRPC: "2.0",
ID: json.RawMessage(idStr),
Method: method,
Params: rawParams,
}); err != nil {
return err
}
select {
case resp := <-ch:
if resp.Error != nil {
return errors.New(resp.Error.Message)
}
if out != nil && len(resp.Result) > 0 && string(resp.Result) != "null" {
return json.Unmarshal(resp.Result, out)
}
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// SpawnVMProcess requests Reims-Go to spawn a VM process outside the Sidecar's Job Object.
func (s *Server) SpawnVMProcess(ctx context.Context, vmName, exePath string, args []string, workDir string, env []string) (int, error) {
var resp struct {
PID int `json:"pid"`
}
err := s.CallHost(ctx, "host/vm.spawn", map[string]any{
"vm_name": vmName,
"exe_path": exePath,
"args": args,
"work_dir": workDir,
"env": env,
}, &resp)
return resp.PID, err
}
// StopVMProcess requests Reims-Go to terminate a host-managed VM process.
func (s *Server) StopVMProcess(ctx context.Context, pid int) error {
return s.CallHost(ctx, "host/vm.stop", map[string]any{"pid": pid}, nil)
}
// IsVMProcessRunning queries whether a host-managed VM process is still alive.
func (s *Server) IsVMProcessRunning(ctx context.Context, pid int) (bool, error) {
var resp struct {
Running bool `json:"running"`
}
err := s.CallHost(ctx, "host/vm.isRunning", map[string]any{"pid": pid}, &resp)
return resp.Running, err
}
// Notify requests a host UI notification (requires ui:notify permission).
func (s *Server) Notify(ctx context.Context, title, body string) error {
return s.CallHost(ctx, "host/notify", map[string]any{"title": title, "body": body}, nil)
}
// Serve runs the JSON-RPC frame loop until EOF or `plugin/shutdown`.
func (s *Server) Serve(ctx context.Context) error {
for {
if ctx.Err() != nil {
return ctx.Err()
}
frame, err := readFrame(s.in)
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
var env envelope
if err := json.Unmarshal(frame, &env); err != nil {
continue
}
if env.Method == "plugin/shutdown" {
return nil
}
if env.Method != "" {
go s.dispatch(ctx, env)
continue
}
if len(env.ID) > 0 {
key := strings.TrimSpace(string(env.ID))
s.mu.Lock()
ch := s.pending[key]
s.mu.Unlock()
if ch != nil {
select {
case ch <- env:
default:
}
}
}
}
}
func (s *Server) dispatch(ctx context.Context, env envelope) {
s.mu.Lock()
h := s.handlers[env.Method]
s.mu.Unlock()
if h == nil {
if len(env.ID) > 0 {
_ = s.writeFrame(envelope{
JSONRPC: "2.0",
ID: env.ID,
Error: &rpcError{Code: -32601, Message: "method not found: " + env.Method},
})
}
return
}
res, err := h(ctx, env.Params)
if len(env.ID) == 0 {
return
}
if err != nil {
_ = s.writeFrame(envelope{
JSONRPC: "2.0",
ID: env.ID,
Error: &rpcError{Code: -32000, Message: err.Error()},
})
return
}
var rawRes json.RawMessage
if res == nil {
rawRes = json.RawMessage("null")
} else {
rawRes, _ = json.Marshal(res)
}
_ = s.writeFrame(envelope{
JSONRPC: "2.0",
ID: env.ID,
Result: rawRes,
})
}
func (s *Server) writeFrame(env envelope) error {
b, err := json.Marshal(env)
if err != nil {
return err
}
s.writeMu.Lock()
defer s.writeMu.Unlock()
if _, err := fmt.Fprintf(s.out, "Content-Length: %d\r\n\r\n", len(b)); err != nil {
return err
}
_, err = s.out.Write(b)
return err
}
func readFrame(r *bufio.Reader) ([]byte, error) {
contentLen := -1
for {
line, err := r.ReadString('\n')
if err != nil {
return nil, err
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
break
}
k, v, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil || n < 0 {
return nil, fmt.Errorf("invalid Content-Length %q", v)
}
contentLen = n
}
}
if contentLen < 0 {
return nil, errors.New("missing Content-Length")
}
buf := make([]byte, contentLen)
if _, err := io.ReadFull(r, buf); err != nil {
return nil, err
}
return buf, nil
}