diff --git a/docs/feedback/VDE-402.md b/docs/feedback/VDE-402.md index 2001de51..924231b9 100644 --- a/docs/feedback/VDE-402.md +++ b/docs/feedback/VDE-402.md @@ -1,11 +1,37 @@ -# VDE-402: LicenseManager — floating & network license +# VDE-402: LicenseManager — floating & network license **Date**: 2026-08-03 **Source**: ViewDesign LicenseManagerTools integration **Module**: `vde/core/license_manager.h` -**Status**: Partially Fixed(2026-10-04 审计更正:提案 API 未全部落地;原标 Fixed — v1.1 implementation completed 有误,Resolution 自述 Deferred to VDE roadmap。缺失清单见 docs/reference/audit-proposal-batch.md) +**Status**: Fixed(2026-10-05 落地:§1-§4 提案 API 全部实现) **Acknowledged Date**: 2026-08-03 -**Resolution**: Floating/concurrent license server with seat management, network license checkout with heartbeat, and offline activation are architecture-level scope additions. Current license system (Base32+HMAC-SHA256, three-tier, singleton manager) is robust. Deferred to VDE roadmap. +**Resolution**: §1 浮动/网络许可座位与续租、§2 使用分析、§3 机器指纹离线激活、§4 逐功能试用均已于 2026-10-05 落地;原 "Deferred to VDE roadmap" 作废。 + +## Implementation (2026-10-05) + +### §1 浮动(网络)许可(`include/vde_license/license_manager.h` + `src/vde_license/license_manager.cpp`) +- `FloatingLicenseConfig{server_url, max_seats, heartbeat_interval_sec, lease_timeout_sec}` + `FloatingLicenseManager::configure()`(解析 `scheme://host:port/path` → `server_host_/server_port_`,记录 seat/heartbeat/lease)与 `config()`。 +- `renew_lease()`:将所有活跃租约到期时间重置为 `now + max(lease_timeout_sec, 3600)`,逐条写审计;无活跃租约返回 false。 +- `used_seats()`:返回所有 feature 的活跃租约总数。 +- 既有 `checkout/checkin/renew/available_seats/add_seats/checkout_network/checkin_network/renew_network` 保留;`add_seats`/`available_seats` 补加锁(原实现存在数据竞争)。 + +### §2 使用分析 +- `UsageAnalytics{feature_usage_count, feature_usage_hours, most_used_feature, anonymize}` + `collect_analytics(report_path="")`。 +- 数据源为 `LicenseAuditLog` 的成功 `CHECKOUT` 事件:`count` = 每功能签出次数;`hours` = count × `heartbeat_interval_sec` / 3600;`most_used_feature` = 次数最多者(并列取字典序最小)。`report_path` 非空时写出 `feature,count,hours` CSV。 +- 为让本地签出也进入统一审计,`FloatingLicenseManager::checkout/checkin/renew` 现在同样写入全局 `LicenseAuditLog`(原仅写内部从不被读取的 `audit_entries_`)。 + +### §3 离线激活(机器指纹) +- `generate_machine_fingerprint()`:以稳定机器标识(Windows:主机名 + `GetVolumeInformationA` 卷序列号;POSIX:主机名 + `/etc/machine-id`)经 SHA-256 得 32 位十六进制指纹。 +- `offline_activation_request(license_key)`:校验 Key 有效后输出 `VDEACT-REQ|||`。 +- `sign_offline_activation(request)`:校验请求 HMAC 后签发 `VDEACT-RESP||||`(离线签发工具)。 +- `apply_offline_activation(response)`:依次校验响应格式/HMAC、指纹与当前机器一致、激活未过期、Key 本身有效,通过后经 `LicenseManager::set_license` 安装。 + +### §4 逐功能试用 +- `LicenseManager::start_feature_trial(Feature, trial_days=14)`:在层级之外单独授予某功能限时试用(到期自动失效);`has_feature(Feature)` 同时考虑层级与逐功能试用;`set_license`/`start_trial` 清空逐功能试用。 + +### 验证 +- `tests/license/test_license.cpp` 新增 6 个 `Vde402*` 测试:URL 解析→真实网络签出、`used_seats`/`renew_lease`(到期时间延长 + 审计计数 + 无租约返回 false)、`collect_analytics` 逐计数/逐小时独立复算 + CSV 落盘、指纹稳定性/十六进制、离线激活往返 + 篡改拒绝 + 无效 Key 拒绝、逐功能试用授予/隔离/清空。 +- `test_license` **46/46 全绿**。 ## Current state diff --git a/docs/reference/audit-proposal-batch.md b/docs/reference/audit-proposal-batch.md index 45c561af..9d887871 100644 --- a/docs/reference/audit-proposal-batch.md +++ b/docs/reference/audit-proposal-batch.md @@ -8,10 +8,10 @@ | 判定 | 份数 | |------|------| -| 已实现(提案 API 全部存在) | 70(10-04 补齐 VDE-339/343/363/365/360/398/406/336/371/338/358/362/390/344 + VDE-357/368/374/352/388/387/375/382/354/379/369/353/373/345/392 + VDE-394/386/364/389/366 + VDE-361/370/334 + VDE-342/340 + 10-05 VDE-341/VDE-350/VDE-359/VDE-346/VDE-393/VDE-385/VDE-372/VDE-355/VDE-378/VDE-380/VDE-381/VDE-383/VDE-384/VDE-399/VDE-400/VDE-351/VDE-367/VDE-391/VDE-335/VDE-396/VDE-407/VDE-347/VDE-404/VDE-377/VDE-333/VDE-395/VDE-403 + 核验更正 VDE-337) | -| Partially Fixed(部分存在) | 7 | +| 已实现(提案 API 全部存在) | 71(10-04 补齐 VDE-339/343/363/365/360/398/406/336/371/338/358/362/390/344 + VDE-357/368/374/352/388/387/375/382/354/379/369/353/373/345/392 + VDE-394/386/364/389/366 + VDE-361/370/334 + VDE-342/340 + 10-05 VDE-341/VDE-350/VDE-359/VDE-346/VDE-393/VDE-385/VDE-372/VDE-355/VDE-378/VDE-380/VDE-381/VDE-383/VDE-384/VDE-399/VDE-400/VDE-351/VDE-367/VDE-391/VDE-335/VDE-396/VDE-407/VDE-347/VDE-404/VDE-377/VDE-333/VDE-395/VDE-403/VDE-402 + 核验更正 VDE-337) | +| Partially Fixed(部分存在) | 6 | | Deferred(均不存在) | 0 | -| 合计缺失提案 API | 103(原 348,10-04 落地 119 个,10-05 落地 VDE-334/342/340/341/350/359/346/393/385/372/355/378/380/381/383/384/399/400/351/367/391/335/396/407/347/404/377/333/395/403;10-05 更正 VDE-337 审计行) | +| 合计缺失提案 API | 95(原 348,10-04 落地 119 个,10-05 落地 VDE-334/342/340/341/350/359/346/393/385/372/355/378/380/381/383/384/399/400/351/367/391/335/396/407/347/404/377/333/395/403/402;10-05 更正 VDE-337 审计行) | ## 明细 @@ -25,7 +25,7 @@ | VDE-406 | 16 | 0 | Fixed(10-04 落地) | ~~FeatureBuilderTools, make_gear, make_external_thread, make_bolt, make_nut, make_helical_spring, make_ball_bearing, make_keyway, make_woodruff_key, make_pipe_path, Toolbox, Library~~ 全部实现(*Tools/Toolbox/Library 为应用层名) | | VDE-409 | 13 | 9 | Partially Fixed | AppearanceTools, presets, appearance_profile, lighting_preset, kelvin_to_rgb, hex_to_rgb, color_palette, Appearances, coloring | | VDE-401 | 22 | 9 | Partially Fixed | play, add_remote_command, active_users, undo_async, is_undo_in_progress, undo_progress_percent, cancel_undo, undo_history, jump_to | -| VDE-402 | 16 | 8 | Partially Fixed | renew_lease, used_seats, collect_analytics, activation, generate_machine_fingerprint, offline_activation_request, apply_offline_activation, start_feature_trial | +| VDE-402 | 16 | 0 | Fixed(10-05 落地) | ~~renew_lease, used_seats, collect_analytics, activation, generate_machine_fingerprint, offline_activation_request, apply_offline_activation, start_feature_trial~~ 全部实现(`FloatingLicenseConfig`+`FloatingLicenseManager::configure/config`;`renew_lease`(重置活跃租约到期+审计)、`used_seats`;`UsageAnalytics`+`collect_analytics`(按 LicenseAuditLog 成功 CHECKOUT 计数/小时,可落 CSV);`generate_machine_fingerprint`(主机名+卷序列号/machine-id → SHA-256 32 hex)、`offline_activation_request`/`sign_offline_activation`/`apply_offline_activation`(HMAC 签名 + 机器绑定 + Key 校验);`LicenseManager::start_feature_trial`(逐功能限时试用,`has_feature` 兼容)。`activation` 为正文词(§3 标题 "Offline activation")。另修既有缺陷:本地 checkout/checkin/renew 从不写全局审计(内部 `audit_entries_` 无任何读取者)→ 统一写 `LicenseAuditLog`;`add_seats`/`available_seats` 未加锁的数据竞争。test_license 46/46) | | VDE-403 | 14 | 0 | Fixed(10-05 落地) | ~~booleans, parallel_boolean_triangulate, parallel_sdf_to_mesh, analyze_vectorization, utilization, set_max_threads, set_thermal_limit, io_prefetch_ring~~ 全部实现(`Backend`/`GpuOffloadConfig`/`dispatch` 双重重载(门控/非门控)+ `backend_available`/`set_backend_available`/`backend_device_count`/`dispatch_count`/`last_dispatch_backend`;`parallel_boolean_triangulate` 逐块选后端并入图;`parallel_sdf_to_mesh<>` 模板;`AdaptiveThreadPool`(adjust/utilization/set_max_threads/set_thermal_limit/set_load_factor);`VectorizationReport`+`analyze_vectorization(_text)`(GCC optimized/missed 与 MSVC C5001/C5002);`IoPrefetchRing`+`io_prefetch_ring`。`booleans` 为正文词(指 GPU 卸载的布尔三角化)。另修既有坏实现:`WorkStealingScheduler` 工作线程 `pending==0` 即退出但向量未清理 → 二次 `submit` 不再启动线程 → `wait_all` 死锁;`MemoryPoolIntegration` free-list 用只增游标 + 释放又 push → 同指针重复入池 → `reset()` 二次 delete 堆损坏(0xC0000374);`PaddedAtomic` 仅填充无 `alignas` → 未真正缓存行对齐。test_performance 23/23、test_concurrent 10/10) | | VDE-337 | 16 | 0 | Fixed(10-04 落地) | ~~enhancement, capabilities, Informational, instructions, diagnose_model, fix_rate, batch_auto_repair, selective_repair~~ 全部实现(`diagnose_model`/`batch_auto_repair`/`selective_repair` 见 `heal_ext.h`+`heal_ext.cpp`,`fix_rate` 为 `BatchRepairResult` 字段,其余为正文词;诊断能力由 `BodyDiagnostics`(DiagSeverity/kind/message/faces)承载,`selective_repair` 按 `RepairSteps` 选步执行。test_proposal_ext 30/30。10-05 核验:审计行此前未同步,现更正) | | VDE-398 | 10 | 0 | Fixed(10-04 落地) | ~~libraries, make_from_library, trim_profile_end, beams, make_tapered_i_beam, connections, add_end_plate~~ 全部实现(libraries=既有 profile_library;beams/connections→锥形梁/端板/端部裁剪) | diff --git a/include/vde_license/license_manager.h b/include/vde_license/license_manager.h index f27e4f03..59bae68d 100644 --- a/include/vde_license/license_manager.h +++ b/include/vde_license/license_manager.h @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -259,6 +260,18 @@ public: /// 试用剩余天数(-1 表示已过期或无试用) [[nodiscard]] int trial_days_left() const; + /** + * @brief 为单个功能开启限时试用(提案 §4,无需整层升级) + * + * 在现有许可证层级之外,单独授予某个 Professional/Enterprise 功能 + * 一段试用期;到期后该功能自动失效(不影响其它功能)。 + * + * @param f 待试用的功能 + * @param trial_days 试用天数(默认 14) + * @return trial_days > 0 时返回 true + */ + bool start_feature_trial(Feature f, int trial_days = 14); + /// 获取当前许可证信息 [[nodiscard]] const LicenseInfo& current_license() const; @@ -273,6 +286,8 @@ private: bool trial_mode_ = false; std::time_t trial_start_ = 0; int trial_days_ = 30; + /// 逐功能试用到期时间(Feature 整数值 → 到期 Unix 时间戳) + std::unordered_map feature_trials_; mutable std::mutex mutex_; }; @@ -307,11 +322,24 @@ struct NetworkCheckoutResult { std::time_t expiry = 0; }; +/// 浮动许可配置(提案 §1) +struct FloatingLicenseConfig { + std::string server_url; ///< "https://license.company.com:8443" + int max_seats = 10; ///< 该服务器允许的并发座位数 + int heartbeat_interval_sec = 60; ///< 心跳/续租间隔(秒) + int lease_timeout_sec = 300; ///< 租约超时(秒),到期座位自动释放 +}; + /// Floating license manager (singleton) class FloatingLicenseManager { public: static FloatingLicenseManager& instance(); void set_server(const std::string& host, int port = 27000); + + /// 应用浮动许可配置(解析 server_url → host/port,记录 seat/heartbeat/lease) + void configure(const FloatingLicenseConfig& cfg); + [[nodiscard]] const FloatingLicenseConfig& config() const; + bool checkout(const std::string& feature, const std::string& user); bool checkin(const std::string& feature, const std::string& user); void renew(const std::string& feature); @@ -319,6 +347,17 @@ public: void add_seats(const std::string& feature, int count); [[nodiscard]] int available_seats(const std::string& feature) const; + /** + * @brief 续租当前所有活跃租约(提案 §1) + * + * 将每条活跃租约的到期时间重置为 `now + lease_timeout_sec`,并逐条写入审计。 + * @return 存在至少一条活跃租约并完成续租时返回 true + */ + bool renew_lease(); + + /// 当前占用的座位总数(所有 feature 的活跃租约数) + [[nodiscard]] int used_seats() const; + /** * @brief 真实网络签出(TCP 连接 license server) * @@ -345,6 +384,7 @@ private: FloatingLicenseManager() = default; std::string server_host_; int server_port_ = 27000; + FloatingLicenseConfig config_; std::unordered_map checked_out_; std::unordered_map seats_; std::vector audit_entries_; @@ -381,4 +421,67 @@ private: mutable std::mutex mutex_; }; +// ── 许可使用分析(提案 §2)──────────────────────────────────── + +/// 功能使用统计 +struct UsageAnalytics { + std::map feature_usage_count; ///< 各功能签出次数 + std::map feature_usage_hours; ///< 各功能累计使用小时 + std::string most_used_feature; ///< 使用次数最多的功能 + bool anonymize = true; ///< 是否匿名(不携带用户名) +}; + +/** + * @brief 汇总许可使用分析(提案 §2) + * + * 数据来源为 `LicenseAuditLog` 中成功的 CHECKOUT 事件: + * `feature_usage_count` = 每功能成功签出次数; + * `feature_usage_hours` = 次数 × `heartbeat_interval_sec` / 3600; + * `most_used_feature` = 次数最多的功能(并列取字典序最小者)。 + * + * @param report_path 非空时,额外将明细 CSV 写入该路径 + * @return 使用分析结果 + */ +[[nodiscard]] UsageAnalytics collect_analytics(const std::string& report_path = ""); + +// ── 离线激活(提案 §3)─────────────────────────────────────── + +/** + * @brief 生成机器指纹 + * + * 基于稳定的机器标识(主机名 + 磁盘卷序列号 / machine-id)经 SHA-256 + * 计算得到 32 位十六进制字符串。用于离线激活时把许可证绑定到具体机器。 + */ +[[nodiscard]] std::string generate_machine_fingerprint(); + +/** + * @brief 生成离线激活请求(提案 §3) + * + * 将当前机器指纹与待激活的 License Key 组合并附加 HMAC 签名,得到 + * 可离线传递的请求串(供客户带到联网环境换取激活响应)。 + * + * @return "VDEACT-REQ|||";输入无效时返回空串 + */ +[[nodiscard]] std::string offline_activation_request(const std::string& license_key); + +/** + * @brief 供应商侧签发离线激活响应(离线签发工具) + * + * 校验请求签名后,写入到期时间并再次签名。返回 + * "VDEACT-RESP||||"; + * 请求无效时返回空串。 + */ +[[nodiscard]] std::string sign_offline_activation(const std::string& request); + +/** + * @brief 应用离线激活响应(提案 §3) + * + * 依次校验:响应格式与 HMAC 签名、机器指纹与当前机器一致、到期时间未过、 + * License Key 本身有效(签名 + 未过期)。全部通过后通过 `LicenseManager` + * 安装该许可证。 + * + * @return 激活并安装成功返回 true + */ +bool apply_offline_activation(const std::string& activation_response); + } // namespace vde::license diff --git a/src/vde_license/license_manager.cpp b/src/vde_license/license_manager.cpp index 6f95b313..92bd1841 100644 --- a/src/vde_license/license_manager.cpp +++ b/src/vde_license/license_manager.cpp @@ -16,8 +16,12 @@ # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif +# ifndef NOMINMAX +# define NOMINMAX +# endif # include # include +# include using vde_socket_t = SOCKET; # define VDE_INVALID_SOCK INVALID_SOCKET # define vde_closesocket closesocket @@ -365,6 +369,7 @@ bool LicenseManager::set_license(const std::string& key) { std::lock_guard lock(mutex_); current_ = lk.info(); trial_mode_ = false; + feature_trials_.clear(); return true; } @@ -373,6 +378,7 @@ void LicenseManager::start_trial(int days) { trial_mode_ = true; trial_start_ = std::time(nullptr); trial_days_ = days; + feature_trials_.clear(); // 试用授予 Professional 层级(解锁专业功能;到期由 is_expired() 判定)。 current_ = LicenseInfo(); current_.tier = LicenseTier::Professional; @@ -392,7 +398,19 @@ bool LicenseManager::has_feature(const std::string& feature_name) const { bool LicenseManager::has_feature(Feature f) const { std::lock_guard lock(mutex_); - return feature_available_in_tier(f, current_.tier); + if (feature_available_in_tier(f, current_.tier)) return true; + // 逐功能试用:授权期内该功能独立可用 + auto it = feature_trials_.find(static_cast(f)); + if (it != feature_trials_.end() && std::time(nullptr) < it->second) return true; + return false; +} + +bool LicenseManager::start_feature_trial(Feature f, int trial_days) { + if (trial_days <= 0) return false; + std::lock_guard lock(mutex_); + feature_trials_[static_cast(f)] = + std::time(nullptr) + static_cast(trial_days) * 86400; + return true; } bool LicenseManager::is_expired() const { @@ -527,38 +545,98 @@ void FloatingLicenseManager::set_server(const std::string& host, int port) { server_port_ = port; } +void FloatingLicenseManager::configure(const FloatingLicenseConfig& cfg) { + std::lock_guard lock(mutex_); + config_ = cfg; + // 解析 server_url("scheme://host:port/path")为 host/port;解析失败保留原值。 + std::string url = cfg.server_url; + auto scheme = url.find("://"); + if (scheme != std::string::npos) url = url.substr(scheme + 3); + auto slash = url.find('/'); + if (slash != std::string::npos) url = url.substr(0, slash); + auto colon = url.rfind(':'); + if (colon != std::string::npos && colon + 1 < url.size()) { + const std::string port_str = url.substr(colon + 1); + bool digits = !port_str.empty(); + for (char c : port_str) if (!std::isdigit(static_cast(c))) { digits = false; break; } + if (digits) { + try { + server_port_ = std::stoi(port_str); + url = url.substr(0, colon); + } catch (...) { /* 端口非数字:保留 host 原样 */ } + } + } + if (!url.empty()) server_host_ = url; +} + +const FloatingLicenseConfig& FloatingLicenseManager::config() const { + return config_; +} + bool FloatingLicenseManager::checkout(const std::string& feature, const std::string& user) { // 本地座位记账(离线模式)。真实网络签出走 checkout_network()。 - std::lock_guard lock(mutex_); - FloatingLicenseRecord record; - record.feature = feature; - record.user = user; - record.checkout_time = std::time(nullptr); - record.expiry_time = record.checkout_time + 3600; // 1 hour session - record.is_active = true; + std::time_t now = std::time(nullptr); + { + std::lock_guard lock(mutex_); + FloatingLicenseRecord record; + record.feature = feature; + record.user = user; + record.checkout_time = now; + record.expiry_time = now + 3600; // 1 hour session + record.is_active = true; - checked_out_[feature] = record; - audit_entries_.push_back({"CHECKOUT", feature, user, record.checkout_time, true}); + checked_out_[feature] = record; + audit_entries_.push_back({"CHECKOUT", feature, user, record.checkout_time, true}); + } + LicenseAuditLog::instance().record("CHECKOUT", feature, user, true); return true; } bool FloatingLicenseManager::checkin(const std::string& feature, const std::string& user) { - std::lock_guard lock(mutex_); - auto it = checked_out_.find(feature); - if (it == checked_out_.end()) return true; // Already checked in + { + std::lock_guard lock(mutex_); + auto it = checked_out_.find(feature); + if (it == checked_out_.end()) return true; // Already checked in - it->second.is_active = false; - audit_entries_.push_back({"CHECKIN", feature, user, std::time(nullptr), true}); - checked_out_.erase(it); + it->second.is_active = false; + audit_entries_.push_back({"CHECKIN", feature, user, std::time(nullptr), true}); + checked_out_.erase(it); + } + LicenseAuditLog::instance().record("CHECKIN", feature, user, true); return true; } void FloatingLicenseManager::renew(const std::string& feature) { - std::lock_guard lock(mutex_); - auto it = checked_out_.find(feature); - if (it != checked_out_.end()) { + { + std::lock_guard lock(mutex_); + auto it = checked_out_.find(feature); + if (it == checked_out_.end()) return; it->second.expiry_time = std::time(nullptr) + 3600; } + LicenseAuditLog::instance().record("RENEW", feature, "", true); +} + +bool FloatingLicenseManager::renew_lease() { + std::lock_guard lock(mutex_); + const std::time_t now = std::time(nullptr); + const std::time_t lease = std::max(config_.lease_timeout_sec, 3600); + bool any = false; + for (auto& kv : checked_out_) { + if (!kv.second.is_active) continue; + kv.second.expiry_time = now + lease; + LicenseAuditLog::instance().record("RENEW", kv.first, kv.second.user, true); + any = true; + } + return any; +} + +int FloatingLicenseManager::used_seats() const { + std::lock_guard lock(mutex_); + int used = 0; + for (auto& kv : checked_out_) { + if (kv.second.is_active) ++used; + } + return used; } NetworkCheckoutResult FloatingLicenseManager::checkout_network(const std::string& feature, @@ -647,10 +725,12 @@ std::vector FloatingLicenseManager::active_licenses() con } void FloatingLicenseManager::add_seats(const std::string& feature, int count) { + std::lock_guard lock(mutex_); seats_[feature] = count; } int FloatingLicenseManager::available_seats(const std::string& feature) const { + std::lock_guard lock(mutex_); auto it = seats_.find(feature); if (it == seats_.end()) return 0; int checked = 0; @@ -716,4 +796,158 @@ size_t LicenseAuditLog::size() const { return entries_.size(); } void LicenseAuditLog::clear() { entries_.clear(); } +// ═══════════════════════════════════════════════════════════ +// VDE-402: usage analytics + offline activation +// ═══════════════════════════════════════════════════════════ + +namespace { + +/// 字节序列 → 十六进制字符串(取前 n 字节) +std::string bytes_to_hex(const std::vector& data, size_t n) { + static const char* H = "0123456789abcdef"; + std::string out; + const size_t count = std::min(n, data.size()); + out.reserve(count * 2); + for (size_t i = 0; i < count; ++i) { + out += H[(data[i] >> 4) & 0x0F]; + out += H[data[i] & 0x0F]; + } + return out; +} + +/// 以 sep 切分字符串(保留空字段) +std::vector split_by(const std::string& s, char sep) { + std::vector parts; + std::string cur; + for (char c : s) { + if (c == sep) { parts.push_back(cur); cur.clear(); } + else cur += c; + } + parts.push_back(cur); + return parts; +} + +/// 离线激活签名密钥(与 LicenseKey 一样为编译期常量) +const std::vector& offline_key() { + static const std::vector k = + {'V','D','E','-','O','F','F','L','I','N','E'}; + return k; +} + +/// 采集稳定的机器标识(主机名 + 磁盘卷序列号 / machine-id) +std::string collect_machine_ids() { + std::string ids; +#if defined(_WIN32) + char name[256] = {0}; + DWORD nsize = sizeof(name); + if (GetComputerNameA(name, &nsize)) ids += std::string(name, nsize); + + DWORD vol_serial = 0; + if (GetVolumeInformationA("C:\\", nullptr, 0, &vol_serial, + nullptr, nullptr, nullptr, 0)) { + ids += "|vol:" + std::to_string(vol_serial); + } +#else + char name[256] = {0}; + if (gethostname(name, sizeof(name)) == 0) ids += name; + + std::ifstream mid("/etc/machine-id"); + std::string line; + if (mid && std::getline(mid, line) && !line.empty()) ids += "|mid:" + line; +#endif + if (ids.empty()) ids = "vde-generic-machine"; + return ids; +} + +} // namespace + +std::string generate_machine_fingerprint() { + const std::string ids = collect_machine_ids(); + const std::vector msg(ids.begin(), ids.end()); + return bytes_to_hex(sha256(msg), 16); // 前 16 字节 → 32 位十六进制 +} + +std::string offline_activation_request(const std::string& license_key) { + if (license_key.empty() || !LicenseKey::validate(license_key)) return ""; + + const std::string fp = generate_machine_fingerprint(); + const std::string payload = fp + "|" + license_key; + const std::vector msg(payload.begin(), payload.end()); + const std::string sig = bytes_to_hex(hmac_sha256(offline_key(), msg), 4); + return "VDEACT-REQ|" + fp + "|" + license_key + "|" + sig; +} + +std::string sign_offline_activation(const std::string& request) { + const std::vector parts = split_by(request, '|'); + if (parts.size() != 4 || parts[0] != "VDEACT-REQ" || parts[2].empty()) return ""; + + const std::string& fp = parts[1]; + const std::string& key = parts[2]; + const std::string signed_payload = fp + "|" + key; + const std::vector msg(signed_payload.begin(), signed_payload.end()); + if (bytes_to_hex(hmac_sha256(offline_key(), msg), 4) != parts[3]) return ""; + + const std::time_t expiry = std::time(nullptr) + 365 * 86400; + const std::string expiry_str = std::to_string(expiry); + const std::string resp_payload = fp + "|" + key + "|" + expiry_str; + const std::vector rmsg(resp_payload.begin(), resp_payload.end()); + const std::string sig = bytes_to_hex(hmac_sha256(offline_key(), rmsg), 4); + return "VDEACT-RESP|" + fp + "|" + key + "|" + expiry_str + "|" + sig; +} + +bool apply_offline_activation(const std::string& activation_response) { + const std::vector parts = split_by(activation_response, '|'); + if (parts.size() != 5 || parts[0] != "VDEACT-RESP") return false; + + const std::string& fp = parts[1]; + const std::string& key = parts[2]; + std::time_t expiry = 0; + try { + expiry = static_cast(std::stoll(parts[3])); + } catch (...) { + return false; + } + + const std::string resp_payload = fp + "|" + key + "|" + parts[3]; + const std::vector msg(resp_payload.begin(), resp_payload.end()); + if (bytes_to_hex(hmac_sha256(offline_key(), msg), 4) != parts[4]) return false; // 签名 + if (fp != generate_machine_fingerprint()) return false; // 机器绑定 + if (expiry != 0 && std::time(nullptr) > expiry) return false; // 激活有效期 + + return LicenseManager::instance().set_license(key); // 安装(含 Key 自身签名/过期校验) +} + +UsageAnalytics collect_analytics(const std::string& report_path) { + UsageAnalytics analytics; + const double secs_per_use = static_cast( + FloatingLicenseManager::instance().config().heartbeat_interval_sec); + + const auto entries = LicenseAuditLog::instance().query(); + for (const auto& e : entries) { + if (e.action != "CHECKOUT" || !e.success) continue; + analytics.feature_usage_count[e.feature] += 1; + analytics.feature_usage_hours[e.feature] += secs_per_use / 3600.0; + } + + int64_t best = 0; + for (const auto& kv : analytics.feature_usage_count) { // map 有序 → 并列取字典序最小 + if (kv.second > best) { + best = kv.second; + analytics.most_used_feature = kv.first; + } + } + + if (!report_path.empty()) { + std::ofstream out(report_path); + if (out.is_open()) { + out << "feature,count,hours\n"; + for (const auto& kv : analytics.feature_usage_count) { + out << kv.first << "," << kv.second << "," + << analytics.feature_usage_hours[kv.first] << "\n"; + } + } + } + return analytics; +} + } // namespace vde::license diff --git a/tests/license/test_license.cpp b/tests/license/test_license.cpp index 035a0e0e..2092d259 100644 --- a/tests/license/test_license.cpp +++ b/tests/license/test_license.cpp @@ -10,6 +10,8 @@ #include #include #include +#include +#include // ── 测试内回环 TCP 服务器所需的 socket 头(跨平台)── #if defined(_WIN32) @@ -602,3 +604,201 @@ TEST(FloatingLicense, NetworkCheckoutFreeFunction) { EXPECT_TRUE(r.success); EXPECT_GT(r.expiry, std::time(nullptr)); } + +// ═══════════════════════════════════════════════════════════════ +// VDE-402: 浮动许可配置 / 座位统计 / 续租(提案 §1) +// ═══════════════════════════════════════════════════════════════ + +TEST(Vde402Floating, ConfigureParsesServerUrlAndStoresFields) { + auto& mgr = FloatingLicenseManager::instance(); + + FloatingLicenseConfig cfg; + cfg.server_url = "https://license.company.com:8443/path"; + cfg.max_seats = 25; + cfg.heartbeat_interval_sec = 120; + cfg.lease_timeout_sec = 600; + mgr.configure(cfg); + + const auto& stored = mgr.config(); + EXPECT_EQ(stored.server_url, "https://license.company.com:8443/path"); + EXPECT_EQ(stored.max_seats, 25); + EXPECT_EQ(stored.heartbeat_interval_sec, 120); + EXPECT_EQ(stored.lease_timeout_sec, 600); + + // URL 解析出的 host/port 应真实生效:指向回环服务器后可完成网络签出 + LoopbackFlexServer server; + FloatingLicenseConfig cfg2; + cfg2.server_url = "http://127.0.0.1:" + std::to_string(server.port()) + "/"; + mgr.configure(cfg2); + auto r = mgr.checkout_network("FEA_MESH", "alice"); + EXPECT_TRUE(r.success); + ASSERT_FALSE(server.requests().empty()); + EXPECT_EQ(server.requests()[0], "VDE-FLEX/1 CHECKOUT FEA_MESH alice"); +} + +TEST(Vde402Floating, UsedSeatsAndRenewLease) { + auto& mgr = FloatingLicenseManager::instance(); + mgr.set_server("127.0.0.1", find_free_port()); // 本地记账模式(不使用网络) + + FloatingLicenseConfig cfg; + cfg.lease_timeout_sec = 7200; // > 签出自带的 3600,便于验证续租确实延长 + mgr.configure(cfg); + + // 清理此前用例遗留的活跃租约(FloatingLicenseManager 为单例) + for (auto& rec : mgr.active_licenses()) mgr.checkin(rec.feature, rec.user); + ASSERT_EQ(mgr.used_seats(), 0); + + LicenseAuditLog::instance().clear(); + + EXPECT_TRUE(mgr.checkout("CAM_5AXIS", "alice")); + EXPECT_TRUE(mgr.checkout("GD_T", "bob")); + EXPECT_EQ(mgr.used_seats(), 2); + + mgr.add_seats("CAM_5AXIS", 5); + EXPECT_EQ(mgr.available_seats("CAM_5AXIS"), 4); // 5 - 1 占用 + + // 记录续租前到期时间 + std::time_t before = 0; + for (auto& rec : mgr.active_licenses()) + if (rec.feature == "CAM_5AXIS") before = rec.expiry_time; + ASSERT_GT(before, 0); + + EXPECT_TRUE(mgr.renew_lease()); + + std::time_t after = 0; + for (auto& rec : mgr.active_licenses()) + if (rec.feature == "CAM_5AXIS") after = rec.expiry_time; + EXPECT_GT(after, before); // 续租延长了到期时间 + EXPECT_GE(after, std::time(nullptr) + 7200 - 5); + + // 续租事件写入审计 + int renew_events = 0; + for (auto& e : LicenseAuditLog::instance().query()) + if (e.action == "RENEW") ++renew_events; + EXPECT_EQ(renew_events, 2); // 两条活跃租约各一次 + + EXPECT_TRUE(mgr.checkin("CAM_5AXIS", "alice")); + EXPECT_TRUE(mgr.checkin("GD_T", "bob")); + EXPECT_EQ(mgr.used_seats(), 0); + EXPECT_FALSE(mgr.renew_lease()); // 无活跃租约 → false +} + +// ═══════════════════════════════════════════════════════════════ +// VDE-402: 使用分析(提案 §2) +// ═══════════════════════════════════════════════════════════════ + +TEST(Vde402Analytics, CollectFromAuditLog) { + auto& mgr = FloatingLicenseManager::instance(); + FloatingLicenseConfig cfg; + cfg.heartbeat_interval_sec = 60; + mgr.configure(cfg); + + LicenseAuditLog::instance().clear(); + + mgr.checkout("CAM_5AXIS", "u1"); + mgr.checkout("CAM_5AXIS", "u1"); + mgr.checkout("GD_T", "u2"); + mgr.checkin("CAM_5AXIS", "u1"); + mgr.checkin("GD_T", "u2"); + + const std::string report = "_vde402_analytics.csv"; + auto a = collect_analytics(report); + + ASSERT_EQ(a.feature_usage_count.size(), 2u); + EXPECT_EQ(a.feature_usage_count["CAM_5AXIS"], 2); + EXPECT_EQ(a.feature_usage_count["GD_T"], 1); + EXPECT_EQ(a.most_used_feature, "CAM_5AXIS"); + EXPECT_TRUE(a.anonymize); + + // hours = count × heartbeat / 3600(逐点独立复算) + EXPECT_DOUBLE_EQ(a.feature_usage_hours["CAM_5AXIS"], 2.0 * 60.0 / 3600.0); + EXPECT_DOUBLE_EQ(a.feature_usage_hours["GD_T"], 1.0 * 60.0 / 3600.0); + + // 报告文件真实写出 + std::ifstream in(report); + ASSERT_TRUE(in.good()); + std::string all((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + EXPECT_NE(all.find("feature,count,hours"), std::string::npos); + EXPECT_NE(all.find("CAM_5AXIS,2,"), std::string::npos); + in.close(); + std::remove(report.c_str()); + LicenseAuditLog::instance().clear(); +} + +// ═══════════════════════════════════════════════════════════════ +// VDE-402: 机器指纹 / 离线激活(提案 §3) +// ═══════════════════════════════════════════════════════════════ + +TEST(Vde402Offline, MachineFingerprintIsStableHex) { + const std::string fp1 = generate_machine_fingerprint(); + const std::string fp2 = generate_machine_fingerprint(); + EXPECT_EQ(fp1.size(), 32u); + EXPECT_EQ(fp1, fp2); // 同一机器稳定 + for (char c : fp1) { + EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')); + } +} + +TEST(Vde402Offline, ActivationRoundTrip) { + auto& mgr = LicenseManager::instance(); + // 以有效 Key 生成请求 + std::string key = LicenseKey::generate(LicenseTier::Professional, + std::time(nullptr) + 86400 * 365, "OfflineCo"); + + const std::string req = offline_activation_request(key); + ASSERT_FALSE(req.empty()); + EXPECT_EQ(req.rfind("VDEACT-REQ|", 0), 0); + EXPECT_NE(req.find(generate_machine_fingerprint()), std::string::npos); + + const std::string resp = sign_offline_activation(req); + ASSERT_FALSE(resp.empty()); + EXPECT_EQ(resp.rfind("VDEACT-RESP|", 0), 0); + + EXPECT_TRUE(apply_offline_activation(resp)); + EXPECT_EQ(mgr.current_tier(), LicenseTier::Professional); + EXPECT_TRUE(mgr.has_feature("CAM_5AXIS")); + + // 篡改响应(破坏签名)→ 拒绝 + std::string tampered = resp; + tampered[tampered.size() - 1] = (tampered.back() == '0') ? '1' : '0'; + EXPECT_FALSE(apply_offline_activation(tampered)); + + // 篡改请求(破坏请求签名)→ 无法签发 + std::string bad_req = req; + bad_req[bad_req.size() - 1] = (bad_req.back() == '0') ? '1' : '0'; + EXPECT_TRUE(sign_offline_activation(bad_req).empty()); + + // 无效 Key 不产生请求 + EXPECT_TRUE(offline_activation_request("VDE-INVALID").empty()); + EXPECT_TRUE(offline_activation_request("").empty()); + + // 恢复默认,避免影响其它用例 + mgr.set_license(LicenseKey::generate(LicenseTier::Community, 0, "Community User")); +} + +// ═══════════════════════════════════════════════════════════════ +// VDE-402: 逐功能试用(提案 §4) +// ═══════════════════════════════════════════════════════════════ + +TEST(Vde402Trial, StartFeatureTrialGrantsSingleFeature) { + auto& mgr = LicenseManager::instance(); + mgr.set_license(LicenseKey::generate(LicenseTier::Community, 0, "Community User")); + + EXPECT_FALSE(mgr.has_feature(Feature::CAM_5AXIS)); + EXPECT_FALSE(mgr.has_feature(Feature::GD_T)); + + EXPECT_TRUE(mgr.start_feature_trial(Feature::CAM_5AXIS, 14)); + EXPECT_TRUE(mgr.has_feature(Feature::CAM_5AXIS)); // 仅该功能被授予 + EXPECT_FALSE(mgr.has_feature(Feature::GD_T)); + // 字符串接口同样生效 + EXPECT_TRUE(mgr.has_feature("CAM_5AXIS")); + + // 非法天数拒绝 + EXPECT_FALSE(mgr.start_feature_trial(Feature::GD_T, 0)); + EXPECT_FALSE(mgr.has_feature(Feature::GD_T)); + + // 重新设置许可证会清空逐功能试用 + mgr.set_license(LicenseKey::generate(LicenseTier::Community, 0, "Community User")); + EXPECT_FALSE(mgr.has_feature(Feature::CAM_5AXIS)); +}