Files
ecom-dmb/ecom-license/DESIGN.md
T

53 KiB
Raw Blame History

Ecom-DMB 授权许可与系统初始化设计方案

1. 概述

1.1 目标

Ecom-DMB 支持 SaaS 部署 和 私有部署 两种模式,所有模式均需通过 License 授权才能正常使用。系统首次运行时必须完成初始化(管理员创建 + License 激活),激活后方可使用订单导入等受限功能。

1.2 授权策略

项目 说明
校验方式 RSA 非对称签名 JWT,绑定机器指纹(安装 ID),本地离线校验为主
授权粒度 按公司维度授权,每套部署一个 License
限制范围 仅限制订单导入相关接口,其他功能不做限制
受限制接口 POST /ec/order/batch-import、POST /ec/import-task/create
License 内容 客户信息、版本类型、有效期、机器指纹、安装 ID、功能特性、jti

1.3 关键概念

概念 说明
License 服务器 运营方部署的授权管理平台(NestJS + Vue 3),用于签发和管理 License
License JWT RS256 签名的 JWT Token,包含授权信息和机器指纹,不可篡改
机器指纹 根据系统 machine-id(/etc/machine-id)+ 主机名生成的唯一哈希值
安装 ID 系统 machine-id(Linux /etc/machine-id),由 systemd 在首次启动时自动生成,唯一标识一次 OS 安装
系统初始化 首次运行时的引导流程:创建管理员 + License 激活
激活 License 与机器指纹绑定并生效的过程

2. 总体架构

                        运营方                                         客户
 ┌──────────────────────────────────────────┐     ┌───────────────────────────────┐
 │          License 授权管理服务器             │     │      Ecom-DMB 主应用           │
 │                                          │     │                               │
 │  ┌──────────────────┐   ┌─────────────┐  │     │  ┌─────────────────────────┐  │
 │  │ Vue 3 管理后台     │   │ NestJS 后端  │  │     │  │ Spring Boot 后端         │  │
 │  │ (Ant Design Vue)  │──▶│             │  │     │  │                         │  │
 │  │                   │   │ · 客户管理   │──┼─────┼──│ · LicenseValidator      │  │
 │  │ · 客户管理         │   │ · 签发License│  │     │  │ · MachineFingerprint    │  │
 │  │ · 签发License      │   │ · 在线验证   │  │     │  │ · InitController       │  │
 │  │ · 下载License文件   │   │ · 操作日志   │  │     │  │ · LicenseAspect        │  │
 │  │ · 操作日志         │   └─────────────┘  │     │  └─────────────────────────┘  │
 │  └──────────────────┘                     │     │                               │
 └──────────────────────────────────────────┘     │  ┌─────────────────────────┐  │
                                                  │  │ Vue 3 前端 (Vben Admin)  │  │
                                                  │  │                         │  │
                                                  │  │ · 初始化向导页面          │  │
                                                  │  │ · 订单导入页面            │  │
                                                  │  │ · 系统设置页面            │  │
                                                  │  └─────────────────────────┘  │
                                                  └───────────────────────────────┘

2.1 两种部署模式的 License 获取方式

私有部署模式:
  客户部署系统 → 初始化页面显示机器指纹 → 客户将指纹发给运营方
  → 运营方在 License 后台签发绑定该指纹的 License
  → 客户输入 License Key → 系统校验通过 → 激活完成

SaaS 部署模式:
  运营方在 License 后台签发一个不限指纹的 License(machineFingerprint 填 "*")
  → 部署系统时直接配置 License → 初始化时自动完成激活
  → License 校验时跳过指纹比对

SaaS 模式指纹策略:SaaS 环境通常有多台服务器负载均衡,且 IP/网络环境多变,不适合绑定具体硬件指纹。签发 License 时将 machineFingerprint 设置为特殊值 *,主应用在校验时检测到该值则跳过指纹比对,仅校验签名和有效期。


3. 系统初始化设计

3.1 初始化流程

系统启动时检测是否已初始化,未初始化则强制跳转到初始化向导。

系统首次启动
      │
      ▼
┌──────────────────┐
│ 检测 License      │──── 有 License ──▶ 正常进入系统
│ 与初始化状态       │
└────────┬─────────┘
         │ 未初始化
         ▼
┌──────────────────────────────────────────┐
│  Step 1: 创建超级管理员账号                │
│  (用户名、密码、邮箱)                      │
└────────────────┬─────────────────────────┘
                 ▼
┌──────────────────────────────────────────┐
│  Step 2: 填写公司基本信息                   │
│  (公司名称、联系方式)                       │
└────────────────┬─────────────────────────┘
                 ▼
┌──────────────────────────────────────────┐
│  Step 3: License 激活                     │
│                                          │
│  ┌────────────────────────────────────┐  │
│  │  机器指纹(只读显示):              │  │
│  │  FP-7A8D9F0E1B2C3D4E5F6...        │  │
│  │  ┌──────────────────────────────┐  │  │
│  │  │ 请输入 License Key            │  │  │
│  │  └──────────────────────────────┘  │  │
│  │  [激活]  [离线激活说明]             │  │
│  └────────────────────────────────────┘  │
│                                          │
│  说明:客户将机器指纹发给运营方,运营方      │
│  在 License 后台生成绑定该指纹的 License    │
└────────────────┬─────────────────────────┘
                 ▼
┌──────────────────────────────────────────┐
│  License 校验                             │
│  · RSA 签名验证                           │
│  · 有效期校验                              │
│  · 机器指纹匹配校验                         │
│  · 全部通过 → 写入数据库 → 初始化完成       │
└──────────────────────────────────────────┘

3.2 初始化 API(主应用 Spring Boot 端)

