Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
230 changes: 230 additions & 0 deletions docs/extension-system.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
---
sidebar_position: 5
---

# GeneralUpdate.Extension — 扩展系统指南

> **目标读者:** 使用 GeneralUpdate.Extension 构建插件/扩展机制的 .NET 应用开发者
>
> **阅读完你将理解:**
> - 扩展的完整生命周期(查询 → 下载 → 校验 → 安装 → 激活/卸载 → 回滚)
> - 11.0 版本的安全基线:断点续传、Zip Slip / zip bomb 防护、哈希与签名校验
> - 依赖解析与 `id@range` 版本约束
> - CheckForUpdatesAsync 与内置自动更新调度
> - side-by-side 版本布局、回滚与健康扫描
> - AssemblyLoadContext 加载器(独立包)的使用与限制

---

## 1. 快速开始

```csharp
var host = new ExtensionHostBuilder()
.ConfigureOptions(o =>
{
o.HostVersion = "1.0.0"; // 宿主版本(兼容性检查的基准)
o.ServerUrl = "https://server.example/Extension";
o.ExtensionsDirectory = "./extensions"; // 扩展安装目录(也是默认 catalog 目录)
})
.Build();
```

`ExtensionHostBuilder` 会自动注册默认实现(HTTP 客户端、下载队列、兼容性检查器、平台匹配器、
依赖解析器、catalog、注册表式加载器)。任何一项都可以用 `ConfigureServices` 覆盖。

## 2. 生命周期总览

| 阶段 | API | 说明 |
|---|---|---|
| 查询 | `QueryExtensionsAsync` / `QueryAllExtensionsAsync` | 后者是自动翻页的 `IAsyncEnumerable` 迭代器 |
| 检查更新 | `CheckForUpdatesAsync` | 对比已安装与服务器版本,仅返回"更新且兼容"的列表 |
| 下载 | `DownloadExtensionAsync` | 经下载队列:并发上限、同 Id 去重、可取消、断点续传 |
| 更新 | `UpdateExtensionAsync(id, allowDowngrade, ct)` | 查询→兼容性→依赖→下载→校验→安装→事件,失败自动回滚 |
| 本地安装 | `InstallFromLocalAsync(path, expectedSha256)` | 离线包一等公民:显式哈希校验 + 写 manifest 入 catalog |
| 激活/停用 | `ActivateExtensionAsync` / `DeactivateExtensionAsync` | 通过 `IExtensionLoader` 加载/卸载 |
| 卸载 | `UninstallExtensionAsync` | 先卸载再删除目录与 catalog 条目 |
| 回滚 | `RollbackToAsync(id, version?)` | 从保留的上一版本备份恢复,或 side-by-side 切换激活版本 |
| 健康扫描 | `ScanAsync(repair)` | 孤儿目录/残留包/备份超限/丢失目录的发现与修复 |

所有操作都支持 `CancellationToken`;状态变化通过 `ExtensionUpdateStatusChanged` 事件通知,
事件的 `Phase` 字段(Download/Install/Uninstall/Activation/Rollback/Check)区分同一
状态值所属的生命周期阶段。

## 3. 安全模型

### 3.1 传输完整性
- 下载支持 HTTP Range 断点续传:**只在服务器返回 206 时续传**;服务器忽略 Range 返回 200
时自动从头重下(旧版本把完整响应追加到半截文件上,会产生损坏包)。
- 416(Range Not Satisfiable)会对照服务器 `Content-Range` 声明的总大小校验本地文件,
不匹配则删除重下,避免把损坏的半截包误判为"已下载完成"。

