接入授权窗口、启动拦截和运行中到期续期

This commit is contained in:
tfarcraw 2026-11-23 09:28:33 +08:00
parent 5ebd36124f
commit 6e997a88bb
9 changed files with 304 additions and 3 deletions

3
.gitignore vendored
View File

@ -399,3 +399,6 @@ FodyWeavers.xsd
*.pt
/python/
# 发码私钥只允许保存在发行方安全目录,防止意外复制进仓库后被提交。
issuer-private.pem

53
AUTHORIZATION.md Normal file
View File

@ -0,0 +1,53 @@
# 试用与主板授权
首次运行本版本,从当前时刻开始试用一个自然月。例如 1 月 31 日开始,到 2 月最后一天同一时刻到期。已有版本升级后首次启动本功能才开始计时。
主窗口右上角“软件授权”可以查看有效期、复制主板机器码和输入授权码。到期启动只显示授权窗口,通过授权后才创建业务主界面和自动启动 D3。运行中每 30 秒检查一次,到期会停止 SOP 和相机检测并遮挡业务界面,续期后需手动重新开始作业。关闭到期授权窗口会退出软件。
- 短期码 `Month`:从当前有效期与激活时间中较晚的一项开始,延长一个自然月。提前续期不会损失剩余时间;过期后从激活时刻续期。每个码只可兑换一次,不同码可以累加。
- 长期码 `Permanent`:绑定本机主板永久使用。已永久授权时不再消耗短期码。
- 所有码均验证发行方 RSA-PSS/SHA-256 签名及主板机器码。主板序列号缺失或为厂商占位值时不启动试用,也不生成共用的兜底机器码。
- 检测到超过 5 分钟的系统时间回拨会暂停有限期授权,校准时间后可重新检查。永久授权不依赖时间到期检查。
## 发行方发码
客户复制“软件授权”窗口里的 64 位机器码。发行方在仓库根目录使用 **PowerShell 7(pwsh)** 执行:
```powershell
# 一个自然月的短期码
pwsh -File tools/New-License.ps1 -Machine 客户的64位机器码 -Kind Month
# 永久码
pwsh -File tools/New-License.ps1 -Machine 客户的64位机器码 -Kind Permanent
```
将输出的完整 `AISOP1.…` 字符串交给客户粘贴激活,换行和空白可自动忽略。无需联网,也无需客户安装发码工具。
工具默认每次生成新的授权 ID,因此每次运行都代表新的一份授权。需保存订单、授权 ID 与完整码;同一订单直接重发原码。也可通过 `-Id 32位小写十六进制订单授权ID` 沿用原 ID 重新签发,避免重复续期。再次购买或续费应使用新 ID。
本次已在发行方电脑生成 RSA 3072 位密钥对。私钥默认位置:
```text
C:\Users\Administrator\.codex\secrets\aisop-license\issuer-private.pem
```
此目录已限制为当前 Windows 用户访问;私钥保留在仓库外,没有打包进客户端。**请立即将私钥备份到发行方安全存储,不要发送给客户或提交 Git。** 换发行电脑时可用 `-PrivateKeyPath` 指定安全备份的位置。私钥丢失后不能为现有客户端签发新码;更换密钥需要更新客户端嵌入公钥并重新发行。工具会检查私钥与本仓库公钥是否匹配,防止误用密钥。
客户端仅嵌入 `src/SopHelper.CrossPlatform.Engine/Licensing/issuer-public.pem` 公钥。
## 存储、设备与支持边界
授权记录与安装、配方目录独立,位于当前系统用户的 LocalApplicationData 下 `Bellwether/AISOP/license.dat`。Windows 采用当前用户 DPAPI 加密并在 `HKCU\Software\Bellwether\AISOP\Licensing` 保存相同密文镜像;单独删除文件不会重置试用。记录损坏、镜像不一致或写入失败时禁止放行,不会自动重建试用。应对文件和注册表记录做同一时点的备份与恢复。
主板机器码由厂家、型号和固件主板序列号散列得到,移动程序或更换硬盘不会因路径或磁盘编号改变机器码。Windows 读取 CIM 的 `Win32_BaseBoard`;Linux 读取 `/sys/class/dmi/id/board_*`,运行账号必须具备读取权限。某些主板没有有效固件序列号,这类设备需要先由供应商修复固件信息。
当前授权记录按“电脑+系统账号”保存:不同系统账号需要各自激活,同一主板的授权码可在另一个账号使用。更换主板后原码失效,需要联系发行方重新签发,并由支持人员处理旧的本地记录。重装操作系统、清除全部记录、更换系统账号、完整回滚系统快照或修改客户端,无法靠纯离线方案彻底限制。Linux 使用主板派生 AES-GCM 密钥及用户文件权限保护记录,其防本机调试能力弱于 Windows DPAPI。严格的全机跨账号试用、防回滚或撤销授权需增加在线授权服务或受保护的安装服务。
## 验证
```powershell
dotnet run --project tests/D3Startup.Smoke -- --license-only
dotnet run --project tests/Avalonia.Smoke -- --license-ui-only
```
测试使用独立签名密钥及内存记录,不会消耗发行方授权或修改本机正式试用记录。授权界面截图固定写入工作区的 `scratch/screenshots/license-window.png`。