方法 路径 说明
GET /api/init/status 获取初始化状态
POST /api/init/admin 创建超级管理员(Step 1)
POST /api/init/company 保存公司信息(Step 2)
GET /api/init/fingerprint 获取当前机器指纹
POST /api/init/activate 提交 License Key 完成激活(Step 3)
PUT /api/system/license License 续期/更新(已激活后调用)
GET /api/system/license 获取当前 License 信息
GET /api/system/fingerprint 获取当前机器指纹(已激活后查看)

GET /api/init/status 响应

{
  "initialized": false,
  "currentStep": 0,
  "adminCreated": false,
  "companySaved": false,
  "licenseActivated": false
}

GET /api/init/fingerprint 响应

{
  "fingerprint": "FP-A1B2C3D4E5F67890...",
  "raw": {
    "macAddress": "00:1a:2b:3c:4d:5e",
    "cpuSerial": "BFEBFBFF00090672",
    "diskSerial": "S3Z8NB0M123456",
    "hostname": "ecom-server-01"
  }
}

POST /api/init/activate 请求

{
  "licenseKey": "eyJhbGciOiJSUzI1NiJ9..."
}

校验逻辑:

  1. 用内置公钥验证 JWT 签名
  2. 校验 exp 是否过期
  3. 校验 JWT 中的 machineFingerprint 与当前机器指纹是否一致(除非指纹为 * 表示不限)
  4. 校验通过 → 保存 License 到 sys_license 表 → 标记初始化完成

PUT /api/system/license 请求

{
  "licenseKey": "eyJhbGciOiJSUzI1NiJ9..."
}

说明:与激活接口逻辑一致,但已激活状态下调用时不会重置初始化状态,仅更新 sys_license 表和内存缓存。前端在「系统设置 → License 信息」页面调用此接口。

GET /api/system/license 响应

{
  "company": "某某科技有限公司",
  "edition": "enterprise",
  "machineFingerprint": "FP-A1B2C3D4E5F67890...",
  "expiresAt": "2027-01-01T00:00:00Z",
  "activatedAt": "2026-01-01T00:00:00Z",
  "status": "active"
}

GET /api/system/fingerprint 响应

{
  "fingerprint": "FP-A1B2C3D4E5F67890..."
}

说明:已激活后,用户可在「系统设置 → 机器指纹」页面查看当前指纹,用于迁移服务器时提供给运营方。

3.3 初始化前端页面(主应用 Vue 3 前端)

初始化页面属于主应用的 ecom-dmb-frontend,在路由守卫中检测初始化状态。

src/views/init/
├── InitWizard.vue              # 初始化向导容器(Step 步骤条)
├── InitStepAdmin.vue           # Step 1: 创建管理员
├── InitStepCompany.vue         # Step 2: 公司信息
├── InitStepLicense.vue         # Step 3: License 激活(显示指纹 + 输入 License)
└── components/
    └── FingerprintDisplay.vue  # 机器指纹展示组件(带复制功能)

src/views/system/
└── license/                    # ← 新增:系统设置下的 License 相关页面
    ├── LicenseInfo.vue         # License 信息查看 + 续期
    └── FingerprintInfo.vue     # 机器指纹查看(用于迁移服务器)

路由守卫逻辑:

// router/index.ts
router.beforeEach(async (to) => {
  if (to.path.startsWith('/init')) return true

  const initStatus = await initApi.getStatus()
  if (!initStatus.initialized) {
    return '/init'
  }
  return true
})

3.4 主应用数据库设计

新增两张表:

sys_init 初始化状态表

字段 类型 说明
id bigint PK 主键(固定为 1,仅一行)
step tinyint 当前完成步骤:0=未开始 1=管理员 2=公司 3=已完成
admin_id bigint 创建的超级管理员 ID
company_name varchar(200) 公司名称
created_at datetime 创建时间
updated_at datetime 更新时间

该表为单行表,id 固定为 1,通过 INSERT ... ON DUPLICATE KEY UPDATE 或先删后插保证唯一性。

sys_license License 表(单行数据)

字段 类型 说明
id bigint PK 主键
company_name varchar(200) License 中的公司名称
edition varchar(20) 版本:trial / enterprise / unlimited
machine_fingerprint varchar(100) 绑定的机器指纹
installation_id varchar(64) 安装 ID(首次运行时生成)
license_key text JWT License Token
issued_at datetime 签发时间
expires_at datetime 过期时间
activated_at datetime 激活时间
is_active tinyint 是否有效 0=否 1=是
created_at datetime 创建时间
updated_at datetime 更新时间

4. 机器指纹设计

4.1 指纹生成策略

机器指纹用于将 License 绑定到特定的部署实例,防止 License 被复制到其他机器使用。

采用系统 machine-id + 主机名方案:

要素 来源 说明
系统 machine-id Linux /etc/machine-id systemd 在首次启动时自动生成,不同 OS 安装不同;非 Linux 系统回退到随机 UUID
主机名 InetAddress.getLocalHost().getHostName() 辅助指纹,方便识别

为什么用 /etc/machine-id 而不是自定义 UUID 文件?

攻击场景 自定义 UUID 文件 系统 /etc/machine-id
拷贝 DB + 配置文件到新机器 随文件一起复制,指纹校验通过 ❌ 新机器有独立 machine-id,校验失败 ✅
整盘克隆(dd) machine-id 被一并克隆,防不住 同左,整盘克隆不在防护范围
云镜像创建新实例 镜像自带 UUID 文件,所有实例相同 ❌ 首次引导时 systemd 自动重新生成,每个实例不同 ✅

结论:使用系统 /etc/machine-id 能让大部分实际克隆场景(文件级别复制、云镜像复用)自动失效,且不需要引入额外组件。整盘克隆超出了客户端授权技术可防护的范围。

