feat: 新增license

This commit is contained in:
小蟑螂
2026-07-06 19:34:53 +08:00
parent 8a6cb23c07
commit ac890dcc5c
110 changed files with 10678 additions and 1368 deletions
@@ -46,6 +46,7 @@ public class SecurityConfig {
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/login", "/auth/register", "/auth/refresh").permitAll()
.requestMatchers("/init/**").permitAll()
.requestMatchers("/uploads/**").permitAll() // 允许直接访问上传的文件
.requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**",
"/swagger-ui/**", "/swagger-ui.html")
@@ -11,6 +11,7 @@ import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.license.LicenseException;
import java.util.stream.Collectors;
@@ -20,6 +21,15 @@ import java.util.stream.Collectors;
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理 License 授权异常
*/
@ExceptionHandler(LicenseException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public ApiResponse<String> handleLicenseException(LicenseException e) {
return ApiResponse.fail(e.getMessage());
}
/**
* 处理业务异常
*/
@@ -22,6 +22,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.impl.PromotionFeeImportProcessor;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopProductRelationMapper;
import top.xyquan.ecomdmbbackend.modules.license.LicenseFeature;
import top.xyquan.ecomdmbbackend.modules.license.LicenseFeatureGuard;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.OssService;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileVO;
@@ -64,6 +66,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private final PromotionFeeImportProcessor promotionFeeImportProcessor;
private final OrderStatRefreshCoordinator orderStatRefreshCoordinator;
private final FeeStatRefreshService feeStatRefreshService;
private final LicenseFeatureGuard licenseFeatureGuard;
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
ProductSpecService productSpecService,
@@ -78,8 +81,10 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
SysFileService sysFileService,
PromotionFeeImportProcessor promotionFeeImportProcessor,
OrderStatRefreshCoordinator orderStatRefreshCoordinator,
FeeStatRefreshService feeStatRefreshService) {
FeeStatRefreshService feeStatRefreshService,
LicenseFeatureGuard licenseFeatureGuard) {
this.importTaskService = importTaskService;
this.licenseFeatureGuard = licenseFeatureGuard;
this.orderMapper = orderMapper;
this.sseNotificationService = sseNotificationService;
this.objectMapper = objectMapper;
@@ -107,6 +112,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask));
if ("order".equals(task.getType())) {
licenseFeatureGuard.require(LicenseFeature.ORDER_IMPORT);
processOrderImport(task);
} else if ("product".equals(task.getType())) {
updateTaskStatus(taskId, "failed", "商品导入功能暂未实现", 0, 0, 0);
@@ -20,6 +20,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskQueue
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskService;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.license.LicenseFeature;
import top.xyquan.ecomdmbbackend.modules.license.LicenseFeatureGuard;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDate;
@@ -39,13 +41,16 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
private final CurrentUserContext currentUserContext;
private final ImportTaskQueueService importTaskQueueService;
private final LicenseFeatureGuard licenseFeatureGuard;
public ImportTaskServiceImpl(CurrentUserContext currentUserContext,
ImportTaskQueueService importTaskQueueService,
ShopService shopService) {
ShopService shopService,
LicenseFeatureGuard licenseFeatureGuard) {
this.currentUserContext = currentUserContext;
this.importTaskQueueService = importTaskQueueService;
this.shopService = shopService;
this.licenseFeatureGuard = licenseFeatureGuard;
}
/**
@@ -57,6 +62,9 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
@Override
@Transactional
public ImportTaskVO createImportTask(CreateImportTaskDTO createImportTaskDTO) {
if ("order".equals(createImportTaskDTO.getType())) {
licenseFeatureGuard.require(LicenseFeature.ORDER_IMPORT);
}
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
Long currentUserId = currentUserContext.getCurrentUserId();
@@ -6,6 +6,8 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.modules.license.LicenseRequired;
import top.xyquan.ecomdmbbackend.modules.license.RequiresOrderCreateLicense;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
@@ -38,6 +40,7 @@ public class OrderController {
@Operation(summary = "创建订单", description = "创建新的订单")
@PostMapping("/create")
@RequiresOrderCreateLicense
@RequirePermission(value = "ecom:order:create", description = "创建订单", allowSuper = true)
public ApiResponse<OrderVO> createOrder(@Valid @RequestBody CreateOrderDTO createOrderDTO) {
OrderVO orderVO = orderService.createOrder(createOrderDTO);
@@ -90,6 +93,7 @@ public class OrderController {
@Operation(summary = "批量导入订单", description = "批量导入订单数据,支持部分成功部分失败")
@PostMapping("/batch-import")
@LicenseRequired
@RequirePermission(value = "ecom:order:import", description = "批量导入订单", allowSuper = true)
public ApiResponse<BatchImportResultVO> batchImportOrders(@Valid @RequestBody BatchImportOrderDTO batchImportOrderDTO) {
BatchImportResultVO result = orderService.batchImportOrders(batchImportOrderDTO);
@@ -33,6 +33,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatCrudCoordinator;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.license.LicenseFeature;
import top.xyquan.ecomdmbbackend.modules.license.LicenseFeatureGuard;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.ZoneId;
@@ -58,17 +60,20 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
private final ProductSpecService productSpecService;
private final OrderStatusService orderStatusService;
private final OrderStatCrudCoordinator orderStatCrudCoordinator;
private final LicenseFeatureGuard licenseFeatureGuard;
public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
ProductService productService, ProductSpecService productSpecService,
OrderStatusService orderStatusService,
OrderStatCrudCoordinator orderStatCrudCoordinator) {
OrderStatCrudCoordinator orderStatCrudCoordinator,
LicenseFeatureGuard licenseFeatureGuard) {
this.currentUserContext = currentUserContext;
this.shopService = shopService;
this.productService = productService;
this.productSpecService = productSpecService;
this.orderStatusService = orderStatusService;
this.orderStatCrudCoordinator = orderStatCrudCoordinator;
this.licenseFeatureGuard = licenseFeatureGuard;
}
/**
@@ -79,6 +84,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
@Override
@Transactional
public OrderVO createOrder(CreateOrderDTO createOrderDTO) {
licenseFeatureGuard.require(LicenseFeature.ORDER_CREATE);
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
@@ -375,6 +381,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
@Override
@Transactional
public BatchImportResultVO batchImportOrders(BatchImportOrderDTO batchImportOrderDTO) {
licenseFeatureGuard.require(LicenseFeature.ORDER_IMPORT);
List<CreateOrderDTO> orders = batchImportOrderDTO.getOrders();
List<OrderVO> successOrders = new ArrayList<>();
List<BatchImportResultVO.ImportFailureRecord> failureRecords = new ArrayList<>();
@@ -382,21 +389,23 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
int totalCount = orders.size();
int successCount = 0;
int failureCount = 0;
Long importCompanyId = currentUserContext.getCurrentCompanyId();
Long importUserId = currentUserContext.getCurrentUserId();
for (int i = 0; i < orders.size(); i++) {
CreateOrderDTO orderDTO = orders.get(i);
CreateOrderDTO rowOrder = orders.get(i);
int rowNumber = i + 1; // 行号从1开始
try {
// 尝试创建订单
OrderVO orderVO = createOrder(orderDTO);
// 批量导入走专用写入路径,授权已在方法入口校验 ORDER_IMPORT
OrderVO orderVO = this.createOrderForImport(rowOrder, importCompanyId, importUserId);
successOrders.add(orderVO);
successCount++;
} catch (Exception e) {
// 记录失败信息
BatchImportResultVO.ImportFailureRecord failureRecord = new BatchImportResultVO.ImportFailureRecord();
failureRecord.setRowNumber(rowNumber);
failureRecord.setPlatformOrderNo(orderDTO.getPlatformOrderNo());
failureRecord.setPlatformOrderNo(rowOrder.getPlatformOrderNo());
failureRecord.setFailureReason(e.getMessage());
failureRecords.add(failureRecord);
failureCount++;
@@ -0,0 +1,41 @@
package top.xyquan.ecomdmbbackend.modules.license;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* License 授权切面:拦截 @LicenseRequired 方法
*/
@Aspect
@Component
@Slf4j
public class LicenseAspect {
private final LicenseValidator licenseValidator;
public LicenseAspect(LicenseValidator licenseValidator) {
this.licenseValidator = licenseValidator;
}
@Around("@annotation(top.xyquan.ecomdmbbackend.modules.license.LicenseRequired)"
+ " || @annotation(top.xyquan.ecomdmbbackend.modules.license.RequiresOrderCreateLicense)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
if (!LicenseEnforcement.isEnforced()) {
return joinPoint.proceed();
}
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LicenseRequired annotation = AnnotatedElementUtils.findMergedAnnotation(method, LicenseRequired.class);
LicenseFeature feature = annotation != null ? annotation.value() : LicenseFeature.ORDER_IMPORT;
licenseValidator.check();
licenseValidator.requireFeature(feature);
return joinPoint.proceed();
}
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.license;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* License 模块自动配置
*/
@Configuration
@EnableConfigurationProperties(LicenseProperties.class)
public class LicenseAutoConfig {
}
@@ -0,0 +1,41 @@
package top.xyquan.ecomdmbbackend.modules.license;
/**
* License 信任锚与强制开关(编译期常量,不可通过配置文件或环境变量覆盖)。
* <p>
* 私有部署若允许通过 yml/env 修改开关或公钥,部署方可自签 License 从而绕过授权。
* 发行构建必须保持 {@link #ENFORCED} 为 {@code true},公钥与 License Server 私钥配对。
* <p>
* 本地开发需跳过 License 时:仅在本机临时将 {@link #ENFORCED} 改为 {@code false},勿提交。
*/
public final class LicenseEnforcement {
/**
* 发行包必须为 {@code true}。
* 本地调试可临时改为 {@code false}(勿提交)。
*/
private static final boolean ENFORCED = false;
/**
* Ed25519 验签公钥(SPKI PEM),与 ecom-license/server 签发私钥配对。
* 密钥轮换时需发新版主应用并同步更新 License Server 密钥对。
*/
private static final String EMBEDDED_PUBLIC_KEY_PEM = """
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAIB3yRtn+hCR/tXTUh1WA6ZFrpUha7WcBYLDWk2ZoTMc=
-----END PUBLIC KEY-----
""";
private LicenseEnforcement() {
}
/** 是否执行 License 校验(忽略一切外部配置) */
public static boolean isEnforced() {
return ENFORCED;
}
/** 内置验签公钥 PEM,不可通过配置文件替换 */
public static String getEmbeddedPublicKeyPem() {
return EMBEDDED_PUBLIC_KEY_PEM;
}
}
@@ -0,0 +1,33 @@
package top.xyquan.ecomdmbbackend.modules.license;
import lombok.Getter;
/**
* License 校验失败异常,由全局异常处理器返回 HTTP 403
*/
@Getter
public class LicenseException extends RuntimeException {
private final String errorCode;
public LicenseException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public static LicenseException invalid(String message) {
return new LicenseException("LICENSE_INVALID", message);
}
public static LicenseException fingerprintMismatch() {
return new LicenseException("LICENSE_FINGERPRINT_MISMATCH", "License 与当前机器指纹不匹配");
}
public static LicenseException featureDenied(LicenseFeature feature) {
return new LicenseException("LICENSE_FEATURE_DENIED", "未授权功能: " + feature.getCode());
}
public static LicenseException revoked() {
return new LicenseException("LICENSE_REVOKED", "License 已被吊销");
}
}
@@ -0,0 +1,22 @@
package top.xyquan.ecomdmbbackend.modules.license;
import lombok.Getter;
/**
* License 授权功能枚举
*/
@Getter
public enum LicenseFeature {
/** 订单批量/文件导入 */
ORDER_IMPORT("order-import"),
/** 手动创建单条订单 */
ORDER_CREATE("order-create");
private final String code;
LicenseFeature(String code) {
this.code = code;
}
}
@@ -0,0 +1,23 @@
package top.xyquan.ecomdmbbackend.modules.license;
import org.springframework.stereotype.Component;
/**
* Service 层功能门禁,防止绕过 Controller AOP 直接调用 Service
*/
@Component
public class LicenseFeatureGuard {
private final LicenseValidator licenseValidator;
public LicenseFeatureGuard(LicenseValidator licenseValidator) {
this.licenseValidator = licenseValidator;
}
public void require(LicenseFeature feature) {
if (!LicenseEnforcement.isEnforced()) {
return;
}
licenseValidator.requireFeature(feature);
}
}
@@ -0,0 +1,42 @@
package top.xyquan.ecomdmbbackend.modules.license;
import lombok.Builder;
import lombok.Data;
import java.time.Instant;
import java.util.List;
/**
* 解析并校验后的 License 内存模型
*/
@Data
@Builder
public class LicenseInfo {
private String subject;
private String companyName;
private String edition;
private String machineFingerprint;
private String installationId;
private String jti;
private String issuer;
private List<String> features;
private Instant issuedAt;
private Instant expiresAt;
private String rawLicenseKey;
/** 是否已过期 */
public boolean isExpired() {
return expiresAt != null && Instant.now().isAfter(expiresAt);
}
/** 是否包含指定功能 */
public boolean hasFeature(LicenseFeature feature) {
return features != null && features.contains(feature.getCode());
}
/** SaaS 模式:指纹为 * 时不校验硬件 */
public boolean isWildcardFingerprint() {
return "*".equals(machineFingerprint);
}
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.license;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* License 模块配置项,对应 application.yml 中 ecom.license.*
*/
@Data
@ConfigurationProperties(prefix = "ecom.license")
public class LicenseProperties {
/** 环境变量预置的 License JWT */
private String licenseKey = "";
/** License 文件路径 */
private String licenseFile = "config/license.key";
/** 本地吊销 jti 列表文件,每行一个 jti */
private String revocationFile = "config/revoked.jti";
/** 后台全量重验间隔(分钟) */
private int revalidateInterval = 10;
/** 是否启用在线吊销同步 */
private boolean onlineRevocationCheck = false;
/** License 服务器根地址,用于在线吊销查询 */
private String licenseServerUrl = "";
}
@@ -0,0 +1,17 @@
package top.xyquan.ecomdmbbackend.modules.license;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标注需要 License 授权才能访问的 Controller 方法
*/
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface LicenseRequired {
/** 需要的功能,默认订单导入 */
LicenseFeature value() default LicenseFeature.ORDER_IMPORT;
}
@@ -0,0 +1,366 @@
package top.xyquan.ecomdmbbackend.modules.license;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nimbusds.jose.crypto.Ed25519Verifier;
import com.nimbusds.jose.jwk.Curve;
import com.nimbusds.jose.jwk.OctetKeyPair;
import com.nimbusds.jose.util.Base64URL;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import top.xyquan.ecomdmbbackend.modules.license.mapper.SysLicenseMapper;
import top.xyquan.ecomdmbbackend.modules.license.model.po.SysLicensePO;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
/**
* License 验签、缓存与定时重验
*/
@Slf4j
@Component
public class LicenseValidator {
private static final String ISSUER = "ecom-license-server";
private final LicenseProperties properties;
private final SysLicenseMapper sysLicenseMapper;
private final RestTemplate restTemplate;
/** 内存缓存,请求链路零 I/O */
private final AtomicReference<LicenseInfo> cachedLicense = new AtomicReference<>();
/** 吊销 jti 黑名单 */
private volatile Set<String> revokedJtiSet = Collections.emptySet();
private volatile OctetKeyPair publicJwk;
public LicenseValidator(LicenseProperties properties,
SysLicenseMapper sysLicenseMapper) {
this.properties = properties;
this.sysLicenseMapper = sysLicenseMapper;
this.restTemplate = new RestTemplate();
}
@PostConstruct
public void init() {
loadEmbeddedPublicKey();
reloadRevokedJti();
if (LicenseEnforcement.isEnforced()) {
try {
fullValidate();
} catch (Exception e) {
log.warn("启动时 License 全量校验未通过: {}", e.getMessage());
cachedLicense.set(null);
}
}
}
/** 从源码内置公钥加载验签器,禁止通过配置文件替换 */
private void loadEmbeddedPublicKey() {
try {
this.publicJwk = parsePublicJwk(LicenseEnforcement.getEmbeddedPublicKeyPem());
} catch (Exception e) {
if (LicenseEnforcement.isEnforced()) {
throw new IllegalStateException("内置 License 公钥加载失败", e);
}
log.warn("内置 License 公钥加载失败(当前未强制校验): {}", e.getMessage());
}
}
/** 请求链路轻量校验(仅读内存) */
public void check() {
if (!LicenseEnforcement.isEnforced()) {
return;
}
LicenseInfo info = cachedLicense.get();
if (info == null) {
throw LicenseException.invalid("未激活 License 或 License 无效");
}
assertMemoryValid(info);
}
/** 校验并确保包含指定功能 */
public void requireFeature(LicenseFeature feature) {
if (!LicenseEnforcement.isEnforced()) {
return;
}
check();
LicenseInfo info = cachedLicense.get();
if (info != null && !info.hasFeature(feature)) {
throw LicenseException.featureDenied(feature);
}
}
/**
* 解析并全量校验 JWT(激活/续期时调用)
*/
public LicenseInfo parseAndValidate(String licenseKey) {
LicenseInfo info = parseJwt(licenseKey);
validateBusinessRules(info);
return info;
}
/** 后台全量重验:重新加载来源并验签 */
public synchronized void fullValidate() {
if (!LicenseEnforcement.isEnforced()) {
return;
}
reloadRevokedJti();
String licenseKey = resolveLicenseKey();
if (!StringUtils.hasText(licenseKey)) {
cachedLicense.set(null);
throw LicenseException.invalid("未找到 License");
}
LicenseInfo info = parseJwt(licenseKey.trim());
validateBusinessRules(info);
cachedLicense.set(info);
log.debug("License 全量校验通过, jti={}", info.getJti());
}
/** 激活后刷新内存缓存 */
public void refreshCache(LicenseInfo info) {
cachedLicense.set(info);
}
public LicenseInfo getCachedLicense() {
return cachedLicense.get();
}
/** 持久化 License 到数据库并刷新缓存 */
public void persistLicense(LicenseInfo info) {
// 旧记录全部置为无效
sysLicenseMapper.update(null, new LambdaUpdateWrapper<SysLicensePO>()
.set(SysLicensePO::getIsActive, 0));
SysLicensePO po = new SysLicensePO();
po.setCompanyName(info.getCompanyName());
po.setEdition(info.getEdition());
po.setMachineFingerprint(info.getMachineFingerprint());
po.setInstallationId(info.getInstallationId());
po.setLicenseKey(info.getRawLicenseKey());
po.setJti(info.getJti());
po.setIssuedAt(toLocalDateTime(info.getIssuedAt()));
po.setExpiresAt(toLocalDateTime(info.getExpiresAt()));
po.setActivatedAt(LocalDateTime.now());
po.setIsActive(1);
sysLicenseMapper.insert(po);
refreshCache(info);
}
@Scheduled(fixedDelayString = "#{${ecom.license.revalidate-interval:10} * 60 * 1000}")
public void scheduledRevalidate() {
if (!LicenseEnforcement.isEnforced()) {
return;
}
try {
fullValidate();
} catch (Exception e) {
log.warn("定时 License 重验失败,清空缓存: {}", e.getMessage());
cachedLicense.set(null);
}
}
@Scheduled(fixedDelay = 3600_000)
public void scheduledOnlineRevocationSync() {
if (!LicenseEnforcement.isEnforced() || !properties.isOnlineRevocationCheck()) {
return;
}
LicenseInfo info = cachedLicense.get();
if (info == null || !StringUtils.hasText(properties.getLicenseServerUrl())) {
return;
}
try {
String url = properties.getLicenseServerUrl().replaceAll("/$", "")
+ "/api/licenses/status?jti=" + info.getJti();
@SuppressWarnings("unchecked")
var body = restTemplate.getForObject(URI.create(url), java.util.Map.class);
if (body != null && "revoked".equals(String.valueOf(body.get("status")))) {
revokedJtiSet = new HashSet<>(revokedJtiSet);
revokedJtiSet.add(info.getJti());
cachedLicense.set(null);
log.warn("在线吊销同步:jti={} 已吊销", info.getJti());
}
} catch (Exception e) {
log.debug("在线吊销查询失败: {}", e.getMessage());
}
}
@Scheduled(fixedDelay = 86400_000)
public void scheduledNtpCheck() {
// 首版仅日志告警,不拒绝请求
long offset = Math.abs(System.currentTimeMillis() - Instant.now().toEpochMilli());
if (offset > 60_000) {
log.warn("系统时钟可能异常,偏移约 {} ms", offset);
}
}
private void assertMemoryValid(LicenseInfo info) {
if (info.isExpired()) {
throw LicenseException.invalid("License 已过期");
}
if (revokedJtiSet.contains(info.getJti())) {
throw LicenseException.revoked();
}
if (!info.isWildcardFingerprint()) {
String current = MachineFingerprintUtil.computeFingerprint();
if (!current.equals(info.getMachineFingerprint())) {
throw LicenseException.fingerprintMismatch();
}
}
}
private void validateBusinessRules(LicenseInfo info) {
if (info.isExpired()) {
throw LicenseException.invalid("License 已过期");
}
if (revokedJtiSet.contains(info.getJti())) {
throw LicenseException.revoked();
}
if (!ISSUER.equals(info.getIssuer())) {
throw LicenseException.invalid("License 签发方无效");
}
if (!info.isWildcardFingerprint()) {
String current = MachineFingerprintUtil.computeFingerprint();
if (!current.equals(info.getMachineFingerprint())) {
throw LicenseException.fingerprintMismatch();
}
}
}
private LicenseInfo parseJwt(String licenseKey) {
if (publicJwk == null) {
throw LicenseException.invalid("License 验签公钥未就绪");
}
try {
SignedJWT signedJWT = SignedJWT.parse(licenseKey);
Ed25519Verifier verifier = new Ed25519Verifier(publicJwk);
if (!signedJWT.verify(verifier)) {
throw LicenseException.invalid("License 签名验证失败");
}
JWTClaimsSet claims = signedJWT.getJWTClaimsSet();
String jti = claims.getJWTID();
if (!StringUtils.hasText(jti)) {
throw LicenseException.invalid("License 缺少 jti");
}
List<String> features = claims.getStringListClaim("features");
if (features == null) {
features = List.of();
}
return LicenseInfo.builder()
.subject(claims.getSubject())
.companyName(stringClaim(claims, "company"))
.edition(stringClaim(claims, "edition"))
.machineFingerprint(stringClaim(claims, "machineFingerprint"))
.installationId(stringClaim(claims, "installationId"))
.jti(jti)
.issuer(claims.getIssuer())
.features(features)
.issuedAt(claims.getIssueTime() != null ? claims.getIssueTime().toInstant() : null)
.expiresAt(claims.getExpirationTime() != null ? claims.getExpirationTime().toInstant() : null)
.rawLicenseKey(licenseKey)
.build();
} catch (LicenseException e) {
throw e;
} catch (Exception e) {
throw LicenseException.invalid("License 解析失败: " + e.getMessage());
}
}
private String resolveLicenseKey() {
// 1. 数据库
SysLicensePO active = sysLicenseMapper.selectOne(new LambdaQueryWrapper<SysLicensePO>()
.eq(SysLicensePO::getIsActive, 1)
.orderByDesc(SysLicensePO::getActivatedAt)
.last("LIMIT 1"));
if (active != null && StringUtils.hasText(active.getLicenseKey())) {
return active.getLicenseKey();
}
// 2. 环境变量
if (StringUtils.hasText(properties.getLicenseKey())) {
return properties.getLicenseKey();
}
// 3. 文件
Path path = Paths.get(properties.getLicenseFile());
if (Files.exists(path)) {
try {
return Files.readString(path, StandardCharsets.UTF_8).trim();
} catch (IOException e) {
log.warn("读取 License 文件失败: {}", e.getMessage());
}
}
return null;
}
private void reloadRevokedJti() {
Path path = Paths.get(properties.getRevocationFile());
if (!Files.exists(path)) {
revokedJtiSet = Collections.emptySet();
return;
}
try {
Set<String> set = new HashSet<>();
Files.lines(path, StandardCharsets.UTF_8)
.map(String::trim)
.filter(StringUtils::hasText)
.forEach(set::add);
revokedJtiSet = Collections.unmodifiableSet(set);
} catch (IOException e) {
log.warn("读取吊销列表失败: {}", e.getMessage());
}
}
/** 将 Ed25519 SPKI PEM 转为 nimbus OctetKeyPair */
private OctetKeyPair parsePublicJwk(String pem) {
try {
String normalized = pem
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s", "");
byte[] decoded = Base64.getDecoder().decode(normalized);
// X509 SPKI 末尾 32 字节为 Ed25519 原始公钥
if (decoded.length < 32) {
throw new IllegalArgumentException("公钥长度无效");
}
byte[] rawPublic = Arrays.copyOfRange(decoded, decoded.length - 32, decoded.length);
return new OctetKeyPair.Builder(Curve.Ed25519, Base64URL.encode(rawPublic)).build();
} catch (Exception e) {
throw new IllegalStateException("License 公钥解析失败: " + e.getMessage(), e);
}
}
private String stringClaim(JWTClaimsSet claims, String name) {
try {
return claims.getStringClaim(name);
} catch (Exception e) {
return null;
}
}
private LocalDateTime toLocalDateTime(Instant instant) {
if (instant == null) {
return null;
}
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
}
@@ -0,0 +1,82 @@
package top.xyquan.ecomdmbbackend.modules.license;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.UUID;
/**
* 机器指纹工具:machine-id + hostname → FP-{SHA256}
*/
@Slf4j
public final class MachineFingerprintUtil {
private static final Path MACHINE_ID_PATH = Paths.get("/etc/machine-id");
private static final Path FALLBACK_MACHINE_ID_PATH = Paths.get("/etc/ecom-machine-id");
private MachineFingerprintUtil() {
}
/** 读取或生成 machine-id */
public static String getMachineId() {
String machineId = readTrimmed(MACHINE_ID_PATH);
if (machineId != null && !machineId.isEmpty()) {
return machineId;
}
machineId = readTrimmed(FALLBACK_MACHINE_ID_PATH);
if (machineId != null && !machineId.isEmpty()) {
return machineId;
}
// 无 machine-id 时生成并持久化(容器/开发环境)
machineId = UUID.randomUUID().toString();
try {
Files.writeString(FALLBACK_MACHINE_ID_PATH, machineId, StandardCharsets.UTF_8);
log.info("已生成备用 machine-id: {}", FALLBACK_MACHINE_ID_PATH);
} catch (IOException e) {
log.warn("无法写入备用 machine-id 文件,使用内存 UUID: {}", e.getMessage());
}
return machineId;
}
/** 获取主机名 */
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
return "unknown-host";
}
}
/** 计算机器指纹 FP-{SHA256} */
public static String computeFingerprint() {
String machineId = getMachineId();
String hostname = getHostname();
String raw = machineId + "|" + hostname;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(raw.getBytes(StandardCharsets.UTF_8));
return "FP-" + HexFormat.of().formatHex(hash).toUpperCase();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 不可用", e);
}
}
private static String readTrimmed(Path path) {
try {
if (Files.exists(path)) {
return Files.readString(path, StandardCharsets.UTF_8).trim();
}
} catch (IOException e) {
log.debug("读取 {} 失败: {}", path, e.getMessage());
}
return null;
}
}
@@ -0,0 +1,15 @@
package top.xyquan.ecomdmbbackend.modules.license;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 创建订单接口的 License 门禁(元注解封装,避免 Controller 上 {@code @LicenseRequired(LicenseFeature.xxx)} 触发 IDE 误报)
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@LicenseRequired(LicenseFeature.ORDER_CREATE)
public @interface RequiresOrderCreateLicense {
}
@@ -0,0 +1,66 @@
package top.xyquan.ecomdmbbackend.modules.license.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.license.model.dto.ActivateLicenseDTO;
import top.xyquan.ecomdmbbackend.modules.license.model.dto.InitAdminDTO;
import top.xyquan.ecomdmbbackend.modules.license.model.dto.InitCompanyDTO;
import top.xyquan.ecomdmbbackend.modules.license.model.vo.FingerprintVO;
import top.xyquan.ecomdmbbackend.modules.license.model.vo.InitStatusVO;
import top.xyquan.ecomdmbbackend.modules.license.model.vo.LicenseSummaryVO;
import top.xyquan.ecomdmbbackend.modules.license.service.InitializeService;
/**
* 系统初始化向导 API(无需登录)
*/
@Tag(name = "系统初始化", description = "首次部署初始化向导")
@RestController
@RequestMapping("/init")
public class InitController {
private final InitializeService initializeService;
public InitController(InitializeService initializeService) {
this.initializeService = initializeService;
}
@Operation(summary = "获取初始化状态")
@GetMapping("/status")
public ApiResponse<InitStatusVO> status() {
return ApiResponse.success(initializeService.getStatus());
}
@Operation(summary = "Step1 创建超级管理员")
@PostMapping("/admin")
public ApiResponse<Void> createAdmin(@Valid @RequestBody InitAdminDTO dto) {
initializeService.createAdmin(dto);
return ApiResponse.success("超级管理员创建成功");
}
@Operation(summary = "Step2 保存公司信息")
@PostMapping("/company")
public ApiResponse<Void> saveCompany(@Valid @RequestBody InitCompanyDTO dto) {
initializeService.saveCompany(dto);
return ApiResponse.success("公司信息保存成功");
}
@Operation(summary = "获取机器指纹")
@GetMapping("/fingerprint")
public ApiResponse<FingerprintVO> fingerprint() {
return ApiResponse.success(initializeService.getFingerprint());
}
@Operation(summary = "Step3 激活 License")
@PostMapping("/activate")
public ApiResponse<LicenseSummaryVO> activate(@Valid @RequestBody ActivateLicenseDTO dto) {
LicenseSummaryVO summary = initializeService.activate(dto);
return ApiResponse.success("License 激活成功", summary);
}
}
@@ -0,0 +1,49 @@
package top.xyquan.ecomdmbbackend.modules.license.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.license.model.dto.ActivateLicenseDTO;
import top.xyquan.ecomdmbbackend.modules.license.model.vo.FingerprintVO;
import top.xyquan.ecomdmbbackend.modules.license.model.vo.LicenseSummaryVO;
import top.xyquan.ecomdmbbackend.modules.license.service.InitializeService;
/**
* 已登录用户的 License 管理 API
*/
@Tag(name = "系统-License", description = "License 信息查看与续期")
@RestController
@RequestMapping("/system")
public class SystemLicenseController {
private final InitializeService initializeService;
public SystemLicenseController(InitializeService initializeService) {
this.initializeService = initializeService;
}
@Operation(summary = "获取当前 License 信息")
@GetMapping("/license")
public ApiResponse<LicenseSummaryVO> getLicense() {
return ApiResponse.success(initializeService.getLicenseSummary());
}
@Operation(summary = "更新/续期 License")
@PutMapping("/license")
public ApiResponse<LicenseSummaryVO> updateLicense(@Valid @RequestBody ActivateLicenseDTO dto) {
LicenseSummaryVO summary = initializeService.updateLicense(dto);
return ApiResponse.success("License 更新成功", summary);
}
@Operation(summary = "获取机器指纹")
@GetMapping("/fingerprint")
public ApiResponse<FingerprintVO> fingerprint() {
return ApiResponse.success(initializeService.getFingerprint());
}
}
@@ -0,0 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.license.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.license.model.po.SysInitPO;
@Mapper
public interface SysInitMapper extends BaseMapper<SysInitPO> {
}
@@ -0,0 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.license.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.license.model.po.SysLicensePO;
@Mapper
public interface SysLicenseMapper extends BaseMapper<SysLicensePO> {
}
@@ -0,0 +1,14 @@
package top.xyquan.ecomdmbbackend.modules.license.model.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 激活 / 更新 License 请求
*/
@Data
public class ActivateLicenseDTO {
@NotBlank(message = "License Key 不能为空")
private String licenseKey;
}
@@ -0,0 +1,22 @@
package top.xyquan.ecomdmbbackend.modules.license.model.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 初始化 Step1:创建超级管理员
*/
@Data
public class InitAdminDTO {
@NotBlank(message = "登录账号不能为空")
private String loginCode;
private String phone;
@NotBlank(message = "密码不能为空")
private String password;
@NotBlank(message = "姓名不能为空")
private String realName;
}
@@ -0,0 +1,18 @@
package top.xyquan.ecomdmbbackend.modules.license.model.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 初始化 Step2:公司信息
*/
@Data
public class InitCompanyDTO {
@NotBlank(message = "公司名称不能为空")
private String companyName;
private String contactPhone;
private String contactEmail;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.license.model.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 系统初始化状态(单行 id=1)
*/
@Data
@TableName("sys_init")
public class SysInitPO {
@TableId(value = "id", type = IdType.INPUT)
private Long id;
/** 初始化步骤 0~3 */
private Integer step;
private Long adminId;
private String companyName;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,44 @@
package top.xyquan.ecomdmbbackend.modules.license.model.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 当前生效的 License 记录
*/
@Data
@TableName("sys_license")
public class SysLicensePO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String companyName;
private String edition;
private String machineFingerprint;
private String installationId;
private String licenseKey;
private String jti;
private LocalDateTime issuedAt;
private LocalDateTime expiresAt;
private LocalDateTime activatedAt;
/** 1=有效 0=无效 */
private Integer isActive;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,16 @@
package top.xyquan.ecomdmbbackend.modules.license.model.vo;
import lombok.Builder;
import lombok.Data;
/**
* 机器指纹信息
*/
@Data
@Builder
public class FingerprintVO {
private String fingerprint;
private String machineId;
private String hostname;
}
@@ -0,0 +1,18 @@
package top.xyquan.ecomdmbbackend.modules.license.model.vo;
import lombok.Builder;
import lombok.Data;
/**
* 初始化状态
*/
@Data
@Builder
public class InitStatusVO {
private boolean initialized;
private int currentStep;
private boolean adminCreated;
private boolean companySaved;
private boolean licenseActivated;
}
@@ -0,0 +1,24 @@
package top.xyquan.ecomdmbbackend.modules.license.model.vo;
import lombok.Builder;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 当前 License 摘要(不含完整 JWT)
*/
@Data
@Builder
public class LicenseSummaryVO {
private String companyName;
private String edition;
private String machineFingerprint;
private List<String> features;
private LocalDateTime issuedAt;
private LocalDateTime expiresAt;
private Long daysRemaining;
private String status;
}
@@ -0,0 +1,213 @@
package top.xyquan.ecomdmbbackend.modules.license.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.license.LicenseEnforcement;
import top.xyquan.ecomdmbbackend.modules.license.LicenseInfo;
import top.xyquan.ecomdmbbackend.modules.license.LicenseValidator;
import top.xyquan.ecomdmbbackend.modules.license.MachineFingerprintUtil;
import top.xyquan.ecomdmbbackend.modules.license.mapper.SysInitMapper;
import top.xyquan.ecomdmbbackend.modules.license.model.dto.ActivateLicenseDTO;
import top.xyquan.ecomdmbbackend.modules.license.model.dto.InitAdminDTO;
import top.xyquan.ecomdmbbackend.modules.license.model.dto.InitCompanyDTO;
import top.xyquan.ecomdmbbackend.modules.license.model.po.SysInitPO;
import top.xyquan.ecomdmbbackend.modules.license.model.vo.FingerprintVO;
import top.xyquan.ecomdmbbackend.modules.license.model.vo.InitStatusVO;
import top.xyquan.ecomdmbbackend.modules.license.model.vo.LicenseSummaryVO;
import top.xyquan.ecomdmbbackend.modules.sys.user.mapper.UserMapper;
import top.xyquan.ecomdmbbackend.modules.sys.user.model.po.UserPO;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
/**
* 系统初始化与 License 管理服务
*/
@Service
public class InitializeService {
private static final long INIT_ROW_ID = 1L;
private final SysInitMapper sysInitMapper;
private final UserMapper userMapper;
private final PasswordEncoder passwordEncoder;
private final LicenseValidator licenseValidator;
public InitializeService(SysInitMapper sysInitMapper,
UserMapper userMapper,
PasswordEncoder passwordEncoder,
LicenseValidator licenseValidator) {
this.sysInitMapper = sysInitMapper;
this.userMapper = userMapper;
this.passwordEncoder = passwordEncoder;
this.licenseValidator = licenseValidator;
}
public InitStatusVO getStatus() {
SysInitPO init = getOrCreateInitRow();
int step = init.getStep() != null ? init.getStep() : 0;
return InitStatusVO.builder()
.initialized(step >= 3)
.currentStep(step)
.adminCreated(step >= 1)
.companySaved(step >= 2)
.licenseActivated(step >= 3)
.build();
}
public FingerprintVO getFingerprint() {
return FingerprintVO.builder()
.fingerprint(MachineFingerprintUtil.computeFingerprint())
.machineId(MachineFingerprintUtil.getMachineId())
.hostname(MachineFingerprintUtil.getHostname())
.build();
}
@Transactional
public void createAdmin(InitAdminDTO dto) {
SysInitPO init = getOrCreateInitRow();
if (init.getStep() != null && init.getStep() >= 3) {
throw new BusinessException("系统已完成初始化");
}
if (init.getStep() != null && init.getStep() >= 1) {
throw new BusinessException("超级管理员已创建");
}
// 检查账号唯一
if (StringUtils.hasText(dto.getLoginCode())) {
Long count = userMapper.selectCount(new LambdaQueryWrapper<UserPO>()
.eq(UserPO::getLoginCode, dto.getLoginCode()));
if (count > 0) {
throw new BusinessException("登录账号已存在");
}
}
if (StringUtils.hasText(dto.getPhone())) {
Long count = userMapper.selectCount(new LambdaQueryWrapper<UserPO>()
.eq(UserPO::getPhone, dto.getPhone()));
if (count > 0) {
throw new BusinessException("手机号码已存在");
}
}
UserPO user = new UserPO();
user.setLoginCode(dto.getLoginCode());
user.setPhone(dto.getPhone());
user.setPassword(passwordEncoder.encode(dto.getPassword()));
user.setRealName(dto.getRealName());
user.setRole("super");
user.setStatus(1);
user.setPwdSecurityLevel(3);
user.setPwdUpdateTime(LocalDateTime.now());
userMapper.insert(user);
init.setAdminId(user.getId());
init.setStep(1);
init.setUpdatedAt(LocalDateTime.now());
sysInitMapper.updateById(init);
}
@Transactional
public void saveCompany(InitCompanyDTO dto) {
SysInitPO init = getOrCreateInitRow();
if (init.getStep() == null || init.getStep() < 1) {
throw new BusinessException("请先创建超级管理员");
}
if (init.getStep() >= 3) {
throw new BusinessException("系统已完成初始化");
}
init.setCompanyName(dto.getCompanyName());
init.setStep(2);
init.setUpdatedAt(LocalDateTime.now());
sysInitMapper.updateById(init);
}
@Transactional
public LicenseSummaryVO activate(ActivateLicenseDTO dto) {
SysInitPO init = getOrCreateInitRow();
if (init.getStep() == null || init.getStep() < 2) {
throw new BusinessException("请先完成前两步初始化");
}
LicenseInfo info = licenseValidator.parseAndValidate(dto.getLicenseKey().trim());
info = LicenseInfo.builder()
.subject(info.getSubject())
.companyName(StringUtils.hasText(info.getCompanyName()) ? info.getCompanyName() : init.getCompanyName())
.edition(info.getEdition())
.machineFingerprint(info.getMachineFingerprint())
.installationId(MachineFingerprintUtil.getMachineId())
.jti(info.getJti())
.issuer(info.getIssuer())
.features(info.getFeatures())
.issuedAt(info.getIssuedAt())
.expiresAt(info.getExpiresAt())
.rawLicenseKey(dto.getLicenseKey().trim())
.build();
licenseValidator.persistLicense(info);
init.setStep(3);
init.setUpdatedAt(LocalDateTime.now());
sysInitMapper.updateById(init);
return toSummary(info);
}
@Transactional
public LicenseSummaryVO updateLicense(ActivateLicenseDTO dto) {
if (!LicenseEnforcement.isEnforced()) {
throw new BusinessException("License 校验未启用,无法更新");
}
LicenseInfo info = licenseValidator.parseAndValidate(dto.getLicenseKey().trim());
licenseValidator.persistLicense(info);
return toSummary(info);
}
public LicenseSummaryVO getLicenseSummary() {
LicenseInfo info = licenseValidator.getCachedLicense();
if (info == null) {
throw new BusinessException("当前无有效 License");
}
return toSummary(info);
}
private LicenseSummaryVO toSummary(LicenseInfo info) {
LocalDateTime expiresAt = info.getExpiresAt() != null
? LocalDateTime.ofInstant(info.getExpiresAt(), java.time.ZoneId.systemDefault())
: null;
LocalDateTime issuedAt = info.getIssuedAt() != null
? LocalDateTime.ofInstant(info.getIssuedAt(), java.time.ZoneId.systemDefault())
: null;
Long daysRemaining = null;
String status = "active";
if (expiresAt != null) {
daysRemaining = ChronoUnit.DAYS.between(LocalDateTime.now(), expiresAt);
if (info.isExpired()) {
status = "expired";
} else if (daysRemaining <= 30) {
status = "expiring";
}
}
return LicenseSummaryVO.builder()
.companyName(info.getCompanyName())
.edition(info.getEdition())
.machineFingerprint(info.getMachineFingerprint())
.features(info.getFeatures() != null ? info.getFeatures() : List.of())
.issuedAt(issuedAt)
.expiresAt(expiresAt)
.daysRemaining(daysRemaining)
.status(status)
.build();
}
private SysInitPO getOrCreateInitRow() {
SysInitPO init = sysInitMapper.selectById(INIT_ROW_ID);
if (init == null) {
init = new SysInitPO();
init.setId(INIT_ROW_ID);
init.setStep(0);
init.setCreatedAt(LocalDateTime.now());
init.setUpdatedAt(LocalDateTime.now());
sysInitMapper.insert(init);
}
return init;
}
}
@@ -6,6 +6,7 @@ import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope;
import top.xyquan.ecomdmbbackend.modules.license.LicenseRequired;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.BatchImportOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.vo.BatchImportResultVO;
@@ -32,6 +33,7 @@ public class OpenOrderController {
}
@PostMapping("/batch-import")
@LicenseRequired
@RequireOpenScope(value = OpenApiScopeConstants.ORDER_IMPORT, description = "批量导入订单")
@Operation(summary = "批量导入订单")
public ApiResponse<BatchImportResultVO> batchImportOrders(@Valid @RequestBody BatchImportOrderDTO dto) {