View File

@ -6,6 +6,8 @@ Windows / Linux 共用一套 Avalonia 桌面程序:相机采集、双手关键
## 运行
软件首次运行可试用一个自然月,到期后通过右上角“软件授权”输入绑定主板的短期码或永久码。发码、私钥备份及离线限制见 [AUTHORIZATION.md](AUTHORIZATION.md)。
```powershell
dotnet build SopHelper.Avalonia.slnx
dotnet run --project src/SopHelper.Avalonia

View File

@ -10,6 +10,8 @@ using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Licensing;
using Avalonia.Threading;
using SopHelper.Models;
using SopHelper.VVMs.MainWindow;
using SopHelper.VVMs.RecipeEditor;
@ -35,6 +37,9 @@ public partial class App : PrismApplication
// 保存实际启动配置;退出时不重新读取环境,确保停止与启动时相同的本机服务。
private D3StartupOptions? _d3Options;
private bool _closing, _shutdownComplete;
private LicenseService? _license;
private DispatcherTimer? _licenseTimer;
private bool _licensePromptOpen;
/// <summary>默认应用构造入口,启用 D3 服务自动启动。</summary>
public App() { }
@ -46,6 +51,9 @@ public partial class App : PrismApplication
/// <param name="camera">供界面和检测流水线共享的相机服务。</param>
public App(ICameraService camera) { _camera=camera; _autoStartD3=false; }
/// <summary>测试宿主显式注入隔离授权存储,避免自动化测试修改用户真实试用记录。</summary>
public App(ICameraService camera, LicenseService license) : this(camera) { _license = license; }
/// <summary>加载 App.axaml 中的应用资源,再执行 Prism 的初始化流程。</summary>
public override void Initialize() { AvaloniaXamlLoader.Load(this); base.Initialize(); }
@ -76,9 +84,41 @@ public partial class App : PrismApplication
containerRegistry.RegisterDialog<RecipeEditor,RecipeEditorViewModel>("RecipeEditorDialog");
containerRegistry.RegisterDialogWindow<RecipeDialogWindow>();
}
/// <summary>创建主窗口,按页面特性生成侧栏导航,并绑定窗口打开和关闭时的生命周期逻辑。</summary>
/// <returns>由 Prism 容器解析出的主窗口。</returns>
/// <summary>读取主板及授权状态;有效时创建业务窗口,否则只创建授权拦截窗口。</summary>
/// <returns>当前许可状态允许展示的窗口。</returns>
protected override AvaloniaObject CreateShell()
{
string? error = null;
try
{
if (_license is null)
{
var machine = MotherboardIdentity.ReadMachineCode();
_license = new LicenseService(machine, new ProtectedLicenseStore(machine), LicenseService.ReadIssuerPublicKey());
}
if (_license.Check().Allowed) return CreateAuthorizedShell();
}
catch (Exception exception) { error = exception.Message; }
// 到期时不解析业务主窗口,因此导航、相机预览和 D3 自动启动都不会进入。
var gate = new LicenseWindow(_license, error);
gate.Authorized += () =>
{
if (_license?.Check().Allowed != true) return;
var main = CreateAuthorizedShell();
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) desktop.MainWindow = main;
main.Show(); gate.Close();
};
gate.Closed += (_, _) =>
{
// 未激活直接退出时尚未安装主窗口清理回调,仍需释放注册阶段创建的资源。
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow == gate)
{ _pipeline?.Dispose(); _camera?.Dispose(); _d3StartupCancellation.Dispose(); }
};
return gate;
}
/// <summary>授权通过后才创建导航与业务主窗口,并安装授权巡检及原有生命周期清理。</summary>
private MainWindow CreateAuthorizedShell()
{
var navigation=Container.Resolve<NavigationModel>();
// Index 决定侧栏顺序;显示名称和导航目标来自页面的 NavigationPageAttribute。
@ -92,6 +132,17 @@ public partial class App : PrismApplication
var window=Container.Resolve<MainWindow>();
window.Opened+=(_,_)=>
{
_licenseTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
_licenseTimer.Tick += async (_, _) =>
{
if (!_closing && _license?.Check().Allowed != true)
{
// 即使用户已打开授权窗口,也必须在期限到达时停止后台检测。
BlockUnlicensedWork(window);
if (!_licensePromptOpen) await ShowLicenseAsync(window);
}
};
_licenseTimer.Start();
// 等窗口打开、内容区域就绪后再选中首页;SelectedIndex 的 setter 会触发导航。
if(navigation.Pages.Count>0) navigation.SelectedIndex=0;
// 不阻塞窗口打开;保留异步任务,确保本应用实例最多发起一次自动启动。
@ -104,6 +155,7 @@ public partial class App : PrismApplication
e.Cancel=true;
if(_closing) return;
_closing=true;
_licenseTimer?.Stop();
try
{
_d3StartupCancellation.Cancel();
@ -129,6 +181,38 @@ public partial class App : PrismApplication
};
return window;
}
/// <summary>授权入口在到期时停止检测并遮挡业务内容;续期成功后恢复界面,关闭提示则退出软件。</summary>
public async Task ShowLicenseAsync(Window owner)
{
if (_licensePromptOpen || _license is null) return;
_licensePromptOpen = true;
var blocked = !_license.Check().Allowed;
var content = owner.Content as Control;
try
{
if (blocked)
{
BlockUnlicensedWork(owner);
}
var dialog = new LicenseWindow(_license);
dialog.Authorized += dialog.Close;
await dialog.ShowDialog(owner);
if (!_license.Check().Allowed) owner.Close();
else if (content is not null) content.IsVisible = true;
}
catch (Exception error) { Log(error, "License"); owner.Close(); }
finally { _licensePromptOpen = false; }
}
/// <summary>先遮挡业务内容,再停止 SOP 与检测;续期后需要用户主动重新启动作业。</summary>
private void BlockUnlicensedWork(Window owner)
{
if (owner.Content is Control content) content.IsVisible = false;
Container.Resolve<SopPageViewModel>().IsRunning = false;
_pipeline?.Stop();
Container.Resolve<SopEngine>().Stop();
}
/// <summary>
/// 按环境配置检查 D3 服务并在需要时启动本机进程,将进度与结果显示到 SOP 页面日志。
/// 具体的健康探测、已有服务复用、本机启动和超时控制由 D3ServiceStartup 负责。

View File

@ -0,0 +1,63 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Input.Platform;
using SopHelper.Engine.Licensing;
namespace SopHelper.VVMs.MainWindow;
/// <summary>展示机器码和有效期并兑换授权;启动拦截及运行中续期复用同一窗口。</summary>
public sealed class LicenseWindow : Window
{
/// <summary>兑换成功后通知应用切换到主窗口;事件仅在授权状态已经写盘后触发。</summary>
public event Action? Authorized;
/// <summary>主板读取失败时保留错误说明并禁止激活,避免使用空机器码签发授权。</summary>
public LicenseWindow(LicenseService? service, string? initializationError = null)
{
Title = "软件授权"; Width = 600; SizeToContent = SizeToContent.Height; CanResize = false;
WindowStartupLocation = WindowStartupLocation.CenterScreen;
var panel = new StackPanel { Margin = new Thickness(24), Spacing = 12 };
panel.Children.Add(new TextBlock { Text = "试用与授权", FontSize = 22 });
var status = new TextBlock { Name = "LicenseStatus", TextWrapping = TextWrapping.Wrap,
Text = service?.Check().Message ?? "无法读取主板信息:" + initializationError + "。请排除问题后重启软件。" };
panel.Children.Add(status);
panel.Children.Add(new TextBlock { Text = "本机主板机器码(请提供给软件发行方)" });
var machine = new TextBox { Name = "LicenseMachineCode", Text = service?.Machine ?? "无法获取", IsReadOnly = true };
panel.Children.Add(machine);
var copy = new Button { Content = "复制机器码", IsEnabled = service is not null };
copy.Click += async (_, _) =>
{
try { if (Clipboard is { } clipboard) await clipboard.SetTextAsync(machine.Text); }
catch (Exception error) { status.Text = "复制失败,请手动选择机器码复制:" + error.Message; }
};
panel.Children.Add(copy);
panel.Children.Add(new TextBlock { Text = "短期码延长一个自然月;长期码永久有效。授权仅限本机主板。", TextWrapping = TextWrapping.Wrap });
var code = new TextBox { Name = "LicenseCodeInput", PlaceholderText = "粘贴完整授权码", AcceptsReturn = true,
TextWrapping = TextWrapping.Wrap, Height = 110 };
panel.Children.Add(code);
var buttons = new StackPanel { Orientation = Avalonia.Layout.Orientation.Horizontal, Spacing = 12 };
var activate = new Button { Name = "ActivateLicenseButton", Content = "激活授权", IsDefault = true, IsEnabled = service is not null };
var refresh = new Button { Content = "重新检查", IsEnabled = service is not null };
var close = new Button { Content = "关闭", IsCancel = true };
activate.Click += (_, _) =>
{
try
{
var result = service!.Activate(code.Text ?? "");
status.Text = result.Message; code.Text = "";
Authorized?.Invoke();
}
catch (Exception error) { status.Text = error.Message; }
};
refresh.Click += (_, _) =>
{
var result = service!.Check(); status.Text = result.Message;
if (result.Allowed) Authorized?.Invoke();
};
close.Click += (_, _) => Close();
buttons.Children.Add(activate); buttons.Children.Add(refresh); buttons.Children.Add(close);
panel.Children.Add(buttons);
Content = panel;
}
}

View File

@ -66,6 +66,8 @@
</Grid>
<!-- 账号切换在停机后进行,避免运行中失去操作身份。 -->
<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="10" Margin="0,8,0,10">
<!-- 授权与账号角色独立,到期时无需先登录即可续期。 -->
<Button Content="软件授权" Click="ShowLicense" />
<TextBlock Text="{Binding Access.DisplayName}" VerticalAlignment="Center" />
<Button Content="登录 / 切换用户" Click="Login" IsEnabled="{Binding CanChangeAccount}" />
<Button Content="退出登录" Click="Logout" IsEnabled="{Binding CanChangeAccount}" IsVisible="{Binding Access.IsAuthenticated}" />

View File

@ -21,6 +21,11 @@ public partial class MainWindow : Window
finally { _permissionPromptOpen = false; }
}
private bool CanChange => DataContext is MainWindowViewModel model && model.CanChangeAccount;
/// <summary>显示主板机器码及授权状态,支持试用期内提前续期或升级永久授权。</summary>
private async void ShowLicense(object? sender, RoutedEventArgs e)
{
if (Avalonia.Application.Current is App app) await app.ShowLicenseAsync(this);
}
private async void Login(object? sender, RoutedEventArgs e) { if (CanChange) await new AccountWindow().ShowDialog(this); }
private void Logout(object? sender, RoutedEventArgs e) { if (CanChange) UserAccess.Current.Logout(); }
/// <summary>所有已登录角色均可修改本人密码;沿用停机后操作账号的交互约定。</summary>

View File

@ -0,0 +1,85 @@
using System.Reflection;
using System.Security.Cryptography;
using System.Text.Json;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
using Avalonia.Threading;
using Avalonia.VisualTree;
using SopHelper;
using SopHelper.Engine.Licensing;
using SopHelper.VVMs.MainWindow;
/// <summary>隔离的授权界面测试夹具;只使用内存记录与测试签名,绝不消耗正式授权或改变真实试用状态。</summary>
internal sealed class LicenseUiTests
{
private sealed class MemoryStore : ILicenseStore
{
private byte[]? _value;
public byte[]? Read() => _value;
public void Write(byte[] value) => _value = value;
}
private readonly RSA _rsa = RSA.Create(2048);
private DateTimeOffset _now = new(2026, 1, 31, 12, 0, 0, TimeSpan.Zero);
public LicenseService Service { get; }
public LicenseUiTests()
{
Service = new(LicenseService.MachineCode("UI-TEST-BOARD"), new MemoryStore(), _rsa.ExportSubjectPublicKeyInfoPem(), () => _now);
}
public void Expire() => _now = Service.Check().ExpiresUtc!.Value;
private static T Find<T>(Window window, string name) where T : Control => window.GetVisualDescendants().OfType<T>().Single(control => control.Name == name);
/// <summary>覆盖启动到期、错误反馈、激活切换主窗口、对话框打开期间到期以及永久授权。</summary>
public async Task Run(App app, IClassicDesktopStyleApplicationLifetime desktop)
{
static void Check(bool ok, string message) { if (!ok) throw new Exception(message); Console.WriteLine("PASS: " + message); }
static void Submit(LicenseWindow dialog, string code)
{
Find<TextBox>(dialog, "LicenseCodeInput").Text = code;
Find<Button>(dialog, "ActivateLicenseButton").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
string Code(string kind = "Month")
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(new LicenseGrant(1, Guid.NewGuid().ToString("N"), Service.Machine, kind, _now));
return "AISOP1." + Convert.ToBase64String(bytes) + "." + Convert.ToBase64String(_rsa.SignData(bytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pss));
}
Check(desktop.MainWindow is LicenseWindow, "到期启动仅显示授权拦截窗口");
var gate = (LicenseWindow)desktop.MainWindow!;
Check(Find<TextBox>(gate, "LicenseMachineCode").Text == Service.Machine, "授权窗口提供可选择复制的主板机器码");
Submit(gate, "invalid");
Check(gate.IsVisible && Find<TextBlock>(gate, "LicenseStatus").Text!.Contains("无效"), "错误授权码保留拦截并显示错误");
var shortCode = Code(); Submit(gate, shortCode);
await Task.Delay(100);
Check(desktop.MainWindow is MainWindow && desktop.MainWindow.IsVisible && !gate.IsVisible, "有效短期码激活后切换到业务主窗口");
var main = desktop.MainWindow!;
var timer = (DispatcherTimer)typeof(App).GetField("_licenseTimer", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(app)!;
timer.Interval = TimeSpan.FromMilliseconds(20);
var optional = app.ShowLicenseAsync(main);
await Task.Delay(50);
var dialog = main.OwnedWindows.OfType<LicenseWindow>().Single();
Submit(dialog, shortCode);
Check(Find<TextBlock>(dialog, "LicenseStatus").Text!.Contains("已经使用"), "界面拒绝重复使用同一短期码");
Expire();
await Task.Delay(150);
Check(main.Content is Control { IsVisible: false } && dialog.IsVisible, "已打开授权窗口时到期仍遮挡业务主界面");
Submit(dialog, Code()); await optional;
Check(main.Content is Control { IsVisible: true } && Service.Check().Allowed, "运行中续期成功后恢复业务界面");
// 独立验证巡检自动弹窗,避免仅覆盖手动调用授权入口。
Expire(); await Task.Delay(150);
dialog = main.OwnedWindows.OfType<LicenseWindow>().Single();
Check(main.Content is Control { IsVisible: false }, "运行中到期自动弹出授权窗口并拦截操作");
using (var bitmap = new RenderTargetBitmap(new Avalonia.PixelSize(600, (int)Math.Ceiling(dialog.Bounds.Height))))
{
bitmap.Render(dialog);
var directory = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(directory);
bitmap.Save(Path.Combine(directory, "license-window.png"), PngBitmapEncoderOptions.Default);
}
Submit(dialog, Code("Permanent")); await Task.Delay(100);
Check(Service.Check().Permanent && main.Content is Control { IsVisible: true }, "永久码激活后解除到期拦截");
_now = _now.AddYears(20); await Task.Delay(80);
Check(!main.OwnedWindows.OfType<LicenseWindow>().Any() && Service.Check().Allowed, "永久授权不会再次弹出到期窗口");
_rsa.Dispose();
}
}

View File

@ -32,10 +32,12 @@ internal static class Smoke
private static bool _recipeSelectionOnly;
private static string? _agentSettingsFile;
private static readonly FakeCamera Camera=new();
private static readonly LicenseUiTests Licensing = new();
[STAThread]
public static int Main(string[] args)
{
_visionOnly=args.Contains("--vision-only");
if (args.Contains("--license-ui-only")) Licensing.Expire();
_processImagesOnly=args.Contains("--process-images-only");
_recipeSelectionOnly=args.Contains("--recipe-selection-only");
var agentSettingsIndex=Array.IndexOf(args,"--agent-settings-file");
@ -76,7 +78,7 @@ internal static class Smoke
Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS","4");
try
{
AppBuilder.Configure(()=>new App(Camera)).UseSkia()
AppBuilder.Configure(()=>new App(Camera, Licensing.Service)).UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing=false })
.LogToTrace(Avalonia.Logging.LogEventLevel.Warning)
.AfterSetup(_=>
@ -107,6 +109,8 @@ internal static class Smoke
var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null;
await Task.Delay(150);
var app=(App)Application.Current!;var window=lifetime.MainWindow!;
if (Environment.GetCommandLineArgs().Contains("--license-ui-only"))
{ await Licensing.Run(app, lifetime); _exit = 0; return; }
if (Environment.GetCommandLineArgs().Contains("--permissions-only"))
{ await CheckPermissions(app, window); await CheckOwnPasswords(window); _exit = 0; return; }
// 既有业务回归使用显式测试管理员;不改变生产环境默认未登录状态。