4.2 指纹算法

machineId = 读取 /etc/machine-id(不存在则生成 UUID 并写入 /etc/ecom-machine-id 回退)
raw = machineId + "|" + hostname
fingerprint = "FP-" + SHA256(raw).toUpperCase()

4.3 Java 指纹采集实现

public class MachineFingerprint {
    private static final String SYSTEM_MACHINE_ID = "/etc/machine-id";
    private static final String FALLBACK_FILE = "/etc/ecom-machine-id";

    public static String generate() {
        String machineId = getMachineId();
        String hostname = getHostname();
        String raw = machineId + "|" + hostname;
        String hash = DigestUtils.sha256Hex(raw);
        return "FP-" + hash.toUpperCase();
    }

    public static String getMachineId() {
        // 优先使用系统 machine-id
        File sysFile = new File(SYSTEM_MACHINE_ID);
        if (sysFile.exists()) {
            try {
                return new String(Files.readAllBytes(sysFile.toPath())).trim();
            } catch (IOException e) {
                // fall through
            }
        }
        // 回退到自定义 UUID 文件(非 Linux 系统 or 容器)
        File fallback = new File(FALLBACK_FILE);
        if (fallback.exists()) {
            try {
                return new String(Files.readAllBytes(fallback.toPath())).trim();
            } catch (IOException e) {
                // fall through
            }
        }
        // 首次运行:生成 UUID 写入回退文件
        String id = UUID.randomUUID().toString();
        try {
            Files.write(fallback.toPath(), id.getBytes());
        } catch (IOException e) {
            log.warn("无法写入 machine-id 文件: {}", e.getMessage());
        }
        return id;
    }
}

4.4 指纹在 License 中的作用

  • License 签发时:运营方将客户提供的机器指纹写入 JWT Payload 的 machineFingerprint 字段
  • License 验证时:主应用计算当前机器指纹,与 JWT 中的指纹比对,不一致则拒绝
  • SaaS 模式:指纹设为 *,跳过比对

5. License 文件格式

采用 RS256 签名的 JWT 作为 License 载体。

5.1 JWT Payload 结构

{
  "sub": "CUST-20260101-001",
  "company": "某某科技有限公司",
  "machineFingerprint": "FP-A1B2C3D4E5F67890123456789ABCDEF0",
  "edition": "enterprise",
  "issuedAt": "2026-01-01T00:00:00Z",
  "expiresAt": "2027-01-01T00:00:00Z",
  "features": ["order-import"],
  "jti": "LIC-AABBCCDD-001",
  "iss": "ecom-license-server",
  "iat": 1767225600,
  "exp": 1798761600
}

5.2 字段说明

字段 必填 说明
sub 是 客户编号
company 是 客户公司名称
machineFingerprint 是 绑定的机器指纹(FP- 前缀 + SHA256 大写)
edition 是 版本类型:trial / enterprise / unlimited
expiresAt 是 过期时间
features 是 授权功能列表(目前只有 order-import)
jti 是 License 唯一编号
iss 是 签发者
iat 是 签发时间戳
exp 是 过期时间戳
issuedAt 否 签发时间(可读格式)

5.3 License JWT 的存储与加载机制

存储方式

License JWT 支持三种来源,按优先级从高到低:

优先级 来源 说明
1(最高) 数据库 sys_license.license_key 初始化/激活时写入,运行时持久化
2 环境变量 ECOM_LICENSE_KEY 容器/Docker 部署时注入,覆盖数据库
3 文件 config/license.key 文件挂载,仅首次启动或备用兜底

完整的 License 存储与生命周期

┌──────────────────────────────────────────────────────────┐
│                   License JWT 在哪里                        │
│                                                           │
│  ┌──────────────┐    ┌──────────────┐   ┌──────────────┐ │
│  │ 环境变量       │    │ 文件          │   │ 数据库        │ │
│  │ ECOM_LICENSE  │    │ config/      │   │ sys_license  │ │
│  │ _KEY          │    │ license.key  │   │ .license_key │ │
│  └──────┬───────┘    └──────┬───────┘   └──────┬───────┘ │
│         │                   │                   │          │
│         └───────────┬───────┘                   │          │
│                     │                           │          │
│                     ▼                           │          │
│           ┌─────────────────┐                   │          │
│           │ 启动时加载到内存  │───────────────────┘          │
│           │ (LicenseHolder) │  写入(激活/更新时)           │
│           │                 │                               │
│           │ LicenseInfo:    │                               │
│           │  · jwtToken     │                               │
│           │  · company      │                               │
│           │  · edition      │                               │
│           │  · expiresAt    │                               │
│           │  · fingerprint  │                               │
│           └────────┬────────┘                               │
│                    │                                         │
│                    ▼ 每次请求只读内存,不读文件不查库             │
│           ┌─────────────────┐                               │
│           │ AOP 切面校验     │                               │
│           │ · 是否过期       │                               │
│           │ · 指纹是否匹配   │                               │
│           └─────────────────┘                               │
└──────────────────────────────────────────────────────────┘

首次部署 vs 运行时

阶段 License 来源 说明
首次启动(未初始化) 环境变量或文件 初始化前数据库无数据,从环境变量或文件读取,用于预激活
激活后 数据库 激活时将 License 写入 sys_license 表,此后任何来源都不再读取
License 更新 数据库 用户在系统设置页面上传新 License → 更新 sys_license 表 → 刷新内存缓存
容器重启 数据库 启动时重新从数据库加载到内存

