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
+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')}`;
}
}
@@ -0,0 +1,14 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { DashboardService } from './dashboard.service';
@Controller('dashboard')
@UseGuards(JwtAuthGuard)
export class DashboardController {
constructor(private readonly dashboardService: DashboardService) {}
@Get('stats')
stats() {
return this.dashboardService.stats();
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { LcLicense } from '../../entities/lc-license.entity';
import { DashboardController } from './dashboard.controller';
import { DashboardService } from './dashboard.service';
@Module({
imports: [TypeOrmModule.forFeature([LcCustomer, LcLicense])],
controllers: [DashboardController],
providers: [DashboardService],
})
export class DashboardModule {}
@@ -0,0 +1,41 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, MoreThan } from 'typeorm';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { LcLicense } from '../../entities/lc-license.entity';
@Injectable()
export class DashboardService {
constructor(
@InjectRepository(LcCustomer)
private readonly customerRepo: Repository<LcCustomer>,
@InjectRepository(LcLicense)
private readonly licenseRepo: Repository<LcLicense>,
) {}
async stats() {
const customerCount = await this.customerRepo.count();
const activeLicenseCount = await this.licenseRepo.count({ where: { status: 'active' } });
const thirtyDaysLater = new Date();
thirtyDaysLater.setDate(thirtyDaysLater.getDate() + 30);
const expiringSoonCount = await this.licenseRepo.count({
where: {
status: 'active',
expiresAt: MoreThan(new Date()),
},
});
const expiring = await this.licenseRepo
.createQueryBuilder('l')
.where('l.status = :status', { status: 'active' })
.andWhere('l.expires_at <= :date', { date: thirtyDaysLater })
.andWhere('l.expires_at > NOW()')
.getCount();
return {
customerCount,
activeLicenseCount,
expiringSoonCount: expiring,
totalLicenses: await this.licenseRepo.count(),
};
}
}
@@ -0,0 +1,59 @@
import {
Body,
Controller,
Get,
Param,
ParseIntPipe,
Post,
Query,
Res,
UseGuards,
} from '@nestjs/common';
import { Response } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { GenerateLicenseDto, LicenseQueryDto } from './license.dto';
import { LicenseService } from './license.service';
@Controller('licenses')
export class LicenseController {
constructor(private readonly licenseService: LicenseService) {}
/** 在线吊销状态查询(主应用调用,无需管理员 JWT) */
@Get('status')
status(@Query('jti') jti: string) {
return this.licenseService.getStatusByJti(jti);
}
@Get()
@UseGuards(JwtAuthGuard)
list(@Query() query: LicenseQueryDto) {
return this.licenseService.list(query);
}
@Post('generate')
@UseGuards(JwtAuthGuard)
generate(@Body() dto: GenerateLicenseDto) {
return this.licenseService.generate(dto);
}
@Get(':id')
@UseGuards(JwtAuthGuard)
findOne(@Param('id', ParseIntPipe) id: number) {
return this.licenseService.findOne(id);
}
@Post(':id/revoke')
@UseGuards(JwtAuthGuard)
revoke(@Param('id', ParseIntPipe) id: number) {
return this.licenseService.revoke(id);
}
@Get(':id/download')
@UseGuards(JwtAuthGuard)
async download(@Param('id', ParseIntPipe) id: number, @Res() res: Response) {
const file = await this.licenseService.download(id);
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="${file.filename}"`);
res.send(file.content);
}
}
@@ -0,0 +1,58 @@
import {
IsArray,
IsDateString,
IsInt,
IsNotEmpty,
IsOptional,
IsString,
Min,
} from 'class-validator';
import { Type } from 'class-transformer';
export class GenerateLicenseDto {
@Type(() => Number)
@IsInt()
customerId!: number;
@IsString()
@IsNotEmpty()
company!: string;
@IsString()
@IsNotEmpty()
machineFingerprint!: string;
@IsString()
@IsNotEmpty()
edition!: string;
@IsDateString()
expiresAt!: string;
@IsArray()
@IsString({ each: true })
features!: string[];
}
export class LicenseQueryDto {
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
page?: number = 1;
@Type(() => Number)
@IsInt()
@Min(1)
@IsOptional()
size?: number = 20;
@Type(() => Number)
@IsInt()
@IsOptional()
customerId?: number;
@IsString()
@IsOptional()
status?: string;
}
@@ -0,0 +1,18 @@
import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JwtSignerService } from '../../common/jwt-signer.service';
import { LcLicense } from '../../entities/lc-license.entity';
import { CustomerModule } from '../customer/customer.module';
import { LicenseController } from './license.controller';
import { LicenseService } from './license.service';
@Module({
imports: [
TypeOrmModule.forFeature([LcLicense]),
forwardRef(() => CustomerModule),
],
controllers: [LicenseController],
providers: [LicenseService, JwtSignerService],
exports: [LicenseService, JwtSignerService],
})
export class LicenseModule {}
@@ -0,0 +1,123 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { JwtSignerService } from '../../common/jwt-signer.service';
import { LcCustomer } from '../../entities/lc-customer.entity';
import { LcLicense } from '../../entities/lc-license.entity';
import { CustomerService } from '../customer/customer.service';
import { GenerateLicenseDto, LicenseQueryDto } from './license.dto';
@Injectable()
export class LicenseService {
constructor(
@InjectRepository(LcLicense)
private readonly licenseRepo: Repository<LcLicense>,
private readonly customerService: CustomerService,
private readonly jwtSigner: JwtSignerService,
) {}
async list(query: LicenseQueryDto) {
const page = query.page || 1;
const size = query.size || 20;
const qb = this.licenseRepo
.createQueryBuilder('l')
.leftJoinAndSelect('l.customer', 'c')
.orderBy('l.id', 'DESC')
.skip((page - 1) * size)
.take(size);
if (query.customerId) {
qb.andWhere('l.customer_id = :customerId', { customerId: query.customerId });
}
if (query.status) {
qb.andWhere('l.status = :status', { status: query.status });
}
const [items, total] = await qb.getManyAndCount();
return { items, total, page, size };
}
async findOne(id: number) {
const license = await this.licenseRepo.findOne({
where: { id },
relations: ['customer'],
});
if (!license) throw new NotFoundException('许可证不存在');
return license;
}
async listByCustomer(customerId: number) {
await this.customerService.findOne(customerId);
return this.licenseRepo.find({
where: { customerId },
order: { id: 'DESC' },
});
}
async generate(dto: GenerateLicenseDto) {
const customer = await this.customerService.findOne(dto.customerId);
const expiresAt = new Date(dto.expiresAt);
const signed = await this.jwtSigner.signLicense({
sub: customer.code,
company: dto.company,
machineFingerprint: dto.machineFingerprint,
edition: dto.edition,
features: dto.features,
expiresAt,
});
const license = this.licenseRepo.create({
customerId: customer.id,
licenseKey: signed.licenseKey,
jti: signed.jti,
edition: dto.edition,
machineFingerprint: dto.machineFingerprint,
features: dto.features,
status: 'active',
issuedAt: signed.issuedAt,
expiresAt: signed.expiresAt,
activationCount: 0,
});
const saved = await this.licenseRepo.save(license);
return {
id: saved.id,
licenseKey: saved.licenseKey,
jti: saved.jti,
edition: saved.edition,
machineFingerprint: saved.machineFingerprint,
expiresAt: saved.expiresAt,
status: saved.status,
};
}
async revoke(id: number) {
const license = await this.findOne(id);
license.status = 'revoked';
license.revokedAt = new Date();
await this.licenseRepo.save(license);
return { id: license.id, jti: license.jti, status: license.status, revokedAt: license.revokedAt };
}
/** 在线吊销查询(主应用可选同步) */
async getStatusByJti(jti: string) {
const license = await this.licenseRepo.findOne({ where: { jti } });
if (!license) {
throw new NotFoundException('许可证不存在');
}
// 过期自动标记
if (license.status === 'active' && license.expiresAt < new Date()) {
license.status = 'expired';
await this.licenseRepo.save(license);
}
return {
jti: license.jti,
status: license.status,
revokedAt: license.revokedAt,
};
}
async download(id: number) {
const license = await this.findOne(id);
return {
filename: `license-${license.jti}.key`,
content: license.licenseKey,
};
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "dist", "**/*spec.ts"]
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"baseUrl": "./",
"skipLibCheck": true,
"strict": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"types": ["node"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}