feat(V1.1.1): 软件授权(license)——MAC 绑定 .lic 校验,未授权禁用导出

- 新增 lib/license/license_service.dart:读取 exe 同级 license/*.lic,按算法由本机 MAC 计算期望授权串比对
- 算法:MAC 去分隔符 → A=01..Z=26(数字 00..09)→ 末尾加 26 → 整串倒序
- 未授权时「导出 SVG / PNG」置灰,并在导出入口二次拦截
- 关于页:显示授权状态、本机 MAC、授权申请邮箱 liuyu65@126.com,并可「提交授权申请」(唤起邮件客户端发送 MAC+发件人信息)
- 新增 license/ 目录(含说明);构建脚本把 license/ 复制到 dist/
- 新增 tools/keygen(Win32 图形界面 keygen.exe + 构建脚本)用于生成 .lic
- 版本 1.1.1+3;新增授权算法单元测试;重新构建 dist
This commit is contained in:
呆头鹅
2026-09-19 11:08:39 +08:00
parent 43c99fc4b6
commit 5d0238260f
15 changed files with 592 additions and 21 deletions
+158
View File
@@ -0,0 +1,158 @@
/// 软件授权(License)服务。
///
/// 授权模型:
/// - 应用启动时读取可执行文件同级目录下的 `license/*.lic`(每个文件一行文本);
/// - 由**本机 MAC 地址**按固定算法算出期望的授权串,与 .lic 内容比对;
/// - 有效则可导出 SVG / PNG,无效则导出按钮置灰;
/// - 关于页展示授权状态、本机 MAC,并提供「提交授权申请」。
///
/// 授权算法(与 keygen 保持一致):
/// 1. MAC `AA-BB-CC-DD-EE-FF` → 去掉横线 / 空格 → `AABBCCDDEEFF`;
/// 2. 每个字符按 `A=01 … Z=26`(数字 `0..9` 记作 `00..09`)转两位十进制;
/// 3. 尾部追加固定串 `26`;
/// 4. 整串倒序,即为 .lic 文件内容。
///
/// 例:`AABBCCDDEEFF` → `010102020303040405050606` → 加 `26`
/// → `01010202030304040505060626` → 倒序 → `62606050504040303020201010`。
library;
import 'dart:io';
/// 授权状态快照。
class LicenseInfo {
/// 构造授权信息。
const LicenseInfo({required this.mac, required this.valid, this.filePath, this.content});
/// 本机主 MAC 地址(形如 `AA-BB-CC-DD-EE-FF`);读取失败为 null。
final String? mac;
/// 是否存在有效授权。
final bool valid;
/// 命中的 .lic 文件路径(若有)。
final String? filePath;
/// 命中的 .lic 文件内容(若有)。
final String? content;
/// 期望的授权串(由本机 MAC 计算);无法获取 MAC 时为 null。
String? get expected => mac == null ? null : LicenseService.encodeMac(mac!);
}
/// 授权服务(单例)。
class LicenseService {
LicenseService._();
/// 单例。
static final LicenseService instance = LicenseService._();
LicenseInfo _info = const LicenseInfo(mac: null, valid: false);
/// 最近一次的授权信息。
LicenseInfo get info => _info;
/// 是否已授权。
bool get licensed => _info.valid;
/// license 目录(可执行文件同级目录下的 `license`)。
Directory get licenseDir => Directory('${Directory.current.path}${Platform.pathSeparator}license');
/// 初始化:读取 MAC 并校验 `license/*.lic`。
Future<LicenseInfo> init() async {
final String? mac = await _readMac();
bool valid = false;
String? hitPath;
String? hitContent;
final Directory dir = licenseDir;
if (dir.existsSync()) {
final List<File> files = dir
.listSync()
.whereType<File>()
.where((File f) => f.path.toLowerCase().endsWith('.lic'))
.toList()
..sort((File a, File b) => a.path.compareTo(b.path));
final String? expected = mac == null ? null : encodeMac(mac);
for (final File f in files) {
String content;
try {
content = f.readAsStringSync().trim();
} catch (_) {
continue;
}
if (expected != null && content == expected) {
valid = true;
hitPath = f.path;
hitContent = content;
break;
}
}
}
_info = LicenseInfo(mac: mac, valid: valid, filePath: hitPath, content: hitContent);
return _info;
}
/// 读取本机第一个 MAC 地址(通过系统 `getmac`)。
Future<String?> _readMac() async {
try {
final ProcessResult r = await Process.run(
'getmac',
<String>['/fo', 'csv', '/nh'],
runInShell: true,
);
final String out = '${r.stdout}';
final Match? m = RegExp(r'([0-9A-Fa-f]{2}[-:]){5}[0-9A-Fa-f]{2}').firstMatch(out);
if (m == null) return null;
return m.group(0)!.toUpperCase().replaceAll(':', '-');
} catch (_) {
return null;
}
}
/// 按授权算法,由 [mac] 计算期望的授权串(.lic 内容)。
static String encodeMac(String mac) {
final String clean = mac.replaceAll(RegExp(r'[^0-9A-Za-z]'), '').toUpperCase();
final StringBuffer sb = StringBuffer();
for (final int code in clean.codeUnits) {
int v;
if (code >= 0x30 && code <= 0x39) {
v = code - 0x30; // '0'..'9' -> 0..9
} else if (code >= 0x41 && code <= 0x5A) {
v = code - 0x40; // 'A'..'Z' -> 1..26
} else {
continue;
}
sb.write(v.toString().padLeft(2, '0'));
}
sb.write('26');
final String fwd = sb.toString();
return String.fromCharCodes(fwd.codeUnits.reversed);
}
/// 提交授权申请:通过网络(默认邮件客户端)把 MAC 与发件人信息发送到指定邮箱。
///
/// 返回 true 表示已成功唤起邮件客户端。
Future<bool> submitApplication({required String sender, String? note}) async {
const String to = 'liuyu65@126.com';
final String mac = _info.mac ?? '(读取失败)';
final String subject = Uri.encodeComponent('时序图设计器 V1.1.1 授权申请');
final String body = Uri.encodeComponent(
'MAC 地址:$mac\n'
'发件人信息:$sender\n'
'备注:${note ?? '(无)'}\n'
'软件版本:V1.1.1\n',
);
final String url = 'mailto:$to?subject=$subject&body=$body';
try {
await Process.run('rundll32', <String>['url.dll,FileProtocolHandler', url]);
return true;
} catch (_) {
try {
await Process.run('cmd', <String>['/c', 'start', '', url], runInShell: true);
return true;
} catch (_) {
return false;
}
}
}
}
+5
View File
@@ -10,6 +10,7 @@ import 'dart:ui' show AppExitResponse;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'license/license_service.dart';
import 'model/models.dart';
import 'persistence/storage.dart';
import 'state/app_controller.dart';
@@ -52,6 +53,10 @@ class _SequenceDiagramAppState extends State<SequenceDiagramApp> {
super.initState();
_controller = AppController()..start();
_controller.addListener(_updateWindowTitle);
// 启动即校验授权(读取可执行文件同级 license/*.lic)。
LicenseService.instance.init().then((LicenseInfo info) {
_controller.setLicensed(info.valid);
});
_lifecycle = AppLifecycleListener(
onExitRequested: () async {
await _controller.markCleanOnExit();
+13
View File
@@ -34,6 +34,19 @@ class AppController extends ChangeNotifier {
/// 当前主题亮度(默认浅色 / 白底)。
Brightness _brightness = Brightness.light;
/// 是否已获得有效授权(有效时才允许导出 SVG / PNG)。
bool _licensed = false;
/// 是否已授权。
bool get licensed => _licensed;
/// 设置授权状态并刷新(启动时校验 / 重新读取 .lic 后调用)。
void setLicensed(bool value) {
if (_licensed == value) return;
_licensed = value;
notifyListeners();
}
/// 当前项目对应的文件路径;null 表示尚未保存。
String? _filePath;
+19 -9
View File
@@ -150,6 +150,10 @@ class _AppShellState extends State<AppShell> {
/// 导出 SVG:将当前视图交给 [SvgWriter] 生成矢量内容并写入文件。
Future<void> _exportSvg() async {
if (!c.licensed) {
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。');
return;
}
final String? path = await pickFile(context, save: true, initialPath: c.filePath);
if (path == null) return;
final String svgPath = path.replaceAll(RegExp(r'\.json$'), '.svg');
@@ -169,6 +173,10 @@ class _AppShellState extends State<AppShell> {
/// 导出 PNG:把画布舞台的 [RenderRepaintBoundary] 以 2 倍像素比
/// 渲染为位图并写入文件。
Future<void> _exportPng() async {
if (!c.licensed) {
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。');
return;
}
final String? path = await pickFile(context, save: true, initialPath: c.filePath);
if (path == null) return;
final String pngPath = path.replaceAll(RegExp(r'\.(json|svg)$'), '.png');
@@ -347,9 +355,10 @@ class _AppShellState extends State<AppShell> {
_segmented(t),
];
right = <Widget>[
_primaryBtn(t, '导出 SVG', _exportSvg),
// 未授权时导出按钮置灰(授权有效才允许导出)。
_primaryBtn(t, '导出 SVG', c.licensed ? _exportSvg : null),
const SizedBox(width: 6),
_ghost(t, '导出 PNG', _exportPng),
_ghost(t, '导出 PNG', c.licensed ? _exportPng : null),
const SizedBox(width: 6),
_zoomBox(t),
const SizedBox(width: 6),
@@ -384,10 +393,10 @@ class _AppShellState extends State<AppShell> {
_segmented(t, compact: true),
];
right = <Widget>[
// 导出保持两个独立按钮(不用合并菜单,便于一眼识别)。
_ghost(t, '导出 SVG', _exportSvg),
// 导出保持两个独立按钮;未授权时置灰。
_ghost(t, '导出 SVG', c.licensed ? _exportSvg : null),
const SizedBox(width: 4),
_ghost(t, '导出 PNG', _exportPng),
_ghost(t, '导出 PNG', c.licensed ? _exportPng : null),
const SizedBox(width: 4),
_zoomBox(t),
_iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图'),
@@ -586,13 +595,14 @@ class _AppShellState extends State<AppShell> {
);
}
/// 主色填充按钮(用于导出等主要动作)。
Widget _primaryBtn(Tokens t, String label, VoidCallback onTap) {
/// 主色填充按钮(用于导出等主要动作);[onTap] 为 null 时禁用(置灰)。
Widget _primaryBtn(Tokens t, String label, VoidCallback? onTap) {
final bool enabled = onTap != null;
return FilledButton(
onPressed: onTap,
style: FilledButton.styleFrom(
backgroundColor: t.accent2,
foregroundColor: Colors.white,
backgroundColor: enabled ? t.accent2 : t.panel2,
foregroundColor: enabled ? Colors.white : t.dim,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
minimumSize: const Size(0, 34),
+95 -9
View File
@@ -11,6 +11,7 @@ import 'dart:math' as math;
import 'package:flutter/material.dart' hide Action;
import '../license/license_service.dart';
import '../model/models.dart';
import '../model/units.dart';
import '../state/app_controller.dart';
@@ -1650,15 +1651,8 @@ class HelpDialog extends StatelessWidget {
<String>['导出入口', '导出 SVG / PNG 统一放在顶部工具栏右侧,避免多处重复。'],
<String>['其它', 'F2 编辑时序与节拍参数(含单位与相位分区);F3 切换深/浅主题;Delete 删除选中动作。'],
]),
// 关于:设计人、版本与版权声明。
_section(t, <List<String>>[
<String>['软件名称', '时序图设计器 · Sequence Diagram Studio'],
<String>['设计人', '呆头鹅'],
<String>['版本', 'V1.0.1'],
<String>['版权声明', 'Copyright © 2026 呆头鹅。保留所有权利。'],
<String>['用途', '面向 PLC 流程节拍 / 相位角设计;未经许可不得用于商业再分发。'],
<String>['技术栈', 'Flutter Desktop · 自绘 Canvas · 纯 Dart 几何 · JSON 持久化 · SVG 导出。'],
]),
// 关于:设计人、版本、版权、授权信息与本机 MAC。
_about(context, t),
],
),
),
@@ -1677,6 +1671,98 @@ class HelpDialog extends StatelessWidget {
);
}
/// 「关于」页:软件信息 + 授权状态 + 本机 MAC + 提交授权申请。
Widget _about(BuildContext context, Tokens t) {
final LicenseInfo info = LicenseService.instance.info;
final String lic = info.valid
? '已授权(${info.filePath?.split(RegExp(r'[\\/]')).last ?? '.lic'})'
: '未授权';
Widget row(String k, String v, {Color? vc}) => Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
width: 120,
child: Text(k, style: TextStyle(color: t.accent, fontWeight: FontWeight.w600, fontSize: 12.5)),
),
Expanded(
child: SelectableText(v, style: TextStyle(color: vc ?? t.sub, fontSize: 12.5, height: 1.5)),
),
],
),
);
return ListView(
padding: const EdgeInsets.only(top: 14),
children: <Widget>[
row('软件名称', '时序图设计器 · Sequence Diagram Studio'),
row('设计人', '呆头鹅'),
row('版本', 'V1.1.1'),
row('授权状态', lic, vc: info.valid ? t.ok : t.danger),
row('本机 MAC', info.mac ?? '读取失败'),
row('授权申请邮箱', 'liuyu65@126.com'),
if (!info.valid) row('期望授权串', info.expected ?? '(无法获取 MAC)'),
row('版权声明', 'Copyright © 2026 呆头鹅。保留所有权利。'),
row('用途', '面向 PLC 流程节拍 / 相位角设计;未经许可不得用于商业再分发。'),
const SizedBox(height: 4),
if (!info.valid)
Align(
alignment: Alignment.centerLeft,
child: FilledButton.icon(
onPressed: () => _submitApplication(context),
icon: const Icon(Icons.outgoing_mail, size: 16),
label: const Text('提交授权申请(发送 MAC 到 liuyu65@126.com)'),
),
),
const SizedBox(height: 10),
Text(
'申请授权:请把上方的「本机 MAC」发送到邮箱 liuyu65@126.com 申请授权;'
'收到 .lic 文件后放入软件目录下的 license 文件夹,重启软件即可导出 SVG / PNG。',
style: TextStyle(color: t.dim, fontSize: 11.5, height: 1.6),
),
],
);
}
/// 弹出「提交授权申请」对话框,收集发件人信息后唤起系统邮件客户端。
Future<void> _submitApplication(BuildContext context) async {
final TextEditingController ctrl = TextEditingController();
final String? sender = await showDialog<String>(
context: context,
builder: (BuildContext ctx) => AlertDialog(
title: const Text('提交授权申请'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Text('将把本机 MAC 地址与以下发件人信息发送到 liuyu65@126.com:'),
const SizedBox(height: 10),
TextField(
controller: ctrl,
autofocus: true,
decoration: const InputDecoration(labelText: '发件人信息(单位 / 姓名 / 联系方式)'),
),
],
),
actions: <Widget>[
TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('取消')),
FilledButton(onPressed: () => Navigator.pop(ctx, ctrl.text.trim()), child: const Text('发送')),
],
),
);
ctrl.dispose();
if (sender == null) return;
final bool ok = await LicenseService.instance
.submitApplication(sender: sender.isEmpty ? '(未填写)' : sender);
if (context.mounted) {
await showMessage(
context,
ok ? '已发起申请' : '发送失败',
ok ? '已调用系统邮件客户端,请确认后发送到 liuyu65@126.com。' : '无法唤起邮件客户端,请手动将 MAC 发送到 liuyu65@126.com。',
);
}
}
/// 渲染帮助中的一个条目列表,每行左侧为标题、右侧为说明。
Widget _section(Tokens t, List<List<String>> rows) {
return ListView(