关键原则

  • 启动时一次加载:Spring @PostConstruct / ApplicationRunner 中加载 License 到内存,后续请求不读文件、不查 DB
  • 运行时内存缓存:LicenseValidator 是 Spring 单例 Bean,持有 LicenseInfo 对象,每次请求直接从内存判断
  • 更新时刷新:License 更新/续期时,同时更新 DB 和内存缓存

6. License 服务器 API 设计

6.1 认证

方法 路径 说明
POST /api/auth/login 管理员登录,返回 JWT Token
POST /api/auth/logout 退出登录

6.2 仪表盘

方法 路径 说明
GET /api/dashboard/stats 统计数据(客户数、许可证数、即将过期数)

6.3 客户管理

方法 路径 说明
GET /api/customers 客户列表(分页)
POST /api/customers 创建客户
GET /api/customers/:id 客户详情
PUT /api/customers/:id 更新客户
DELETE /api/customers/:id 删除客户
GET /api/customers/:id/licenses 客户的许可证列表

6.4 许可证管理

方法 路径 说明
GET /api/licenses 许可证列表(分页)
GET /api/licenses/:id 许可证详情
POST /api/licenses/generate 签发新 License(核心接口)
POST /api/licenses/:id/revoke 吊销 License
GET /api/licenses/:id/download 下载 License 文件

6.5 签发 License 接口

请求 POST /api/licenses/generate:

{
  "customerId": 1,
  "company": "某某科技有限公司",
  "machineFingerprint": "FP-A1B2C3D4E5F67890...",
  "edition": "enterprise",
  "expiresAt": "2027-01-01T00:00:00Z",
  "features": ["order-import"]
}

响应:

{
  "id": 1,
  "licenseKey": "eyJhbGciOiJSUzI1NiJ9...(JWT Token)",
  "edition": "enterprise",
  "machineFingerprint": "FP-A1B2C3D4E5F67890...",
  "expiresAt": "2027-01-01T00:00:00Z",
  "status": "active"
}

7. License 服务器数据库设计

7.1 管理员表 lc_admin

字段 类型 说明
id bigint PK 主键
username varchar(50) 用户名
password varchar(255) BCrypt 加密密码
nickname varchar(50) 昵称
status tinyint 状态:0=禁用 1=启用
created_at datetime 创建时间
updated_at datetime 更新时间

7.2 客户表 lc_customer

字段 类型 说明
id bigint PK 主键
code varchar(50) UK 客户编码(如 CUST-20260101-001)
name varchar(200) 公司名称
contact_name varchar(50) 联系人
contact_phone varchar(20) 联系电话
contact_email varchar(100) 联系邮箱
status tinyint 状态:0=禁用 1=启用
remark text 备注
created_at datetime 创建时间
updated_at datetime 更新时间

7.3 许可证表 lc_license

字段 类型 说明
id bigint PK 主键
customer_id bigint FK 关联客户 ID
license_key text JWT License Token
edition varchar(20) 版本:trial / enterprise / unlimited
machine_fingerprint varchar(100) 绑定的机器指纹
features varchar(500) 功能特性列表(JSON 数组)
status varchar(20) 状态:active / revoked / expired
issued_at datetime 签发时间
expires_at datetime 过期时间
revoked_at datetime 吊销时间(可空)
max_activations int 允许的最大激活次数(null 为不限)
activation_count int 当前已激活次数
created_at datetime 创建时间
updated_at datetime 更新时间

7.4 激活日志表 lc_activation_log

字段 类型 说明
id bigint PK 主键
license_id bigint FK 关联许可证 ID
machine_fingerprint varchar(100) 激活时的机器指纹
installation_id varchar(64) 激活时的安装 ID
hostname varchar(200) 激活时的机器主机名
ip varchar(50) 请求 IP
action varchar(20) 动作:activate / deactivate
created_at datetime 创建时间

7.5 操作日志表 lc_oper_log

字段 类型 说明
id bigint PK 主键
admin_id bigint 操作管理员 ID
action varchar(50) 操作类型
target_type varchar(50) 操作对象类型(customer / license)
target_id bigint 操作对象 ID
detail text 操作详情(JSON)
ip varchar(50) 请求 IP
created_at datetime 创建时间

8. 主应用 License 校验设计(Spring Boot)

8.1 新增模块结构

ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/
└── modules/
    └── license/
        ├── LicenseAutoConfig.java           # 自动配置
        ├── LicenseProperties.java           # 配置属性(public-key, license-key, license-file)
        ├── LicenseValidator.java            # 核心:加载、缓存、校验 License(Spring 单例)
        ├── LicenseAspect.java               # AOP 切面(拦截导入接口)
        ├── LicenseRequired.java             # 注解定义
        ├── LicenseInfo.java                 # License 解析结果(内存缓存对象)
        ├── InitializeService.java           # 初始化服务(创建管理员 + 公司 + 激活)
        ├── MachineFingerprintUtil.java      # 机器指纹生成工具
        ├── entity/
        │   ├── SysInit.java                 # 初始化状态实体
        │   └── SysLicense.java              # License 实体
        ├── mapper/
        │   ├── SysInitMapper.java
        │   └── SysLicenseMapper.java
        ├── controller/
        │   └── InitController.java          # 初始化 API
        └── exception/
            └── LicenseException.java

8.2 License 校验流程(运行时的每次请求)

请求到达导入接口(/batch-import 或 /import-task/create)
       │
       ▼
┌──────────────────────────────────────┐
│ LicenseAspect 拦截 @LicenseRequired  │
└──────────┬───────────────────────────┘
           ▼
┌──────────────────────────────────────┐
│ 1. 从内存缓存读取 LicenseInfo        │  ← 仅读内存,不读文件/不查库
│    (启动时已加载完毕)                │
└──────────┬───────────────────────────┘
           ▼
