feat: 完善安装部署与数字溯源码

This commit is contained in:
Nixevol
2026-07-06 23:26:21 +08:00
parent 7480e4d256
commit 7c6b0bff4c
59 changed files with 2174 additions and 166 deletions
+100 -4
View File
@@ -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 '';
}
}
}