import { Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; import { PrismaService } from '../prisma/prisma.service'; const EDITABLE_KEYS = [ 'appName', 'appIconUrl', 'logRetentionDays', 'operationLogRetentionDays', 'watermarkText', 'filingInfo', 'carouselInterval', 'backupEnabled', 'backupSchedule', 'backupRetentionDays', 'backupRetentionCount', 'clientBaseUrl', 'storageDriver', 'storageLocalDir', 'storagePublicPrefix', 'cdnBaseUrl', 'ossEndpoint', 'ossRegion', 'ossBucket', 'ossAccessKeyId', 'ossAccessKeySecret', 'storageMigrationTarget', 'storageMigrationFingerprint', 'storageMigrationCopied', 'blockchainDriver', 'tianheEnv', 'tianheBaseUrl', 'tianheAppId', 'tianheAppKey', 'tianheUserId', 'tianheUserKey', ]; // 加密存储的密钥(enc:v1:)。注意:tianheUserKey 有意不加密—— // 它是全系统唯一无外部恢复途径的钱包密码,明文存库才能让备份跨重装恢复 // (加密依赖 .env 的 SETTING_ENCRYPTION_KEY,重装换密钥后密文将无法解密); // 且单有 userKey 无 appKey(仍加密)无法操作钱包。 const SECRET_KEYS = new Set(['ossAccessKeySecret', 'tianheAppKey']); // 展示层掩码的密钥(getAll 输出打码;明文经专用揭示接口获取) const MASKED_KEYS = new Set(['ossAccessKeySecret', 'tianheAppKey', 'tianheUserKey']); const ENCRYPTED_PREFIX = 'enc:v1:'; @Injectable() export class SettingsService { private readonly logger = new Logger(SettingsService.name); constructor( private readonly prisma: PrismaService, private readonly config: ConfigService, ) {} async getAll(): Promise> { return this.getAllInternal(true); } async getAllRaw(): Promise> { return this.getAllInternal(false); } private async getAllInternal(maskSecrets: boolean): Promise> { const rows = await this.prisma.systemSetting.findMany(); const map: Record = { appName: this.config.get('appName') || '', appIconUrl: '', logRetentionDays: String(this.config.get('logRetentionDays') || 365), operationLogRetentionDays: '365', watermarkText: this.config.get('watermarkText') || '仅供溯源核验使用', filingInfo: '备案信息待补充', carouselInterval: '3', backupEnabled: 'false', backupSchedule: 'daily', backupRetentionDays: '30', backupRetentionCount: '10', clientBaseUrl: this.config.get('clientOrigin') || 'http://localhost:5174', storageDriver: this.config.get('storage.driver') || 'local', storageLocalDir: this.config.get('storage.localDir') || './storage', storagePublicPrefix: this.config.get('storage.publicPrefix') || '/uploads', cdnBaseUrl: this.config.get('storage.cdnBaseUrl') || '', ossEndpoint: this.config.get('storage.oss.endpoint') || '', ossRegion: this.config.get('storage.oss.region') || '', ossBucket: this.config.get('storage.oss.bucket') || '', ossAccessKeyId: this.config.get('storage.oss.accessKeyId') || '', ossAccessKeySecret: this.config.get('storage.oss.accessKeySecret') || '', settingsEncryptionKey: this.config.get('settingsEncryptionKey') || '', blockchainDriver: this.config.get('blockchain.driver') || 'mock', tianheEnv: 'test', tianheBaseUrl: this.config.get('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com', tianheAppId: this.config.get('blockchain.tianhe.appId') || '', tianheAppKey: this.config.get('blockchain.tianhe.appKey') || '', tianheUserId: this.config.get('blockchain.tianhe.userId') || '', tianheUserKey: this.config.get('blockchain.tianhe.userKey') || '', }; for (const r of rows) { // 带 enc:v1: 前缀的值统一解密(兼容历史上曾加密存储、现已改为明文的键,如 tianheUserKey) const value = await this.decryptSecret(r.value); map[r.key] = r.key === 'appName' && value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : value; } if (map.appIconUrl === '/app-icon.svg') map.appIconUrl = ''; if (maskSecrets) { for (const key of MASKED_KEYS) { if (map[key]) map[key] = this.maskSecret(map[key]); } delete map.settingsEncryptionKey; } return map; } async get(key: string): Promise { const row = await this.prisma.systemSetting.findUnique({ where: { key } }); if (!row) return null; return this.decryptSecret(row.value); } async getClientBaseUrl(): Promise { const fromDb = await this.get('clientBaseUrl'); return (fromDb || this.config.get('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)}`; } // 对外暴露的掩码工具(供控制器展示 userKey 掩码,不返回明文) maskSecretPublic(value: string): string { return this.maskSecret(value); } isMaskedSecret(value?: string | null): boolean { return typeof value === 'string' && /^\*+$|^.{1,8}\*{3,}.{1,8}$/.test(value); } async update(values: Record): Promise> { for (const [key, value] of Object.entries(values)) { if (!EDITABLE_KEYS.includes(key)) continue; if (MASKED_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: nextValue }, create: { key, value: nextValue }, }); } return this.getAll(); } // 服务内部直写(不做白名单/加密处理),用于系统自身生成的运行时值(如天河链钱包身份) async setRaw(key: string, value: string): Promise { await this.prisma.systemSetting.upsert({ where: { key }, update: { value }, create: { key, value } }); } private async encryptionKey(): Promise { const row = await this.prisma.systemSetting.findUnique({ where: { key: 'settingsEncryptionKey' } }).catch(() => null); const secret = row?.value || this.config.get('settingsEncryptionKey') || process.env.SETTING_ENCRYPTION_KEY || this.config.get('jwt.secret') || 'artveris_dev_secret'; return createHash('sha256').update(secret).digest(); } private async encryptSecret(value: string): Promise { 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 { 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 (e) { // 解密失败通常意味着 SETTING_ENCRYPTION_KEY 与加密时不一致(配置损坏), // 显式告警而非静默返回空串,避免把「配置损坏」误当成「未配置」 this.logger.warn(`密钥解密失败,可能是 SETTING_ENCRYPTION_KEY 已变更:${(e as Error).message}`); return ''; } } }