┌──────────────────────────────────────┐
│ 2. 是否有 LicenseInfo ?             │──── 无 ──▶ 拒绝(未激活)
└──────────┬───────────────────────────┘
           ▼ 有
┌──────────────────────────────────────┐
│ 3. 校验有效期(exp)                  │──── 过期 ──▶ 拒绝
│    与当前服务器时间比对                │
└──────────┬───────────────────────────┘
           ▼ 有效
┌──────────────────────────────────────┐
│ 4. 校验机器指纹                       │──── 不匹配 ──▶ 拒绝
│    (LicenseInfo.fingerprint          │
│     vs MachineFingerprintUtil.generate())│
└──────────┬───────────────────────────┘
           ▼ 匹配
┌──────────────────────────────────────┐
│ 5. 校验吊销列表(内存黑名单 jti)     │──── 已吊销 ──▶ 拒绝
└──────────┬───────────────────────────┘
           ▼ 未吊销
┌──────────────────────────────────────┐
│ 6. 放行请求                           │
│    执行导入                           │
└──────────────────────────────────────┘

注意:

  • RSA 验签只在首次加载时做一次,运行时请求直接比对内存中的 LicenseInfo 字段
  • NTP 时间偏差校验不在此链路中执行,改为启动时 + 定时任务(见 8.6 节)
  • 本地吊销黑名单在启动时加载到内存,运行时只读匹配,不产生 I/O

8.3 配置项 application.yml

ecom:
  license:
    enabled: true                        # 是否启用 license 校验
    public-key: |                        # RSA 公钥
      -----BEGIN PUBLIC KEY-----
      MIIBIjANBgkqhkiG9w0BAQEFAAOC...
      -----END PUBLIC KEY-----
    license-key: ""                      # License JWT(优先于文件)
    license-file: config/license.key     # License 文件路径
    max-clock-skew: 5                    # 与 NTP 最大时钟偏差(分钟),超时拒绝
    ntp-server: "pool.ntp.org"           # NTP 时间源,用于校验本地时间是否被篡改
    ntp-check-interval: 10               # NTP 定时检测间隔(分钟),启动时立即检查一次
    revocation-file: config/revoked.jti  # 吊销黑名单文件路径(每行一个 jti)

注意:@Scheduled 定时任务需要在某个 @Configuration 类上添加 @EnableScheduling 注解。建议在 LicenseAutoConfig 上配置。

8.4 AOP 注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LicenseRequired {
    /**
     * 是否校验机器指纹(默认 true)
     */
    boolean checkFingerprint() default true;
}

// 使用方式
@PostMapping("/batch-import")
@RequirePermission("ecom:order:import")
@LicenseRequired
public ApiResponse<BatchImportResultVO> batchImportOrders(...) { ... }

@PostMapping("/create")
@RequirePermission("data:import")
@LicenseRequired
public ApiResponse<ImportTaskVO> createImportTask(...) { ... }

8.5 License JWT 验证逻辑

/**
 * License 验证器(Spring 单例,启动时加载,运行时只读内存)
 */
@Component
public class LicenseValidator {

    private final PublicKey publicKey;
    private final SysLicenseMapper licenseMapper;
    private final LicenseProperties properties;

    /**
     * 内存缓存的 License 信息
     */
    private volatile LicenseInfo cachedLicense;

    /**
     * 吊销列表黑名单(jti 集合)
     */
    private final Set<String> revokedJtiSet = new ConcurrentHashSet<>();

    /**
     * NTP 时间偏差缓存(毫秒)
     */
    private volatile long clockSkewMs = 0;

    /**
     * 上次 NTP 检测时间
     */
    private volatile long lastNtpCheck = 0;

    public LicenseValidator(LicenseProperties props, SysLicenseMapper licenseMapper) throws Exception {
        this.licenseMapper = licenseMapper;
        this.properties = props;
        this.publicKey = loadPublicKey(props.getPublicKey());
        this.cachedLicense = null;
    }

    /**
     * 启动时加载 License + 吊销列表
     */
    @PostConstruct
    public void init() {
        loadLicense();
        loadRevocationList();
        checkSystemClock();
    }

    /**
     * 定时检测 NTP 时间偏差(每 ntpCheckInterval 分钟执行一次)
     */
    @Scheduled(fixedDelayString = "#{@licenseProperties.ntpCheckInterval * 60 * 1000}")
    public void scheduledNtpCheck() {
        checkSystemClock();
    }

    /**
     * 启动时加载 License(@PostConstruct 或 ApplicationRunner 调用)
     * 依次尝试:数据库 → 环境变量 → 文件
     */
    public void loadLicense() {
        String jwtToken = null;

        // 1. 尝试数据库
        SysLicense sysLicense = licenseMapper.selectOne(new LambdaQueryWrapper<>());
        if (sysLicense != null) {
            jwtToken = sysLicense.getLicenseKey();
        }

        // 2. 尝试环境变量
        if (jwtToken == null) {
            jwtToken = System.getenv("ECOM_LICENSE_KEY");
        }

        // 3. 尝试文件
        if (jwtToken == null) {
            jwtToken = readLicenseFile("config/license.key");
        }

        if (jwtToken != null) {
            String fingerprint = MachineFingerprintUtil.generate();
            this.cachedLicense = fullValidate(jwtToken, fingerprint);
        }
    }

    /**
     * 加载吊销列表黑名单(文件 → 内存)
     */
    private void loadRevocationList() {
        String path = properties.getRevocationFile();
        if (path == null || path.isEmpty()) return;
        File file = new File(path);
        if (!file.exists()) return;
        try {
            Files.readAllLines(file.toPath()).stream()
                .map(String::trim)
                .filter(l -> !l.isEmpty() && !l.startsWith("#"))
                .forEach(revokedJtiSet::add);
            log.info("已加载 {} 个吊销 JTI", revokedJtiSet.size());
        } catch (IOException e) {
            log.warn("吊销列表加载失败: {}", e.getMessage());
        }
    }