### 3.2 包完整性
- `Hash`(SHA256):服务器下发十六进制哈希,安装前强制比对,不符即删除包并中止。
- 包签名(可选):配置 `ExtensionHostOptions.SigningPublicKey`(.NET XML 格式 RSA 公钥)后,
服务器元数据的 `Signature`(base64,对包 SHA256 摘要的 RSA-SHA256 PKCS#1 签名)会被强制
校验;未签名的包直接拒绝。签名工具可用
`PackageSignatureVerifier.Sign(path, rsaPrivateKey)` 生成。

### 3.3 包结构防护
- **Zip Slip**:解析每个条目的完整路径,越出目标目录的条目使**整个安装失败**(旧版本只跳过
恶意条目继续安装,会留下部分安装的污染状态)。
- **zip bomb**:`MaxArchiveEntries`(默认 4096)与 `MaxUncompressedBytes`(默认 512 MB)
双限制,超限整体失败。
- 解压失败且无旧版本可回滚时,清理半成品目录,不留部分安装。

## 4. 依赖管理

依赖声明写在扩展元数据的 `Dependencies` 列表里,支持两种格式:

- `dep-id` —— 任意版本
- `dep-id@range` —— 版本约束,语法:
- `1.2.3` / `=1.2.3` 精确版本
- `^1.2.3` 锁主版本(`0.x` 特殊处理:`^0.2.3` 锁次版本、`^0.0.3` 锁补丁版本)
- `~1.2.3` 锁次版本
- `>=`、`>`、`<=`、`<` 比较约束,可用逗号/空格组合(AND 语义),如 `>=1.0.0 <2.0.0`
- `*` 任意版本

解析顺序为拓扑排序(存在循环依赖时抛出异常)。宿主安装扩展时会:

1. 对每个缺失依赖或**版本不满足约束**的已安装依赖,递归执行完整更新流程;
2. 递归过程用调用链集合做环保护——`A→B→A` 这类跨服务器元数据的循环不会再栈溢出;
3. 依赖装完后校验约束,服务器版本不满足约束时中止父扩展安装。

## 5. 自动更新

```csharp
o.AutoUpdateEnabled = true; // 构造后立即启动调度器
o.AutoUpdateCheckInterval = TimeSpan.FromHours(1);
```

调度行为:
- 每个周期调用 `CheckForUpdatesAsync`,对"可用更新且 `IsAutoUpdateEnabled(id)` 为真"的扩展
逐个执行 `UpdateExtensionAsync`(同一时刻最多一个周期在跑,不重叠)。
- `SetGlobalAutoUpdate(false)` 会暂停周期内的实际更新动作(定时器仍在,恢复开关即恢复)。
- 设置持久化:`PersistAutoUpdateSettings = true`(默认)时,全局开关写入
`{extensionsDir}/hostsettings.json`,每个扩展开关写入各自 manifest 的 `AutoUpdate` 字段,
重启后生效。判定顺序:运行时覆盖 → manifest 值 → 全局开关。
- 每次检查完成触发 `ExtensionUpdatesChecked` 事件,UI 可据此提示。
- `StartAutoUpdate()` / `StopAutoUpdate()` 可编程控制;宿主 disposal 时自动停止。

## 6. 版本布局与回滚

- 默认布局:`{extensionsDir}/{name}/`,更新即覆盖。
- `SideBySideVersions = true`:`{extensionsDir}/{name}/{version}/`,manifest 写在版本目录里,
catalog 用 `{name}/.active` 指针记录激活版本,`RollbackToAsync(id, version)` 直接切换指针。
- 默认布局的回滚依赖保留的备份:`PreviousVersionBackupsToKeep`(默认 2)控制
`.backup/{name}_{version}_{timestamp}` 的保留数量;`0` 恢复旧版行为(安装成功即删备份,
无法回滚)。`RollbackToAsync(id)` 不带版本号时恢复最近一份备份。
- 更新过程中失败自动回滚(`rollbackOnFailure: true`)。

## 7. 健康扫描

```csharp
var report = await host.ScanAsync(repair: true);
```

检查项:catalog 有条目但目录丢失(ghost)、无 manifest 的孤儿目录、超限备份、根目录残留
`.zip` 包。`repair: true` 时逐项修复并标记 `Repaired`。注意单个损坏的 manifest 只会跳过并
告警,不会让整个 catalog 加载失败(10.x 会整体抛异常)。

## 8. 扩展加载(AssemblyLoadContext)

`GeneralUpdate.Extension`(netstandard2.0)主包内置 `RegistryExtensionLoader`——只做注册表
记账,不加载程序集。真正的程序集加载用独立包:

```xml
<PackageReference Include="GeneralUpdate.Extension.Loader" Version="11.0.*" />
```

```csharp
.ConfigureServices(services =>
services.AddSingleton<IExtensionLoader, AssemblyContextExtensionLoader>())
```

- 每个扩展一个 collectible `AssemblyLoadContext`,主程序集按约定发现:
`{name}.dll` → 目录内唯一 `.dll` → 与目录同名的 `.dll`。
- 依赖解析:deps.json → 扩展目录内松散 DLL → 回落默认上下文(宿主程序集共享,
这也是可卸载的前提)。
- 扩展程序集实现 `IExtensionEntryPoint`(`OnActivateAsync` / `OnDeactivateAsync`),
激活管线自动实例化并调用。
- 卸载后做尽力 GC 回收;若宿主代码持有扩展类型/实例的引用,程序集会延迟到引用释放后才真正卸载。
- `AssemblyLoadContext` 在 netstandard2.0 不可用,因此加载器包目标框架为 net8.0+。

## 9. 与服务器 API 的约定

| 端点 | 方法 | 说明 |
|---|---|---|
| `{ServerUrl}/Query` | GET + body(默认)或 POST | 查询扩展。GET 带 body 会被部分网关丢弃——客户端默认在 GET 解析失败后自动回退 POST 一次(`AutoFallbackToPost`),可用 `UsePostForQuery` 直接切 POST |
| `{ServerUrl}/Download/{id}` | GET | 支持 Range 续传;响应 PNG 伪装等特殊站点逻辑不在此层 |

响应模型:`HttpResponseDTO<PagedResultDTO<ExtensionDTO>>`(Code/Message/Body)。

**代理注意**:默认情况下 HTTP 客户端遵循操作系统代理设置。若部署环境存在系统级代理
(v2rayN/Clash 系统代理模式等)且扩展服务器需要直连(内网/本机),设置
`UseSystemProxy = false` 强制直连,或用 `Proxy` 显式指定代理地址。

## 10. 可观测性

`GeneralTracer`(`GeneralUpdate.Extension` 命名空间)默认输出到 DebugOutput/Console/日志文件
(`{BaseDirectory}/Logs/generalupdate-trace {yyyy-MM-dd}.log`)。11.0 起不再清空宿主自己的
`Trace.Listeners`,并支持完全接管:

```csharp
GeneralTracer.Configure(loggerFactory); // 路由到 Microsoft.Extensions.Logging
GeneralTracer.Configure(myTraceSink); // 路由到自定义 ITraceSink
GeneralTracer.ResetToDefaultListeners(); // 恢复默认
GeneralTracer.EnableFileLogging = false; // 关闭日志文件
```

## 11. 生产部署清单

### 上线前必做

1. **真实服务器联调**:用只读冒烟工具对真实服务端验证契约
```
dotnet run --project samples/GeneralUpdate.Extension.SmokeTool -- \
--server https://your-host/Extension [--scheme Bearer --token xxx] \
[--download <extensionId>] [--direct]
```
检查项:POST /Query 解析、GET-with-body 是否可用(不可用则保持 `AutoFallbackToPost` 开启)、
`/Download/{id}` 的 206 续传响应与 `Content-Range` 格式、返回字节是否为 .zip(PK 头)。
2. **.NET Framework 兼容**:宿主跑在 .NET Framework 4.x 时,确认
`tests/ExtensionNet48SmokeTest` 在目标机器规格上通过(该套件已在 .NET Framework 4.8
真机运行时上验证 IO/压缩/RSA/HTTP/续传链路)。
3. **签名链路**:生成 RSA 密钥对(私钥保存在发包侧,公钥 XML 配置进
`ExtensionHostOptions.SigningPublicKey`),用
`PackageSignatureVerifier.Sign(path, privateKey)` 签一个真实包走完整更新链路。
4. **失败演练**:模拟服务器 500/断网/断电——验证重试与续传、`UpdateFailed` 事件、
安装回滚、`ScanAsync(repair)` 自愈。

### 部署配置基线(推荐)

```csharp
o.DownloadRetryAttempts = 3; // 瞬时故障重试(续传友好)
o.SigningPublicKey = publicKeyXml; // 强制包签名校验
o.PreviousVersionBackupsToKeep = 2; // 保留回滚能力
o.UseSystemProxy = false; // 系统代理环境且服务器需直连时
o.MaxUncompressedBytes = 512 * 1024 * 1024; // 按业务包大小调整
```

### 已知边界

| 边界 | 说明 | 对策 |
|---|---|---|
| 多进程共享目录 | catalog 跨进程文件锁已加(`.catalog.lock`,进程崩溃自动释放),但安装/回滚的目录操作阶段不互斥 | 避免两个进程同时对同一扩展执行更新 |
| ScanAsync 修复窗口 | 10 分钟内修改过的 `.zip` 视为进行中下载不清理;更早的残留包会被删除 | 在维护窗口跑,或确认没有超过 10 分钟的长下载 |
| 定时器精度 | `System.Threading.Timer` 在系统休眠时的补齐策略由 OS 决定 | 休眠恢复后的首个 tick 可能提前/延后,属正常 |
| GeneralTracer 全局态 | 静态配置影响整个进程 | 宿主接 `Configure(ILoggerFactory)` 后可完全接管 |

## 12. 升级注意事项(10.x → 11.0)

- `IExtensionHost` / `IExtensionCatalog` 接口新增成员与可选参数:自定义实现类需要补齐。
- 损坏 manifest 从"抛异常中断加载"改为"跳过并告警"。
- Zip Slip 从"跳过恶意条目"改为"整体安装失败"。
- GET 查询失败会自动 POST 重试一次;如不希望该行为,设 `AutoFallbackToPost = false`。
- 默认保留 2 份旧版本备份(旧版安装成功即删);设 `PreviousVersionBackupsToKeep = 0` 恢复旧行为。
- 下载默认重试 2 次(`DownloadRetryAttempts`);设 1 恢复旧行为。重试从断点续传。
- catalog 读写新增跨进程文件锁(`.catalog.lock`);对同一目录的外部独占占用会使操作
在 5 秒后抛 `InvalidOperationException`(单进程环境可无视)。
- 服务器可控字段(Name/Version/Format)下载/安装前被净化——恶意元数据无法再构造路径穿越。
- `GeneralTracer` 不再 `Trace.Listeners.Clear()`;全局监听器可见性变化需自查宿主侧配置。
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
using System.IO;
using System.Linq;

namespace GeneralUpdate.Extension.Examples;
namespace GeneralUpdate.Extension.Samples;

/// <summary>
/// Example demonstrating the use of DependencyResolver for managing extension dependencies.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System;
using System.Threading.Tasks;

namespace GeneralUpdate.Extension.Examples;
namespace GeneralUpdate.Extension.Samples;

/// <summary>
/// Example demonstrating the use of DownloadQueueManager for managing extension downloads.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using System.IO;
using System.Linq;

namespace GeneralUpdate.Extension.Examples;
namespace GeneralUpdate.Extension.Samples;

/// <summary>
/// Example demonstrating the use of ExtensionCatalog for managing installed extensions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using System;
using System.Threading.Tasks;

namespace GeneralUpdate.Extension.Examples;
namespace GeneralUpdate.Extension.Samples;

/// <summary>
/// Example demonstrating core extension operations including querying, updating, and managing installed extensions.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<IsPackable>false</IsPackable>
<Description>Usage examples for GeneralUpdate.Extension. Shipped in the repository (not in the NuGet package) so the library DLL stays free of dead sample code.</Description>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\GeneralUpdate.Extension\GeneralUpdate.Extension.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using System.IO.Compression;
using System.Threading.Tasks;

namespace GeneralUpdate.Extension.Examples;
namespace GeneralUpdate.Extension.Samples;

/// <summary>
/// Example demonstrating how to generate a valid extension package (zip file) and install it using InstallExtensionAsync.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using GeneralUpdate.Extension.Compatibility;
using System;

namespace GeneralUpdate.Extension.Examples;
namespace GeneralUpdate.Extension.Samples;

/// <summary>
/// Example demonstrating the use of PlatformMatcher for checking platform compatibility.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using GeneralUpdate.Extension.Compatibility;
using System;

namespace GeneralUpdate.Extension.Examples;
namespace GeneralUpdate.Extension.Samples;

/// <summary>
/// Example demonstrating the use of VersionCompatibilityChecker for verifying extension compatibility.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<IsPackable>false</IsPackable>
<Description>Read-only smoke-test tool for verifying a real GeneralUpdate extension server: query, download with resume, and package integrity checks. Safe to run against production (writes only to a temp directory).</Description>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\GeneralUpdate.Extension\GeneralUpdate.Extension.csproj" />
</ItemGroup>

</Project>
Loading
Loading