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
+6
View File
@@ -89,6 +89,12 @@
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- License 验签(Ed25519 JWT,与登录 jjwt 分离) -->
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>9.37.3</version>
</dependency>
<!--Spring Boot测试启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -0,0 +1,30 @@
-- License 与系统初始化表
CREATE TABLE IF NOT EXISTS sys_init (
id BIGINT PRIMARY KEY DEFAULT 1,
step TINYINT NOT NULL DEFAULT 0 COMMENT '初始化步骤 0~3',
admin_id BIGINT NULL COMMENT '超级管理员用户ID',
company_name VARCHAR(200) NULL COMMENT '公司名称',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) COMMENT '系统初始化状态(单行)';
CREATE TABLE IF NOT EXISTS sys_license (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
company_name VARCHAR(200) NOT NULL COMMENT '授权公司名称',
edition VARCHAR(20) NOT NULL COMMENT '版本 trial/enterprise/unlimited',
machine_fingerprint VARCHAR(100) NOT NULL COMMENT '绑定的机器指纹',
installation_id VARCHAR(64) NULL COMMENT '安装ID',
license_key TEXT NOT NULL COMMENT 'License JWT',
jti VARCHAR(64) NOT NULL COMMENT 'JWT唯一标识',
issued_at DATETIME NOT NULL COMMENT '签发时间',
expires_at DATETIME NOT NULL COMMENT '过期时间',
activated_at DATETIME NOT NULL COMMENT '激活时间',
is_active TINYINT NOT NULL DEFAULT 1 COMMENT '是否有效 1=是 0=否',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_jti (jti)
) COMMENT '当前生效的 License';
-- 已有环境跳过初始化门禁(仅开发/存量部署)
INSERT INTO sys_init (id, step) VALUES (1, 3)
ON DUPLICATE KEY UPDATE step = GREATEST(step, 3);
+38
View File
@@ -168,4 +168,42 @@ CREATE TABLE `sys_file` (
CONSTRAINT `fk_sys_file_uploader` FOREIGN KEY (`upload_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '系统模块-统一文件资源表(支持本地存储和对象存储)'
-- ========================================
-- 系统初始化状态表(单行 id=1,首次部署向导进度)
-- ========================================
DROP TABLE IF EXISTS `sys_init`;
CREATE TABLE `sys_init` (
`id` bigint UNSIGNED NOT NULL DEFAULT 1 COMMENT '固定主键(单行记录)',
`step` tinyint UNSIGNED NOT NULL DEFAULT 0 COMMENT '初始化步骤(0-未开始 1-超管已创建 2-公司已填写 3-已完成)',
`admin_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '超级管理员用户ID',
`company_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '公司名称',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `fk_sys_init_admin`(`admin_id` ASC) USING BTREE,
CONSTRAINT `fk_sys_init_admin` FOREIGN KEY (`admin_id`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '系统模块-初始化状态表(单行)'
-- ========================================
-- License 授权表(当前部署生效的 License)
-- ========================================
DROP TABLE IF EXISTS `sys_license`;
CREATE TABLE `sys_license` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`company_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '授权公司名称',
`edition` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '版本(trial/enterprise/unlimited)',
`machine_fingerprint` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '绑定的机器指纹(SaaS 为 *)',
`installation_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '安装ID(machine-id)',
`license_key` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'License JWT',
`jti` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'JWT 唯一标识(吊销用)',
`issued_at` timestamp NOT NULL COMMENT '签发时间',
`expires_at` timestamp NOT NULL COMMENT '过期时间',
`activated_at` timestamp NOT NULL COMMENT '激活时间',
`is_active` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '是否有效(0-无效 1-有效)',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_jti`(`jti` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '系统模块-License 授权表'
@@ -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) {
@@ -138,6 +138,16 @@ oss:
file:
access-domain: http://localhost:5666 # 本地文件访问域名
# License 授权配置(开关与公钥见 LicenseEnforcement 源码硬编码)
ecom:
license:
license-key: ${ECOM_LICENSE_KEY:}
license-file: ${ECOM_LICENSE_FILE:config/license.key}
revocation-file: ${ECOM_LICENSE_REVOCATION_FILE:config/revoked.jti}
revalidate-interval: ${ECOM_LICENSE_REVALIDATE_INTERVAL:10}
online-revocation-check: ${ECOM_LICENSE_ONLINE_REVOKE:false}
license-server-url: ${ECOM_LICENSE_SERVER_URL:}
# 日志配置
logging:
level:
@@ -0,0 +1,42 @@
import type { LicenseDTO, LicenseVO } from './types';
import { baseRequestClient, requestClient } from '#/api/request';
/** 初始化相关 API(无需登录) */
export async function getInitStatusApi() {
return baseRequestClient.get<LicenseVO.InitStatus>('/init/status');
}
export async function createInitAdminApi(data: LicenseDTO.InitAdmin) {
return baseRequestClient.post<void>('/init/admin', data);
}
export async function saveInitCompanyApi(data: LicenseDTO.InitCompany) {
return baseRequestClient.post<void>('/init/company', data);
}
export async function getInitFingerprintApi() {
return baseRequestClient.get<LicenseVO.Fingerprint>('/init/fingerprint');
}
export async function activateLicenseApi(data: LicenseDTO.ActivateLicense) {
return baseRequestClient.post<LicenseVO.LicenseSummary>(
'/init/activate',
data,
);
}
/** 已登录用户的 License 管理 API */
export async function getLicenseInfoApi() {
return requestClient.get<LicenseVO.LicenseSummary>('/system/license');
}
export async function updateLicenseApi(data: LicenseDTO.ActivateLicense) {
return requestClient.put<LicenseVO.LicenseSummary>('/system/license', data);
}
export async function getSystemFingerprintApi() {
return requestClient.get<LicenseVO.Fingerprint>('/system/fingerprint');
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,2 @@
export * from './types.dto';
export * from './types.vo';
@@ -0,0 +1,21 @@
/**
* License 模块 — 请求 DTO
*/
export namespace LicenseDTO {
export interface InitAdmin {
loginCode: string;
phone?: string;
password: string;
realName: string;
}
export interface InitCompany {
companyName: string;
contactPhone?: string;
contactEmail?: string;
}
export interface ActivateLicense {
licenseKey: string;
}
}
@@ -0,0 +1,32 @@
/**
* License 模块 — 响应 VO
*/
export namespace LicenseVO {
/** 初始化状态 */
export interface InitStatus {
initialized: boolean;
currentStep: number;
adminCreated: boolean;
companySaved: boolean;
licenseActivated: boolean;
}
/** 机器指纹 */
export interface Fingerprint {
fingerprint: string;
machineId: string;
hostname: string;
}
/** License 摘要 */
export interface LicenseSummary {
companyName?: string;
edition?: string;
machineFingerprint?: string;
features?: string[];
issuedAt?: string;
expiresAt?: string;
daysRemaining?: number;
status?: string;
}
}
@@ -5,11 +5,45 @@ import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import { startProgress, stopProgress } from '@vben/utils';
import { accessRoutes, coreRouteNames } from '#/router/routes';
import { getInitStatusApi } from '#/api/system/license';
import { INIT_PATH, accessRoutes, coreRouteNames } from '#/router/routes';
import { useAuthStore } from '#/store';
import { generateAccess } from './access';
/** 缓存初始化状态,避免每次路由切换都请求 */
let initStatusCache: { checked: boolean; initialized: boolean } = {
checked: false,
initialized: true,
};
/** 初始化完成后清除缓存(激活成功后可由页面调用) */
export function resetInitStatusCache() {
initStatusCache = { checked: false, initialized: true };
}
async function ensureInitialized(toPath: string): Promise<boolean | { path: string; replace: boolean }> {
if (toPath === INIT_PATH || toPath.startsWith(`${INIT_PATH}/`)) {
return true;
}
if (!initStatusCache.checked) {
try {
const status = await getInitStatusApi();
initStatusCache = {
checked: true,
initialized: status.initialized,
};
} catch {
// 后端不可达时不阻断(本地纯前端开发)
initStatusCache = { checked: true, initialized: true };
}
}
if (!initStatusCache.initialized) {
return { path: INIT_PATH, replace: true };
}
return true;
}
/**
* 通用守卫配置
* @param router
@@ -50,6 +84,12 @@ function setupAccessGuard(router: Router) {
const userStore = useUserStore();
const authStore = useAuthStore();
// 未初始化则强制进入初始化向导(Init 路由本身跳过)
const initCheck = await ensureInitialized(to.path);
if (initCheck !== true) {
return initCheck;
}
// 基本路由,这些路由不需要进入权限拦截
if (coreRouteNames.includes(to.name as string)) {
if (to.path === LOGIN_PATH && accessStore.accessToken) {
@@ -20,6 +20,9 @@ const fallbackNotFoundRoute: RouteRecordRaw = {
path: '/:path(.*)*',
};
/** 系统初始化路径(未初始化时强制跳转) */
export const INIT_PATH = '/init';
/** 基本路由,这些路由是必须存在的 */
const coreRoutes: RouteRecordRaw[] = [
/**
@@ -38,6 +41,17 @@ const coreRoutes: RouteRecordRaw[] = [
redirect: preferences.app.defaultHomePath,
children: [],
},
{
name: 'Init',
path: INIT_PATH,
component: () => import('#/views/init/InitWizard.vue'),
meta: {
hideInBreadcrumb: true,
hideInMenu: true,
hideInTab: true,
title: '系统初始化',
},
},
{
component: AuthPageLayout,
meta: {
@@ -2,7 +2,7 @@ import type { RouteRecordRaw } from 'vue-router';
import { mergeRouteModules, traverseTreeValues } from '@vben/utils';
import { coreRoutes, fallbackNotFoundRoute } from './core';
import { coreRoutes, fallbackNotFoundRoute, INIT_PATH } from './core';
const dynamicRouteFiles = import.meta.glob('./modules/**/*.ts', {
eager: true,
@@ -41,4 +41,4 @@ const routes: RouteRecordRaw[] = [
/** 有权限校验的路由列表,包含动态路由 */
const accessRoutes = [...dynamicRoutes];
export { accessRoutes, coreRouteNames, routes };
export { accessRoutes, coreRouteNames, INIT_PATH, routes };
@@ -63,6 +63,16 @@ const routes: RouteRecordRaw[] = [
requiresAuth: true,
},
},
{
name: 'SystemLicense',
path: '/platform-admin/license',
component: () => import('#/views/system/license/LicenseInfo.vue'),
meta: {
icon: 'lucide:key-round',
title: 'License 管理',
requiresAuth: true,
},
},
];
export default routes;
@@ -0,0 +1,85 @@
<script setup lang="ts">
import type { LicenseDTO } from '#/api/system/license';
import { reactive, ref } from 'vue';
import { Button, Form, Input, message } from 'ant-design-vue';
import { createInitAdminApi } from '#/api/system/license';
defineOptions({ name: 'InitStepAdmin' });
const emit = defineEmits<{
next: [];
}>();
const submitting = ref(false);
const formState = reactive<LicenseDTO.InitAdmin>({
loginCode: '',
phone: '',
password: '',
realName: '',
});
const rules = {
loginCode: [{ required: true, message: '请输入登录账号' }],
password: [{ required: true, message: '请输入密码' }],
realName: [{ required: true, message: '请输入姓名' }],
};
async function handleSubmit() {
submitting.value = true;
const hide = message.loading('正在创建超级管理员...', 0);
try {
await createInitAdminApi({
...formState,
phone: formState.phone || undefined,
});
message.success('超级管理员创建成功');
emit('next');
} finally {
hide();
submitting.value = false;
}
}
</script>
<template>
<Form
layout="vertical"
:model="formState"
:rules="rules"
@finish="handleSubmit"
>
<Form.Item label="登录账号" name="loginCode">
<Input
v-model:value="formState.loginCode"
placeholder="超级管理员登录账号"
autocomplete="username"
/>
</Form.Item>
<Form.Item label="手机号码" name="phone">
<Input
v-model:value="formState.phone"
placeholder="选填"
autocomplete="tel"
/>
</Form.Item>
<Form.Item label="姓名" name="realName">
<Input v-model:value="formState.realName" placeholder="管理员姓名" />
</Form.Item>
<Form.Item label="登录密码" name="password">
<Input.Password
v-model:value="formState.password"
placeholder="设置登录密码"
autocomplete="new-password"
/>
</Form.Item>
<Form.Item>
<Button type="primary" html-type="submit" :loading="submitting" block>
下一步
</Button>
</Form.Item>
</Form>
</template>
@@ -0,0 +1,77 @@
<script setup lang="ts">
import type { LicenseDTO } from '#/api/system/license';
import { reactive, ref } from 'vue';
import { Button, Form, Input, message } from 'ant-design-vue';
import { saveInitCompanyApi } from '#/api/system/license';
defineOptions({ name: 'InitStepCompany' });
const emit = defineEmits<{
back: [];
next: [];
}>();
const submitting = ref(false);
const formState = reactive<LicenseDTO.InitCompany>({
companyName: '',
contactPhone: '',
contactEmail: '',
});
const rules = {
companyName: [{ required: true, message: '请输入公司名称' }],
};
async function handleSubmit() {
submitting.value = true;
const hide = message.loading('正在保存公司信息...', 0);
try {
await saveInitCompanyApi({
...formState,
contactPhone: formState.contactPhone || undefined,
contactEmail: formState.contactEmail || undefined,
});
message.success('公司信息保存成功');
emit('next');
} finally {
hide();
submitting.value = false;
}
}
</script>
<template>
<Form
layout="vertical"
:model="formState"
:rules="rules"
@finish="handleSubmit"
>
<Form.Item label="公司名称" name="companyName">
<Input v-model:value="formState.companyName" placeholder="公司全称" />
</Form.Item>
<Form.Item label="联系电话" name="contactPhone">
<Input v-model:value="formState.contactPhone" placeholder="选填" />
</Form.Item>
<Form.Item label="联系邮箱" name="contactEmail">
<Input v-model:value="formState.contactEmail" placeholder="选填" />
</Form.Item>
<Form.Item>
<div class="flex gap-3">
<Button class="flex-1" @click="emit('back')">上一步</Button>
<Button
type="primary"
html-type="submit"
class="flex-1"
:loading="submitting"
>
下一步
</Button>
</div>
</Form.Item>
</Form>
</template>
@@ -0,0 +1,103 @@
<script setup lang="ts">
import type { LicenseVO } from '#/api/system/license';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { Button, Form, Input, message, Typography } from 'ant-design-vue';
import {
activateLicenseApi,
getInitFingerprintApi,
} from '#/api/system/license';
import { resetInitStatusCache } from '#/router/guard';
import FingerprintDisplay from './components/FingerprintDisplay.vue';
defineOptions({ name: 'InitStepLicense' });
const emit = defineEmits<{
back: [];
}>();
const router = useRouter();
const submitting = ref(false);
const fingerprintLoading = ref(false);
const fingerprint = ref<LicenseVO.Fingerprint | null>(null);
const licenseKey = ref('');
async function loadFingerprint() {
fingerprintLoading.value = true;
try {
fingerprint.value = await getInitFingerprintApi();
} finally {
fingerprintLoading.value = false;
}
}
async function handleActivate() {
if (!licenseKey.value.trim()) {
message.warning('请输入 License Key');
return;
}
submitting.value = true;
const hide = message.loading('正在激活 License...', 0);
try {
await activateLicenseApi({ licenseKey: licenseKey.value.trim() });
resetInitStatusCache();
message.success('系统初始化完成,请登录');
await router.replace(LOGIN_PATH);
} finally {
hide();
submitting.value = false;
}
}
onMounted(() => {
loadFingerprint();
});
</script>
<template>
<div class="space-y-4">
<Typography.Paragraph type="secondary" class="!mb-0 text-sm">
将机器指纹提供给运营方,获取 License Key 后粘贴到下方完成激活。
</Typography.Paragraph>
<div v-if="fingerprintLoading" class="py-6 text-center text-gray-400">
正在获取机器指纹...
</div>
<FingerprintDisplay
v-else-if="fingerprint"
:fingerprint="fingerprint.fingerprint"
:hostname="fingerprint.hostname"
:machine-id="fingerprint.machineId"
/>
<Form layout="vertical" @finish="handleActivate">
<Form.Item label="License Key" required>
<Input.TextArea
v-model:value="licenseKey"
:rows="4"
placeholder="粘贴运营方签发的 License JWT"
class="font-mono text-xs"
/>
</Form.Item>
<Form.Item>
<div class="flex gap-3">
<Button class="flex-1" @click="emit('back')">上一步</Button>
<Button
type="primary"
html-type="submit"
class="flex-1"
:loading="submitting"
>
激活并完成
</Button>
</div>
</Form.Item>
</Form>
</div>
</template>
@@ -0,0 +1,91 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { Card, Spin, Steps, Typography } from 'ant-design-vue';
import { getInitStatusApi } from '#/api/system/license';
import InitStepAdmin from './InitStepAdmin.vue';
import InitStepCompany from './InitStepCompany.vue';
import InitStepLicense from './InitStepLicense.vue';
defineOptions({ name: 'InitWizard' });
const router = useRouter();
const currentStep = ref(0);
const statusLoading = ref(true);
const stepItems = [
{ title: '超级管理员' },
{ title: '公司信息' },
{ title: 'License 激活' },
];
async function loadStatus() {
statusLoading.value = true;
try {
const status = await getInitStatusApi();
if (status.initialized) {
await router.replace(LOGIN_PATH);
return;
}
// 根据后端进度定位到对应步骤
if (status.licenseActivated || status.currentStep >= 3) {
currentStep.value = 2;
} else if (status.companySaved || status.currentStep >= 2) {
currentStep.value = 2;
} else if (status.adminCreated || status.currentStep >= 1) {
currentStep.value = 1;
} else {
currentStep.value = 0;
}
} finally {
statusLoading.value = false;
}
}
function goNext() {
currentStep.value = Math.min(currentStep.value + 1, 2);
}
function goBack() {
currentStep.value = Math.max(currentStep.value - 1, 0);
}
onMounted(() => {
loadStatus();
});
</script>
<template>
<div
class="flex min-h-screen flex-col items-center justify-center bg-gradient-to-b from-background to-muted/30 px-4 py-10"
>
<div class="mb-8 text-center">
<Typography.Title :level="3" class="!mb-1">
{{ preferences.app.name }} 系统初始化
</Typography.Title>
<Typography.Text type="secondary">
首次部署请按步骤完成配置
</Typography.Text>
</div>
<Card class="w-full max-w-lg shadow-sm">
<Steps :current="currentStep" :items="stepItems" class="mb-8" />
<Spin :spinning="statusLoading">
<InitStepAdmin v-if="currentStep === 0" @next="goNext" />
<InitStepCompany
v-else-if="currentStep === 1"
@back="goBack"
@next="goNext"
/>
<InitStepLicense v-else @back="goBack" />
</Spin>
</Card>
</div>
</template>
@@ -0,0 +1,56 @@
<script setup lang="ts">
import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, Input, message, Space, Typography } from 'ant-design-vue';
defineOptions({ name: 'FingerprintDisplay' });
const props = defineProps<{
fingerprint: string;
hostname?: string;
machineId?: string;
}>();
const CopyIcon = createIconifyIcon('lucide:copy');
const copying = ref(false);
async function copyFingerprint() {
if (!props.fingerprint) return;
copying.value = true;
try {
await navigator.clipboard.writeText(props.fingerprint);
message.success('机器指纹已复制');
} catch {
message.error('复制失败,请手动选择复制');
} finally {
copying.value = false;
}
}
</script>
<template>
<div class="rounded-lg border border-dashed border-primary/30 bg-primary/5 p-4">
<Typography.Text type="secondary" class="mb-2 block text-sm">
请将以下机器指纹发送给运营方签发 License
</Typography.Text>
<Input :value="fingerprint" readonly class="font-mono text-xs" />
<Space class="mt-3" wrap>
<Button
type="primary"
ghost
size="small"
:loading="copying"
@click="copyFingerprint"
>
<CopyIcon class="mr-1 size-4" />
复制指纹
</Button>
<Typography.Text v-if="hostname" type="secondary" class="text-xs">
主机名:{{ hostname }}
</Typography.Text>
</Space>
</div>
</template>
@@ -0,0 +1,46 @@
<script setup lang="ts">
import type { LicenseVO } from '#/api/system/license';
import { onMounted, ref } from 'vue';
import { Card, Spin } from 'ant-design-vue';
import { getSystemFingerprintApi } from '#/api/system/license';
import FingerprintDisplay from '#/views/init/components/FingerprintDisplay.vue';
defineOptions({ name: 'FingerprintInfo' });
const loading = ref(false);
const fingerprint = ref<LicenseVO.Fingerprint | null>(null);
async function load() {
loading.value = true;
try {
fingerprint.value = await getSystemFingerprintApi();
} finally {
loading.value = false;
}
}
onMounted(() => {
load();
});
</script>
<template>
<Card title="机器指纹" :bordered="false">
<Spin :spinning="loading">
<FingerprintDisplay
v-if="fingerprint"
:fingerprint="fingerprint.fingerprint"
:hostname="fingerprint.hostname"
:machine-id="fingerprint.machineId"
/>
<div v-else-if="!loading" class="text-gray-400">暂无指纹信息</div>
</Spin>
<p class="mt-4 text-sm text-gray-500">
迁机或重新签发 License 时,请将新环境的机器指纹提供给运营方。
</p>
</Card>
</template>
@@ -0,0 +1,160 @@
<script setup lang="ts">
import type { LicenseVO } from '#/api/system/license';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import {
Button,
Card,
Descriptions,
Form,
Input,
message,
Space,
Tag,
Typography,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import {
getLicenseInfoApi,
updateLicenseApi,
} from '#/api/system/license';
import FingerprintInfo from './FingerprintInfo.vue';
defineOptions({ name: 'LicenseInfo' });
const loading = ref(false);
const updating = ref(false);
const license = ref<LicenseVO.LicenseSummary | null>(null);
const renewKey = ref('');
const statusTag = computed(() => {
const status = license.value?.status;
if (status === 'active') return { color: 'success', text: '有效' };
if (status === 'expiring') return { color: 'warning', text: '即将过期' };
if (status === 'expired') return { color: 'error', text: '已过期' };
if (status === 'dev-disabled') return { color: 'default', text: '开发模式' };
return { color: 'default', text: status || '未知' };
});
const editionLabel: Record<string, string> = {
trial: '试用版',
enterprise: '企业版',
unlimited: '无限版',
};
async function loadLicense() {
loading.value = true;
try {
license.value = await getLicenseInfoApi();
} catch (error: any) {
license.value = null;
if (!error?.message?.includes('无有效')) {
message.error(error?.message || '获取 License 信息失败');
}
} finally {
loading.value = false;
}
}
async function handleRenew() {
if (!renewKey.value.trim()) {
message.warning('请输入新的 License Key');
return;
}
updating.value = true;
const hide = message.loading('正在更新 License...', 0);
try {
license.value = await updateLicenseApi({ licenseKey: renewKey.value.trim() });
renewKey.value = '';
message.success('License 更新成功');
} finally {
hide();
updating.value = false;
}
}
function formatDate(value?: string) {
return value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '-';
}
onMounted(() => {
loadLicense();
});
</script>
<template>
<Page title="License 管理" description="查看授权信息与续期更新">
<div class="grid gap-4 lg:grid-cols-2">
<Card title="授权信息" :loading="loading">
<template v-if="license">
<Descriptions :column="1" bordered size="small">
<Descriptions.Item label="状态">
<Tag :color="statusTag.color">{{ statusTag.text }}</Tag>
</Descriptions.Item>
<Descriptions.Item label="授权公司">
{{ license.companyName || '-' }}
</Descriptions.Item>
<Descriptions.Item label="版本">
{{ editionLabel[license.edition || ''] || license.edition || '-' }}
</Descriptions.Item>
<Descriptions.Item label="机器指纹">
<Typography.Text code class="text-xs break-all">
{{ license.machineFingerprint || '-' }}
</Typography.Text>
</Descriptions.Item>
<Descriptions.Item label="授权功能">
<Space wrap>
<Tag v-for="f in license.features" :key="f">{{ f }}</Tag>
<span v-if="!license.features?.length">-</span>
</Space>
</Descriptions.Item>
<Descriptions.Item label="签发时间">
{{ formatDate(license.issuedAt) }}
</Descriptions.Item>
<Descriptions.Item label="过期时间">
{{ formatDate(license.expiresAt) }}
</Descriptions.Item>
<Descriptions.Item
v-if="license.daysRemaining != null"
label="剩余天数"
>
{{ license.daysRemaining }} 天
</Descriptions.Item>
</Descriptions>
</template>
<Typography.Text v-else type="secondary">
暂无有效 License(本地开发可能未启用校验)
</Typography.Text>
<Button class="mt-4" size="small" @click="loadLicense">刷新</Button>
</Card>
<Card title="续期 / 更新 License">
<Typography.Paragraph type="secondary" class="text-sm">
运营方签发新 License 后,将完整 JWT 粘贴到下方并提交。
</Typography.Paragraph>
<Form layout="vertical" @finish="handleRenew">
<Form.Item label="新 License Key" required>
<Input.TextArea
v-model:value="renewKey"
:rows="5"
placeholder="粘贴新的 License JWT"
class="font-mono text-xs"
/>
</Form.Item>
<Button type="primary" html-type="submit" :loading="updating">
更新 License
</Button>
</Form>
</Card>
</div>
<div class="mt-4">
<FingerprintInfo />
</div>
</Page>
</template>
+23
View File
@@ -0,0 +1,23 @@
# 依赖(pnpm workspace 根目录 + 子包软链)
node_modules/
# 构建产物
dist/
*.tsbuildinfo
# 环境变量与密钥(勿提交)
.env
.env.*
!.env.example
server/keys/*.pem
# 日志
logs/
*.log
pnpm-debug.log*
# 系统/编辑器
.DS_Store
.idea/
.vscode/
*.swp
+2
View File
@@ -0,0 +1,2 @@
# 允许 bcrypt 等原生依赖执行 install 脚本
enable-pre-post-scripts=true
+434
View File
@@ -0,0 +1,434 @@
我看完你这份**Ed25519 版 License 设计**了,这一版已经明显比你上一版(JWT + RSA)更专业,基本已经进入“可商用架构”层级了。
我还是按**架构评审的方式**给你拆:
👉 不讲表面优化,只讲**会影响你后期成本 / 安全 / 可维护性**的点
---
# ✅ 一、整体评价(先给结论)
> ✅ 架构成熟度:**85分(可以上线)**
> ⚠️ 差的这 15 分:主要在 **抗破解能力 + 生命周期控制 + 可扩展性**
---
# ✅ 二、这版比上一版“质变”的地方(做对的)
### ✔ 1. 从 RSA → Ed25519(这是关键升级)
👉 这个决策是对的
* 签名更小
* 性能更好
* 无 padding 坑
* 更适合 License 这种高频校验场景
👉 这一点已经是“架构升级”,不是优化
---
### ✔ 2. 去掉 JWT,改自定义结构
你现在:
```json
{
"payload": "...",
"signature": "..."
}
```
👉 这是正确方向:
* 去掉 JWT 历史坑(alg / 解析差异)
* 结构完全可控
* 更适合 License 场景
---
### ✔ 3. 引入 AES 加密(GCM)
👉 很加分的一点
你已经做到:
> “不仅不能改,还看不懂”
这已经是:
```text
签名(防篡改) + 加密(防分析)
```
👉 商业软件常规做法
---
### ✔ 4. LicenseManager 分层设计(非常好)
```text
LicenseManager
├── load
├── verify
├── decrypt
├── cache
```
👉 说明你已经在做:
* 生命周期管理
* 统一入口
👉 这是“工程能力”的体现
---
# ⚠️ 三、关键问题(这一版的“隐患点”)
下面这些才是你现在**真正需要改的**
---
# ❗问题1:AES Key 放在客户端 = “伪加密”
你现在:
> AES key 内置在服务端代码
---
## ⚠️ 本质问题
```text
攻击者 = 有代码
→ 就有 key
→ 就能解密
```
👉 所以:
> ❗这只是“增加难度”,不是安全
---
## ✅ 改进建议(分级)
### ✔ 低成本优化(推荐你现在做)
```text
key = hash(machineId + salt)
```
👉 每台机器不同
---
### ✔ 中级方案
```text
key = 服务端激活时下发
```
👉 不写死
---
### ✔ 高级方案(企业级)
```text
key = 动态生成 + 混淆 + 分段存储
```
---
# ❗问题2:你“只在初始化时验签”(不够)
你现在:
> init 时验证 → 后续只用缓存
---
## ⚠️ 风险
攻击者可以:
* hook verify 方法
* patch init 逻辑
* 修改内存对象
👉 然后:
> 永远有效
---
## ✅ 正确做法(必须改)
👉 增加:
```text
1. 定时重新验签(例如 5~10 分钟)
2. 关键操作前轻量校验
```
---
# ❗问题3:功能校验点太少(严重)
你现在:
> 只在“订单导入接口”校验
---
## ⚠️ 问题
攻击者可以:
* 直接绕 controller
* 或改调用路径
---
## ✅ 正确做法
👉 必须:
```text
License → Feature Gate → Service 层
```
例如:
```java
if (!license.hasFeature("order-import")) {
throw new ForbiddenException();
}
```
👉 不要只放在 controller
---
# ❗问题4:机器指纹还是“硬绑定”(老问题)
你现在:
```text
cpu + mac + disk → hash
```
---
## ⚠️ 现实问题
* 云服务器 → 会变
* docker → 会变
* 虚拟机 → 不稳定
👉 结果:
> ❗客户频繁失效
---
## ✅ 建议(你这一版必须改)
👉 改为:
```text
machineId = 安装时生成 UUID
```
再:
```text
fingerprint = hash(uuid + 部分硬件信息)
```
---
# ❗问题5:没有 License 吊销机制(依然缺)
你现在:
> 完全离线
---
## ⚠️ 风险
* 客户退款
* License 泄露
* 被破解传播
👉 你无法控制
---
## ✅ 必须补
```json
{
"jti": "license-id"
}
```
👉 + 可选:
```text
定期请求 License Server 校验
```
---
# ❗问题6:没有“抗复制机制”
现在可以:
```text
复制:
- DB
- license 文件
```
👉 到另一台机器
---
## ⚠️ 如果指纹被绕:
> 完全成功
---
## ✅ 建议
增加:
* installId
* 激活记录
* 最大激活次数
---
# ❗问题7:加密顺序可以优化
你现在:
```text
payload → AES → sign
```
---
## 更推荐:
```text
payload → sign → encrypt
```
👉 为什么?
* 签名保护“原始数据”
* 加密保护“整体结构”
👉 更标准(类似 TLS 思路)
---
# ❗问题8:缺少“反调试 / 防hook”
你现在:
> 完全信任 JVM
---
## ⚠️ 实际上:
攻击者可以:
* 用 Java Agent
* 用 ByteBuddy
* 改方法返回值
---
## ✅ 建议(至少做一点)
* 校验关键类 hash
* 检测 debug 模式
* 方法多点校验(不要单点)
---
# ✅ 四、推荐你升级后的结构(最终版)
我帮你整理一个更合理的👇
---
## License 结构
```json
{
"data": "AES加密内容",
"signature": "Ed25519"
}
```
---
## payload(解密后)
```json
{
"companyId": "xxx",
"edition": "enterprise",
"expireAt": 1234567890,
"features": ["order-import"],
"machineId": "xxx",
"jti": "xxx"
}
```
---
## 核心机制
| 模块 | 建议 |
| -- | ---------- |
| 签名 | Ed25519 |
| 加密 | AES-GCM |
| 校验 | 启动 + 定时 |
| 指纹 | UUID + 软绑定 |
| 控制 | Service 层 |
| 吊销 | jti + 在线校验 |
---
# ✅ 五、最终结论(很直接)
你现在这版:
> ✅ 已经不是“练手设计”,而是“可卖钱的版本”
但:
> ❗ 还没到“抗破解级”
---
# 👉 如果你下一步想做到“商业对抗级”
我可以帮你补这三块(这才是真正的差距):
1. ✅ License 混淆(防逆向)
2. ✅ 动态校验(防 patch)
3. ✅ 多点校验(防绕过)
你可以直接说:
👉 **“帮我做一版抗破解 license(对抗用户逆向)”**
+223 -1356
View File
File diff suppressed because it is too large Load Diff
+318
View File
@@ -0,0 +1,318 @@
# Ecom-DMB License 参考附录
> 实施时以 [`DESIGN.md`](./DESIGN.md) 为准。本文供查 JSON 示例、完整 DDL、CLI 细节;**v3 已统一 EdDSA,文中若出现 RS256 请忽略**。
---
## A. 主应用 API 请求/响应
### A.1 `GET /init/status`
```json
{
"initialized": false,
"currentStep": 0,
"adminCreated": false,
"companySaved": false,
"licenseActivated": false
}
```
### A.2 `GET /init/fingerprint`
```json
{
"fingerprint": "FP-A1B2C3D4E5F67890ABCDEF...",
"machineId": "a1b2c3d4-...",
"hostname": "ecom-server-01"
}
```
### A.3 `POST /init/activate` / `PUT /system/license`
请求:
```json
{ "licenseKey": "eyJhbGciOiJFZERTQSJ9..." }
```
激活校验:EdDSA 验签 → `exp` → 指纹匹配(`*` 跳过)→ 写 `sys_license` → `step=3`。
### A.4 `GET /system/license`
```json
{
"companyName": "某某科技",
"edition": "enterprise",
"machineFingerprint": "FP-...",
"features": ["order-import"],
"issuedAt": "2026-01-01T00:00:00Z",
"expiresAt": "2027-01-01T00:00:00Z",
"daysRemaining": 180,
"status": "active"
}
```
### A.5 错误码(导入受限)
| 场景 | HTTP | 业务码建议 |
|------|------|------------|
| 未激活 / 过期 | 403 | `LICENSE_INVALID` |
| 指纹不匹配 | 403 | `LICENSE_FINGERPRINT_MISMATCH` |
| 功能未授权 | 403 | `LICENSE_FEATURE_DENIED` |
| 已吊销 jti | 403 | `LICENSE_REVOKED` |
---
## B. 主应用 DDL(Flyway)
```sql
CREATE TABLE IF NOT EXISTS sys_init (
id BIGINT PRIMARY KEY DEFAULT 1,
step TINYINT NOT NULL DEFAULT 0 COMMENT '0~3',
admin_id BIGINT NULL,
company_name VARCHAR(200) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) COMMENT '系统初始化状态(单行)';
CREATE TABLE IF NOT EXISTS sys_license (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
company_name VARCHAR(200) NOT NULL,
edition VARCHAR(20) NOT NULL,
machine_fingerprint VARCHAR(100) NOT NULL,
installation_id VARCHAR(64) NULL,
license_key TEXT NOT NULL,
jti VARCHAR(64) NOT NULL,
issued_at DATETIME NOT NULL,
expires_at DATETIME NOT NULL,
activated_at DATETIME NOT NULL,
is_active TINYINT NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_jti (jti)
) COMMENT '当前生效 License';
-- 已有环境跳过初始化门禁(仅开发)
INSERT INTO sys_init (id, step) VALUES (1, 3)
ON DUPLICATE KEY UPDATE step = GREATEST(step, 3);
```
---
## C. License 服务器表结构
### `lc_admin`
`id`, `username`, `password`(BCrypt), `nickname`, `status`, `created_at`, `updated_at`
### `lc_customer`
`id`, `code`(UK), `name`, `contact_name`, `contact_phone`, `contact_email`, `status`, `remark`, 时间戳
### `lc_license`
`id`, `customer_id`, `license_key`, `jti`(UK), `edition`, `machine_fingerprint`, `features`(JSON), `status`(active/revoked/expired), `issued_at`, `expires_at`, `revoked_at`, `max_activations`, `activation_count`, 时间戳
### `lc_activation_log`
`license_id`, `machine_fingerprint`, `installation_id`, `hostname`, `ip`, `action`(activate/deactivate), `created_at`
### `lc_oper_log`
`admin_id`, `action`, `target_type`, `target_id`, `detail`(JSON), `ip`, `created_at`
---
## D. License 服务器 API 补充
| 方法 | 路径 | 说明 |
|------|------|------|
| POST | `/api/auth/logout` | 退出 |
| GET | `/api/dashboard/stats` | 统计 |
| GET | `/api/licenses` | 列表 |
| GET | `/api/licenses/:id` | 详情 |
| GET | `/api/licenses/:id/download` | 下载 `.key` 文件 |
| GET | `/api/customers/:id/licenses` | 客户下许可证 |
### `POST /api/licenses/generate`
```json
{
"customerId": 1,
"company": "某某科技有限公司",
"machineFingerprint": "FP-A1B2...",
"edition": "enterprise",
"expiresAt": "2027-01-01T00:00:00Z",
"features": ["order-import"]
}
```
响应含 `licenseKey`(EdDSA JWT)、`jti`、`status: active`。
### `GET /api/licenses/status?jti=xxx`
```json
{ "jti": "uuid", "status": "active", "revokedAt": null }
```
---
## E. CLI 参考
### E.1 交互体验规格(必达)
**原则**:运营工具要「像产品」—— 默认交互模式赏心悦目;脚本/管道模式干净无噪。
#### 技术栈
| 能力 | 库 | 用途 |
|------|-----|------|
| 提问向导 | `@inquirer/prompts` | select / input / confirm / password |
| 颜色语义 | `chalk` | 成功绿、警告黄、错误红、信息灰蓝 |
| 加载态 | `ora` | 请求中 spinner,成功 ✓ / 失败 ✗ |
| 表格 | `cli-table3` | `customer list`、`license list` |
| 信息面板 | `boxen` | 签发结果、whoami、stats 摘要 |
| 品牌标题 | `gradient-string` + `figlet`(可选) | 首次 `login` 或无子命令时轻量 banner |
#### TTY 检测
```
isInteractive = process.stdout.isTTY && !process.env.CI && !--json && !--quiet
```
| 模式 | 行为 |
|------|------|
| 交互(默认) | 缺参走向导;列表用表格;API 用 spinner |
| `--json` | 纯 JSON 一行/结构化,无颜色无 spinner |
| `--quiet` | 只输出关键值(如 `licenseKey`、文件路径) |
| 管道/重定向 | 同 `--json` 语义,禁止 boxen/figlet |
#### 全局体验
- **无子命令** / `ecom-license --help`:简短 banner + 常用命令示例(带颜色)
- **未登录**:友好提示 + 引导 `ecom-license login`,非裸 `401`
- **网络/超时**:spinner 停止后一行人话错误 + 可选 `--verbose` 看堆栈
- **Ctrl+C**:优雅退出,不打印 Node 堆栈
#### 命令级交互
**`login`**(交互)
```
╭─ Ecom License CLI ─────────────────╮
│ 授权管理平台 · 运营端 │
╰─────────────────────────────────────╯
? API 地址 › http://localhost:3100
? 用户名 › admin
? 密码 › ********
⠋ 正在登录...
✔ 登录成功 · admin · Token 有效期至 2026-06-01
```
**`license generate`**(交互向导,分步 confirm)
1. `search` 选客户(支持输入过滤,非手打 ID)
2. 公司名(默认带出客户名,可改)
3. 指纹:`input` 或选「SaaS 不限指纹 (*)」
4. `select` edition:trial / enterprise / unlimited(带简短说明)
5. 过期日:`input` + 校验,提供快捷项「+1年」「+30天」
6. features:默认勾选 `order-import`,`checkbox` 确认
7. **摘要面板**(boxen)展示全部字段 → `confirm` 签发
8. 成功:绿色面板输出 `jti`、过期日;`licenseKey` 可复制(长文本折行 + 提示 `--quiet` 取纯 key)
**`license revoke`**:`confirm` 二次确认(展示 jti/公司/指纹),`--yes` 跳过
**`customer list` / `license list`**:表格列对齐;空列表提示「暂无数据」+ 下一步建议(如 `customer create`)
**`stats`**:boxen 数字卡片风格(客户数 / 有效证 / 即将过期)
**`download`**:spinner + 成功显示保存路径(绿色)
#### 输出示例(列表表格)
```
ID CODE NAME STATUS
─── ──────────────── ─────────────────── ──────
1 CUST-20260101-01 某某科技有限公司 启用
2 CUST-20260215-02 示例客户有限公司 启用
共 2 条 · 第 1/1 页
```
#### 实现约束
- 交互逻辑与 API 调用分离:`commands/*.ts` + `ui/prompts.ts` + `ui/render.ts`
- 所有 spinner 在 `finally` 中 `stop()`,避免残留
- 颜色跟随 `NO_COLOR` / `FORCE_COLOR` 环境变量
- 单元测试覆盖非交互路径;交互路径用 snapshot 测 `render.ts` 纯文本
---
### E.2 配置 `~/.config/ecom-license/config.json`
```json
{
"apiUrl": "http://localhost:3100",
"token": "eyJ...",
"username": "admin",
"expiresAt": "2026-05-25T12:00:00Z"
}
```
优先级:命令行 flag > 环境变量 > 配置文件。
### 全局选项
| 选项 | 环境变量 |
|------|----------|
| `--url` | `ECOM_LICENSE_API_URL` |
| `--token` | `ECOM_LICENSE_TOKEN` |
| `--json` / `--quiet` / `--yes` | — |
### 非交互签发示例
```bash
ecom-license license generate \
--customer-id 1 \
--company "某某科技" \
--fingerprint "FP-A1B2..." \
--edition enterprise \
--expires "2027-01-01" \
--features order-import \
--json
```
SaaS:`--fingerprint "*"`
### E.3 交互式 `license generate` 步骤
客户(可搜索选择)→ 公司名 → 指纹或 `*` → edition → 过期日(快捷 +1年)→ features → 摘要确认 → 签发。
完整视觉与组件选型见 **§E.1**。
---
## F. v3 相对 v2 / 评审 `1.md` 的决策记录
| 议题 | 决策 |
|------|------|
| 签名算法 | **Ed25519 / EdDSA**(非 RSA) |
| 格式 | **标准 JWT**,payload 明文(非自定义结构、非 AES) |
| 校验 | Controller AOP + **Service 双点** |
| 定时验签 | **采纳**,默认 10 分钟 `fullValidate` |
| 在线吊销 | **可选**,默认关 |
| 反调试 / NTP 拒请求 | **首版不做** |
完整评审原文见 [`1.md`](./1.md)。
---
## G. 历史完整设计
Git 中 v2 长文档(RSA、含大段 Java 伪代码)可通过以下命令查看,**勿作为实现依据**:
```bash
git show HEAD:ecom-license/DESIGN.md
```
+58
View File
@@ -0,0 +1,58 @@
# Ecom License 平台
`ecom-license/` 是**文档 + 两个独立 Node 子项目**的目录,不是 pnpm monorepo:
```
ecom-license/
├── DESIGN.md # 设计文档
├── server/ # NestJS 签发服务(独立 pnpm 项目)
└── cli/ # 运营 CLI(独立 pnpm 项目)
```
各子项目在自己的目录里 `pnpm install`,依赖装在 `server/node_modules`、`cli/node_modules`,**根目录不会有 node_modules**。
## 环境要求
- Node.js >= 18
- pnpm >= 8
- MySQL
## Server 快速开始
```bash
cd ecom-license/server
pnpm install
# 初始化表(在目标库执行 sql/schema.sql)
mysql -h <host> -u ecom_license_dev -p ecom_license_dev < sql/schema.sql
# 生成密钥
openssl genpkey -algorithm Ed25519 -out keys/private.pem
openssl pkey -in keys/private.pem -pubout -out keys/public.pem
cp .env.example .env
pnpm build
pnpm start:dev # http://localhost:3100
```
## CLI 快速开始
```bash
cd ecom-license/cli
pnpm install
pnpm build
# 开发(改代码后即时运行,需带子命令)
pnpm dev login
pnpm dev license generate
# 或构建后运行
pnpm start login # 默认 admin / admin123
pnpm stats
```
> 不要用裸 `pnpm dev` / `npm run dev`(无子命令只会显示引导)。请用 `pnpm dev login` 等。
## 主应用公钥
将 `server/keys/public.pem` 配置到主应用 `ECOM_LICENSE_PUBLIC_KEY`。
+393
View File
@@ -0,0 +1,393 @@
# ecom-license CLI
Ecom-DMB License 运营管理命令行工具,用于登录 License Server、管理客户与签发/吊销许可证。
**前置条件**:License Server 已启动(默认 `http://localhost:3100`)。首次登录默认账号 `admin` / `admin123`。
---
## 安装与运行
```bash
cd ecom-license/cli
pnpm install
pnpm build # 可选,生产模式需要
```
| 方式 | 命令 | 说明 |
|------|------|------|
| 开发模式 | `pnpm dev <子命令>` | 使用 `tsx` 直接运行源码 |
| 构建产物 | `pnpm start <子命令>` | 运行 `dist/index.js` |
| 全局安装 | `pnpm link --global` 后 `ecom-license` | 需先 `pnpm build` |
| 快捷脚本 | `pnpm login` / `pnpm whoami` / `pnpm stats` | 等价于 `pnpm dev <命令>` |
无子命令时显示常用命令引导;完整帮助:
```bash
pnpm dev -- --help
pnpm dev customer --help
pnpm dev license --help
```
---
## 配置
登录成功后写入本地配置文件:
| 项 | 值 |
|----|-----|
| 默认路径 | `~/.config/ecom-license/config.json` |
| 自定义路径 | 环境变量 `ECOM_LICENSE_CONFIG` |
```json
{
"apiUrl": "http://localhost:3100",
"token": "eyJ...",
"username": "admin",
"expiresAt": "2026-06-01T00:00:00.000Z"
}
```
`logout` 会清除 token,保留 `apiUrl`。
---
## 环境变量
| 变量 | 作用 |
|------|------|
| `ECOM_LICENSE_API_URL` | API 根地址(优先级低于 `--url`) |
| `ECOM_LICENSE_TOKEN` | Bearer Token(优先级低于 `--token`) |
| `ECOM_LICENSE_USERNAME` | 非交互 `login` 用户名 |
| `ECOM_LICENSE_PASSWORD` | 非交互 `login` 密码 |
| `ECOM_LICENSE_CONFIG` | 配置文件路径 |
| `CI` | 存在时禁用交互向导 |
| `NO_COLOR` / `FORCE_COLOR` | 控制终端颜色 |
---
## 全局选项
所有命令均支持(写在子命令前或后均可,由 Commander 解析):
| 选项 | 说明 |
|------|------|
| `--url <base>` | API 根地址,如 `http://localhost:3100` |
| `--token <jwt>` | 临时指定 Token,不写配置文件 |
| `--json` | 纯 JSON 输出,适合脚本 |
| `--quiet` | 仅输出关键值(如 ID、licenseKey、文件路径) |
| `--yes` | 跳过确认(删除客户、吊销许可证) |
| `--verbose` | 显示详细错误堆栈 |
| `-V, --version` | 版本号 |
| `-h, --help` | 帮助 |
### 输出模式
| 模式 | 条件 | 行为 |
|------|------|------|
| 交互(默认) | TTY 且非 `CI`,无 `--json`/`--quiet` | 缺参时向导提问;列表用表格;请求有 spinner |
| `--json` | 显式指定 | 结构化 JSON,无颜色 |
| `--quiet` | 显式指定 | 单行关键值,便于管道 |
| 管道/重定向 | stdout 非 TTY | 同 `--json` 语义,不展示 banner/boxen |
---
## 命令总览
```
ecom-license [--url] [--token] [--json] [--quiet] [--yes] [--verbose]
login [--username] [--password]
logout
whoami
stats
customer list [--page] [--size]
customer create [--code] [--name] [--contact-name] [--contact-phone] [--contact-email]
customer show <id>
customer delete <id>
license list [--page] [--size] [--customer-id] [--status]
license show <id>
license generate [--customer-id] [--company] [--fingerprint] [--edition] [--expires] [--features]
license revoke <id>
license download <id> [-o|--output <file>]
```
---
## 认证与会话
### `login`
登录 License 平台,保存 Token 到配置文件。
| 选项 | 说明 |
|------|------|
| `--username <name>` | 用户名(非交互必填其一) |
| `--password <pwd>` | 密码 |
**交互模式**:依次询问 API 地址(默认当前配置或 `http://localhost:3100`)、用户名、密码。
```bash
pnpm dev login
pnpm dev login --username admin --password admin123
ECOM_LICENSE_USERNAME=admin ECOM_LICENSE_PASSWORD=admin123 pnpm dev login
pnpm dev login --url http://192.168.1.10:3100
```
### `logout`
清除本地 Token,不删除 API 地址配置。
```bash
pnpm dev logout
```
### `whoami`
查看当前登录状态(API 地址、用户名、Token 过期时间)。
```bash
pnpm dev whoami
pnpm dev whoami --json
pnpm dev whoami --quiet # 仅输出用户名
```
未登录时退出码 `1`,并提示运行 `login`。
### `stats`
获取平台统计:客户数、有效许可证、即将过期、许可证总数。
```bash
pnpm dev stats
pnpm dev stats --json
pnpm dev stats --quiet # 仅输出有效许可证数量
```
---
## 客户管理 `customer`
### `customer list`
分页列出客户。
| 选项 | 默认 | 说明 |
|------|------|------|
| `--page <n>` | `1` | 页码 |
| `--size <n>` | `20` | 每页条数 |
```bash
pnpm dev customer list
pnpm dev customer list --page 2 --size 10
pnpm dev customer list --json
```
### `customer create`
创建客户。交互模式下会逐步询问公司名、联系人、电话、邮箱、客户编码(编码可留空自动生成)。
| 选项 | 说明 |
|------|------|
| `--name <name>` | 公司名称(**必填**,非交互) |
| `--code <code>` | 客户编码,省略则服务端自动生成 |
| `--contact-name <n>` | 联系人 |
| `--contact-phone <p>` | 联系电话 |
| `--contact-email <e>` | 联系邮箱 |
```bash
pnpm dev customer create
pnpm dev customer create --name "某某科技有限公司" --contact-name 张三 --contact-phone 13800138000
pnpm dev customer create --name "示例公司" --code CUST-001 --json
pnpm dev customer create --name "示例公司" --quiet # 仅输出新客户 ID
```
### `customer show <id>`
查看单个客户详情(JSON 格式)。
```bash
pnpm dev customer show 1
pnpm dev customer show 1 --json
```
### `customer delete <id>`
删除客户。交互模式下需二次确认;`--yes` 跳过确认。
```bash
pnpm dev customer delete 1
pnpm dev customer delete 1 --yes
```
---
## 许可证管理 `license`
### `license list`
分页列出许可证,可按客户、状态筛选。
| 选项 | 默认 | 说明 |
|------|------|------|
| `--page <n>` | `1` | 页码 |
| `--size <n>` | `20` | 每页条数 |
| `--customer-id <id>` | — | 按客户 ID 过滤 |
| `--status <s>` | — | 按状态过滤(如 `active`、`revoked`) |
```bash
pnpm dev license list
pnpm dev license list --customer-id 1 --status active
pnpm dev license list --json
```
### `license show <id>`
查看单个许可证详情。
```bash
pnpm dev license show 1
pnpm dev license show 1 --json
```
### `license generate`
签发新许可证。交互模式为分步向导:选择客户 → 公司名 → 机器指纹 → 版本 → 有效期 → 功能 → 确认摘要。
| 选项 | 默认 | 说明 |
|------|------|------|
| `--customer-id <id>` | — | 客户 ID |
| `--company <name>` | — | 授权公司名 |
| `--fingerprint <fp>` | — | 机器指纹,`FP-xxx` 或 `*`(SaaS 不限) |
| `--edition <e>` | `enterprise` | 版本:`trial` / `enterprise` / `unlimited` |
| `--expires <date>` | — | 过期日 `YYYY-MM-DD` |
| `--features <list>` | `order-import` | 逗号分隔功能列表 |
**非交互模式**必须同时提供:`--customer-id`、`--company`、`--fingerprint`、`--expires`。
```bash
# 交互向导(推荐)
pnpm dev license generate
# 脚本签发
pnpm dev license generate \
--customer-id 1 \
--company "某某科技有限公司" \
--fingerprint "FP-abc123" \
--edition enterprise \
--expires 2027-05-28 \
--features order-import
# SaaS 不限指纹
pnpm dev license generate \
--customer-id 1 \
--company "SaaS 客户" \
--fingerprint "*" \
--expires 2027-05-28
# 仅输出 licenseKey(便于复制到主应用激活)
pnpm dev license generate ... --quiet
pnpm dev license generate ... --json
```
签发成功后交互模式以绿色面板展示 ID、JTI、过期日与完整 `licenseKey`。
### `license revoke <id>`
吊销许可证。交互模式下展示 JTI、指纹并二次确认;`--yes` 跳过。
```bash
pnpm dev license revoke 1
pnpm dev license revoke 1 --yes
pnpm dev license revoke 1 --json
```
### `license download <id>`
下载许可证文件到本地。
| 选项 | 默认 | 说明 |
|------|------|------|
| `-o, --output <file>` | `license-<id>.key` | 保存路径 |
```bash
pnpm dev license download 1
pnpm dev license download 1 -o ./my-license.key
pnpm dev license download 1 --quiet # 仅输出文件路径
```
---
## 典型工作流
### 1. 首次使用
```bash
# 1. 确保 License Server 已启动(ecom-license/server)
cd ../server && pnpm start:dev
# 2. 登录
cd ../cli && pnpm dev login
# 3. 查看平台概况
pnpm dev stats
```
### 2. 为客户签发 License
```bash
pnpm dev customer create --name "某某科技有限公司"
pnpm dev customer list --quiet # 记下客户 ID,或直接用交互 generate
pnpm dev license generate # 交互向导
# 或
pnpm dev license generate \
--customer-id 1 \
--company "某某科技有限公司" \
--fingerprint "FP-xxxxxxxx" \
--expires 2027-12-31 \
--quiet > license.key
```
### 3. CI / 脚本集成
```bash
export ECOM_LICENSE_API_URL=http://license.internal:3100
export ECOM_LICENSE_TOKEN="$(pnpm dev login --username admin --password "$SECRET" --json | jq -r .token)"
pnpm dev customer list --json | jq '.items | length'
pnpm dev stats --json
```
---
## 错误与提示
| 情况 | 行为 |
|------|------|
| 未登录调用需鉴权 API | 提示运行 `ecom-license login`,非裸 401 |
| 网络/服务端错误 | spinner 停止后显示可读错误;加 `--verbose` 看堆栈 |
| Ctrl+C 中断向导 | 优雅退出,不打印 Node 堆栈 |
| 空列表 | 提示下一步建议(如「运行 customer create」) |
---
## 当前未实现的子命令
以下能力在 License Server API 中可能存在,CLI 尚未接入:
- `customer update` — 更新客户信息
- `customer licenses <id>` — 查看某客户下全部许可证
如需使用,可直接调用 Server REST API,或后续在 CLI 中补充。
---
## 相关文档
- 整体设计:`../DESIGN.md`
- CLI 交互规格:`../DESIGN.reference.md` §E
- Server 启动:`../server/README.md`(若有)或 `../README.md`
+32
View File
@@ -0,0 +1,32 @@
{
"name": "ecom-license-cli",
"version": "0.1.0",
"private": true,
"packageManager": "pnpm@10.32.0",
"type": "module",
"bin": {
"ecom-license": "./dist/index.js"
},
"scripts": {
"build": "tsc",
"dev": "tsx src/index.ts",
"start": "node dist/index.js",
"login": "tsx src/index.ts login",
"whoami": "tsx src/index.ts whoami",
"stats": "tsx src/index.ts stats"
},
"dependencies": {
"@inquirer/prompts": "^7.2.0",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"cli-table3": "^0.6.5",
"commander": "^13.0.0",
"gradient-string": "^3.0.0",
"ora": "^8.1.1"
},
"devDependencies": {
"@types/node": "^22.10.2",
"tsx": "^4.19.2",
"typescript": "^5.7.2"
}
}
+959
View File
@@ -0,0 +1,959 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
dependencies:
'@inquirer/prompts':
specifier: ^7.2.0
version: 7.10.1(@types/node@22.19.20)
boxen:
specifier: ^8.0.1
version: 8.0.1
chalk:
specifier: ^5.4.1
version: 5.6.2
cli-table3:
specifier: ^0.6.5
version: 0.6.5
commander:
specifier: ^13.0.0
version: 13.1.0
gradient-string:
specifier: ^3.0.0
version: 3.0.0
ora:
specifier: ^8.1.1
version: 8.2.0
devDependencies:
'@types/node':
specifier: ^22.10.2
version: 22.19.20
tsx:
specifier: ^4.19.2
version: 4.22.4
typescript:
specifier: ^5.7.2
version: 5.9.3
packages:
'@colors/colors@1.5.0':
resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
engines: {node: '>=0.1.90'}
'@esbuild/aix-ppc64@0.28.0':
resolution: {integrity: sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [aix]
'@esbuild/android-arm64@0.28.0':
resolution: {integrity: sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [android]
'@esbuild/android-arm@0.28.0':
resolution: {integrity: sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==}
engines: {node: '>=18'}
cpu: [arm]
os: [android]
'@esbuild/android-x64@0.28.0':
resolution: {integrity: sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==}
engines: {node: '>=18'}
cpu: [x64]
os: [android]
'@esbuild/darwin-arm64@0.28.0':
resolution: {integrity: sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==}
engines: {node: '>=18'}
cpu: [arm64]
os: [darwin]
'@esbuild/darwin-x64@0.28.0':
resolution: {integrity: sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [darwin]
'@esbuild/freebsd-arm64@0.28.0':
resolution: {integrity: sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==}
engines: {node: '>=18'}
cpu: [arm64]
os: [freebsd]
'@esbuild/freebsd-x64@0.28.0':
resolution: {integrity: sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==}
engines: {node: '>=18'}
cpu: [x64]
os: [freebsd]
'@esbuild/linux-arm64@0.28.0':
resolution: {integrity: sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==}
engines: {node: '>=18'}
cpu: [arm64]
os: [linux]
'@esbuild/linux-arm@0.28.0':
resolution: {integrity: sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==}
engines: {node: '>=18'}
cpu: [arm]
os: [linux]
'@esbuild/linux-ia32@0.28.0':
resolution: {integrity: sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==}
engines: {node: '>=18'}
cpu: [ia32]
os: [linux]
'@esbuild/linux-loong64@0.28.0':
resolution: {integrity: sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==}
engines: {node: '>=18'}
cpu: [loong64]
os: [linux]
'@esbuild/linux-mips64el@0.28.0':
resolution: {integrity: sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==}
engines: {node: '>=18'}
cpu: [mips64el]
os: [linux]
'@esbuild/linux-ppc64@0.28.0':
resolution: {integrity: sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [linux]
'@esbuild/linux-riscv64@0.28.0':
resolution: {integrity: sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==}
engines: {node: '>=18'}
cpu: [riscv64]
os: [linux]
'@esbuild/linux-s390x@0.28.0':
resolution: {integrity: sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==}
engines: {node: '>=18'}
cpu: [s390x]
os: [linux]
'@esbuild/linux-x64@0.28.0':
resolution: {integrity: sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [linux]
'@esbuild/netbsd-arm64@0.28.0':
resolution: {integrity: sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [netbsd]
'@esbuild/netbsd-x64@0.28.0':
resolution: {integrity: sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==}
engines: {node: '>=18'}
cpu: [x64]
os: [netbsd]
'@esbuild/openbsd-arm64@0.28.0':
resolution: {integrity: sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openbsd]
'@esbuild/openbsd-x64@0.28.0':
resolution: {integrity: sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==}
engines: {node: '>=18'}
cpu: [x64]
os: [openbsd]
'@esbuild/openharmony-arm64@0.28.0':
resolution: {integrity: sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openharmony]
'@esbuild/sunos-x64@0.28.0':
resolution: {integrity: sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==}
engines: {node: '>=18'}
cpu: [x64]
os: [sunos]
'@esbuild/win32-arm64@0.28.0':
resolution: {integrity: sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==}
engines: {node: '>=18'}
cpu: [arm64]
os: [win32]
'@esbuild/win32-ia32@0.28.0':
resolution: {integrity: sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==}
engines: {node: '>=18'}
cpu: [ia32]
os: [win32]
'@esbuild/win32-x64@0.28.0':
resolution: {integrity: sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==}
engines: {node: '>=18'}
cpu: [x64]
os: [win32]
'@inquirer/ansi@1.0.2':
resolution: {integrity: sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ==}
engines: {node: '>=18'}
'@inquirer/checkbox@4.3.2':
resolution: {integrity: sha512-VXukHf0RR1doGe6Sm4F0Em7SWYLTHSsbGfJdS9Ja2bX5/D5uwVOEjr07cncLROdBvmnvCATYEWlHqYmXv2IlQA==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/confirm@5.1.21':
resolution: {integrity: sha512-KR8edRkIsUayMXV+o3Gv+q4jlhENF9nMYUZs9PA2HzrXeHI8M5uDag70U7RJn9yyiMZSbtF5/UexBtAVtZGSbQ==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/core@10.3.2':
resolution: {integrity: sha512-43RTuEbfP8MbKzedNqBrlhhNKVwoK//vUFNW3Q3vZ88BLcrs4kYpGg+B2mm5p2K/HfygoCxuKwJJiv8PbGmE0A==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/editor@4.2.23':
resolution: {integrity: sha512-aLSROkEwirotxZ1pBaP8tugXRFCxW94gwrQLxXfrZsKkfjOYC1aRvAZuhpJOb5cu4IBTJdsCigUlf2iCOu4ZDQ==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/expand@4.0.23':
resolution: {integrity: sha512-nRzdOyFYnpeYTTR2qFwEVmIWypzdAx/sIkCMeTNTcflFOovfqUk+HcFhQQVBftAh9gmGrpFj6QcGEqrDMDOiew==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/external-editor@1.0.3':
resolution: {integrity: sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/figures@1.0.15':
resolution: {integrity: sha512-t2IEY+unGHOzAaVM5Xx6DEWKeXlDDcNPeDyUpsRc6CUhBfU3VQOEl+Vssh7VNp1dR8MdUJBWhuObjXCsVpjN5g==}
engines: {node: '>=18'}
'@inquirer/input@4.3.1':
resolution: {integrity: sha512-kN0pAM4yPrLjJ1XJBjDxyfDduXOuQHrBB8aLDMueuwUGn+vNpF7Gq7TvyVxx8u4SHlFFj4trmj+a2cbpG4Jn1g==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/number@3.0.23':
resolution: {integrity: sha512-5Smv0OK7K0KUzUfYUXDXQc9jrf8OHo4ktlEayFlelCjwMXz0299Y8OrI+lj7i4gCBY15UObk76q0QtxjzFcFcg==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/password@4.0.23':
resolution: {integrity: sha512-zREJHjhT5vJBMZX/IUbyI9zVtVfOLiTO66MrF/3GFZYZ7T4YILW5MSkEYHceSii/KtRk+4i3RE7E1CUXA2jHcA==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/prompts@7.10.1':
resolution: {integrity: sha512-Dx/y9bCQcXLI5ooQ5KyvA4FTgeo2jYj/7plWfV5Ak5wDPKQZgudKez2ixyfz7tKXzcJciTxqLeK7R9HItwiByg==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/rawlist@4.1.11':
resolution: {integrity: sha512-+LLQB8XGr3I5LZN/GuAHo+GpDJegQwuPARLChlMICNdwW7OwV2izlCSCxN6cqpL0sMXmbKbFcItJgdQq5EBXTw==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/search@3.2.2':
resolution: {integrity: sha512-p2bvRfENXCZdWF/U2BXvnSI9h+tuA8iNqtUKb9UWbmLYCRQxd8WkvwWvYn+3NgYaNwdUkHytJMGG4MMLucI1kA==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/select@4.4.2':
resolution: {integrity: sha512-l4xMuJo55MAe+N7Qr4rX90vypFwCajSakx59qe/tMaC1aEHWLyw68wF4o0A4SLAY4E0nd+Vt+EyskeDIqu1M6w==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@inquirer/type@3.0.10':
resolution: {integrity: sha512-BvziSRxfz5Ov8ch0z/n3oijRSEcEsHnhggm4xFZe93DHcUCTlutlq9Ox4SVENAfcRD22UQq7T/atg9Wr3k09eA==}
engines: {node: '>=18'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
'@types/node@22.19.20':
resolution: {integrity: sha512-6tELRwSDYWW9EdZhbeZmYGZ1/7Djkt+Ah3/ScEYT9cDord7UJzasR/4D3VONg9tQI5CDp+/CZC1AXj2pCFOvpw==}
'@types/tinycolor2@1.4.6':
resolution: {integrity: sha512-iEN8J0BoMnsWBqjVbWH/c0G0Hh7O21lpR2/+PrvAVgWdzL7eexIFm4JN/Wn10PTcmNdtS6U67r499mlWMXOxNw==}
ansi-align@3.0.1:
resolution: {integrity: sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==}
ansi-regex@5.0.1:
resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
engines: {node: '>=8'}
ansi-regex@6.2.2:
resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==}
engines: {node: '>=12'}
ansi-styles@4.3.0:
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
engines: {node: '>=8'}
ansi-styles@6.2.3:
resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}
engines: {node: '>=12'}
boxen@8.0.1:
resolution: {integrity: sha512-F3PH5k5juxom4xktynS7MoFY+NUWH5LC4CnH11YB8NPew+HLpmBLCybSAEyb2F+4pRXhuhWqFesoQd6DAyc2hw==}
engines: {node: '>=18'}
camelcase@8.0.0:
resolution: {integrity: sha512-8WB3Jcas3swSvjIeA2yvCJ+Miyz5l1ZmB6HFb9R1317dt9LCQoswg/BGrmAmkWVEszSrrg4RwmO46qIm2OEnSA==}
engines: {node: '>=16'}
chalk@5.6.2:
resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==}
engines: {node: ^12.17.0 || ^14.13 || >=16.0.0}
chardet@2.1.1:
resolution: {integrity: sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==}
cli-boxes@3.0.0:
resolution: {integrity: sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==}
engines: {node: '>=10'}
cli-cursor@5.0.0:
resolution: {integrity: sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==}
engines: {node: '>=18'}
cli-spinners@2.9.2:
resolution: {integrity: sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==}
engines: {node: '>=6'}
cli-table3@0.6.5:
resolution: {integrity: sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==}
engines: {node: 10.* || >= 12.*}
cli-width@4.1.0:
resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==}
engines: {node: '>= 12'}
color-convert@2.0.1:
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
engines: {node: '>=7.0.0'}
color-name@1.1.4:
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
commander@13.1.0:
resolution: {integrity: sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==}
engines: {node: '>=18'}
emoji-regex@10.6.0:
resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==}
emoji-regex@8.0.0:
resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
esbuild@0.28.0:
resolution: {integrity: sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==}
engines: {node: '>=18'}
hasBin: true
fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
get-east-asian-width@1.6.0:
resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==}
engines: {node: '>=18'}
gradient-string@3.0.0:
resolution: {integrity: sha512-frdKI4Qi8Ihp4C6wZNB565de/THpIaw3DjP5ku87M+N9rNSGmPTjfkq61SdRXB7eCaL8O1hkKDvf6CDMtOzIAg==}
engines: {node: '>=14'}
iconv-lite@0.7.2:
resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==}
engines: {node: '>=0.10.0'}
is-fullwidth-code-point@3.0.0:
resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
engines: {node: '>=8'}
is-interactive@2.0.0:
resolution: {integrity: sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==}
engines: {node: '>=12'}
is-unicode-supported@1.3.0:
resolution: {integrity: sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==}
engines: {node: '>=12'}
is-unicode-supported@2.1.0:
resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==}
engines: {node: '>=18'}
log-symbols@6.0.0:
resolution: {integrity: sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==}
engines: {node: '>=18'}
mimic-function@5.0.1:
resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}
engines: {node: '>=18'}
mute-stream@2.0.0:
resolution: {integrity: sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA==}
engines: {node: ^18.17.0 || >=20.5.0}
onetime@7.0.0:
resolution: {integrity: sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==}
engines: {node: '>=18'}
ora@8.2.0:
resolution: {integrity: sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw==}
engines: {node: '>=18'}
restore-cursor@5.1.0:
resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==}
engines: {node: '>=18'}
safer-buffer@2.1.2:
resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
signal-exit@4.1.0:
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
engines: {node: '>=14'}
stdin-discarder@0.2.2:
resolution: {integrity: sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==}
engines: {node: '>=18'}
string-width@4.2.3:
resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
engines: {node: '>=8'}
string-width@7.2.0:
resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==}
engines: {node: '>=18'}
strip-ansi@6.0.1:
resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
engines: {node: '>=8'}
strip-ansi@7.2.0:
resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==}
engines: {node: '>=12'}
tinycolor2@1.6.0:
resolution: {integrity: sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==}
tinygradient@1.1.5:
resolution: {integrity: sha512-8nIfc2vgQ4TeLnk2lFj4tRLvvJwEfQuabdsmvDdQPT0xlk9TaNtpGd6nNRxXoK6vQhN6RSzj+Cnp5tTQmpxmbw==}
tsx@4.22.4:
resolution: {integrity: sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg==}
engines: {node: '>=18.0.0'}
hasBin: true
type-fest@4.41.0:
resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==}
engines: {node: '>=16'}
typescript@5.9.3:
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
engines: {node: '>=14.17'}
hasBin: true
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
widest-line@5.0.0:
resolution: {integrity: sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==}
engines: {node: '>=18'}
wrap-ansi@6.2.0:
resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==}
engines: {node: '>=8'}
wrap-ansi@9.0.2:
resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==}
engines: {node: '>=18'}
yoctocolors-cjs@2.1.3:
resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==}
engines: {node: '>=18'}
snapshots:
'@colors/colors@1.5.0':
optional: true
'@esbuild/aix-ppc64@0.28.0':
optional: true
'@esbuild/android-arm64@0.28.0':
optional: true
'@esbuild/android-arm@0.28.0':
optional: true
'@esbuild/android-x64@0.28.0':
optional: true
'@esbuild/darwin-arm64@0.28.0':
optional: true
'@esbuild/darwin-x64@0.28.0':
optional: true
'@esbuild/freebsd-arm64@0.28.0':
optional: true
'@esbuild/freebsd-x64@0.28.0':
optional: true
'@esbuild/linux-arm64@0.28.0':
optional: true
'@esbuild/linux-arm@0.28.0':
optional: true
'@esbuild/linux-ia32@0.28.0':
optional: true
'@esbuild/linux-loong64@0.28.0':
optional: true
'@esbuild/linux-mips64el@0.28.0':
optional: true
'@esbuild/linux-ppc64@0.28.0':
optional: true
'@esbuild/linux-riscv64@0.28.0':
optional: true
'@esbuild/linux-s390x@0.28.0':
optional: true
'@esbuild/linux-x64@0.28.0':
optional: true
'@esbuild/netbsd-arm64@0.28.0':
optional: true
'@esbuild/netbsd-x64@0.28.0':
optional: true
'@esbuild/openbsd-arm64@0.28.0':
optional: true
'@esbuild/openbsd-x64@0.28.0':
optional: true
'@esbuild/openharmony-arm64@0.28.0':
optional: true
'@esbuild/sunos-x64@0.28.0':
optional: true
'@esbuild/win32-arm64@0.28.0':
optional: true
'@esbuild/win32-ia32@0.28.0':
optional: true
'@esbuild/win32-x64@0.28.0':
optional: true
'@inquirer/ansi@1.0.2': {}
'@inquirer/checkbox@4.3.2(@types/node@22.19.20)':
dependencies:
'@inquirer/ansi': 1.0.2
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/figures': 1.0.15
'@inquirer/type': 3.0.10(@types/node@22.19.20)
yoctocolors-cjs: 2.1.3
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/confirm@5.1.21(@types/node@22.19.20)':
dependencies:
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/type': 3.0.10(@types/node@22.19.20)
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/core@10.3.2(@types/node@22.19.20)':
dependencies:
'@inquirer/ansi': 1.0.2
'@inquirer/figures': 1.0.15
'@inquirer/type': 3.0.10(@types/node@22.19.20)
cli-width: 4.1.0
mute-stream: 2.0.0
signal-exit: 4.1.0
wrap-ansi: 6.2.0
yoctocolors-cjs: 2.1.3
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/editor@4.2.23(@types/node@22.19.20)':
dependencies:
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/external-editor': 1.0.3(@types/node@22.19.20)
'@inquirer/type': 3.0.10(@types/node@22.19.20)
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/expand@4.0.23(@types/node@22.19.20)':
dependencies:
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/type': 3.0.10(@types/node@22.19.20)
yoctocolors-cjs: 2.1.3
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/external-editor@1.0.3(@types/node@22.19.20)':
dependencies:
chardet: 2.1.1
iconv-lite: 0.7.2
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/figures@1.0.15': {}
'@inquirer/input@4.3.1(@types/node@22.19.20)':
dependencies:
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/type': 3.0.10(@types/node@22.19.20)
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/number@3.0.23(@types/node@22.19.20)':
dependencies:
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/type': 3.0.10(@types/node@22.19.20)
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/password@4.0.23(@types/node@22.19.20)':
dependencies:
'@inquirer/ansi': 1.0.2
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/type': 3.0.10(@types/node@22.19.20)
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/prompts@7.10.1(@types/node@22.19.20)':
dependencies:
'@inquirer/checkbox': 4.3.2(@types/node@22.19.20)
'@inquirer/confirm': 5.1.21(@types/node@22.19.20)
'@inquirer/editor': 4.2.23(@types/node@22.19.20)
'@inquirer/expand': 4.0.23(@types/node@22.19.20)
'@inquirer/input': 4.3.1(@types/node@22.19.20)
'@inquirer/number': 3.0.23(@types/node@22.19.20)
'@inquirer/password': 4.0.23(@types/node@22.19.20)
'@inquirer/rawlist': 4.1.11(@types/node@22.19.20)
'@inquirer/search': 3.2.2(@types/node@22.19.20)
'@inquirer/select': 4.4.2(@types/node@22.19.20)
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/rawlist@4.1.11(@types/node@22.19.20)':
dependencies:
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/type': 3.0.10(@types/node@22.19.20)
yoctocolors-cjs: 2.1.3
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/search@3.2.2(@types/node@22.19.20)':
dependencies:
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/figures': 1.0.15
'@inquirer/type': 3.0.10(@types/node@22.19.20)
yoctocolors-cjs: 2.1.3
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/select@4.4.2(@types/node@22.19.20)':
dependencies:
'@inquirer/ansi': 1.0.2
'@inquirer/core': 10.3.2(@types/node@22.19.20)
'@inquirer/figures': 1.0.15
'@inquirer/type': 3.0.10(@types/node@22.19.20)
yoctocolors-cjs: 2.1.3
optionalDependencies:
'@types/node': 22.19.20
'@inquirer/type@3.0.10(@types/node@22.19.20)':
optionalDependencies:
'@types/node': 22.19.20
'@types/node@22.19.20':
dependencies:
undici-types: 6.21.0
'@types/tinycolor2@1.4.6': {}
ansi-align@3.0.1:
dependencies:
string-width: 4.2.3
ansi-regex@5.0.1: {}
ansi-regex@6.2.2: {}
ansi-styles@4.3.0:
dependencies:
color-convert: 2.0.1
ansi-styles@6.2.3: {}
boxen@8.0.1:
dependencies:
ansi-align: 3.0.1
camelcase: 8.0.0
chalk: 5.6.2
cli-boxes: 3.0.0
string-width: 7.2.0
type-fest: 4.41.0
widest-line: 5.0.0
wrap-ansi: 9.0.2
camelcase@8.0.0: {}
chalk@5.6.2: {}
chardet@2.1.1: {}
cli-boxes@3.0.0: {}
cli-cursor@5.0.0:
dependencies:
restore-cursor: 5.1.0
cli-spinners@2.9.2: {}
cli-table3@0.6.5:
dependencies:
string-width: 4.2.3
optionalDependencies:
'@colors/colors': 1.5.0
cli-width@4.1.0: {}
color-convert@2.0.1:
dependencies:
color-name: 1.1.4
color-name@1.1.4: {}
commander@13.1.0: {}
emoji-regex@10.6.0: {}
emoji-regex@8.0.0: {}
esbuild@0.28.0:
optionalDependencies:
'@esbuild/aix-ppc64': 0.28.0
'@esbuild/android-arm': 0.28.0
'@esbuild/android-arm64': 0.28.0
'@esbuild/android-x64': 0.28.0
'@esbuild/darwin-arm64': 0.28.0
'@esbuild/darwin-x64': 0.28.0
'@esbuild/freebsd-arm64': 0.28.0
'@esbuild/freebsd-x64': 0.28.0
'@esbuild/linux-arm': 0.28.0
'@esbuild/linux-arm64': 0.28.0
'@esbuild/linux-ia32': 0.28.0
'@esbuild/linux-loong64': 0.28.0
'@esbuild/linux-mips64el': 0.28.0
'@esbuild/linux-ppc64': 0.28.0
'@esbuild/linux-riscv64': 0.28.0
'@esbuild/linux-s390x': 0.28.0
'@esbuild/linux-x64': 0.28.0
'@esbuild/netbsd-arm64': 0.28.0
'@esbuild/netbsd-x64': 0.28.0
'@esbuild/openbsd-arm64': 0.28.0
'@esbuild/openbsd-x64': 0.28.0
'@esbuild/openharmony-arm64': 0.28.0
'@esbuild/sunos-x64': 0.28.0
'@esbuild/win32-arm64': 0.28.0
'@esbuild/win32-ia32': 0.28.0
'@esbuild/win32-x64': 0.28.0
fsevents@2.3.3:
optional: true
get-east-asian-width@1.6.0: {}
gradient-string@3.0.0:
dependencies:
chalk: 5.6.2
tinygradient: 1.1.5
iconv-lite@0.7.2:
dependencies:
safer-buffer: 2.1.2
is-fullwidth-code-point@3.0.0: {}
is-interactive@2.0.0: {}
is-unicode-supported@1.3.0: {}
is-unicode-supported@2.1.0: {}
log-symbols@6.0.0:
dependencies:
chalk: 5.6.2
is-unicode-supported: 1.3.0
mimic-function@5.0.1: {}
mute-stream@2.0.0: {}
onetime@7.0.0:
dependencies:
mimic-function: 5.0.1
ora@8.2.0:
dependencies:
chalk: 5.6.2
cli-cursor: 5.0.0
cli-spinners: 2.9.2
is-interactive: 2.0.0
is-unicode-supported: 2.1.0
log-symbols: 6.0.0
stdin-discarder: 0.2.2
string-width: 7.2.0
strip-ansi: 7.2.0
restore-cursor@5.1.0:
dependencies:
onetime: 7.0.0
signal-exit: 4.1.0
safer-buffer@2.1.2: {}
signal-exit@4.1.0: {}
stdin-discarder@0.2.2: {}
string-width@4.2.3:
dependencies:
emoji-regex: 8.0.0
is-fullwidth-code-point: 3.0.0
strip-ansi: 6.0.1
string-width@7.2.0:
dependencies:
emoji-regex: 10.6.0
get-east-asian-width: 1.6.0
strip-ansi: 7.2.0
strip-ansi@6.0.1:
dependencies:
ansi-regex: 5.0.1
strip-ansi@7.2.0:
dependencies:
ansi-regex: 6.2.2
tinycolor2@1.6.0: {}
tinygradient@1.1.5:
dependencies:
'@types/tinycolor2': 1.4.6
tinycolor2: 1.6.0
tsx@4.22.4:
dependencies:
esbuild: 0.28.0
optionalDependencies:
fsevents: 2.3.3
type-fest@4.41.0: {}
typescript@5.9.3: {}
undici-types@6.21.0: {}
widest-line@5.0.0:
dependencies:
string-width: 7.2.0
wrap-ansi@6.2.0:
dependencies:
ansi-styles: 4.3.0
string-width: 4.2.3
strip-ansi: 6.0.1
wrap-ansi@9.0.2:
dependencies:
ansi-styles: 6.2.3
string-width: 7.2.0
strip-ansi: 7.2.0
yoctocolors-cjs@2.1.3: {}
+95
View File
@@ -0,0 +1,95 @@
import { getGlobalOpts, isInteractive } from '../context.js';
import { loadConfig, resolveApiUrl, resolveToken } from '../config.js';
import { failSpinner, runSpinner } from '../ui/render.js';
export class ApiError extends Error {
constructor(
message: string,
public status?: number,
) {
super(message);
}
}
async function parseError(res: Response): Promise<string> {
try {
const body = await res.json();
if (typeof body?.message === 'string') return body.message;
if (Array.isArray(body?.message)) return body.message.join(', ');
return JSON.stringify(body);
} catch {
return res.statusText || `HTTP ${res.status}`;
}
}
export async function apiRequest<T>(
method: string,
path: string,
body?: unknown,
auth = true,
): Promise<T> {
const opts = getGlobalOpts();
const config = await loadConfig();
const baseUrl = resolveApiUrl(opts.url, config);
const token = resolveToken(opts.token, config);
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
if (auth && token) {
headers.Authorization = `Bearer ${token}`;
}
const doFetch = async () => {
const res = await fetch(`${baseUrl}/api${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (!res.ok) {
throw new ApiError(await parseError(res), res.status);
}
if (res.status === 204) return undefined as T;
const contentType = res.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
return (await res.json()) as T;
}
return (await res.text()) as T;
};
if (isInteractive() && !opts.quiet && !opts.json) {
return runSpinner(doFetch, '请求中...');
}
try {
return await doFetch();
} catch (e) {
if (e instanceof ApiError && e.status === 401 && auth) {
failSpinner('未登录或 Token 已过期,请运行: ecom-license login');
}
throw e;
}
}
export async function apiDownload(path: string, outfile: string): Promise<string> {
const opts = getGlobalOpts();
const config = await loadConfig();
const baseUrl = resolveApiUrl(opts.url, config);
const token = resolveToken(opts.token, config);
const doFetch = async () => {
const res = await fetch(`${baseUrl}/api${path}`, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
if (!res.ok) throw new ApiError(await parseError(res), res.status);
const { writeFile } = await import('fs/promises');
const text = await res.text();
await writeFile(outfile, text, 'utf8');
return outfile;
};
if (isInteractive()) {
return runSpinner(doFetch, '正在下载...');
}
return doFetch();
}
+104
View File
@@ -0,0 +1,104 @@
import { confirm, input } from '@inquirer/prompts';
import { apiRequest } from '../api/client.js';
import { getGlobalOpts, isInteractive } from '../context.js';
import {
printEmptyHint,
printJson,
printQuiet,
printSuccess,
printTable,
} from '../ui/render.js';
interface Customer {
id: number;
code: string;
name: string;
status: number;
contactName?: string;
contactPhone?: string;
}
interface PageResult<T> {
items: T[];
total: number;
page: number;
size: number;
}
export async function customerList(opts: { page?: number; size?: number }) {
const global = getGlobalOpts();
const page = opts.page || 1;
const size = opts.size || 20;
const data = await apiRequest<PageResult<Customer>>(
'GET',
`/customers?page=${page}&size=${size}`,
);
if (global.json) {
printJson(data);
return;
}
if (!data.items.length) {
printEmptyHint('运行 ecom-license customer create 创建客户');
return;
}
printTable(
['ID', 'CODE', 'NAME', 'STATUS'],
data.items.map((c) => [
String(c.id),
c.code,
c.name,
c.status === 1 ? '启用' : '禁用',
]),
);
console.log(`共 ${data.total} 条 · 第 ${data.page}/${Math.ceil(data.total / data.size) || 1} 页`);
}
export async function customerCreate(opts: {
code?: string;
name?: string;
contactName?: string;
contactPhone?: string;
contactEmail?: string;
}) {
const global = getGlobalOpts();
let payload = { ...opts };
if (isInteractive() && !opts.name) {
payload.name = await input({ message: '公司名称', validate: (v) => !!v || '必填' });
payload.contactName = await input({ message: '联系人', default: '' });
payload.contactPhone = await input({ message: '联系电话', default: '' });
payload.contactEmail = await input({ message: '联系邮箱', default: '' });
payload.code = await input({ message: '客户编码(留空自动生成)', default: '' });
if (!payload.code) delete payload.code;
}
if (!payload.name) {
console.error('请提供 --name');
process.exit(1);
}
const created = await apiRequest<Customer>('POST', '/customers', payload);
if (global.json) printJson(created);
else if (global.quiet) printQuiet(String(created.id));
else printSuccess(`客户已创建: ${created.code} · ${created.name}`);
}
export async function customerShow(id: number) {
const global = getGlobalOpts();
const customer = await apiRequest<Customer>('GET', `/customers/${id}`);
if (global.json) printJson(customer);
else printJson(customer);
}
export async function customerDelete(id: number, yes?: boolean) {
const global = getGlobalOpts();
if (isInteractive() && !yes && !global.yes) {
const ok = await confirm({ message: `确认删除客户 #${id}?`, default: false });
if (!ok) return;
}
await apiRequest('DELETE', `/customers/${id}`);
printSuccess(`客户 #${id} 已删除`);
}
+257
View File
@@ -0,0 +1,257 @@
import { checkbox, confirm, input, search, select } from '@inquirer/prompts';
import { apiRequest, apiDownload } from '../api/client.js';
import { getGlobalOpts, isInteractive } from '../context.js';
import {
printBox,
printEmptyHint,
printJson,
printQuiet,
printSuccess,
printTable,
} from '../ui/render.js';
interface Customer {
id: number;
code: string;
name: string;
}
interface License {
id: number;
jti: string;
edition: string;
machineFingerprint: string;
status: string;
expiresAt: string;
licenseKey?: string;
customer?: Customer;
}
interface PageResult<T> {
items: T[];
total: number;
page: number;
size: number;
}
interface GenerateResult {
id: number;
licenseKey: string;
jti: string;
edition: string;
machineFingerprint: string;
expiresAt: string;
status: string;
}
export async function licenseList(opts: {
page?: number;
size?: number;
customerId?: number;
status?: string;
}) {
const global = getGlobalOpts();
const params = new URLSearchParams();
if (opts.page) params.set('page', String(opts.page));
if (opts.size) params.set('size', String(opts.size));
if (opts.customerId) params.set('customerId', String(opts.customerId));
if (opts.status) params.set('status', opts.status);
const data = await apiRequest<PageResult<License>>(
'GET',
`/licenses?${params.toString()}`,
);
if (global.json) {
printJson(data);
return;
}
if (!data.items.length) {
printEmptyHint('运行 ecom-license license generate 签发许可证');
return;
}
printTable(
['ID', 'JTI', 'EDITION', 'FINGERPRINT', 'STATUS', 'EXPIRES'],
data.items.map((l) => [
String(l.id),
l.jti.slice(0, 8) + '...',
l.edition,
l.machineFingerprint.slice(0, 16) + (l.machineFingerprint.length > 16 ? '...' : ''),
l.status,
l.expiresAt?.slice(0, 10) || '-',
]),
);
console.log(`共 ${data.total} 条`);
}
export async function licenseShow(id: number) {
const global = getGlobalOpts();
const license = await apiRequest<License>('GET', `/licenses/${id}`);
if (global.json) printJson(license);
else printJson(license);
}
export async function licenseGenerate(opts: {
customerId?: number;
company?: string;
fingerprint?: string;
edition?: string;
expires?: string;
features?: string;
}) {
const global = getGlobalOpts();
let customerId = opts.customerId;
let company = opts.company;
let fingerprint = opts.fingerprint;
let edition = opts.edition || 'enterprise';
let expiresAt = opts.expires;
let features = opts.features?.split(',').map((s) => s.trim()).filter(Boolean) || [
'order-import',
'order-create',
];
if (isInteractive() && !customerId) {
const customers = await apiRequest<PageResult<Customer>>('GET', '/customers?page=1&size=100');
if (!customers.items.length) {
console.error('暂无客户,请先 ecom-license customer create');
process.exit(1);
}
customerId = await search({
message: '选择客户',
source: async (term) => {
const q = (term || '').toLowerCase();
return customers.items
.filter(
(c) =>
!q ||
c.name.toLowerCase().includes(q) ||
c.code.toLowerCase().includes(q),
)
.map((c) => ({ name: `${c.code} · ${c.name}`, value: c.id }));
},
});
const picked = customers.items.find((c) => c.id === customerId)!;
company = await input({ message: '授权公司名', default: picked.name });
const fpMode = await select({
message: '机器指纹',
choices: [
{ name: '私有部署(输入 FP-xxx)', value: 'custom' },
{ name: 'SaaS 不限指纹 (*)', value: '*' },
],
});
fingerprint =
fpMode === '*'
? '*'
: await input({
message: '机器指纹',
validate: (v) => v.startsWith('FP-') || v === '*' || '格式应为 FP-...',
});
edition = await select({
message: '版本类型',
choices: [
{ name: 'trial · 试用', value: 'trial' },
{ name: 'enterprise · 企业', value: 'enterprise' },
{ name: 'unlimited · 无限', value: 'unlimited' },
],
});
const expireChoice = await select({
message: '有效期',
choices: [
{ name: '+30 天', value: '30d' },
{ name: '+1 年', value: '1y' },
{ name: '自定义日期', value: 'custom' },
],
});
if (expireChoice === 'custom') {
expiresAt = await input({
message: '过期日期 (YYYY-MM-DD)',
validate: (v) => /^\d{4}-\d{2}-\d{2}$/.test(v) || '格式 YYYY-MM-DD',
});
} else {
const d = new Date();
if (expireChoice === '30d') d.setDate(d.getDate() + 30);
else d.setFullYear(d.getFullYear() + 1);
expiresAt = d.toISOString().slice(0, 10);
}
features = await checkbox({
message: '授权功能',
choices: [
{ name: 'order-import · 订单导入', value: 'order-import', checked: true },
{ name: 'order-create · 创建订单', value: 'order-create', checked: true },
],
});
const summary = [
`客户 ID: ${customerId}`,
`公司: ${company}`,
`指纹: ${fingerprint}`,
`版本: ${edition}`,
`过期: ${expiresAt}`,
`功能: ${features.join(', ')}`,
].join('\n');
const ok = await confirm({ message: `确认签发?\n${summary}`, default: true });
if (!ok) return;
}
if (!customerId || !company || !fingerprint || !expiresAt) {
console.error('缺少参数,交互模式请直接运行 ecom-license license generate');
process.exit(1);
}
const result = await apiRequest<GenerateResult>('POST', '/licenses/generate', {
customerId,
company,
machineFingerprint: fingerprint,
edition,
expiresAt: new Date(expiresAt).toISOString(),
features,
});
if (global.json) {
printJson(result);
return;
}
if (global.quiet) {
printQuiet(result.licenseKey);
return;
}
printBox(
'签发成功',
[
`ID: ${result.id}`,
`JTI: ${result.jti}`,
`过期: ${result.expiresAt?.slice(0, 10)}`,
'',
result.licenseKey,
'',
'提示: 使用 --quiet 仅输出 licenseKey',
].join('\n'),
'green',
);
}
export async function licenseRevoke(id: number, yes?: boolean) {
const global = getGlobalOpts();
const license = await apiRequest<License>('GET', `/licenses/${id}`);
if (isInteractive() && !yes && !global.yes) {
const ok = await confirm({
message: `确认吊销?\nJTI: ${license.jti}\n指纹: ${license.machineFingerprint}`,
default: false,
});
if (!ok) return;
}
const result = await apiRequest('POST', `/licenses/${id}/revoke`);
if (global.json) printJson(result);
else printSuccess(`许可证 #${id} 已吊销`);
}
export async function licenseDownload(id: number, output?: string) {
const global = getGlobalOpts();
const outfile = output || `license-${id}.key`;
const path = await apiDownload(`/licenses/${id}/download`, outfile);
if (global.json) printJson({ path });
else if (global.quiet) printQuiet(path);
else printSuccess(`已保存到 ${path}`);
}
+63
View File
@@ -0,0 +1,63 @@
import { input, password } from '@inquirer/prompts';
import { apiRequest } from '../api/client.js';
import { loadConfig, resolveApiUrl, saveConfig } from '../config.js';
import { getGlobalOpts, isInteractive } from '../context.js';
import { printBanner, printError, printJson, printSuccess } from '../ui/render.js';
interface LoginResult {
token: string;
username: string;
expiresAt: string | null;
}
export async function loginCommand(opts: {
url?: string;
username?: string;
password?: string;
}) {
const global = getGlobalOpts();
const config = await loadConfig();
const apiUrl = resolveApiUrl(opts.url || global.url, config);
if (isInteractive()) printBanner();
let username = opts.username || process.env.ECOM_LICENSE_USERNAME;
let pass = opts.password || process.env.ECOM_LICENSE_PASSWORD;
if (isInteractive()) {
username = await input({ message: '用户名', default: username || 'admin' });
pass = await password({ message: '密码', mask: '*' });
}
if (!username || !pass) {
printError('请提供用户名和密码');
process.exit(1);
}
try {
const result = await apiRequest<LoginResult>(
'POST',
'/auth/login',
{ username, password: pass },
false,
);
await saveConfig({
apiUrl,
token: result.token,
username: result.username,
expiresAt: result.expiresAt || undefined,
});
if (global.json) {
printJson({ username: result.username, expiresAt: result.expiresAt, apiUrl });
return;
}
printSuccess(
`登录成功 · ${result.username}` +
(result.expiresAt ? ` · Token 有效期至 ${result.expiresAt.slice(0, 10)}` : ''),
);
} catch (e: any) {
printError(e?.message || '登录失败');
process.exit(1);
}
}
+7
View File
@@ -0,0 +1,7 @@
import { clearConfig } from '../config.js';
import { printSuccess } from '../ui/render.js';
export async function logoutCommand() {
await clearConfig();
printSuccess('已退出登录');
}
+35
View File
@@ -0,0 +1,35 @@
import { apiRequest } from '../api/client.js';
import { getGlobalOpts } from '../context.js';
import { printBox, printJson, printQuiet } from '../ui/render.js';
interface Stats {
customerCount: number;
activeLicenseCount: number;
expiringSoonCount: number;
totalLicenses: number;
}
export async function statsCommand() {
const global = getGlobalOpts();
const stats = await apiRequest<Stats>('GET', '/dashboard/stats');
if (global.json) {
printJson(stats);
return;
}
if (global.quiet) {
printQuiet(String(stats.activeLicenseCount));
return;
}
printBox(
'平台概览',
[
`客户数: ${stats.customerCount}`,
`有效许可证: ${stats.activeLicenseCount}`,
`即将过期: ${stats.expiringSoonCount}`,
`许可证总数: ${stats.totalLicenses}`,
].join('\n'),
'green',
);
}
+39
View File
@@ -0,0 +1,39 @@
import { loadConfig, resolveApiUrl } from '../config.js';
import { getGlobalOpts } from '../context.js';
import { printBox, printError, printJson, printQuiet } from '../ui/render.js';
export async function whoamiCommand() {
const global = getGlobalOpts();
const config = await loadConfig();
const apiUrl = resolveApiUrl(global.url, config);
if (!config?.token && !global.token) {
printError('未登录,请运行: ecom-license login');
process.exit(1);
}
const info = {
apiUrl,
username: config?.username,
expiresAt: config?.expiresAt,
loggedIn: Boolean(config?.token || global.token),
};
if (global.json) {
printJson(info);
return;
}
if (global.quiet) {
printQuiet(config?.username || '');
return;
}
printBox(
'当前会话',
[
`API: ${apiUrl}`,
`用户: ${config?.username || '(未知)'}`,
`过期: ${config?.expiresAt || '-'}`,
].join('\n'),
);
}
+53
View File
@@ -0,0 +1,53 @@
import { mkdir, readFile, writeFile } from 'fs/promises';
import { homedir } from 'os';
import { dirname, join } from 'path';
export interface CliConfig {
apiUrl: string;
token?: string;
username?: string;
expiresAt?: string;
}
const DEFAULT_CONFIG_PATH = join(
homedir(),
'.config',
'ecom-license',
'config.json',
);
export function getConfigPath(): string {
return process.env.ECOM_LICENSE_CONFIG || DEFAULT_CONFIG_PATH;
}
export async function loadConfig(): Promise<CliConfig | null> {
try {
const raw = await readFile(getConfigPath(), 'utf8');
return JSON.parse(raw) as CliConfig;
} catch {
return null;
}
}
export async function saveConfig(config: CliConfig): Promise<void> {
const path = getConfigPath();
await mkdir(dirname(path), { recursive: true });
await writeFile(path, JSON.stringify(config, null, 2), 'utf8');
}
export async function clearConfig(): Promise<void> {
await saveConfig({ apiUrl: (await loadConfig())?.apiUrl || 'http://localhost:3100' });
}
export function resolveApiUrl(flagUrl?: string, config?: CliConfig | null): string {
return (
flagUrl ||
process.env.ECOM_LICENSE_API_URL ||
config?.apiUrl ||
'http://localhost:3100'
).replace(/\/$/, '');
}
export function resolveToken(flagToken?: string, config?: CliConfig | null): string | undefined {
return flagToken || process.env.ECOM_LICENSE_TOKEN || config?.token;
}
+30
View File
@@ -0,0 +1,30 @@
/** 全局 CLI 运行上下文(由 commander 注入) */
export interface GlobalOpts {
url?: string;
token?: string;
json?: boolean;
quiet?: boolean;
yes?: boolean;
verbose?: boolean;
}
let globalOpts: GlobalOpts = {};
export function setGlobalOpts(opts: GlobalOpts) {
globalOpts = opts;
}
export function getGlobalOpts(): GlobalOpts {
return globalOpts;
}
/** TTY 交互模式检测 */
export function isInteractive(): boolean {
const opts = getGlobalOpts();
return (
Boolean(process.stdout.isTTY) &&
!process.env.CI &&
!opts.json &&
!opts.quiet
);
}
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env node
import { Command } from 'commander';
import { customerCreate, customerDelete, customerList, customerShow } from './commands/customer.js';
import { licenseDownload, licenseGenerate, licenseList, licenseRevoke, licenseShow } from './commands/license.js';
import { loginCommand } from './commands/login.js';
import { logoutCommand } from './commands/logout.js';
import { statsCommand } from './commands/stats.js';
import { whoamiCommand } from './commands/whoami.js';
import { setGlobalOpts } from './context.js';
import { printBanner } from './ui/render.js';
function applyGlobals(cmd: Command) {
return cmd
.option('--url <base>', 'API 根地址')
.option('--token <jwt>', 'Bearer Token')
.option('--json', 'JSON 输出')
.option('--quiet', '仅输出关键值')
.option('--yes', '跳过确认')
.option('--verbose', '显示详细错误')
.hook('preAction', (thisCmd) => {
const root = thisCmd.optsWithGlobals();
setGlobalOpts({
url: root.url,
token: root.token,
json: root.json,
quiet: root.quiet,
yes: root.yes,
verbose: root.verbose,
});
});
}
const program = new Command();
program.name('ecom-license').description('Ecom-DMB License 运营管理 CLI').version('0.1.0');
applyGlobals(program);
program
.command('login')
.description('登录 License 平台')
.option('--username <name>')
.option('--password <pwd>')
.action((opts, cmd) => loginCommand({ ...opts, url: cmd.optsWithGlobals().url }));
program.command('logout').description('退出登录').action(logoutCommand);
program.command('whoami').description('查看当前登录状态').action(whoamiCommand);
program.command('stats').description('平台统计').action(statsCommand);
const customer = program.command('customer').description('客户管理');
applyGlobals(customer);
customer.command('list').option('--page <n>').option('--size <n>').action((opts) =>
customerList({ page: Number(opts.page) || 1, size: Number(opts.size) || 20 }),
);
customer
.command('create')
.option('--code <code>')
.option('--name <name>')
.option('--contact-name <n>')
.option('--contact-phone <p>')
.option('--contact-email <e>')
.action((opts) => customerCreate(opts));
customer.command('show <id>').action((id) => customerShow(Number(id)));
customer.command('delete <id>').action((id, opts, cmd) =>
customerDelete(Number(id), cmd.optsWithGlobals().yes),
);
const license = program.command('license').description('许可证管理');
applyGlobals(license);
license
.command('list')
.option('--page <n>')
.option('--size <n>')
.option('--customer-id <id>')
.option('--status <s>')
.action((opts) =>
licenseList({
page: Number(opts.page) || 1,
size: Number(opts.size) || 20,
customerId: opts.customerId ? Number(opts.customerId) : undefined,
status: opts.status,
}),
);
license.command('show <id>').action((id) => licenseShow(Number(id)));
license
.command('generate')
.option('--customer-id <id>')
.option('--company <name>')
.option('--fingerprint <fp>')
.option('--edition <e>')
.option('--expires <date>')
.option('--features <list>')
.action((opts) => licenseGenerate(opts));
license.command('revoke <id>').action((id, _o, cmd) =>
licenseRevoke(Number(id), cmd.optsWithGlobals().yes),
);
license
.command('download <id>')
.option('-o, --output <file>')
.action((id, opts) => licenseDownload(Number(id), opts.output));
// 无子命令时只展示引导,不输出冗长 --help
program.action(() => {
printBanner();
console.log('常用命令:');
console.log(' pnpm dev login # 开发模式登录');
console.log(' pnpm dev customer create # 创建客户');
console.log(' pnpm dev license generate # 签发 License');
console.log(' pnpm start login # 使用构建产物');
console.log('');
console.log('完整帮助: pnpm dev -- --help');
});
program.parseAsync(process.argv).catch((err) => {
if (err?.name === 'ExitPromptError') process.exit(0);
console.error(err?.message || err);
process.exit(1);
});
+100
View File
@@ -0,0 +1,100 @@
import boxen from 'boxen';
import chalk from 'chalk';
import Table from 'cli-table3';
import gradient from 'gradient-string';
import ora, { type Ora } from 'ora';
import { getGlobalOpts, isInteractive } from '../context.js';
export function printBanner() {
if (!isInteractive()) return;
const title = gradient.pastel('Ecom License CLI');
console.log(
boxen(`${title}\n${chalk.gray('授权管理平台 · 运营端')}`, {
padding: 1,
borderColor: 'cyan',
borderStyle: 'round',
}),
);
}
export function printJson(data: unknown) {
console.log(JSON.stringify(data, null, getGlobalOpts().json ? 2 : 0));
}
export function printQuiet(value: string) {
console.log(value);
}
export function printSuccess(msg: string) {
if (getGlobalOpts().json || getGlobalOpts().quiet) return;
console.log(chalk.green('✔'), msg);
}
export function printError(msg: string) {
if (getGlobalOpts().json) {
printJson({ error: msg });
return;
}
console.error(chalk.red('✖'), msg);
}
export function printInfo(msg: string) {
if (getGlobalOpts().json || getGlobalOpts().quiet) return;
console.log(chalk.blue('ℹ'), msg);
}
export function printBox(title: string, content: string, borderColor: 'green' | 'cyan' | 'yellow' = 'cyan') {
if (!isInteractive()) return;
console.log(
boxen(content, {
title: chalk.bold(title),
padding: 1,
borderColor,
}),
);
}
export function printTable(headers: string[], rows: string[][]) {
if (getGlobalOpts().json) {
printJson(
rows.map((row) =>
Object.fromEntries(headers.map((h, i) => [h, row[i]])),
),
);
return;
}
if (getGlobalOpts().quiet) return;
const table = new Table({ head: headers.map((h) => chalk.cyan(h)) });
rows.forEach((r) => table.push(r));
console.log(table.toString());
}
export function printEmptyHint(hint: string) {
if (getGlobalOpts().json || getGlobalOpts().quiet) return;
console.log(chalk.yellow('暂无数据。'), chalk.gray(hint));
}
let activeSpinner: Ora | null = null;
export async function runSpinner<T>(fn: () => Promise<T>, text: string): Promise<T> {
const spinner = ora(text).start();
activeSpinner = spinner;
try {
const result = await fn();
spinner.succeed();
return result;
} catch (e) {
spinner.fail();
throw e;
} finally {
activeSpinner = null;
}
}
export function failSpinner(msg: string) {
if (activeSpinner) {
activeSpinner.fail(msg);
activeSpinner = null;
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": false
},
"include": ["src/**/*"]
}
+10
View File
@@ -0,0 +1,10 @@
PORT=3100
DB_HOST=192.168.3.100
DB_PORT=3306
DB_USERNAME=ecom_license_dev
DB_PASSWORD=ecom_license_dev
DB_DATABASE=ecom_license_dev
JWT_SECRET=change-me-in-production
JWT_EXPIRES_IN=8h
LICENSE_PRIVATE_KEY_PATH=keys/private.pem
LICENSE_KID=2026-v1
+2
View File
@@ -0,0 +1,2 @@
# 提升依赖到 node_modules 顶层,改善 IDE / tsserver 模块解析(pnpm 默认隔离布局对部分编辑器不友好)
shamefully-hoist=true
+2
View File
@@ -0,0 +1,2 @@
*.pem
!/.gitkeep
View File
+9
View File
@@ -0,0 +1,9 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true,
"tsConfigPath": "tsconfig.build.json"
}
}
+47
View File
@@ -0,0 +1,47 @@
{
"name": "ecom-license-server",
"version": "0.1.0",
"private": true,
"packageManager": "pnpm@10.32.0",
"scripts": {
"clean": "rm -rf dist",
"build": "nest build",
"prestart": "pnpm run build",
"start": "node dist/main.js",
"start:dev": "nest start --watch",
"start:prod": "node dist/main.js"
},
"dependencies": {
"@nestjs/common": "^10.4.15",
"@nestjs/config": "^3.3.0",
"@nestjs/core": "^10.4.15",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.4.15",
"@nestjs/typeorm": "^10.0.2",
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"jose": "^5.9.6",
"mysql2": "^3.11.5",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20",
"uuid": "^11.0.3"
},
"pnpm": {
"onlyBuiltDependencies": ["bcrypt", "@nestjs/core"]
},
"devDependencies": {
"@nestjs/cli": "^10.4.9",
"@nestjs/schematics": "^10.2.3",
"@types/bcrypt": "^5.0.2",
"@types/express": "^5.0.0",
"@types/node": "^22.10.2",
"@types/passport-jwt": "^4.0.1",
"@types/uuid": "^10.0.0",
"typescript": "^5.7.2"
}
}
+3967
View File
File diff suppressed because it is too large Load Diff
+76
View File
@@ -0,0 +1,76 @@
-- Ecom License Server 表结构
-- 目标库: ecom_license_dev(执行: mysql ... ecom_license_dev < schema.sql)
CREATE TABLE IF NOT EXISTS lc_admin (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL COMMENT 'BCrypt',
nickname VARCHAR(50) NULL,
status TINYINT NOT NULL DEFAULT 1 COMMENT '0=禁用 1=启用',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_username (username)
) ENGINE=InnoDB COMMENT='License 平台管理员';
CREATE TABLE IF NOT EXISTS lc_customer (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
code VARCHAR(50) NOT NULL,
name VARCHAR(200) NOT NULL,
contact_name VARCHAR(50) NULL,
contact_phone VARCHAR(20) NULL,
contact_email VARCHAR(100) NULL,
status TINYINT NOT NULL DEFAULT 1,
remark TEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_code (code)
) ENGINE=InnoDB COMMENT='License 客户';
CREATE TABLE IF NOT EXISTS lc_license (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
customer_id BIGINT UNSIGNED NOT NULL,
license_key TEXT NOT NULL,
jti VARCHAR(64) NOT NULL,
edition VARCHAR(20) NOT NULL,
machine_fingerprint VARCHAR(100) NOT NULL,
features JSON NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'active',
issued_at TIMESTAMP NOT NULL,
expires_at TIMESTAMP NOT NULL,
revoked_at TIMESTAMP NULL,
max_activations INT NULL,
activation_count INT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_jti (jti),
KEY idx_customer_id (customer_id),
CONSTRAINT fk_license_customer FOREIGN KEY (customer_id) REFERENCES lc_customer (id)
) ENGINE=InnoDB COMMENT='签发的 License';
CREATE TABLE IF NOT EXISTS lc_activation_log (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
license_id BIGINT UNSIGNED NOT NULL,
machine_fingerprint VARCHAR(100) NOT NULL,
installation_id VARCHAR(64) NULL,
hostname VARCHAR(200) NULL,
ip VARCHAR(50) NULL,
action VARCHAR(20) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_license_id (license_id)
) ENGINE=InnoDB COMMENT='激活日志';
CREATE TABLE IF NOT EXISTS lc_oper_log (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
admin_id BIGINT UNSIGNED NULL,
action VARCHAR(50) NOT NULL,
target_type VARCHAR(50) NULL,
target_id BIGINT UNSIGNED NULL,
detail JSON NULL,
ip VARCHAR(50) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB COMMENT='操作日志';
+37
View File
@@ -0,0 +1,37 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './modules/auth/auth.module';
import { CustomerModule } from './modules/customer/customer.module';
import { DashboardModule } from './modules/dashboard/dashboard.module';
import { LicenseModule } from './modules/license/license.module';
import { LcAdmin } from './entities/lc-admin.entity';
import { LcActivationLog } from './entities/lc-activation-log.entity';
import { LcCustomer } from './entities/lc-customer.entity';
import { LcLicense } from './entities/lc-license.entity';
import { LcOperLog } from './entities/lc-oper-log.entity';
import { AdminSeedService } from './common/admin-seed.service';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRoot({
type: 'mysql',
host: process.env.DB_HOST || 'localhost',
port: Number(process.env.DB_PORT || 3306),
username: process.env.DB_USERNAME || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_DATABASE || 'ecom_license_dev',
entities: [LcAdmin, LcCustomer, LcLicense, LcActivationLog, LcOperLog],
synchronize: process.env.DB_SYNC === 'true',
timezone: '+08:00',
}),
TypeOrmModule.forFeature([LcAdmin]),
AuthModule,
CustomerModule,
LicenseModule,
DashboardModule,
],
providers: [AdminSeedService],
})
export class AppModule {}
@@ -0,0 +1,27 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
import { LcAdmin } from '../entities/lc-admin.entity';
/** 首次启动时创建默认管理员 admin / admin123 */
@Injectable()
export class AdminSeedService implements OnModuleInit {
constructor(
@InjectRepository(LcAdmin)
private readonly adminRepo: Repository<LcAdmin>,
) {}
async onModuleInit() {
const count = await this.adminRepo.count();
if (count > 0) return;
const password = await bcrypt.hash('admin123', 10);
await this.adminRepo.save({
username: 'admin',
password,
nickname: '默认管理员',
status: 1,
});
console.log('[seed] 默认管理员已创建: admin / admin123');
}
}
@@ -0,0 +1,62 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { readFile } from 'fs/promises';
import { importPKCS8, SignJWT, type KeyLike } from 'jose';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
export interface SignLicenseInput {
sub: string;
company: string;
machineFingerprint: string;
edition: string;
features: string[];
expiresAt: Date;
}
export interface SignLicenseResult {
licenseKey: string;
jti: string;
issuedAt: Date;
expiresAt: Date;
}
/** 使用 Ed25519 私钥签发 License JWT */
@Injectable()
export class JwtSignerService implements OnModuleInit {
private privateKey: KeyLike | null = null;
private kid = process.env.LICENSE_KID || '2026-v1';
async onModuleInit() {
const keyPath =
process.env.LICENSE_PRIVATE_KEY_PATH || join(process.cwd(), 'keys', 'private.pem');
try {
const pem = await readFile(keyPath, 'utf8');
this.privateKey = await importPKCS8(pem, 'EdDSA');
} catch (e) {
console.warn(`[license] 未加载私钥 ${keyPath},签发功能不可用。请运行: openssl genpkey -algorithm Ed25519 -out keys/private.pem`);
}
}
async signLicense(input: SignLicenseInput): Promise<SignLicenseResult> {
if (!this.privateKey) {
throw new Error('License 私钥未配置,无法签发');
}
const jti = uuidv4();
const issuedAt = new Date();
const licenseKey = await new SignJWT({
company: input.company,
machineFingerprint: input.machineFingerprint,
edition: input.edition,
features: input.features,
})
.setProtectedHeader({ alg: 'EdDSA', typ: 'JWT', kid: this.kid })
.setIssuer('ecom-license-server')
.setSubject(input.sub)
.setJti(jti)
.setIssuedAt(issuedAt)
.setExpirationTime(input.expiresAt)
.sign(this.privateKey);
return { licenseKey, jti, issuedAt, expiresAt: input.expiresAt };
}
}
@@ -0,0 +1,33 @@
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity('lc_activation_log')
export class LcActivationLog {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ name: 'license_id', type: 'bigint', unsigned: true })
licenseId!: number;
@Column({ name: 'machine_fingerprint', length: 100 })
machineFingerprint!: string;
@Column({ name: 'installation_id', type: 'varchar', length: 64, nullable: true })
installationId!: string | null;
@Column({ type: 'varchar', length: 200, nullable: true })
hostname!: string | null;
@Column({ type: 'varchar', length: 50, nullable: true })
ip!: string | null;
@Column({ length: 20 })
action!: string;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
}
@@ -0,0 +1,31 @@
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity('lc_admin')
export class LcAdmin {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ length: 50, unique: true })
username!: string;
@Column({ length: 255 })
password!: string;
@Column({ type: 'varchar', length: 50, nullable: true })
nickname!: string | null;
@Column({ type: 'tinyint', default: 1 })
status!: number;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt!: Date;
}
@@ -0,0 +1,45 @@
import {
Column,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { LcLicense } from './lc-license.entity';
@Entity('lc_customer')
export class LcCustomer {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ length: 50, unique: true })
code!: string;
@Column({ length: 200 })
name!: string;
@Column({ name: 'contact_name', type: 'varchar', length: 50, nullable: true })
contactName!: string | null;
@Column({ name: 'contact_phone', type: 'varchar', length: 20, nullable: true })
contactPhone!: string | null;
@Column({ name: 'contact_email', type: 'varchar', length: 100, nullable: true })
contactEmail!: string | null;
@Column({ type: 'tinyint', default: 1 })
status!: number;
@Column({ type: 'text', nullable: true })
remark!: string | null;
@OneToMany(() => LcLicense, (license) => license.customer)
licenses!: LcLicense[];
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt!: Date;
}
@@ -0,0 +1,62 @@
import {
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { LcCustomer } from './lc-customer.entity';
@Entity('lc_license')
export class LcLicense {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ name: 'customer_id', type: 'bigint', unsigned: true })
customerId!: number;
@ManyToOne(() => LcCustomer, (customer) => customer.licenses)
@JoinColumn({ name: 'customer_id' })
customer!: LcCustomer;
@Column({ name: 'license_key', type: 'text' })
licenseKey!: string;
@Column({ length: 64, unique: true })
jti!: string;
@Column({ length: 20 })
edition!: string;
@Column({ name: 'machine_fingerprint', length: 100 })
machineFingerprint!: string;
@Column({ type: 'json' })
features!: string[];
@Column({ length: 20, default: 'active' })
status!: string;
@Column({ name: 'issued_at', type: 'timestamp' })
issuedAt!: Date;
@Column({ name: 'expires_at', type: 'timestamp' })
expiresAt!: Date;
@Column({ name: 'revoked_at', type: 'timestamp', nullable: true })
revokedAt!: Date | null;
@Column({ name: 'max_activations', type: 'int', nullable: true })
maxActivations!: number | null;
@Column({ name: 'activation_count', type: 'int', default: 0 })
activationCount!: number;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt!: Date;
}
@@ -0,0 +1,33 @@
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity('lc_oper_log')
export class LcOperLog {
@PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
id!: number;
@Column({ name: 'admin_id', type: 'bigint', unsigned: true, nullable: true })
adminId!: number | null;
@Column({ length: 50 })
action!: string;
@Column({ name: 'target_type', type: 'varchar', length: 50, nullable: true })
targetType!: string | null;
@Column({ name: 'target_id', type: 'bigint', unsigned: true, nullable: true })
targetId!: number | null;
@Column({ type: 'json', nullable: true })
detail!: Record<string, unknown> | null;
@Column({ type: 'varchar', length: 50, nullable: true })
ip!: string | null;
@CreateDateColumn({ name: 'created_at' })
createdAt!: Date;
}
+17
View File
@@ -0,0 +1,17 @@
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.useGlobalPipes(
new ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true }),
);
app.enableCors();
const port = process.env.PORT || 3100;
await app.listen(port);
console.log(`Ecom License Server running on http://localhost:${port}`);
}
bootstrap();
@@ -0,0 +1,18 @@
import { Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto } from './auth.dto';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('login')
login(@Body() dto: LoginDto) {
return this.authService.login(dto);
}
@Post('logout')
logout() {
return { success: true };
}
}
@@ -0,0 +1,11 @@
import { IsNotEmpty, IsString } from 'class-validator';
export class LoginDto {
@IsString()
@IsNotEmpty()
username!: string;
@IsString()
@IsNotEmpty()
password!: string;
}
@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LcAdmin } from '../../entities/lc-admin.entity';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
TypeOrmModule.forFeature([LcAdmin]),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: process.env.JWT_SECRET || 'change-me-in-production',
signOptions: { expiresIn: process.env.JWT_EXPIRES_IN || '8h' },
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [JwtModule],
})
export class AuthModule {}
@@ -0,0 +1,38 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
import { LcAdmin } from '../../entities/lc-admin.entity';
import { LoginDto } from './auth.dto';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(LcAdmin)
private readonly adminRepo: Repository<LcAdmin>,
private readonly jwtService: JwtService,
) {}
async login(dto: LoginDto) {
const admin = await this.adminRepo.findOne({ where: { username: dto.username } });
if (!admin || admin.status !== 1) {
throw new UnauthorizedException('用户名或密码错误');
}
const ok = await bcrypt.compare(dto.password, admin.password);
if (!ok) {
throw new UnauthorizedException('用户名或密码错误');
}
const expiresIn = process.env.JWT_EXPIRES_IN || '8h';
const token = this.jwtService.sign(
{ sub: admin.id, username: admin.username },
{ expiresIn },
);
const decoded = this.jwtService.decode(token) as { exp?: number };
return {
token,
username: admin.username,
expiresAt: decoded?.exp ? new Date(decoded.exp * 1000).toISOString() : null,
};
}
}
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
@@ -0,0 +1,26 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
export interface AdminJwtPayload {
sub: number;
username: string;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET || 'change-me-in-production',
});
}
validate(payload: AdminJwtPayload) {
if (!payload?.sub) {
throw new UnauthorizedException();
}
return { adminId: payload.sub, username: payload.username };
}
}
@@ -0,0 +1,55 @@
import {
Body,
Controller,
Delete,
Get,
Param,
ParseIntPipe,
Post,
Put,
Query,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { LicenseService } from '../license/license.service';
import { CreateCustomerDto, CustomerQueryDto, UpdateCustomerDto } from './customer.dto';
import { CustomerService } from './customer.service';
@Controller('customers')
@UseGuards(JwtAuthGuard)
export class CustomerController {
constructor(
private readonly customerService: CustomerService,
private readonly licenseService: LicenseService,
) {}
@Get()
list(@Query() query: CustomerQueryDto) {
return this.customerService.list(query);
}
@Post()
create(@Body() dto: CreateCustomerDto) {
return this.customerService.create(dto);
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.customerService.findOne(id);
}
@Put(':id')
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateCustomerDto) {
return this.customerService.update(id, dto);
}
@Delete(':id')
remove(@Param('id', ParseIntPipe) id: number) {
return this.customerService.remove(id);
}
@Get(':id/licenses')
licenses(@Param('id', ParseIntPipe) id: number) {
return this.licenseService.listByCustomer(id);
}
}
@@ -0,0 +1,68 @@
import { IsEmail, IsInt, IsNotEmpty, IsOptional, IsString, Min } from 'class-validator';
import { Type } from 'class-transformer';
export class CreateCustomerDto {
@IsString()
@IsOptional()
code?: string;
@IsString()
@IsNotEmpty()
name!: string;
@IsString()
@IsOptional()
contactName?: string;
@IsString()
@IsOptional()
contactPhone?: string;
@IsEmail()
@IsOptional()
contactEmail?: string;
@IsString()
@IsOptional()
remark?: string;
}
export class UpdateCustomerDto {
@IsString()
@IsOptional()
name?: string;
@IsString()
@IsOptional()
contactName?: string;
@IsString()
@IsOptional()
contactPhone?: string;
@IsEmail()
@IsOptional()
contactEmail?: string;
@IsInt()
@IsOptional()
status?: number;
@IsString()
@IsOptional()
remark?: string;
}
export class CustomerQueryDto {
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
page?: number = 1;
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
size?: number = 20;
}
@@ -0,0 +1,17 @@
import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { LicenseModule } from '../license/license.module';
import { CustomerController } from './customer.controller';
import { CustomerService } from './customer.service';
@Module({
imports: [
TypeOrmModule.forFeature([LcCustomer]),
forwardRef(() => LicenseModule),
],
controllers: [CustomerController],
providers: [CustomerService],
exports: [CustomerService],
})
export class CustomerModule {}
@@ -0,0 +1,67 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { CreateCustomerDto, CustomerQueryDto, UpdateCustomerDto } from './customer.dto';
@Injectable()
export class CustomerService {
constructor(
@InjectRepository(LcCustomer)
private readonly customerRepo: Repository<LcCustomer>,
) {}
async list(query: CustomerQueryDto) {
const page = query.page || 1;
const size = query.size || 20;
const [items, total] = await this.customerRepo.findAndCount({
order: { id: 'DESC' },
skip: (page - 1) * size,
take: size,
});
return { items, total, page, size };
}
async findOne(id: number) {
const customer = await this.customerRepo.findOne({ where: { id } });
if (!customer) throw new NotFoundException('客户不存在');
return customer;
}
async create(dto: CreateCustomerDto) {
const code = dto.code || (await this.generateCode());
const customer = this.customerRepo.create({
code,
name: dto.name,
contactName: dto.contactName ?? null,
contactPhone: dto.contactPhone ?? null,
contactEmail: dto.contactEmail ?? null,
remark: dto.remark ?? null,
status: 1,
});
return this.customerRepo.save(customer);
}
async update(id: number, dto: UpdateCustomerDto) {
const customer = await this.findOne(id);
Object.assign(customer, {
...dto,
contactName: dto.contactName ?? customer.contactName,
contactPhone: dto.contactPhone ?? customer.contactPhone,
contactEmail: dto.contactEmail ?? customer.contactEmail,
});
return this.customerRepo.save(customer);
}
async remove(id: number) {
const customer = await this.findOne(id);
await this.customerRepo.remove(customer);
return { success: true };
}
private async generateCode() {
const date = new Date().toISOString().slice(0, 10).replace(/-/g, '');
const count = await this.customerRepo.count();
return `CUST-${date}-${String(count + 1).padStart(3, '0')}`;
}
}

Some files were not shown because too many files have changed in this diff Show More