    /**
     * 运行时校验:直接从内存判断,不做任何 I/O
     */
    public void check() {
        LicenseInfo license = this.cachedLicense;
        if (license == null) {
            throw new LicenseException("系统未激活,请先完成 License 激活");
        }
        if (license.getExpiresAt().before(new Date())) {
            throw new LicenseException("License 已过期");
        }

        // 指纹比对:除非 License 中指纹为 "*"(不限),否则必须匹配
        if (!"*".equals(license.getMachineFingerprint())) {
            String currentFp = MachineFingerprintUtil.generate();
            if (!license.getMachineFingerprint().equals(currentFp)) {
                throw new LicenseException("License 与当前服务器不匹配");
            }
        }

        // 吊销检查
        if (license.getJti() != null && revokedJtiSet.contains(license.getJti())) {
            throw new LicenseException("此 License 已被吊销");
        }
    }

    /**
     * NTP 时间偏差检测(启动时 + 定时任务,不进请求链路)
     */
    private void checkSystemClock() {
        int maxSkew = properties.getMaxClockSkew();
        if (maxSkew <= 0) return;

        try {
            InetAddress addr = InetAddress.getByName(properties.getNtpServer());
            NtpUdpClient client = new NtpUdpClient();
            TimeInfo info = client.getTime(addr);
            long ntpTime = info.getMessage().getTransmitTimeStamp().getTime();
            long localTime = System.currentTimeMillis();
            long diff = Math.abs(ntpTime - localTime);
            this.clockSkewMs = diff;
            this.lastNtpCheck = System.currentTimeMillis();

            if (diff > TimeUnit.MINUTES.toMillis(maxSkew)) {
                log.error("系统时间异常(与标准时间偏差 {} 秒)", diff / 1000);
            }
        } catch (Exception e) {
            log.warn("NTP 时间校验失败,跳过: {}", e.getMessage());
        }
    }

    /**
     * 全量验证(包括 RSA 验签),仅在加载/激活/更新时调用
     */
    public LicenseInfo fullValidate(String jwtToken, String currentFingerprint) {
        Jwt<JwsHeader, Claims> jwt = Jwts.parser()
            .verifyWith(publicKey)
            .build()
            .parseSignedClaims(jwtToken);

        Claims claims = jwt.getPayload();

        Date exp = claims.getExpiration();
        if (exp.before(new Date())) {
            throw new LicenseException("License 已过期");
        }

        String fp = claims.get("machineFingerprint", String.class);
        // 指纹为 "*" 表示不限制(SaaS 模式),或必须与当前指纹匹配
        if (!"*".equals(fp) && !fp.equals(currentFingerprint)) {
            throw new LicenseException("License 与当前服务器不匹配");
        }

        return LicenseInfo.builder()
            .company(claims.get("company", String.class))
            .edition(claims.get("edition", String.class))
            .machineFingerprint(fp)
            .expiresAt(exp)
            .features(claims.get("features", List.class))
            .jti(claims.getId())                        // jti 用于吊销
            .installationId(claims.get("installationId", String.class))
            .jwtToken(jwtToken)
            .build();
    }

    /**
     * 激活时写入 License(初始化/续期时调用)
     */
    public void activate(String jwtToken) {
        String fingerprint = MachineFingerprintUtil.generate();
        LicenseInfo info = fullValidate(jwtToken, fingerprint);

        // 写入数据库
        SysLicense entity = new SysLicense();
        entity.setLicenseKey(jwtToken);
        entity.setCompanyName(info.getCompany());
        entity.setEdition(info.getEdition());
        entity.setMachineFingerprint(fingerprint);
        entity.setInstallationId(MachineFingerprintUtil.getMachineId());
        entity.setExpiresAt(info.getExpiresAt());
        entity.setActivatedAt(new Date());
        entity.setIsActive(1);
        licenseMapper.insertOrUpdate(entity);

        // 刷新内存缓存
        this.cachedLicense = info;
    }

    /**
     * 刷新内存缓存(外部更新 License 后调用)
     */
    public void refresh() {
        loadLicense();
    }
}

8.6 LicenseValidator 生命周期

时机 行为 是否做 I/O
应用启动 @PostConstruct 按优先级(DB→环境变量→文件)加载 JWT,RSA 验签 + 指纹比对,写入内存缓存;加载吊销黑名单文件;触发首次 NTP 时间检测 是(读 DB / 文件 + NTP)
定时任务 @Scheduled 每隔 ntp-check-interval 分钟执行一次 NTP 时间检测,更新 clockSkewMs 缓存;偏差超阈值时记录错误日志(不拒绝请求) 是(NTP 网络请求,不进请求链路)
每次导入请求 check() 从内存读 cachedLicense,比对有效期 + 指纹(* 时跳过) + 吊销黑名单,不做 NTP 请求 否
初始化激活 activate() RSA 验签 + 指纹比对,写入 DB(含 installationId)+ 刷新内存缓存 是(写 DB)
License 续期/更新 PUT /api/system/license 同 activate(),但已激活状态下不重置初始化步骤 是(写 DB)
查看 License 信息 GET /api/system/license 从内存缓存读取,无需解密 否

核心原则:

  • RSA 非对称验签是 CPU 密集型操作,只在加载时做一次;运行时校验仅做内存中的有效期和指纹比对,零开销
  • NTP 时间检测不进请求链路,避免网络 I/O 拖慢接口响应

8.7 AOP 切面实现

