feat: 完善安装部署与数字溯源码
This commit is contained in:
@@ -14,6 +14,7 @@ import { buildOrderBy } from '../common/utils/sort.util';
|
||||
import { AuthUser } from '../common/decorators/current-user.decorator';
|
||||
import { QueryBackupDto } from './dto/backup.dto';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
|
||||
const MODELS = [
|
||||
'sysUser',
|
||||
@@ -26,6 +27,7 @@ const MODELS = [
|
||||
'traceCodeGroup',
|
||||
'batch',
|
||||
'traceCode',
|
||||
'traceCodeDailySequence',
|
||||
'blockchainProof',
|
||||
'queryLog',
|
||||
'job',
|
||||
@@ -48,6 +50,7 @@ const PRISMA_MODEL_BY_DELEGATE: Record<(typeof MODELS)[number], string> = {
|
||||
traceCodeGroup: 'TraceCodeGroup',
|
||||
batch: 'Batch',
|
||||
traceCode: 'TraceCode',
|
||||
traceCodeDailySequence: 'TraceCodeDailySequence',
|
||||
blockchainProof: 'BlockchainProof',
|
||||
queryLog: 'QueryLog',
|
||||
job: 'Job',
|
||||
@@ -112,6 +115,7 @@ export class BackupService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly config: ConfigService,
|
||||
private readonly settings: SettingsService,
|
||||
private readonly storage: StorageService,
|
||||
) {
|
||||
this.storageRoot = resolve(this.config.get<string>('storage.localDir') || './storage');
|
||||
this.backupRoot = resolve(process.env.BACKUP_DIR || join(dirname(this.storageRoot), 'backups'));
|
||||
@@ -141,7 +145,7 @@ export class BackupService {
|
||||
try {
|
||||
const db = await this.dumpDatabase();
|
||||
const zip = new AdmZip();
|
||||
const fileList = this.addStorageFiles(zip);
|
||||
const fileList = await this.addStorageFiles(zip);
|
||||
const manifest = {
|
||||
app: 'artveris',
|
||||
version: '0.1.0',
|
||||
@@ -221,7 +225,7 @@ export class BackupService {
|
||||
try {
|
||||
const zip = new AdmZip(readFileSync(record.filePath));
|
||||
await this.restoreDatabase(zip);
|
||||
this.restoreStorage(zip);
|
||||
await this.restoreStorage(zip);
|
||||
return this.prisma.backupRecord.update({
|
||||
where: { id: restoreId },
|
||||
data: { status: BackupStatus.SUCCESS, error: null },
|
||||
@@ -256,7 +260,7 @@ export class BackupService {
|
||||
private async dumpEffectiveSettings() {
|
||||
const rows = await this.prisma.systemSetting.findMany();
|
||||
const byKey = new Map(rows.map((row) => [row.key, row]));
|
||||
const all = await this.settings.getAll();
|
||||
const all = await this.settings.getAllRaw();
|
||||
let nextId = rows.reduce((max, row) => Math.max(max, row.id), 0) + 1;
|
||||
const now = new Date();
|
||||
for (const [key, value] of Object.entries(all)) {
|
||||
@@ -267,8 +271,17 @@ export class BackupService {
|
||||
return [...byKey.values()];
|
||||
}
|
||||
|
||||
private addStorageFiles(zip: AdmZip) {
|
||||
private async addStorageFiles(zip: AdmZip) {
|
||||
const files: string[] = [];
|
||||
const storageKeys = await this.storage.listKeys();
|
||||
if (storageKeys.length) {
|
||||
for (const key of storageKeys) {
|
||||
if (!isSafeZipPath(key)) continue;
|
||||
files.push(key);
|
||||
zip.addFile(`storage/${key}`, await this.storage.read(key));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
if (!existsSync(this.storageRoot)) return files;
|
||||
const walk = (dir: string) => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
@@ -304,20 +317,25 @@ export class BackupService {
|
||||
}, { timeout: 120000 });
|
||||
}
|
||||
|
||||
private restoreStorage(zip: AdmZip) {
|
||||
mkdirSync(this.storageRoot, { recursive: true });
|
||||
for (const name of readdirSync(this.storageRoot)) {
|
||||
const full = join(this.storageRoot, name);
|
||||
if (isSameOrChildPath(this.backupRoot, full)) continue;
|
||||
rmSync(full, { recursive: true, force: true });
|
||||
private async restoreStorage(zip: AdmZip) {
|
||||
const currentKeys = await this.storage.listKeys();
|
||||
if (currentKeys.length) {
|
||||
for (const key of currentKeys) {
|
||||
if (!key.startsWith('.health/')) await this.storage.remove(key);
|
||||
}
|
||||
} else {
|
||||
mkdirSync(this.storageRoot, { recursive: true });
|
||||
for (const name of readdirSync(this.storageRoot)) {
|
||||
const full = join(this.storageRoot, name);
|
||||
if (isSameOrChildPath(this.backupRoot, full)) continue;
|
||||
rmSync(full, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
for (const entry of zip.getEntries()) {
|
||||
if (entry.isDirectory || !entry.entryName.startsWith('storage/')) continue;
|
||||
const rel = entry.entryName.slice('storage/'.length);
|
||||
if (!isSafeZipPath(rel)) throw new Error(`备份包包含不安全文件路径:${entry.entryName}`);
|
||||
const full = join(this.storageRoot, rel);
|
||||
mkdirSync(dirname(full), { recursive: true });
|
||||
writeFileSync(full, entry.getData());
|
||||
await this.storage.putKey(rel, entry.getData());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ function makeService(): BlockchainService {
|
||||
} as unknown as ConfigService;
|
||||
const settings = {
|
||||
getAll: async () => ({ blockchainDriver: 'mock' }),
|
||||
getAllRaw: async () => ({ blockchainDriver: 'mock' }),
|
||||
} as unknown as SettingsService;
|
||||
return new BlockchainService(config, settings);
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ export class BlockchainService {
|
||||
}
|
||||
|
||||
private async buildProvider(): Promise<AttestationProvider> {
|
||||
const settings = await this.settings.getAll();
|
||||
const settings = await this.settings.getAllRaw();
|
||||
const driver = (settings.blockchainDriver || this.config.get<string>('blockchain.driver') || 'mock') as 'mock' | 'tianhe';
|
||||
if (driver !== 'tianhe') return new MockProvider();
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ErrorMessage } from '@artveris/shared';
|
||||
import { ErrorMessage, ErrorMessageKey } from '@artveris/shared';
|
||||
|
||||
// 业务异常:携带统一业务码,由全局过滤器转换为标准响应体。
|
||||
export class BusinessException extends Error {
|
||||
@@ -6,6 +6,8 @@ export class BusinessException extends Error {
|
||||
public readonly code: number,
|
||||
message?: string,
|
||||
public readonly httpStatus = 400,
|
||||
public readonly messageKey = ErrorMessageKey[code],
|
||||
public readonly params?: Record<string, unknown>,
|
||||
) {
|
||||
super(message || ErrorMessage[code] || '业务处理失败');
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { ErrorCode } from '@artveris/shared';
|
||||
import { ErrorCode, ErrorMessageKey } from '@artveris/shared';
|
||||
import { BusinessException } from '../exceptions/business.exception';
|
||||
|
||||
@Catch()
|
||||
@@ -21,11 +21,15 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
||||
let httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let code: number = ErrorCode.INTERNAL_ERROR;
|
||||
let message = '服务器内部错误';
|
||||
let messageKey = ErrorMessageKey[ErrorCode.INTERNAL_ERROR];
|
||||
let params: Record<string, unknown> | undefined;
|
||||
|
||||
if (exception instanceof BusinessException) {
|
||||
httpStatus = exception.httpStatus;
|
||||
code = exception.code;
|
||||
message = exception.message;
|
||||
messageKey = exception.messageKey || ErrorMessageKey[code];
|
||||
params = exception.params;
|
||||
} else if (exception instanceof HttpException) {
|
||||
httpStatus = exception.getStatus();
|
||||
const r = exception.getResponse();
|
||||
@@ -36,6 +40,7 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
||||
message = Array.isArray(m) ? String(m[0]) : String(m ?? exception.message);
|
||||
}
|
||||
code = this.mapStatusToCode(httpStatus);
|
||||
messageKey = ErrorMessageKey[code];
|
||||
} else {
|
||||
this.logger.error(
|
||||
(exception as Error)?.message ?? String(exception),
|
||||
@@ -43,7 +48,7 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
||||
);
|
||||
}
|
||||
|
||||
res.status(httpStatus).json({ code, message, data: null });
|
||||
res.status(httpStatus).json({ code, message, messageKey, params, data: null });
|
||||
}
|
||||
|
||||
private mapStatusToCode(status: number): number {
|
||||
|
||||
@@ -18,7 +18,7 @@ export class TransformInterceptor<T> implements NestInterceptor<T, ApiResponse<T
|
||||
) {
|
||||
return data as unknown as ApiResponse<T>;
|
||||
}
|
||||
return { code: 0, message: 'success', data: (data ?? null) as T | null };
|
||||
return { code: 0, message: 'success', messageKey: 'common.success', data: (data ?? null) as T | null };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { loadRuntimeConfig } from './runtime-config';
|
||||
|
||||
export interface AppConfig {
|
||||
appName: string;
|
||||
env: string;
|
||||
@@ -8,6 +10,7 @@ export interface AppConfig {
|
||||
clientOrigin: string;
|
||||
traceUrlTemplate: string;
|
||||
jwt: { secret: string; expiresIn: string };
|
||||
settingsEncryptionKey: string;
|
||||
redis: { host: string; port: number; password?: string };
|
||||
storage: {
|
||||
driver: 'local' | 'oss';
|
||||
@@ -32,47 +35,60 @@ export interface AppConfig {
|
||||
}
|
||||
|
||||
export default (): AppConfig => {
|
||||
const clientOrigin = process.env.CLIENT_ORIGIN || 'http://localhost:5174';
|
||||
const runtime = loadRuntimeConfig();
|
||||
if (!process.env.DATABASE_URL && runtime.databaseUrl) process.env.DATABASE_URL = runtime.databaseUrl;
|
||||
if (!process.env.BACKUP_DIR && runtime.backupDir) process.env.BACKUP_DIR = runtime.backupDir;
|
||||
const storage = runtime.storage || {};
|
||||
const oss = storage.oss || {};
|
||||
const blockchain = runtime.blockchain || {};
|
||||
const tianhe = blockchain.tianhe || {};
|
||||
const clientOrigin = process.env.CLIENT_ORIGIN || runtime.clientOrigin || 'http://localhost:5174';
|
||||
return {
|
||||
appName: process.env.APP_NAME || '艺术品溯源平台',
|
||||
appName: process.env.APP_NAME || runtime.appName || '艺术品溯源平台',
|
||||
env: process.env.NODE_ENV || 'development',
|
||||
port: parseInt(process.env.API_PORT || '3000', 10),
|
||||
baseUrl: process.env.BASE_URL || 'http://localhost:3000',
|
||||
port: parseInt(process.env.API_PORT || String(runtime.port || 3000), 10),
|
||||
baseUrl: process.env.BASE_URL || runtime.baseUrl || 'http://localhost:3000',
|
||||
publicTracePath: process.env.PUBLIC_TRACE_PATH || '/t',
|
||||
adminOrigin: process.env.ADMIN_ORIGIN || 'http://localhost:5173',
|
||||
adminOrigin: process.env.ADMIN_ORIGIN || runtime.adminOrigin || 'http://localhost:5173',
|
||||
clientOrigin,
|
||||
// 短链跳转到 C 端溯源页的地址模板,{code} 会被替换为短码
|
||||
traceUrlTemplate: process.env.TRACE_URL_TEMPLATE || `${clientOrigin}/#/trace/{code}`,
|
||||
jwt: {
|
||||
secret: process.env.JWT_SECRET || 'artveris_dev_secret',
|
||||
expiresIn: process.env.JWT_EXPIRES_IN || '7d',
|
||||
secret: process.env.JWT_SECRET || runtime.jwt?.secret || 'artveris_dev_secret',
|
||||
expiresIn: process.env.JWT_EXPIRES_IN || runtime.jwt?.expiresIn || '7d',
|
||||
},
|
||||
settingsEncryptionKey:
|
||||
process.env.SETTING_ENCRYPTION_KEY ||
|
||||
runtime.settingsEncryptionKey ||
|
||||
process.env.JWT_SECRET ||
|
||||
runtime.jwt?.secret ||
|
||||
'artveris_dev_secret',
|
||||
redis: {
|
||||
host: process.env.REDIS_HOST || 'localhost',
|
||||
port: parseInt(process.env.REDIS_PORT || '6379', 10),
|
||||
password: process.env.REDIS_PASSWORD || undefined,
|
||||
host: process.env.REDIS_HOST || runtime.redis?.host || 'localhost',
|
||||
port: parseInt(process.env.REDIS_PORT || String(runtime.redis?.port || 6379), 10),
|
||||
password: process.env.REDIS_PASSWORD || runtime.redis?.password || undefined,
|
||||
},
|
||||
storage: {
|
||||
driver: (process.env.STORAGE_DRIVER as 'local' | 'oss') || 'local',
|
||||
localDir: process.env.STORAGE_LOCAL_DIR || './storage',
|
||||
publicPrefix: process.env.STORAGE_PUBLIC_PREFIX || '/uploads',
|
||||
cdnBaseUrl: process.env.CDN_BASE_URL || '',
|
||||
driver: (process.env.STORAGE_DRIVER as 'local' | 'oss') || storage.driver || 'local',
|
||||
localDir: process.env.STORAGE_LOCAL_DIR || storage.localDir || './storage',
|
||||
publicPrefix: process.env.STORAGE_PUBLIC_PREFIX || storage.publicPrefix || '/uploads',
|
||||
cdnBaseUrl: process.env.CDN_BASE_URL || storage.cdnBaseUrl || '',
|
||||
oss: {
|
||||
endpoint: process.env.OSS_ENDPOINT || '',
|
||||
region: process.env.OSS_REGION || '',
|
||||
bucket: process.env.OSS_BUCKET || '',
|
||||
accessKeyId: process.env.OSS_ACCESS_KEY_ID || '',
|
||||
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET || '',
|
||||
endpoint: process.env.OSS_ENDPOINT || oss.endpoint || '',
|
||||
region: process.env.OSS_REGION || oss.region || '',
|
||||
bucket: process.env.OSS_BUCKET || oss.bucket || '',
|
||||
accessKeyId: process.env.OSS_ACCESS_KEY_ID || oss.accessKeyId || '',
|
||||
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET || oss.accessKeySecret || '',
|
||||
},
|
||||
},
|
||||
blockchain: {
|
||||
driver: (process.env.BLOCKCHAIN_DRIVER as 'mock' | 'tianhe') || 'mock',
|
||||
driver: (process.env.BLOCKCHAIN_DRIVER as 'mock' | 'tianhe') || blockchain.driver || 'mock',
|
||||
tianhe: {
|
||||
baseUrl: process.env.TIANHE_BASE_URL || 'https://test.api.tichain.tianhecloud.com',
|
||||
appId: process.env.TIANHE_APP_ID || '',
|
||||
appKey: process.env.TIANHE_APP_KEY || '',
|
||||
userId: process.env.TIANHE_USER_ID || '',
|
||||
userKey: process.env.TIANHE_USER_KEY || '',
|
||||
baseUrl: process.env.TIANHE_BASE_URL || tianhe.baseUrl || 'https://test.api.tichain.tianhecloud.com',
|
||||
appId: process.env.TIANHE_APP_ID || tianhe.appId || '',
|
||||
appKey: process.env.TIANHE_APP_KEY || tianhe.appKey || '',
|
||||
userId: process.env.TIANHE_USER_ID || tianhe.userId || '',
|
||||
userKey: process.env.TIANHE_USER_KEY || tianhe.userKey || '',
|
||||
},
|
||||
},
|
||||
seedAdmin: {
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
|
||||
export interface RuntimeConfigFile {
|
||||
appName?: string;
|
||||
port?: number;
|
||||
baseUrl?: string;
|
||||
adminOrigin?: string;
|
||||
clientOrigin?: string;
|
||||
databaseUrl?: string;
|
||||
redis?: { host?: string; port?: number; password?: string };
|
||||
jwt?: { secret?: string; expiresIn?: string };
|
||||
settingsEncryptionKey?: string;
|
||||
storage?: {
|
||||
driver?: 'local' | 'oss';
|
||||
localDir?: string;
|
||||
publicPrefix?: string;
|
||||
cdnBaseUrl?: string;
|
||||
oss?: {
|
||||
endpoint?: string;
|
||||
region?: string;
|
||||
bucket?: string;
|
||||
accessKeyId?: string;
|
||||
accessKeySecret?: string;
|
||||
};
|
||||
};
|
||||
backupDir?: string;
|
||||
blockchain?: {
|
||||
driver?: 'mock' | 'tianhe';
|
||||
tianhe?: { baseUrl?: string; appId?: string; appKey?: string; userId?: string; userKey?: string };
|
||||
};
|
||||
}
|
||||
|
||||
export function runtimeRoot(): string {
|
||||
return resolve(process.env.ARTVERIS_RUNTIME_DIR || process.env.RUNTIME_DIR || resolve(process.cwd(), 'runtime'));
|
||||
}
|
||||
|
||||
export function runtimeConfigPath(): string {
|
||||
return resolve(process.env.ARTVERIS_CONFIG_PATH || resolve(runtimeRoot(), 'artveris.config.json'));
|
||||
}
|
||||
|
||||
export function runtimeEnvPath(): string {
|
||||
return resolve(dirname(runtimeConfigPath()), '.env');
|
||||
}
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfigFile {
|
||||
const path = runtimeConfigPath();
|
||||
if (!existsSync(path)) return {};
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, 'utf8')) as RuntimeConfigFile;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function loadEnvFile(path: string): void {
|
||||
if (!existsSync(path)) return;
|
||||
const text = readFileSync(path, 'utf8');
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const eq = line.indexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
const key = line.slice(0, eq).trim();
|
||||
if (process.env[key] !== undefined) continue;
|
||||
let value = line.slice(eq + 1).trim();
|
||||
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
export function preloadRuntimeEnv(): void {
|
||||
loadEnvFile(resolve(process.cwd(), '.env'));
|
||||
loadEnvFile(resolve(process.cwd(), '../../.env'));
|
||||
loadEnvFile(runtimeEnvPath());
|
||||
}
|
||||
|
||||
export function hasRuntimeConfig(): boolean {
|
||||
return existsSync(runtimeConfigPath());
|
||||
}
|
||||
|
||||
export function isInstallMode(): boolean {
|
||||
preloadRuntimeEnv();
|
||||
if (process.env.ARTVERIS_INSTALL_MODE === '1') return true;
|
||||
if (process.env.ARTVERIS_INSTALL_MODE === '0') return false;
|
||||
if (process.env.DATABASE_URL) return false;
|
||||
return !hasRuntimeConfig();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import configuration from './config/configuration';
|
||||
import { InstallModule } from './install/install.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
load: [configuration],
|
||||
envFilePath: ['../../.env', '.env'],
|
||||
}),
|
||||
InstallModule,
|
||||
],
|
||||
})
|
||||
export class InstallAppModule {}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsBoolean, IsIn, IsInt, IsNotEmpty, IsOptional, IsString, IsUrl, MaxLength, Min, MinLength, ValidateNested } from 'class-validator';
|
||||
|
||||
export class InstallMysqlDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
host!: string;
|
||||
|
||||
@ApiProperty({ default: 3306 })
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
port!: number;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
database!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
username!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
password!: string;
|
||||
}
|
||||
|
||||
export class InstallRedisDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
host!: string;
|
||||
|
||||
@ApiProperty({ default: 6379 })
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
port!: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
password?: string;
|
||||
}
|
||||
|
||||
export class InstallAdminDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(50)
|
||||
username!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(6)
|
||||
@MaxLength(64)
|
||||
password!: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(50)
|
||||
realName?: string;
|
||||
}
|
||||
|
||||
export class InstallStorageDto {
|
||||
@ApiProperty({ enum: ['local', 'oss'] })
|
||||
@IsIn(['local', 'oss'])
|
||||
driver!: 'local' | 'oss';
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
localDir?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cdnBaseUrl?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossEndpoint?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossRegion?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossBucket?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossAccessKeyId?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossAccessKeySecret?: string;
|
||||
}
|
||||
|
||||
export class InstallRequestDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
appName!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsUrl({ require_tld: false })
|
||||
baseUrl!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsUrl({ require_tld: false })
|
||||
clientBaseUrl!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@ValidateNested()
|
||||
@Type(() => InstallMysqlDto)
|
||||
mysql!: InstallMysqlDto;
|
||||
|
||||
@ApiProperty()
|
||||
@ValidateNested()
|
||||
@Type(() => InstallRedisDto)
|
||||
redis!: InstallRedisDto;
|
||||
|
||||
@ApiProperty()
|
||||
@ValidateNested()
|
||||
@Type(() => InstallAdminDto)
|
||||
admin!: InstallAdminDto;
|
||||
|
||||
@ApiProperty()
|
||||
@ValidateNested()
|
||||
@Type(() => InstallStorageDto)
|
||||
storage!: InstallStorageDto;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
jwtSecret?: string;
|
||||
|
||||
@ApiPropertyOptional({ default: '7d' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
jwtExpiresIn?: string;
|
||||
|
||||
@ApiPropertyOptional({ default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
backupEnabled?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Body, Controller, Get, Post } from '@nestjs/common';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from '../common/decorators/public.decorator';
|
||||
import { InstallRequestDto } from './dto/install.dto';
|
||||
import { InstallService } from './install.service';
|
||||
|
||||
@ApiTags('Install')
|
||||
@Controller('install')
|
||||
export class InstallController {
|
||||
constructor(private readonly installService: InstallService) {}
|
||||
|
||||
@Public()
|
||||
@Get('status')
|
||||
@ApiOperation({ summary: 'Installation status' })
|
||||
status() {
|
||||
return this.installService.status();
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Initialize installation' })
|
||||
install(@Body() dto: InstallRequestDto) {
|
||||
return this.installService.install(dto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { InstallController } from './install.controller';
|
||||
import { InstallService } from './install.service';
|
||||
|
||||
@Module({
|
||||
controllers: [InstallController],
|
||||
providers: [InstallService],
|
||||
})
|
||||
export class InstallModule {}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { createCipheriv, createHash, randomBytes } from 'crypto';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
import { execFileSync } from 'child_process';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { PrismaClient, RoleType, UserStatus } from '@prisma/client';
|
||||
import Redis from 'ioredis';
|
||||
import { runtimeConfigPath, runtimeEnvPath, runtimeRoot } from '../config/runtime-config';
|
||||
import { InstallRequestDto } from './dto/install.dto';
|
||||
|
||||
const INSTALL_STATE_FILE = 'install-state.json';
|
||||
const ENCRYPTED_PREFIX = 'enc:v1:';
|
||||
|
||||
@Injectable()
|
||||
export class InstallService {
|
||||
status() {
|
||||
const configPath = runtimeConfigPath();
|
||||
const installed = existsSync(configPath) || (process.env.ARTVERIS_INSTALL_MODE !== '1' && Boolean(process.env.DATABASE_URL));
|
||||
return {
|
||||
installed,
|
||||
configPath,
|
||||
traceCodeSalt: installed ? null : this.pendingTraceCodeSalt(),
|
||||
defaults: {
|
||||
mysqlHost: process.env.INSTALL_MYSQL_HOST || 'mysql',
|
||||
mysqlPort: Number(process.env.INSTALL_MYSQL_PORT || 3306),
|
||||
mysqlDatabase: process.env.MYSQL_DATABASE || 'artveris',
|
||||
mysqlUser: process.env.MYSQL_USER || 'artveris',
|
||||
redisHost: process.env.INSTALL_REDIS_HOST || 'redis',
|
||||
redisPort: Number(process.env.INSTALL_REDIS_PORT || 6379),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async install(dto: InstallRequestDto) {
|
||||
if (existsSync(runtimeConfigPath()) || (process.env.ARTVERIS_INSTALL_MODE !== '1' && process.env.DATABASE_URL)) {
|
||||
return { installed: true, restartRequired: false };
|
||||
}
|
||||
const traceCodeSalt = this.pendingTraceCodeSalt();
|
||||
const databaseUrl = this.buildMysqlUrl(dto);
|
||||
await this.assertMysql(databaseUrl);
|
||||
await this.assertRedis(dto);
|
||||
const config = this.buildRuntimeConfig(dto, databaseUrl);
|
||||
this.runPrismaMigrate(databaseUrl);
|
||||
await this.seedInstallData(databaseUrl, dto, traceCodeSalt, String(config.settingsEncryptionKey || ''));
|
||||
this.writeRuntimeConfig(config, traceCodeSalt);
|
||||
setTimeout(() => process.exit(0), 600);
|
||||
return { installed: true, restartRequired: true };
|
||||
}
|
||||
|
||||
private pendingTraceCodeSalt(): string {
|
||||
const path = resolve(runtimeRoot(), INSTALL_STATE_FILE);
|
||||
try {
|
||||
if (existsSync(path)) {
|
||||
const state = JSON.parse(readFileSync(path, 'utf8')) as { traceCodeSalt?: string };
|
||||
if (state.traceCodeSalt) return state.traceCodeSalt;
|
||||
}
|
||||
} catch {
|
||||
// Regenerate below when the pending state file is malformed.
|
||||
}
|
||||
const traceCodeSalt = randomBytes(32).toString('hex');
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, JSON.stringify({ traceCodeSalt }, null, 2), 'utf8');
|
||||
return traceCodeSalt;
|
||||
}
|
||||
|
||||
private buildMysqlUrl(dto: InstallRequestDto): string {
|
||||
const user = encodeURIComponent(dto.mysql.username);
|
||||
const password = encodeURIComponent(dto.mysql.password);
|
||||
const db = encodeURIComponent(dto.mysql.database);
|
||||
return `mysql://${user}:${password}@${dto.mysql.host}:${dto.mysql.port}/${db}`;
|
||||
}
|
||||
|
||||
private async assertMysql(databaseUrl: string): Promise<void> {
|
||||
const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } });
|
||||
try {
|
||||
await prisma.$connect();
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private async assertRedis(dto: InstallRequestDto): Promise<void> {
|
||||
const redis = new Redis({
|
||||
host: dto.redis.host,
|
||||
port: dto.redis.port,
|
||||
password: dto.redis.password || undefined,
|
||||
maxRetriesPerRequest: 1,
|
||||
lazyConnect: true,
|
||||
});
|
||||
try {
|
||||
await redis.connect();
|
||||
await redis.ping();
|
||||
} finally {
|
||||
redis.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private buildRuntimeConfig(dto: InstallRequestDto, databaseUrl: string) {
|
||||
const localDir = dto.storage.localDir || resolve(process.cwd(), 'storage');
|
||||
return {
|
||||
appName: dto.appName,
|
||||
port: Number(process.env.API_PORT || 3000),
|
||||
baseUrl: dto.baseUrl.replace(/\/$/, ''),
|
||||
adminOrigin: `${dto.baseUrl.replace(/\/$/, '')}/admin`,
|
||||
clientOrigin: dto.clientBaseUrl.replace(/\/$/, ''),
|
||||
databaseUrl,
|
||||
redis: {
|
||||
host: dto.redis.host,
|
||||
port: dto.redis.port,
|
||||
password: dto.redis.password || '',
|
||||
},
|
||||
jwt: {
|
||||
secret: dto.jwtSecret || randomBytes(32).toString('hex'),
|
||||
expiresIn: dto.jwtExpiresIn || '7d',
|
||||
},
|
||||
settingsEncryptionKey: randomBytes(32).toString('hex'),
|
||||
storage: {
|
||||
driver: dto.storage.driver,
|
||||
localDir,
|
||||
publicPrefix: '/uploads',
|
||||
cdnBaseUrl: dto.storage.cdnBaseUrl || '',
|
||||
oss: {
|
||||
endpoint: dto.storage.ossEndpoint || '',
|
||||
region: dto.storage.ossRegion || '',
|
||||
bucket: dto.storage.ossBucket || '',
|
||||
accessKeyId: dto.storage.ossAccessKeyId || '',
|
||||
accessKeySecret: '',
|
||||
},
|
||||
},
|
||||
backupDir: resolve(process.cwd(), 'backups'),
|
||||
blockchain: { driver: 'mock', tianhe: {} },
|
||||
};
|
||||
}
|
||||
|
||||
private writeRuntimeConfig(config: Record<string, unknown>, traceCodeSalt: string): void {
|
||||
const path = runtimeConfigPath();
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, JSON.stringify(config, null, 2), 'utf8');
|
||||
const envLines = [
|
||||
`DATABASE_URL="${config.databaseUrl}"`,
|
||||
`TRACE_CODE_SALT=${traceCodeSalt}`,
|
||||
`ARTVERIS_CONFIG_PATH=${path.replace(/\\/g, '/')}`,
|
||||
];
|
||||
writeFileSync(runtimeEnvPath(), `${envLines.join('\n')}\n`, 'utf8');
|
||||
}
|
||||
|
||||
private runPrismaMigrate(databaseUrl: string): void {
|
||||
const prismaBin = require.resolve('prisma/build/index.js');
|
||||
execFileSync(process.execPath, [prismaBin, 'migrate', 'deploy', '--schema', this.prismaSchemaPath()], {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, DATABASE_URL: databaseUrl },
|
||||
});
|
||||
}
|
||||
|
||||
private prismaSchemaPath(): string {
|
||||
const candidates = [
|
||||
resolve(process.cwd(), 'prisma/schema.prisma'),
|
||||
resolve(process.cwd(), 'apps/api/prisma/schema.prisma'),
|
||||
resolve(__dirname, '../../prisma/schema.prisma'),
|
||||
];
|
||||
const found = candidates.find((path) => existsSync(path));
|
||||
if (!found) throw new Error(`Prisma schema not found: ${candidates.join(', ')}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
private async seedInstallData(databaseUrl: string, dto: InstallRequestDto, traceCodeSalt: string, settingsEncryptionKey: string): Promise<void> {
|
||||
const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } });
|
||||
try {
|
||||
await prisma.$connect();
|
||||
const passwordHash = await bcrypt.hash(dto.admin.password, 10);
|
||||
const realName = dto.admin.realName || dto.admin.username;
|
||||
await prisma.sysUser.upsert({
|
||||
where: { username: dto.admin.username },
|
||||
update: { passwordHash, realName, role: RoleType.SUPER_ADMIN, status: UserStatus.ACTIVE },
|
||||
create: { username: dto.admin.username, passwordHash, realName, role: RoleType.SUPER_ADMIN, status: UserStatus.ACTIVE },
|
||||
});
|
||||
const settings: Record<string, string> = {
|
||||
appName: dto.appName,
|
||||
clientBaseUrl: dto.clientBaseUrl.replace(/\/$/, ''),
|
||||
traceCodeSalt,
|
||||
settingsEncryptionKey,
|
||||
backupEnabled: String(Boolean(dto.backupEnabled)),
|
||||
storageDriver: dto.storage.driver,
|
||||
storageLocalDir: dto.storage.localDir || resolve(process.cwd(), 'storage'),
|
||||
storagePublicPrefix: '/uploads',
|
||||
cdnBaseUrl: dto.storage.cdnBaseUrl || '',
|
||||
ossEndpoint: dto.storage.ossEndpoint || '',
|
||||
ossRegion: dto.storage.ossRegion || '',
|
||||
ossBucket: dto.storage.ossBucket || '',
|
||||
ossAccessKeyId: dto.storage.ossAccessKeyId || '',
|
||||
ossAccessKeySecret: this.encryptSecret(dto.storage.ossAccessKeySecret || '', settingsEncryptionKey),
|
||||
};
|
||||
for (const [key, value] of Object.entries(settings)) {
|
||||
await prisma.systemSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
|
||||
}
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private encryptSecret(value: string, key: string): string {
|
||||
if (!value) return '';
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv('aes-256-gcm', createHash('sha256').update(key).digest(), iv);
|
||||
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return `${ENCRYPTED_PREFIX}${Buffer.concat([iv, tag, encrypted]).toString('base64url')}`;
|
||||
}
|
||||
}
|
||||
+48
-25
@@ -1,24 +1,35 @@
|
||||
import 'reflect-metadata';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe, RequestMethod, Logger } from '@nestjs/common';
|
||||
import { Logger, RequestMethod, ValidationPipe } from '@nestjs/common';
|
||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { existsSync, mkdirSync } from 'fs';
|
||||
import { resolve } from 'path';
|
||||
import { AppModule } from './app.module';
|
||||
import { join, resolve } from 'path';
|
||||
import { InstallAppModule } from './install-app.module';
|
||||
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
|
||||
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
|
||||
import { OperationLogInterceptor } from './operation-log/operation-log.interceptor';
|
||||
import { STATIC_ASSET_CACHE_CONTROL } from './storage/storage.service';
|
||||
import { isInstallMode } from './config/runtime-config';
|
||||
|
||||
// 让 BigInt 可被 JSON 序列化为字符串,避免精度问题。
|
||||
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
|
||||
return this.toString();
|
||||
};
|
||||
|
||||
function mountSpa(app: NestExpressApplication, prefix: string, root: string): void {
|
||||
if (!existsSync(root)) return;
|
||||
app.useStaticAssets(root, { prefix });
|
||||
const http = app.getHttpAdapter().getInstance();
|
||||
const index = resolve(root, 'index.html');
|
||||
http.get(prefix, (_req, res) => res.sendFile(index));
|
||||
http.get(`${prefix}/*`, (_req, res) => res.sendFile(index));
|
||||
}
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
|
||||
const installing = isInstallMode();
|
||||
const rootModule = installing ? InstallAppModule : (await import('./app.module')).AppModule;
|
||||
const app = await NestFactory.create<NestExpressApplication>(rootModule, {
|
||||
bodyParser: true,
|
||||
});
|
||||
const config = app.get(ConfigService);
|
||||
@@ -46,28 +57,40 @@ async function bootstrap(): Promise<void> {
|
||||
}),
|
||||
);
|
||||
app.useGlobalFilters(new AllExceptionsFilter());
|
||||
app.useGlobalInterceptors(app.get(OperationLogInterceptor), new TransformInterceptor());
|
||||
if (installing) {
|
||||
app.useGlobalInterceptors(new TransformInterceptor());
|
||||
} else {
|
||||
app.useGlobalInterceptors(app.get(OperationLogInterceptor), new TransformInterceptor());
|
||||
}
|
||||
|
||||
// 本地文件存储静态访问
|
||||
const localDir = resolve(config.get<string>('storage.localDir') || './storage');
|
||||
if (!existsSync(localDir)) {
|
||||
mkdirSync(localDir, { recursive: true });
|
||||
const publicRoot = resolve(process.env.ARTVERIS_PUBLIC_DIR || join(process.cwd(), 'public'));
|
||||
const http = app.getHttpAdapter().getInstance();
|
||||
if (installing) {
|
||||
mountSpa(app, '/install', resolve(publicRoot, 'install'));
|
||||
http.get('/', (_req, res) => res.redirect('/install'));
|
||||
} else {
|
||||
const localDir = resolve(config.get<string>('storage.localDir') || './storage');
|
||||
if (!existsSync(localDir)) mkdirSync(localDir, { recursive: true });
|
||||
app.useStaticAssets(localDir, {
|
||||
prefix: config.get<string>('storage.publicPrefix') || '/uploads',
|
||||
etag: true,
|
||||
lastModified: true,
|
||||
maxAge: '1y',
|
||||
immutable: true,
|
||||
setHeaders: (res) => {
|
||||
res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
|
||||
},
|
||||
});
|
||||
mountSpa(app, '/admin', resolve(publicRoot, 'admin'));
|
||||
mountSpa(app, '/trace', resolve(publicRoot, 'trace'));
|
||||
if (existsSync(resolve(publicRoot, 'admin', 'index.html'))) {
|
||||
http.get('/', (_req, res) => res.redirect('/admin'));
|
||||
}
|
||||
}
|
||||
app.useStaticAssets(localDir, {
|
||||
prefix: config.get<string>('storage.publicPrefix') || '/uploads',
|
||||
etag: true,
|
||||
lastModified: true,
|
||||
maxAge: '1y',
|
||||
immutable: true,
|
||||
setHeaders: (res) => {
|
||||
res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
|
||||
},
|
||||
});
|
||||
|
||||
// Swagger(开发文档)
|
||||
const swaggerConfig = new DocumentBuilder()
|
||||
.setTitle('artveris API')
|
||||
.setDescription('艺术品可信溯源与认证系统接口文档')
|
||||
.setTitle('Artveris API')
|
||||
.setDescription('Artveris traceability and certification API')
|
||||
.setVersion('0.1.0')
|
||||
.addBearerAuth()
|
||||
.build();
|
||||
@@ -76,8 +99,8 @@ async function bootstrap(): Promise<void> {
|
||||
|
||||
const port = config.get<number>('port') || 3000;
|
||||
await app.listen(port);
|
||||
logger.log(`API 已启动: http://localhost:${port}/api`);
|
||||
logger.log(`接口文档: http://localhost:${port}/api/docs`);
|
||||
logger.log(`${installing ? 'Install server' : 'API'} started: http://localhost:${port}/api`);
|
||||
logger.log(`Swagger: http://localhost:${port}/api/docs`);
|
||||
}
|
||||
|
||||
void bootstrap();
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Request, Response } from 'express';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from '../common/decorators/public.decorator';
|
||||
import { extractIp } from '../common/utils/ua.util';
|
||||
import { PublicTraceService } from './public-trace.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
|
||||
@ApiTags('公开溯源')
|
||||
@Controller()
|
||||
export class PublicTraceController {
|
||||
constructor(
|
||||
private readonly service: PublicTraceService,
|
||||
private readonly config: ConfigService,
|
||||
private readonly settings: SettingsService,
|
||||
) {}
|
||||
|
||||
@Public()
|
||||
@@ -26,10 +26,8 @@ export class PublicTraceController {
|
||||
// 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下)
|
||||
@Public()
|
||||
@Get('t/:shortCode')
|
||||
redirect(@Param('shortCode') shortCode: string, @Res() res: Response) {
|
||||
const template =
|
||||
this.config.get<string>('traceUrlTemplate') ||
|
||||
'http://localhost:5174/#/pages/trace/index?code={code}';
|
||||
res.redirect(302, template.replace('{code}', encodeURIComponent(shortCode)));
|
||||
async redirect(@Param('shortCode') shortCode: string, @Res() res: Response) {
|
||||
const clientBaseUrl = await this.settings.getClientBaseUrl();
|
||||
res.redirect(302, `${clientBaseUrl}/#/trace/${encodeURIComponent(shortCode)}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import type Redis from 'ioredis';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { ArtworkStatus, AuditStatus, QueryResult, ProofStatus, TraceCodeStatus } from '@artveris/shared';
|
||||
import { ArtworkStatus, AuditStatus, QueryResult, ProofStatus, TRACE_CODE_PATTERN, TraceCodeStatus } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { REDIS_CLIENT } from '../redis/redis.module';
|
||||
@@ -92,6 +92,10 @@ export class PublicTraceService {
|
||||
}
|
||||
|
||||
async trace(shortCode: string, ctx: TraceContext) {
|
||||
if (!TRACE_CODE_PATTERN.test(shortCode)) {
|
||||
await this.writeLog(null, null, shortCode, QueryResult.INVALID, ctx);
|
||||
return { status: 'INVALID' as const };
|
||||
}
|
||||
const id = await this.resolveId(shortCode);
|
||||
if (id === null) {
|
||||
await this.writeLog(null, null, shortCode, QueryResult.INVALID, ctx);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
const EDITABLE_KEYS = [
|
||||
@@ -14,6 +15,20 @@ const EDITABLE_KEYS = [
|
||||
'backupSchedule',
|
||||
'backupRetentionDays',
|
||||
'backupRetentionCount',
|
||||
'clientBaseUrl',
|
||||
'storageDriver',
|
||||
'storageLocalDir',
|
||||
'storagePublicPrefix',
|
||||
'cdnBaseUrl',
|
||||
'ossEndpoint',
|
||||
'ossRegion',
|
||||
'ossBucket',
|
||||
'ossAccessKeyId',
|
||||
'ossAccessKeySecret',
|
||||
'settingsEncryptionKey',
|
||||
'storageMigrationTarget',
|
||||
'storageMigrationFingerprint',
|
||||
'storageMigrationCopied',
|
||||
'blockchainDriver',
|
||||
'tianheEnv',
|
||||
'tianheBaseUrl',
|
||||
@@ -23,6 +38,9 @@ const EDITABLE_KEYS = [
|
||||
'tianheUserKey',
|
||||
];
|
||||
|
||||
const SECRET_KEYS = new Set(['ossAccessKeySecret', 'tianheAppKey', 'tianheUserKey']);
|
||||
const ENCRYPTED_PREFIX = 'enc:v1:';
|
||||
|
||||
@Injectable()
|
||||
export class SettingsService {
|
||||
constructor(
|
||||
@@ -31,6 +49,14 @@ export class SettingsService {
|
||||
) {}
|
||||
|
||||
async getAll(): Promise<Record<string, string>> {
|
||||
return this.getAllInternal(true);
|
||||
}
|
||||
|
||||
async getAllRaw(): Promise<Record<string, string>> {
|
||||
return this.getAllInternal(false);
|
||||
}
|
||||
|
||||
private async getAllInternal(maskSecrets: boolean): Promise<Record<string, string>> {
|
||||
const rows = await this.prisma.systemSetting.findMany();
|
||||
const map: Record<string, string> = {
|
||||
appName: this.config.get<string>('appName') || '',
|
||||
@@ -44,6 +70,17 @@ export class SettingsService {
|
||||
backupSchedule: 'daily',
|
||||
backupRetentionDays: '30',
|
||||
backupRetentionCount: '10',
|
||||
clientBaseUrl: this.config.get<string>('clientOrigin') || 'http://localhost:5174',
|
||||
storageDriver: this.config.get<string>('storage.driver') || 'local',
|
||||
storageLocalDir: this.config.get<string>('storage.localDir') || './storage',
|
||||
storagePublicPrefix: this.config.get<string>('storage.publicPrefix') || '/uploads',
|
||||
cdnBaseUrl: this.config.get<string>('storage.cdnBaseUrl') || '',
|
||||
ossEndpoint: this.config.get<string>('storage.oss.endpoint') || '',
|
||||
ossRegion: this.config.get<string>('storage.oss.region') || '',
|
||||
ossBucket: this.config.get<string>('storage.oss.bucket') || '',
|
||||
ossAccessKeyId: this.config.get<string>('storage.oss.accessKeyId') || '',
|
||||
ossAccessKeySecret: this.config.get<string>('storage.oss.accessKeySecret') || '',
|
||||
settingsEncryptionKey: this.config.get<string>('settingsEncryptionKey') || '',
|
||||
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
|
||||
tianheEnv: 'test',
|
||||
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
|
||||
@@ -53,26 +90,85 @@ export class SettingsService {
|
||||
tianheUserKey: this.config.get<string>('blockchain.tianhe.userKey') || '',
|
||||
};
|
||||
for (const r of rows) {
|
||||
map[r.key] = r.key === 'appName' && r.value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : r.value;
|
||||
const value = SECRET_KEYS.has(r.key) ? await this.decryptSecret(r.value) : r.value;
|
||||
map[r.key] = r.key === 'appName' && value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : value;
|
||||
}
|
||||
if (!map.appIconUrl) map.appIconUrl = '/app-icon.svg';
|
||||
if (maskSecrets) {
|
||||
if (map.ossAccessKeySecret) map.ossAccessKeySecret = this.maskSecret(map.ossAccessKeySecret);
|
||||
if (map.tianheAppKey) map.tianheAppKey = this.maskSecret(map.tianheAppKey);
|
||||
if (map.tianheUserKey) map.tianheUserKey = this.maskSecret(map.tianheUserKey);
|
||||
delete map.settingsEncryptionKey;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
async get(key: string): Promise<string | null> {
|
||||
const row = await this.prisma.systemSetting.findUnique({ where: { key } });
|
||||
return row?.value ?? null;
|
||||
if (!row) return null;
|
||||
return SECRET_KEYS.has(key) ? this.decryptSecret(row.value) : row.value;
|
||||
}
|
||||
|
||||
async getClientBaseUrl(): Promise<string> {
|
||||
const fromDb = await this.get('clientBaseUrl');
|
||||
return (fromDb || this.config.get<string>('clientOrigin') || 'http://localhost:5174').replace(/\/$/, '');
|
||||
}
|
||||
|
||||
private maskSecret(value: string): string {
|
||||
if (!value || value.length <= 8) return value ? '******' : '';
|
||||
return `${value.slice(0, 3)}******${value.slice(-3)}`;
|
||||
}
|
||||
|
||||
isMaskedSecret(value?: string | null): boolean {
|
||||
return typeof value === 'string' && /^\*+$|^.{1,8}\*{3,}.{1,8}$/.test(value);
|
||||
}
|
||||
|
||||
async update(values: Record<string, string>): Promise<Record<string, string>> {
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (!EDITABLE_KEYS.includes(key)) continue;
|
||||
if (SECRET_KEYS.has(key) && this.isMaskedSecret(value)) continue;
|
||||
const nextValue = SECRET_KEYS.has(key) ? await this.encryptSecret(String(value)) : String(value);
|
||||
await this.prisma.systemSetting.upsert({
|
||||
where: { key },
|
||||
update: { value: String(value) },
|
||||
create: { key, value: String(value) },
|
||||
update: { value: nextValue },
|
||||
create: { key, value: nextValue },
|
||||
});
|
||||
}
|
||||
return this.getAll();
|
||||
}
|
||||
|
||||
private async encryptionKey(): Promise<Buffer> {
|
||||
const row = await this.prisma.systemSetting.findUnique({ where: { key: 'settingsEncryptionKey' } }).catch(() => null);
|
||||
const secret =
|
||||
row?.value ||
|
||||
this.config.get<string>('settingsEncryptionKey') ||
|
||||
process.env.SETTING_ENCRYPTION_KEY ||
|
||||
this.config.get<string>('jwt.secret') ||
|
||||
'artveris_dev_secret';
|
||||
return createHash('sha256').update(secret).digest();
|
||||
}
|
||||
|
||||
private async encryptSecret(value: string): Promise<string> {
|
||||
if (!value || value.startsWith(ENCRYPTED_PREFIX)) return value;
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv('aes-256-gcm', await this.encryptionKey(), iv);
|
||||
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return `${ENCRYPTED_PREFIX}${Buffer.concat([iv, tag, encrypted]).toString('base64url')}`;
|
||||
}
|
||||
|
||||
private async decryptSecret(value: string): Promise<string> {
|
||||
if (!value?.startsWith(ENCRYPTED_PREFIX)) return value;
|
||||
try {
|
||||
const raw = Buffer.from(value.slice(ENCRYPTED_PREFIX.length), 'base64url');
|
||||
const iv = raw.subarray(0, 12);
|
||||
const tag = raw.subarray(12, 28);
|
||||
const encrypted = raw.subarray(28);
|
||||
const decipher = createDecipheriv('aes-256-gcm', await this.encryptionKey(), iv);
|
||||
decipher.setAuthTag(tag);
|
||||
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsIn, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class StorageConfigDto {
|
||||
@ApiPropertyOptional({ enum: ['local', 'oss'] })
|
||||
@IsOptional()
|
||||
@IsIn(['local', 'oss'])
|
||||
driver?: 'local' | 'oss';
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
localDir?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cdnBaseUrl?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossEndpoint?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossRegion?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossBucket?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossAccessKeyId?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ossAccessKeySecret?: string;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs';
|
||||
import { dirname, relative, resolve } from 'path';
|
||||
import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync, rmSync, readFileSync } from 'fs';
|
||||
import { dirname, join, relative, resolve } from 'path';
|
||||
import { PutOptions, StorageDriver } from './storage.types';
|
||||
|
||||
export interface LocalDriverOptions {
|
||||
@@ -43,6 +43,24 @@ export class LocalDriver implements StorageDriver {
|
||||
}
|
||||
}
|
||||
|
||||
async list(): Promise<string[]> {
|
||||
if (!existsSync(this.root)) return [];
|
||||
const keys: string[] = [];
|
||||
const walk = (dir: string) => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const full = join(dir, name);
|
||||
const st = statSync(full);
|
||||
if (st.isDirectory()) {
|
||||
walk(full);
|
||||
} else {
|
||||
keys.push(relative(this.root, full).replace(/\\/g, '/'));
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(this.root);
|
||||
return keys;
|
||||
}
|
||||
|
||||
getPublicUrl(key: string): string {
|
||||
if (this.opts.cdnBaseUrl) {
|
||||
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
DeleteObjectCommand,
|
||||
GetObjectCommand,
|
||||
ListObjectsV2Command,
|
||||
PutObjectCommand,
|
||||
S3Client,
|
||||
} from '@aws-sdk/client-s3';
|
||||
@@ -56,6 +57,19 @@ export class OssDriver implements StorageDriver {
|
||||
await this.client.send(new DeleteObjectCommand({ Bucket: this.opts.bucket, Key: key }));
|
||||
}
|
||||
|
||||
async list(): Promise<string[]> {
|
||||
const keys: string[] = [];
|
||||
let token: string | undefined;
|
||||
do {
|
||||
const res = await this.client.send(new ListObjectsV2Command({ Bucket: this.opts.bucket, ContinuationToken: token }));
|
||||
for (const item of res.Contents || []) {
|
||||
if (item.Key) keys.push(item.Key);
|
||||
}
|
||||
token = res.NextContinuationToken;
|
||||
} while (token);
|
||||
return keys;
|
||||
}
|
||||
|
||||
getPublicUrl(key: string): string {
|
||||
if (this.opts.cdnBaseUrl) {
|
||||
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { StorageAdminService } from './storage-admin.service';
|
||||
import { StorageConfigDto } from './dto/storage-migration.dto';
|
||||
|
||||
@ApiTags('Storage')
|
||||
@ApiBearerAuth()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Controller('storage')
|
||||
export class StorageAdminController {
|
||||
constructor(private readonly service: StorageAdminService) {}
|
||||
|
||||
@Post('test')
|
||||
@ApiOperation({ summary: 'Test storage connection' })
|
||||
test(@Body() dto: StorageConfigDto) {
|
||||
return this.service.test(dto);
|
||||
}
|
||||
|
||||
@Post('migrate')
|
||||
@ApiOperation({ summary: 'Migrate business files to target storage' })
|
||||
migrate(@Body() dto: StorageConfigDto) {
|
||||
return this.service.migrate(dto);
|
||||
}
|
||||
|
||||
@Post('confirm')
|
||||
@ApiOperation({ summary: 'Confirm target storage switch' })
|
||||
confirm(@Body() dto: StorageConfigDto) {
|
||||
return this.service.confirm(dto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createHash } from 'crypto';
|
||||
import { ErrorCode } from '@artveris/shared';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { StorageService } from './storage.service';
|
||||
import { LocalDriver } from './local.driver';
|
||||
import { OssDriver } from './oss.driver';
|
||||
import { StorageConfigDto } from './dto/storage-migration.dto';
|
||||
import { StorageDriver } from './storage.types';
|
||||
|
||||
@Injectable()
|
||||
export class StorageAdminService {
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
private readonly settings: SettingsService,
|
||||
private readonly storage: StorageService,
|
||||
) {}
|
||||
|
||||
async test(dto: StorageConfigDto) {
|
||||
await this.storage.test(await this.driverFromDto(dto));
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async migrate(dto: StorageConfigDto) {
|
||||
const source = await this.currentDriver();
|
||||
const target = await this.driverFromDto(dto);
|
||||
const keys = source.list ? await source.list() : await this.storage.listKeys();
|
||||
let copied = 0;
|
||||
for (const key of keys) {
|
||||
if (key.startsWith('.health/')) continue;
|
||||
const buffer = await source.get(key);
|
||||
await target.put(key, buffer);
|
||||
copied += 1;
|
||||
}
|
||||
await this.settings.update({
|
||||
storageMigrationTarget: JSON.stringify(this.sanitizedTarget(dto)),
|
||||
storageMigrationFingerprint: this.targetFingerprint(dto),
|
||||
storageMigrationCopied: String(copied),
|
||||
});
|
||||
return { success: true, copied };
|
||||
}
|
||||
|
||||
async confirm(dto: StorageConfigDto) {
|
||||
const fingerprint = await this.settings.get('storageMigrationFingerprint');
|
||||
if (fingerprint !== this.targetFingerprint(dto)) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, undefined, 400, 'error.STORAGE_MIGRATION_REQUIRED');
|
||||
}
|
||||
await this.settings.update(this.settingsPayload(dto));
|
||||
await this.storage.reloadFromSettings();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
private async currentDriver(): Promise<StorageDriver> {
|
||||
const s = await this.settings.getAllRaw();
|
||||
return this.storage.createDriver({
|
||||
driver: s.storageDriver || this.config.get<string>('storage.driver') || 'local',
|
||||
localDir: s.storageLocalDir || this.config.get<string>('storage.localDir') || './storage',
|
||||
publicPrefix: s.storagePublicPrefix || this.config.get<string>('storage.publicPrefix') || '/uploads',
|
||||
cdnBaseUrl: s.cdnBaseUrl || this.config.get<string>('storage.cdnBaseUrl') || '',
|
||||
oss: {
|
||||
endpoint: s.ossEndpoint || this.config.get<string>('storage.oss.endpoint') || '',
|
||||
region: s.ossRegion || this.config.get<string>('storage.oss.region') || '',
|
||||
bucket: s.ossBucket || this.config.get<string>('storage.oss.bucket') || '',
|
||||
accessKeyId: s.ossAccessKeyId || this.config.get<string>('storage.oss.accessKeyId') || '',
|
||||
accessKeySecret: s.ossAccessKeySecret || this.config.get<string>('storage.oss.accessKeySecret') || '',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async driverFromDto(dto: StorageConfigDto): Promise<StorageDriver> {
|
||||
const driver = dto.driver || 'local';
|
||||
if (driver === 'oss') {
|
||||
const secret = await this.resolveOssSecret(dto.ossAccessKeySecret);
|
||||
if (!dto.ossBucket || !dto.ossAccessKeyId || !secret) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, undefined, 400, 'error.OSS_CONFIG_INCOMPLETE');
|
||||
}
|
||||
return new OssDriver({
|
||||
endpoint: dto.ossEndpoint || '',
|
||||
region: dto.ossRegion || '',
|
||||
bucket: dto.ossBucket,
|
||||
accessKeyId: dto.ossAccessKeyId,
|
||||
accessKeySecret: secret,
|
||||
cdnBaseUrl: dto.cdnBaseUrl || '',
|
||||
});
|
||||
}
|
||||
return new LocalDriver({
|
||||
localDir: dto.localDir || this.config.get<string>('storage.localDir') || './storage',
|
||||
publicPrefix: '/uploads',
|
||||
cdnBaseUrl: dto.cdnBaseUrl || '',
|
||||
baseUrl: this.config.get<string>('baseUrl') || 'http://localhost:3000',
|
||||
});
|
||||
}
|
||||
|
||||
private settingsPayload(dto: StorageConfigDto): Record<string, string> {
|
||||
const payload: Record<string, string> = {
|
||||
storageDriver: dto.driver || 'local',
|
||||
storageLocalDir: dto.localDir || '',
|
||||
storagePublicPrefix: '/uploads',
|
||||
cdnBaseUrl: dto.cdnBaseUrl || '',
|
||||
ossEndpoint: dto.ossEndpoint || '',
|
||||
ossRegion: dto.ossRegion || '',
|
||||
ossBucket: dto.ossBucket || '',
|
||||
ossAccessKeyId: dto.ossAccessKeyId || '',
|
||||
};
|
||||
if (!this.settings.isMaskedSecret(dto.ossAccessKeySecret)) {
|
||||
payload.ossAccessKeySecret = dto.ossAccessKeySecret || '';
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
private sanitizedTarget(dto: StorageConfigDto): Record<string, string> {
|
||||
return {
|
||||
storageDriver: dto.driver || 'local',
|
||||
storageLocalDir: dto.localDir || '',
|
||||
storagePublicPrefix: '/uploads',
|
||||
cdnBaseUrl: dto.cdnBaseUrl || '',
|
||||
ossEndpoint: dto.ossEndpoint || '',
|
||||
ossRegion: dto.ossRegion || '',
|
||||
ossBucket: dto.ossBucket || '',
|
||||
ossAccessKeyId: dto.ossAccessKeyId || '',
|
||||
};
|
||||
}
|
||||
|
||||
private targetFingerprint(dto: StorageConfigDto): string {
|
||||
return createHash('sha256').update(JSON.stringify(this.sanitizedTarget(dto))).digest('hex');
|
||||
}
|
||||
|
||||
private async resolveOssSecret(value?: string): Promise<string> {
|
||||
if (value && !this.settings.isMaskedSecret(value)) return value;
|
||||
return (await this.settings.get('ossAccessKeySecret')) || this.config.get<string>('storage.oss.accessKeySecret') || '';
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { StorageService } from './storage.service';
|
||||
import { StorageAdminService } from './storage-admin.service';
|
||||
import { StorageAdminController } from './storage-admin.controller';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [StorageService],
|
||||
exports: [StorageService],
|
||||
controllers: [StorageAdminController],
|
||||
providers: [StorageService, StorageAdminService],
|
||||
exports: [StorageService, StorageAdminService],
|
||||
})
|
||||
export class StorageModule {}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createHash } from 'crypto';
|
||||
import dayjs from 'dayjs';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { extname } from 'path';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { LocalDriver } from './local.driver';
|
||||
import { OssDriver } from './oss.driver';
|
||||
import { SavedFile, StorageDriver } from './storage.types';
|
||||
@@ -23,14 +24,42 @@ const MIME_EXT: Record<string, string> = {
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class StorageService {
|
||||
export class StorageService implements OnModuleInit {
|
||||
private readonly logger = new Logger(StorageService.name);
|
||||
private readonly driver: StorageDriver;
|
||||
private driver: StorageDriver;
|
||||
|
||||
constructor(private readonly config: ConfigService) {
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
private readonly settings: SettingsService,
|
||||
) {
|
||||
const s = this.config.get<Record<string, any>>('storage')!;
|
||||
this.driver = this.createDriver(s);
|
||||
}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.reloadFromSettings();
|
||||
}
|
||||
|
||||
async reloadFromSettings(): Promise<void> {
|
||||
const s = await this.settings.getAllRaw();
|
||||
this.driver = this.createDriver({
|
||||
driver: s.storageDriver || this.config.get<string>('storage.driver') || 'local',
|
||||
localDir: s.storageLocalDir || this.config.get<string>('storage.localDir') || './storage',
|
||||
publicPrefix: s.storagePublicPrefix || this.config.get<string>('storage.publicPrefix') || '/uploads',
|
||||
cdnBaseUrl: s.cdnBaseUrl || this.config.get<string>('storage.cdnBaseUrl') || '',
|
||||
oss: {
|
||||
endpoint: s.ossEndpoint || this.config.get<string>('storage.oss.endpoint') || '',
|
||||
region: s.ossRegion || this.config.get<string>('storage.oss.region') || '',
|
||||
bucket: s.ossBucket || this.config.get<string>('storage.oss.bucket') || '',
|
||||
accessKeyId: s.ossAccessKeyId || this.config.get<string>('storage.oss.accessKeyId') || '',
|
||||
accessKeySecret: s.ossAccessKeySecret || this.config.get<string>('storage.oss.accessKeySecret') || '',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
createDriver(s: Record<string, any>): StorageDriver {
|
||||
if (s.driver === 'oss') {
|
||||
this.driver = new OssDriver({
|
||||
const driver = new OssDriver({
|
||||
endpoint: s.oss.endpoint,
|
||||
region: s.oss.region,
|
||||
bucket: s.oss.bucket,
|
||||
@@ -39,14 +68,16 @@ export class StorageService {
|
||||
cdnBaseUrl: s.cdnBaseUrl,
|
||||
});
|
||||
this.logger.log('存储驱动:OSS/S3 兼容');
|
||||
return driver;
|
||||
} else {
|
||||
this.driver = new LocalDriver({
|
||||
const driver = new LocalDriver({
|
||||
localDir: s.localDir,
|
||||
publicPrefix: s.publicPrefix,
|
||||
cdnBaseUrl: s.cdnBaseUrl,
|
||||
baseUrl: this.config.get<string>('baseUrl') || 'http://localhost:3000',
|
||||
});
|
||||
this.logger.log('存储驱动:本地磁盘');
|
||||
return driver;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,4 +132,16 @@ export class StorageService {
|
||||
async remove(key: string): Promise<void> {
|
||||
await this.driver.remove(key);
|
||||
}
|
||||
|
||||
async listKeys(): Promise<string[]> {
|
||||
return this.driver.list ? this.driver.list() : [];
|
||||
}
|
||||
|
||||
async test(driver: StorageDriver): Promise<boolean> {
|
||||
const key = `.health/${Date.now()}-${nanoid()}.txt`;
|
||||
await driver.put(key, Buffer.from('ok'), { contentType: 'text/plain' });
|
||||
await driver.get(key);
|
||||
await driver.remove(key);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface StorageDriver {
|
||||
get(key: string): Promise<Buffer>;
|
||||
remove(key: string): Promise<void>;
|
||||
getPublicUrl(key: string): string;
|
||||
list?(): Promise<string[]>;
|
||||
}
|
||||
|
||||
export interface SavedFile {
|
||||
|
||||
@@ -2,13 +2,13 @@ import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { customAlphabet } from 'nanoid';
|
||||
import { BatchStatus, JobStatus, QUEUE_NAMES, SHORT_CODE_LENGTH } from '@artveris/shared';
|
||||
import { BatchStatus, JobStatus, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { JobsService } from '../jobs/jobs.service';
|
||||
import { TraceCodeService } from './trace-code.service';
|
||||
import { TraceCodeGeneratorService } from './trace-code-generator.service';
|
||||
|
||||
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
||||
const shortId = customAlphabet(ALPHABET, SHORT_CODE_LENGTH);
|
||||
const codeId = customAlphabet(ALPHABET, 18);
|
||||
|
||||
interface GenJobData {
|
||||
@@ -27,6 +27,7 @@ export class GenCodeProcessor extends WorkerHost {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly jobs: JobsService,
|
||||
private readonly traceCode: TraceCodeService,
|
||||
private readonly generator: TraceCodeGeneratorService,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
@@ -41,19 +42,19 @@ export class GenCodeProcessor extends WorkerHost {
|
||||
try {
|
||||
while (generated < quantity) {
|
||||
const n = Math.min(chunkSize, quantity - generated);
|
||||
const rows = Array.from({ length: n }, () => {
|
||||
const shortCode = shortId();
|
||||
const shortCodes = await this.generator.generate(n);
|
||||
const rows = shortCodes.map((shortCode) => {
|
||||
return {
|
||||
code: codeId(),
|
||||
shortCode,
|
||||
artworkId,
|
||||
batchId,
|
||||
groupId: groupId ?? null,
|
||||
url: this.traceCode.buildTraceUrl(shortCode),
|
||||
url: null,
|
||||
};
|
||||
});
|
||||
await this.prisma.traceCode.createMany({ data: rows, skipDuplicates: true });
|
||||
generated += n;
|
||||
const result = await this.prisma.traceCode.createMany({ data: rows, skipDuplicates: true });
|
||||
generated += result.count;
|
||||
await this.jobs.progress(jobId, generated, 0);
|
||||
await this.prisma.batch.update({
|
||||
where: { id: batchId },
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { TraceCodeGeneratorService } from './trace-code-generator.service';
|
||||
|
||||
describe('TraceCodeGeneratorService', () => {
|
||||
const prisma: any = {
|
||||
systemSetting: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
},
|
||||
traceCodeDailySequence: {
|
||||
upsert: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
$transaction: jest.fn(async (fn) => fn(prisma)),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-07-06T08:00:00.000Z'));
|
||||
prisma.systemSetting.findUnique.mockResolvedValue({ value: 'salt-for-test' });
|
||||
prisma.traceCodeDailySequence.upsert.mockResolvedValue({});
|
||||
prisma.traceCodeDailySequence.update.mockResolvedValue({ nextSeq: 1000 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('generates unique 12-digit codes with the Shanghai date embedded', async () => {
|
||||
const service = new TraceCodeGeneratorService(prisma);
|
||||
const codes = await service.generate(1000);
|
||||
|
||||
expect(codes).toHaveLength(1000);
|
||||
expect(new Set(codes).size).toBe(1000);
|
||||
for (const code of codes) {
|
||||
expect(code).toMatch(/^\d{12}$/);
|
||||
expect(`${code.slice(2, 4)}${code.slice(5, 7)}${code.slice(8, 10)}`).toBe('260706');
|
||||
}
|
||||
expect(codes.slice(0, 5)).not.toEqual(['002600700600', '002600700601', '002600700602', '002600700603', '002600700604']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { createHmac, randomBytes } from 'crypto';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { SHORT_CODE_LENGTH } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
const TRACE_CODE_SALT_KEY = 'traceCodeSalt';
|
||||
const MAX_DAILY_SEQUENCE = 1_000_000;
|
||||
const FEISTEL_ROUNDS = 4;
|
||||
|
||||
interface SequenceRange {
|
||||
dateKey: string;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TraceCodeGeneratorService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async ensureSalt(): Promise<string> {
|
||||
const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
|
||||
if (existing?.value) return existing.value;
|
||||
const salt = randomBytes(32).toString('hex');
|
||||
try {
|
||||
await this.prisma.systemSetting.create({ data: { key: TRACE_CODE_SALT_KEY, value: salt } });
|
||||
return salt;
|
||||
} catch (e) {
|
||||
if (this.isUniqueError(e)) {
|
||||
const row = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
|
||||
if (row?.value) return row.value;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async generate(count: number): Promise<string[]> {
|
||||
const salt = await this.ensureSalt();
|
||||
const range = await this.allocateRange(count);
|
||||
return Array.from({ length: range.end - range.start + 1 }, (_, index) =>
|
||||
this.formatCode(this.permute6(range.start + index, salt, range.dateKey), range.dateKey),
|
||||
);
|
||||
}
|
||||
|
||||
private async allocateRange(count: number): Promise<SequenceRange> {
|
||||
const dateKey = this.shanghaiDateKey();
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
try {
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
await tx.traceCodeDailySequence.upsert({
|
||||
where: { dateKey },
|
||||
update: {},
|
||||
create: { dateKey, nextSeq: 0 },
|
||||
});
|
||||
const row = await tx.traceCodeDailySequence.update({
|
||||
where: { dateKey },
|
||||
data: { nextSeq: { increment: count } },
|
||||
});
|
||||
const start = row.nextSeq - count;
|
||||
const end = row.nextSeq - 1;
|
||||
if (end >= MAX_DAILY_SEQUENCE) {
|
||||
throw new Error('trace.code.dailyLimitExceeded');
|
||||
}
|
||||
return { dateKey, start, end };
|
||||
});
|
||||
} catch (e) {
|
||||
if (!this.isUniqueError(e) || attempt === 2) throw e;
|
||||
}
|
||||
}
|
||||
throw new Error('trace.code.sequenceAllocationFailed');
|
||||
}
|
||||
|
||||
private shanghaiDateKey(date = new Date()): string {
|
||||
const parts = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: '2-digit',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).formatToParts(date);
|
||||
const get = (type: string) => parts.find((part) => part.type === type)?.value.padStart(2, '0') ?? '00';
|
||||
return `${get('year')}${get('month')}${get('day')}`;
|
||||
}
|
||||
|
||||
private permute6(seq: number, salt: string, dateKey: string): string {
|
||||
let left = Math.floor(seq / 1000);
|
||||
let right = seq % 1000;
|
||||
const keys = this.roundKeys(salt, dateKey);
|
||||
for (let round = 0; round < FEISTEL_ROUNDS; round += 1) {
|
||||
const nextLeft = right;
|
||||
const f = (right * keys[round].mul + keys[round].add) % 1000;
|
||||
right = (left + f) % 1000;
|
||||
left = nextLeft;
|
||||
}
|
||||
return `${left.toString().padStart(3, '0')}${right.toString().padStart(3, '0')}`;
|
||||
}
|
||||
|
||||
private roundKeys(salt: string, dateKey: string): Array<{ mul: number; add: number }> {
|
||||
const digest = createHmac('sha256', salt).update(`trace-code:${dateKey}`).digest();
|
||||
return Array.from({ length: FEISTEL_ROUNDS }, (_, index) => {
|
||||
const rawMul = digest.readUInt16BE(index * 4) % 1000;
|
||||
return {
|
||||
mul: rawMul % 2 === 0 ? rawMul + 1 : rawMul,
|
||||
add: digest.readUInt16BE(index * 4 + 2) % 1000,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private formatCode(scrambled: string, dateKey: string): string {
|
||||
const code = `${scrambled.slice(0, 2)}${dateKey.slice(0, 2)}${scrambled[2]}${dateKey.slice(2, 4)}${scrambled[3]}${dateKey.slice(4, 6)}${scrambled.slice(4)}`;
|
||||
if (code.length !== SHORT_CODE_LENGTH || !/^\d{12}$/.test(code)) {
|
||||
throw new Error('trace.code.invalidGeneratedCode');
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
private isUniqueError(error: unknown): boolean {
|
||||
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002';
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,12 @@ import { QUEUE_NAMES } from '@artveris/shared';
|
||||
import { TraceCodeService } from './trace-code.service';
|
||||
import { TraceCodeController } from './trace-code.controller';
|
||||
import { GenCodeProcessor } from './gen-code.processor';
|
||||
import { TraceCodeGeneratorService } from './trace-code-generator.service';
|
||||
|
||||
@Module({
|
||||
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.GEN_CODE })],
|
||||
controllers: [TraceCodeController],
|
||||
providers: [TraceCodeService, GenCodeProcessor],
|
||||
exports: [TraceCodeService],
|
||||
providers: [TraceCodeService, TraceCodeGeneratorService, GenCodeProcessor],
|
||||
exports: [TraceCodeService, TraceCodeGeneratorService],
|
||||
})
|
||||
export class TraceCodeModule {}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { buildOrderBy } from '../common/utils/sort.util';
|
||||
import { JobsService } from '../jobs/jobs.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import {
|
||||
BatchDeleteDto,
|
||||
BatchGroupDto,
|
||||
@@ -35,13 +36,28 @@ export class TraceCodeService {
|
||||
private readonly jobs: JobsService,
|
||||
private readonly config: ConfigService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly settings: SettingsService,
|
||||
@InjectQueue(QUEUE_NAMES.GEN_CODE) private readonly genQueue: Queue,
|
||||
) {}
|
||||
|
||||
buildTraceUrl(shortCode: string): string {
|
||||
const clientBase = (this.config.get<string>('clientOrigin') || this.config.get<string>('baseUrl') || 'http://localhost:3000/trace').replace(/\/$/, '');
|
||||
return `${clientBase}/#/trace/${encodeURIComponent(shortCode)}`;
|
||||
}
|
||||
|
||||
buildShortLink(shortCode: string): string {
|
||||
const base = (this.config.get<string>('baseUrl') || 'http://localhost:3000').replace(/\/$/, '');
|
||||
const path = this.config.get<string>('publicTracePath') || '/t';
|
||||
return `${base}${path}/${shortCode}`;
|
||||
return `${base}/t/${encodeURIComponent(shortCode)}`;
|
||||
}
|
||||
|
||||
async buildDynamicShortLink(shortCode: string): Promise<string> {
|
||||
try {
|
||||
const clientBaseUrl = await this.settings.getClientBaseUrl();
|
||||
const origin = new URL(clientBaseUrl).origin;
|
||||
return `${origin}/t/${encodeURIComponent(shortCode)}`;
|
||||
} catch {
|
||||
return this.buildShortLink(shortCode);
|
||||
}
|
||||
}
|
||||
|
||||
private mapOutImages(code: { outImage?: string | null; outImages?: unknown }) {
|
||||
@@ -453,7 +469,7 @@ export class TraceCodeService {
|
||||
async getQrPng(id: bigint): Promise<Buffer> {
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id } });
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||
return QRCode.toBuffer(code.url || this.buildTraceUrl(code.shortCode), {
|
||||
return QRCode.toBuffer(await this.buildDynamicShortLink(code.shortCode), {
|
||||
type: 'png',
|
||||
width: 320,
|
||||
margin: 1,
|
||||
@@ -502,7 +518,7 @@ export class TraceCodeService {
|
||||
|
||||
const qrImages: Array<{ name: string; buffer: Buffer }> = [];
|
||||
for (const c of codes) {
|
||||
const url = c.url || this.buildTraceUrl(c.shortCode);
|
||||
const url = await this.buildDynamicShortLink(c.shortCode);
|
||||
const row = ws.addRow({
|
||||
archiveNo: c.artwork?.archiveNo ?? '',
|
||||
title: c.artwork?.title ?? '',
|
||||
|
||||
Reference in New Issue
Block a user