@Aspect
@Component
public class LicenseAspect {

    private final LicenseValidator licenseValidator;

    public LicenseAspect(LicenseValidator licenseValidator) {
        this.licenseValidator = licenseValidator;
    }

    @Around("@annotation(licenseRequired)")
    public Object checkLicense(ProceedingJoinPoint joinPoint, LicenseRequired licenseRequired) throws Throwable {
        // 直接调用 check() — 只读内存,不做 I/O
        licenseValidator.check();
        return joinPoint.proceed();
    }
}

9. 技术选型

9.1 License 服务器

层 技术 说明
后端框架 NestJS 渐进式 Node.js 后端,模块化架构
语言 TypeScript 类型安全
数据库 MySQL 8.0 与主应用保持一致
ORM TypeORM NestJS 生态,与 MySQL 配合
认证 Passport + JWT 管理后台登录
JWT 签名 node-rsa / jsonwebtoken RS256 算法

9.2 License 管理后台

层 技术 说明
框架 Vue 3 Composition API
UI 库 Ant Design Vue 与主应用前端保持一致
构建 Vite 快速构建
路由 Vue Router 4 前端路由
状态 Pinia 状态管理
HTTP Axios HTTP 请求

9.3 主应用 License 模块

层 技术 说明
签名验证 jjwt (0.11.5) 已经引入,用于 JWT 验签
机器指纹 Java 原生 API(/etc/machine-id / Hostname) 系统 machine-id + 主机名,不依赖硬件
切面 Spring AOP 已有依赖
NTP 检测 Apache Commons Net (NtpUdpClient) 轻量 NTP 客户端

10. 项目结构

ecom-license/                          # ⚠ 新建目录:License 授权管理平台
├── DESIGN.md                          # 本设计文档
├── docker-compose.yml                 # Docker 编排
├── .env.example                       # 环境变量模板
│
├── server/                            # NestJS 后端 ← 新建
│   ├── src/
│   │   ├── main.ts
│   │   ├── app.module.ts
│   │   ├── common/
│   │   │   ├── guards/                # JWT 认证守卫
│   │   │   ├── filters/               # 异常过滤器
│   │   │   └── utils/
│   │   ├── modules/
│   │   │   ├── auth/
│   │   │   ├── customer/
│   │   │   ├── license/               # 签发 RSA 签名的 JWT License
│   │   │   ├── dashboard/
│   │   │   └── oper-log/
│   │   └── config/
│   ├── keys/                          # RSA 密钥对(生产需妥善保管)
│   │   ├── private.pem
│   │   └── public.pem
│   ├── package.json
│   ├── tsconfig.json
│   └── nest-cli.json
│
└── admin/                             # Vue 3 + Ant Design Vue 管理后台 ← 新建
    ├── src/
    │   ├── main.ts
    │   ├── App.vue
    │   ├── router/index.ts
    │   ├── stores/ (auth, app)
    │   ├── api/ (auth, customer, license)
    │   ├── views/
    │   │   ├── login/
    │   │   ├── dashboard/
    │   │   ├── customer/
    │   │   └── license/
    │   └── components/
    ├── package.json
    ├── vite.config.ts
    └── tsconfig.json

以下为现有项目中需新增或修改的部分:

ecom-dmb-backend/                      # 主应用后端(已有)
└── src/main/java/top/xyquan/ecomdmbbackend/
    └── modules/
        └── license/                   # ← 新增:License 校验 + 初始化模块
            ├── LicenseValidator.java
            ├── LicenseAspect.java
            ├── LicenseRequired.java
            ├── LicenseProperties.java
            ├── InitializeService.java
            ├── MachineFingerprintUtil.java
            ├── entity/
            ├── mapper/
            ├── controller/
            │   └── InitController.java
            └── exception/

ecom-dmb-frontend/                     # 主应用前端(已有)
└── apps/web-antd/src/
    ├── views/
    │   ├── init/                      # ← 新增:初始化向导页面
    │   │   ├── InitWizard.vue
    │   │   ├── InitStepAdmin.vue
    │   │   ├── InitStepCompany.vue
    │   │   └── InitStepLicense.vue
    │   └── system/
    │       └── license/               # ← 新增:系统设置
    │           ├── LicenseInfo.vue    #   License 信息查看 + 续期
    │           └── FingerprintInfo.vue #   机器指纹查看

11. RSA 密钥管理

11.1 密钥对生成

# 生成私钥(2048位)
openssl genrsa -out private.pem 2048

# 导出公钥
openssl rsa -in private.pem -pubout -out public.pem

11.2 密钥分发

License 服务器                         Ecom-DMB 主应用
┌─────────────────┐                   ┌────────────────────┐
│  私钥 private.pem│                   │  公钥 public.pem    │
│  (签名 License)  │                   │  (验签 JWT)         │
│                  │                   │                     │
│  JWT = sign(     │                   │  claims = verify(   │
│    payload,      │ ──License JWT──▶ │   jwt, publicKey)   │
│    privateKey)   │                   │                     │
└─────────────────┘                   │  check:              │
                                      │   · 签名有效          │
                                      │   · 未过期            │
                                      │   · 指纹匹配          │
                                      └────────────────────┘
  • 私钥:仅 License 服务器持有,用于签发 License
  • 公钥:内置在 Ecom-DMB 主应用的 application.yml 或编译进代码
  • 公钥原则上不应该让客户随意修改,建议编译在代码中或通过配置文件管理并签名保护

11.3 密钥轮换

密钥泄露或定期轮换时,需要让已部署的系统能使用新公钥验证 License。方案如下:

方案 说明 适用场景
多公钥列表 修改 LicenseProperties 支持多个公钥,验证时逐个尝试 简单可靠,推荐
kid 标头 JWT Header 中携带 kid 标识密钥版本,主应用根据 kid 选择对应公钥 更规范,实现略复杂

推荐采用多公钥列表方案:

ecom:
  license:
    public-keys:
      - id: "2025-v1"
        key: |
          -----BEGIN PUBLIC KEY-----
          MIIBIjANBgkqhkiG9w0BAQEFAAOC...
          -----END PUBLIC KEY-----
      - id: "2026-v2"
        key: |
          -----BEGIN PUBLIC KEY-----
          ...
          -----END PUBLIC KEY-----

轮换流程:

  1. License 服务器用新私钥签发 License(JWT Header 携带 kid)
  2. 主应用发布新版本时内置新旧两个公钥,旧 License 依然可验证
  3. 所有客户续期后,后续版本可移除旧公钥

12. 典型场景流程

12.1 场景一:新客户私有部署(离线)

客户方                                         运营方
───                                           ───
1. 部署 Ecom-DMB
2. 访问系统 → 跳转初始化页面
3. 创建管理员账号
4. 填写公司信息
5. 页面显示机器指纹:FP-A1B2C3...
   ──────────────────────────────────────────▶  6. 收到客户提供的机器指纹
                                                 7. 登录 License 后台
                                                 8. 创建客户资料
                                                 9. 在后台填写机器指纹并签发 License
                                                 10. 下载 License 文件 / 复制 License Key
   ◀────────────────────────────────────────── 11. 将 License Key 发给客户
12. 粘贴 License Key 并点击激活
13. 系统校验通过 → 初始化完成
14. 进入系统,正常使用

12.2 场景二:SaaS 部署

运营方内部流程
───
1. 部署 Ecom-DMB(SaaS 环境)
2. 初始化系统,绑定 SaaS 服务器机器指纹
3. 在 License 后台为每个租户签发 License
4. 新租户注册时,系统自动或手动分配 License
5. 每个租户导入订单时校验所属 License 是否有效

12.3 场景三:License 续期

1. 客户联系运营方续期
2. 运营方在 License 后台找到该客户
3. 用相同的机器指纹签发新 License(更新有效期)
4. 将新的 License Key 发给客户
5. 客户在「系统设置 → License」页面更新 License
6. 系统校验通过,完成续期

12.4 场景四:迁移服务器

1. 客户需要将系统迁移到新服务器
2. 在新服务器上部署 Ecom-DMB
3. 进入初始化页面,获取新服务器的机器指纹(安装 ID + 主机名)
4. 将新指纹发给运营方
5. 运营方吊销旧 License(将旧 JWT 的 jti 加入黑名单),用新指纹签发新 License
6. 客户激活 → 迁移完成
7. 旧服务器的下次请求会因指纹不匹配或 jti 已吊销而失效

13. SaaS 与私有部署的差异点

维度 私有部署 SaaS 部署
部署方 客户 运营方
License 来源 运营方签发后客户手动激活 运营方直接签发并配置
机器指纹 客户服务器的安装 ID + 主机名,严格绑定 License 中指纹填 *,跳过指纹校验
初始化流程 客户自行完成初始化向导 运营方部署时完成初始化
License 更新 客户手动更新 License 运营方在后台更新或自动下发
地址限制 绑定一台服务器 不限服务器

14. 安全注意事项

  1. RSA 私钥保护:私钥是 License 体系的安全基础,必须严格保护,建议存储在 HSM 或密钥管理服务中
  2. 防回滚:License 过期后不能通过篡改系统时间来绕过——校验时使用绝对时间戳,对比服务器时间与 License exp
  3. 系统时间篡改防护:客户端修改系统时间可绕过有效期校验。解决方案:
    • 不进请求链路:NTP 时间偏差检测在启动时 + 定时任务(每 10 分钟)中执行,不阻塞业务请求
    • 偏差超阈值时记录错误日志并告警,不立即拒绝请求(避免 NTP 服务本身不可用导致系统不可用)
    • 管理员可通过系统设置查看 NTP 状态和最近检测结果
  4. 机器指纹绕过防护:指纹基于系统 /etc/machine-id + 主机名生成。/etc/machine-id 由 systemd 在首次启动时自动生成,不同 OS 安装互不相同。文件复制级别的克隆会自动失效(新系统有自己的 machine-id)。root 可伪造,但此时客户已拥有服务器全部权限,不在威胁模型内
  5. License 吊销机制:
    • 本地吊销:通过 config/revoked.jti 文件维护吊销列表(每行一个 jti),启动时加载到内存;运行时 check() 中 匹配内存黑名单,无 I/O 开销
    • 在线吊销(可选):如需强吊销,可在启动定时任务中请求 License 服务器 /api/license/status 接口查询当前 License 状态,将吊销的 jti 同步到本地黑名单
  6. 公钥轮换:参见 11.3 节,防止密钥泄露后无法更新
  7. 激活日志防滥用:License 服务器记录每次激活的 machine_fingerprint、installation_id、hostname、ip;可设置 max_activations 限制 License 的激活次数,防止同一个 License 在大量机器上激活
  8. License 复制防护:License JWT 中的 machineFingerprint 绑定到机器安装 ID,DB 复制到另一台机器后指纹不匹配; installationId 记录在激活日志中,便于审计追溯

15. 后续可扩展

  • 在线激活:初始化时直接输入激活码,主应用自动请求 License 服务器完成激活
  • 批量部署:支持预生成 License,客户部署时自动激活(静默安装)
  • License 监控:License 即将过期时在系统内推送通知
  • 多服务器:支持集群部署的 License 校验(允许同一客户的多台服务器共享一个 License)
  • 分级权限:License 后台支持多级管理员